work around misdetection of stdin attached to a tty
[git/dscho.git] / gitweb / gitweb.perl
blob1f48f1d4b5075ec8f658ffb5dde832e736fcf886
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 = decode_utf8($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 # html snippet to include in the <head> section of each page
89 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
90 # filename of html text to include at top of each page
91 our $site_header = "++GITWEB_SITE_HEADER++";
92 # html text to include at home page
93 our $home_text = "++GITWEB_HOMETEXT++";
94 # filename of html text to include at bottom of each page
95 our $site_footer = "++GITWEB_SITE_FOOTER++";
97 # URI of stylesheets
98 our @stylesheets = ("++GITWEB_CSS++");
99 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
100 our $stylesheet = undef;
101 # URI of GIT logo (72x27 size)
102 our $logo = "++GITWEB_LOGO++";
103 # URI of GIT favicon, assumed to be image/png type
104 our $favicon = "++GITWEB_FAVICON++";
105 # URI of gitweb.js (JavaScript code for gitweb)
106 our $javascript = "++GITWEB_JS++";
108 # URI and label (title) of GIT logo link
109 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
110 #our $logo_label = "git documentation";
111 our $logo_url = "http://git-scm.com/";
112 our $logo_label = "git homepage";
114 # source of projects list
115 our $projects_list = "++GITWEB_LIST++";
117 # the width (in characters) of the projects list "Description" column
118 our $projects_list_description_width = 25;
120 # group projects by category on the projects list
121 # (enabled if this variable evaluates to true)
122 our $projects_list_group_categories = 0;
124 # default category if none specified
125 # (leave the empty string for no category)
126 our $project_list_default_category = "";
128 # default order of projects list
129 # valid values are none, project, descr, owner, and age
130 our $default_projects_order = "project";
132 # show repository only if this file exists
133 # (only effective if this variable evaluates to true)
134 our $export_ok = "++GITWEB_EXPORT_OK++";
136 # don't generate age column on the projects list page
137 our $omit_age_column = 0;
139 # don't generate information about owners of repositories
140 our $omit_owner=0;
142 # show repository only if this subroutine returns true
143 # when given the path to the project, for example:
144 # sub { return -e "$_[0]/git-daemon-export-ok"; }
145 our $export_auth_hook = undef;
147 # only allow viewing of repositories also shown on the overview page
148 our $strict_export = "++GITWEB_STRICT_EXPORT++";
150 # list of git base URLs used for URL to where fetch project from,
151 # i.e. full URL is "$git_base_url/$project"
152 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
154 # default blob_plain mimetype and default charset for text/plain blob
155 our $default_blob_plain_mimetype = 'text/plain';
156 our $default_text_plain_charset = undef;
158 # file to use for guessing MIME types before trying /etc/mime.types
159 # (relative to the current git repository)
160 our $mimetypes_file = undef;
162 # assume this charset if line contains non-UTF-8 characters;
163 # it should be valid encoding (see Encoding::Supported(3pm) for list),
164 # for which encoding all byte sequences are valid, for example
165 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
166 # could be even 'utf-8' for the old behavior)
167 our $fallback_encoding = 'latin1';
169 # rename detection options for git-diff and git-diff-tree
170 # - default is '-M', with the cost proportional to
171 # (number of removed files) * (number of new files).
172 # - more costly is '-C' (which implies '-M'), with the cost proportional to
173 # (number of changed files + number of removed files) * (number of new files)
174 # - even more costly is '-C', '--find-copies-harder' with cost
175 # (number of files in the original tree) * (number of new files)
176 # - one might want to include '-B' option, e.g. '-B', '-M'
177 our @diff_opts = ('-M'); # taken from git_commit
179 # Disables features that would allow repository owners to inject script into
180 # the gitweb domain.
181 our $prevent_xss = 0;
183 # Path to the highlight executable to use (must be the one from
184 # http://www.andre-simon.de due to assumptions about parameters and output).
185 # Useful if highlight is not installed on your webserver's PATH.
186 # [Default: highlight]
187 our $highlight_bin = "++HIGHLIGHT_BIN++";
189 # information about snapshot formats that gitweb is capable of serving
190 our %known_snapshot_formats = (
191 # name => {
192 # 'display' => display name,
193 # 'type' => mime type,
194 # 'suffix' => filename suffix,
195 # 'format' => --format for git-archive,
196 # 'compressor' => [compressor command and arguments]
197 # (array reference, optional)
198 # 'disabled' => boolean (optional)}
200 'tgz' => {
201 'display' => 'tar.gz',
202 'type' => 'application/x-gzip',
203 'suffix' => '.tar.gz',
204 'format' => 'tar',
205 'compressor' => ['gzip', '-n']},
207 'tbz2' => {
208 'display' => 'tar.bz2',
209 'type' => 'application/x-bzip2',
210 'suffix' => '.tar.bz2',
211 'format' => 'tar',
212 'compressor' => ['bzip2']},
214 'txz' => {
215 'display' => 'tar.xz',
216 'type' => 'application/x-xz',
217 'suffix' => '.tar.xz',
218 'format' => 'tar',
219 'compressor' => ['xz'],
220 'disabled' => 1},
222 'zip' => {
223 'display' => 'zip',
224 'type' => 'application/x-zip',
225 'suffix' => '.zip',
226 'format' => 'zip'},
229 # Aliases so we understand old gitweb.snapshot values in repository
230 # configuration.
231 our %known_snapshot_format_aliases = (
232 'gzip' => 'tgz',
233 'bzip2' => 'tbz2',
234 'xz' => 'txz',
236 # backward compatibility: legacy gitweb config support
237 'x-gzip' => undef, 'gz' => undef,
238 'x-bzip2' => undef, 'bz2' => undef,
239 'x-zip' => undef, '' => undef,
242 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
243 # are changed, it may be appropriate to change these values too via
244 # $GITWEB_CONFIG.
245 our %avatar_size = (
246 'default' => 16,
247 'double' => 32
250 # Used to set the maximum load that we will still respond to gitweb queries.
251 # If server load exceed this value then return "503 server busy" error.
252 # If gitweb cannot determined server load, it is taken to be 0.
253 # Leave it undefined (or set to 'undef') to turn off load checking.
254 our $maxload = 300;
256 # configuration for 'highlight' (http://www.andre-simon.de/)
257 # match by basename
258 our %highlight_basename = (
259 #'Program' => 'py',
260 #'Library' => 'py',
261 'SConstruct' => 'py', # SCons equivalent of Makefile
262 'Makefile' => 'make',
264 # match by extension
265 our %highlight_ext = (
266 # main extensions, defining name of syntax;
267 # see files in /usr/share/highlight/langDefs/ directory
268 map { $_ => $_ }
269 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make),
270 # alternate extensions, see /etc/highlight/filetypes.conf
271 'h' => 'c',
272 map { $_ => 'sh' } qw(bash zsh ksh),
273 map { $_ => 'cpp' } qw(cxx c++ cc),
274 map { $_ => 'php' } qw(php3 php4 php5 phps),
275 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
276 map { $_ => 'make'} qw(mak mk),
277 map { $_ => 'xml' } qw(xhtml html htm),
280 # You define site-wide feature defaults here; override them with
281 # $GITWEB_CONFIG as necessary.
282 our %feature = (
283 # feature => {
284 # 'sub' => feature-sub (subroutine),
285 # 'override' => allow-override (boolean),
286 # 'default' => [ default options...] (array reference)}
288 # if feature is overridable (it means that allow-override has true value),
289 # then feature-sub will be called with default options as parameters;
290 # return value of feature-sub indicates if to enable specified feature
292 # if there is no 'sub' key (no feature-sub), then feature cannot be
293 # overridden
295 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
296 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
297 # is enabled
299 # Enable the 'blame' blob view, showing the last commit that modified
300 # each line in the file. This can be very CPU-intensive.
302 # To enable system wide have in $GITWEB_CONFIG
303 # $feature{'blame'}{'default'} = [1];
304 # To have project specific config enable override in $GITWEB_CONFIG
305 # $feature{'blame'}{'override'} = 1;
306 # and in project config gitweb.blame = 0|1;
307 'blame' => {
308 'sub' => sub { feature_bool('blame', @_) },
309 'override' => 0,
310 'default' => [0]},
312 # Enable the 'snapshot' link, providing a compressed archive of any
313 # tree. This can potentially generate high traffic if you have large
314 # project.
316 # Value is a list of formats defined in %known_snapshot_formats that
317 # you wish to offer.
318 # To disable system wide have in $GITWEB_CONFIG
319 # $feature{'snapshot'}{'default'} = [];
320 # To have project specific config enable override in $GITWEB_CONFIG
321 # $feature{'snapshot'}{'override'} = 1;
322 # and in project config, a comma-separated list of formats or "none"
323 # to disable. Example: gitweb.snapshot = tbz2,zip;
324 'snapshot' => {
325 'sub' => \&feature_snapshot,
326 'override' => 0,
327 'default' => ['tgz']},
329 # Enable text search, which will list the commits which match author,
330 # committer or commit text to a given string. Enabled by default.
331 # Project specific override is not supported.
333 # Note that this controls all search features, which means that if
334 # it is disabled, then 'grep' and 'pickaxe' search would also be
335 # disabled.
336 'search' => {
337 'override' => 0,
338 'default' => [1]},
340 # Enable grep search, which will list the files in currently selected
341 # tree containing the given string. Enabled by default. This can be
342 # potentially CPU-intensive, of course.
343 # Note that you need to have 'search' feature enabled too.
345 # To enable system wide have in $GITWEB_CONFIG
346 # $feature{'grep'}{'default'} = [1];
347 # To have project specific config enable override in $GITWEB_CONFIG
348 # $feature{'grep'}{'override'} = 1;
349 # and in project config gitweb.grep = 0|1;
350 'grep' => {
351 'sub' => sub { feature_bool('grep', @_) },
352 'override' => 0,
353 'default' => [1]},
355 # Enable the pickaxe search, which will list the commits that modified
356 # a given string in a file. This can be practical and quite faster
357 # alternative to 'blame', but still potentially CPU-intensive.
358 # Note that you need to have 'search' feature enabled too.
360 # To enable system wide have in $GITWEB_CONFIG
361 # $feature{'pickaxe'}{'default'} = [1];
362 # To have project specific config enable override in $GITWEB_CONFIG
363 # $feature{'pickaxe'}{'override'} = 1;
364 # and in project config gitweb.pickaxe = 0|1;
365 'pickaxe' => {
366 'sub' => sub { feature_bool('pickaxe', @_) },
367 'override' => 0,
368 'default' => [1]},
370 # Enable showing size of blobs in a 'tree' view, in a separate
371 # column, similar to what 'ls -l' does. This cost a bit of IO.
373 # To disable system wide have in $GITWEB_CONFIG
374 # $feature{'show-sizes'}{'default'} = [0];
375 # To have project specific config enable override in $GITWEB_CONFIG
376 # $feature{'show-sizes'}{'override'} = 1;
377 # and in project config gitweb.showsizes = 0|1;
378 'show-sizes' => {
379 'sub' => sub { feature_bool('showsizes', @_) },
380 'override' => 0,
381 'default' => [1]},
383 # Make gitweb use an alternative format of the URLs which can be
384 # more readable and natural-looking: project name is embedded
385 # directly in the path and the query string contains other
386 # auxiliary information. All gitweb installations recognize
387 # URL in either format; this configures in which formats gitweb
388 # generates links.
390 # To enable system wide have in $GITWEB_CONFIG
391 # $feature{'pathinfo'}{'default'} = [1];
392 # Project specific override is not supported.
394 # Note that you will need to change the default location of CSS,
395 # favicon, logo and possibly other files to an absolute URL. Also,
396 # if gitweb.cgi serves as your indexfile, you will need to force
397 # $my_uri to contain the script name in your $GITWEB_CONFIG.
398 'pathinfo' => {
399 'override' => 0,
400 'default' => [0]},
402 # Make gitweb consider projects in project root subdirectories
403 # to be forks of existing projects. Given project $projname.git,
404 # projects matching $projname/*.git will not be shown in the main
405 # projects list, instead a '+' mark will be added to $projname
406 # there and a 'forks' view will be enabled for the project, listing
407 # all the forks. If project list is taken from a file, forks have
408 # to be listed after the main project.
410 # To enable system wide have in $GITWEB_CONFIG
411 # $feature{'forks'}{'default'} = [1];
412 # Project specific override is not supported.
413 'forks' => {
414 'override' => 0,
415 'default' => [0]},
417 # Insert custom links to the action bar of all project pages.
418 # This enables you mainly to link to third-party scripts integrating
419 # into gitweb; e.g. git-browser for graphical history representation
420 # or custom web-based repository administration interface.
422 # The 'default' value consists of a list of triplets in the form
423 # (label, link, position) where position is the label after which
424 # to insert the link and link is a format string where %n expands
425 # to the project name, %f to the project path within the filesystem,
426 # %h to the current hash (h gitweb parameter) and %b to the current
427 # hash base (hb gitweb parameter); %% expands to %.
429 # To enable system wide have in $GITWEB_CONFIG e.g.
430 # $feature{'actions'}{'default'} = [('graphiclog',
431 # '/git-browser/by-commit.html?r=%n', 'summary')];
432 # Project specific override is not supported.
433 'actions' => {
434 'override' => 0,
435 'default' => []},
437 # Allow gitweb scan project content tags of project repository,
438 # and display the popular Web 2.0-ish "tag cloud" near the projects
439 # list. Note that this is something COMPLETELY different from the
440 # normal Git tags.
442 # gitweb by itself can show existing tags, but it does not handle
443 # tagging itself; you need to do it externally, outside gitweb.
444 # The format is described in git_get_project_ctags() subroutine.
445 # You may want to install the HTML::TagCloud Perl module to get
446 # a pretty tag cloud instead of just a list of tags.
448 # To enable system wide have in $GITWEB_CONFIG
449 # $feature{'ctags'}{'default'} = [1];
450 # Project specific override is not supported.
452 # In the future whether ctags editing is enabled might depend
453 # on the value, but using 1 should always mean no editing of ctags.
454 'ctags' => {
455 'override' => 0,
456 'default' => [0]},
458 # The maximum number of patches in a patchset generated in patch
459 # view. Set this to 0 or undef to disable patch view, or to a
460 # negative number to remove any limit.
462 # To disable system wide have in $GITWEB_CONFIG
463 # $feature{'patches'}{'default'} = [0];
464 # To have project specific config enable override in $GITWEB_CONFIG
465 # $feature{'patches'}{'override'} = 1;
466 # and in project config gitweb.patches = 0|n;
467 # where n is the maximum number of patches allowed in a patchset.
468 'patches' => {
469 'sub' => \&feature_patches,
470 'override' => 0,
471 'default' => [16]},
473 # Avatar support. When this feature is enabled, views such as
474 # shortlog or commit will display an avatar associated with
475 # the email of the committer(s) and/or author(s).
477 # Currently available providers are gravatar and picon.
478 # If an unknown provider is specified, the feature is disabled.
480 # Gravatar depends on Digest::MD5.
481 # Picon currently relies on the indiana.edu database.
483 # To enable system wide have in $GITWEB_CONFIG
484 # $feature{'avatar'}{'default'} = ['<provider>'];
485 # where <provider> is either gravatar or picon.
486 # To have project specific config enable override in $GITWEB_CONFIG
487 # $feature{'avatar'}{'override'} = 1;
488 # and in project config gitweb.avatar = <provider>;
489 'avatar' => {
490 'sub' => \&feature_avatar,
491 'override' => 0,
492 'default' => ['']},
494 # Enable displaying how much time and how many git commands
495 # it took to generate and display page. Disabled by default.
496 # Project specific override is not supported.
497 'timed' => {
498 'override' => 0,
499 'default' => [0]},
501 # Enable turning some links into links to actions which require
502 # JavaScript to run (like 'blame_incremental'). Not enabled by
503 # default. Project specific override is currently not supported.
504 'javascript-actions' => {
505 'override' => 0,
506 'default' => [0]},
508 # Enable and configure ability to change common timezone for dates
509 # in gitweb output via JavaScript. Enabled by default.
510 # Project specific override is not supported.
511 'javascript-timezone' => {
512 'override' => 0,
513 'default' => [
514 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
515 # or undef to turn off this feature
516 'gitweb_tz', # name of cookie where to store selected timezone
517 'datetime', # CSS class used to mark up dates for manipulation
520 # Syntax highlighting support. This is based on Daniel Svensson's
521 # and Sham Chukoury's work in gitweb-xmms2.git.
522 # It requires the 'highlight' program present in $PATH,
523 # and therefore is disabled by default.
525 # To enable system wide have in $GITWEB_CONFIG
526 # $feature{'highlight'}{'default'} = [1];
528 'highlight' => {
529 'sub' => sub { feature_bool('highlight', @_) },
530 'override' => 0,
531 'default' => [0]},
533 # Enable displaying of remote heads in the heads list
535 # To enable system wide have in $GITWEB_CONFIG
536 # $feature{'remote_heads'}{'default'} = [1];
537 # To have project specific config enable override in $GITWEB_CONFIG
538 # $feature{'remote_heads'}{'override'} = 1;
539 # and in project config gitweb.remote_heads = 0|1;
540 'remote_heads' => {
541 'sub' => sub { feature_bool('remote_heads', @_) },
542 'override' => 0,
543 'default' => [0]},
546 sub gitweb_get_feature {
547 my ($name) = @_;
548 return unless exists $feature{$name};
549 my ($sub, $override, @defaults) = (
550 $feature{$name}{'sub'},
551 $feature{$name}{'override'},
552 @{$feature{$name}{'default'}});
553 # project specific override is possible only if we have project
554 our $git_dir; # global variable, declared later
555 if (!$override || !defined $git_dir) {
556 return @defaults;
558 if (!defined $sub) {
559 warn "feature $name is not overridable";
560 return @defaults;
562 return $sub->(@defaults);
565 # A wrapper to check if a given feature is enabled.
566 # With this, you can say
568 # my $bool_feat = gitweb_check_feature('bool_feat');
569 # gitweb_check_feature('bool_feat') or somecode;
571 # instead of
573 # my ($bool_feat) = gitweb_get_feature('bool_feat');
574 # (gitweb_get_feature('bool_feat'))[0] or somecode;
576 sub gitweb_check_feature {
577 return (gitweb_get_feature(@_))[0];
581 sub feature_bool {
582 my $key = shift;
583 my ($val) = git_get_project_config($key, '--bool');
585 if (!defined $val) {
586 return ($_[0]);
587 } elsif ($val eq 'true') {
588 return (1);
589 } elsif ($val eq 'false') {
590 return (0);
594 sub feature_snapshot {
595 my (@fmts) = @_;
597 my ($val) = git_get_project_config('snapshot');
599 if ($val) {
600 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
603 return @fmts;
606 sub feature_patches {
607 my @val = (git_get_project_config('patches', '--int'));
609 if (@val) {
610 return @val;
613 return ($_[0]);
616 sub feature_avatar {
617 my @val = (git_get_project_config('avatar'));
619 return @val ? @val : @_;
622 # checking HEAD file with -e is fragile if the repository was
623 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
624 # and then pruned.
625 sub check_head_link {
626 my ($dir) = @_;
627 my $headfile = "$dir/HEAD";
628 return ((-e $headfile) ||
629 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
632 sub check_export_ok {
633 my ($dir) = @_;
634 return (check_head_link($dir) &&
635 (!$export_ok || -e "$dir/$export_ok") &&
636 (!$export_auth_hook || $export_auth_hook->($dir)));
639 # process alternate names for backward compatibility
640 # filter out unsupported (unknown) snapshot formats
641 sub filter_snapshot_fmts {
642 my @fmts = @_;
644 @fmts = map {
645 exists $known_snapshot_format_aliases{$_} ?
646 $known_snapshot_format_aliases{$_} : $_} @fmts;
647 @fmts = grep {
648 exists $known_snapshot_formats{$_} &&
649 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
652 # If it is set to code reference, it is code that it is to be run once per
653 # request, allowing updating configurations that change with each request,
654 # while running other code in config file only once.
656 # Otherwise, if it is false then gitweb would process config file only once;
657 # if it is true then gitweb config would be run for each request.
658 our $per_request_config = 1;
660 # read and parse gitweb config file given by its parameter.
661 # returns true on success, false on recoverable error, allowing
662 # to chain this subroutine, using first file that exists.
663 # dies on errors during parsing config file, as it is unrecoverable.
664 sub read_config_file {
665 my $filename = shift;
666 return unless defined $filename;
667 # die if there are errors parsing config file
668 if (-e $filename) {
669 do $filename;
670 die $@ if $@;
671 return 1;
673 return;
676 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
677 sub evaluate_gitweb_config {
678 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
679 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
680 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
682 # Protect agains duplications of file names, to not read config twice.
683 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
684 # there possibility of duplication of filename there doesn't matter.
685 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
686 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
688 # Common system-wide settings for convenience.
689 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
690 read_config_file($GITWEB_CONFIG_COMMON);
692 # Use first config file that exists. This means use the per-instance
693 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
694 read_config_file($GITWEB_CONFIG) and return;
695 read_config_file($GITWEB_CONFIG_SYSTEM);
698 # Get loadavg of system, to compare against $maxload.
699 # Currently it requires '/proc/loadavg' present to get loadavg;
700 # if it is not present it returns 0, which means no load checking.
701 sub get_loadavg {
702 if( -e '/proc/loadavg' ){
703 open my $fd, '<', '/proc/loadavg'
704 or return 0;
705 my @load = split(/\s+/, scalar <$fd>);
706 close $fd;
708 # The first three columns measure CPU and IO utilization of the last one,
709 # five, and 10 minute periods. The fourth column shows the number of
710 # currently running processes and the total number of processes in the m/n
711 # format. The last column displays the last process ID used.
712 return $load[0] || 0;
714 # additional checks for load average should go here for things that don't export
715 # /proc/loadavg
717 return 0;
720 # version of the core git binary
721 our $git_version;
722 sub evaluate_git_version {
723 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
724 $number_of_git_cmds++;
727 sub check_loadavg {
728 if (defined $maxload && get_loadavg() > $maxload) {
729 die_error(503, "The load average on the server is too high");
733 # ======================================================================
734 # input validation and dispatch
736 # input parameters can be collected from a variety of sources (presently, CGI
737 # and PATH_INFO), so we define an %input_params hash that collects them all
738 # together during validation: this allows subsequent uses (e.g. href()) to be
739 # agnostic of the parameter origin
741 our %input_params = ();
743 # input parameters are stored with the long parameter name as key. This will
744 # also be used in the href subroutine to convert parameters to their CGI
745 # equivalent, and since the href() usage is the most frequent one, we store
746 # the name -> CGI key mapping here, instead of the reverse.
748 # XXX: Warning: If you touch this, check the search form for updating,
749 # too.
751 our @cgi_param_mapping = (
752 project => "p",
753 action => "a",
754 file_name => "f",
755 file_parent => "fp",
756 hash => "h",
757 hash_parent => "hp",
758 hash_base => "hb",
759 hash_parent_base => "hpb",
760 page => "pg",
761 order => "o",
762 searchtext => "s",
763 searchtype => "st",
764 snapshot_format => "sf",
765 extra_options => "opt",
766 search_use_regexp => "sr",
767 ctag => "by_tag",
768 diff_style => "ds",
769 project_filter => "pf",
770 # this must be last entry (for manipulation from JavaScript)
771 javascript => "js"
773 our %cgi_param_mapping = @cgi_param_mapping;
775 # we will also need to know the possible actions, for validation
776 our %actions = (
777 "blame" => \&git_blame,
778 "blame_incremental" => \&git_blame_incremental,
779 "blame_data" => \&git_blame_data,
780 "blobdiff" => \&git_blobdiff,
781 "blobdiff_plain" => \&git_blobdiff_plain,
782 "blob" => \&git_blob,
783 "blob_plain" => \&git_blob_plain,
784 "commitdiff" => \&git_commitdiff,
785 "commitdiff_plain" => \&git_commitdiff_plain,
786 "commit" => \&git_commit,
787 "forks" => \&git_forks,
788 "heads" => \&git_heads,
789 "history" => \&git_history,
790 "log" => \&git_log,
791 "patch" => \&git_patch,
792 "patches" => \&git_patches,
793 "remotes" => \&git_remotes,
794 "rss" => \&git_rss,
795 "atom" => \&git_atom,
796 "search" => \&git_search,
797 "search_help" => \&git_search_help,
798 "shortlog" => \&git_shortlog,
799 "summary" => \&git_summary,
800 "tag" => \&git_tag,
801 "tags" => \&git_tags,
802 "tree" => \&git_tree,
803 "snapshot" => \&git_snapshot,
804 "object" => \&git_object,
805 # those below don't need $project
806 "opml" => \&git_opml,
807 "project_list" => \&git_project_list,
808 "project_index" => \&git_project_index,
811 # finally, we have the hash of allowed extra_options for the commands that
812 # allow them
813 our %allowed_options = (
814 "--no-merges" => [ qw(rss atom log shortlog history) ],
817 # fill %input_params with the CGI parameters. All values except for 'opt'
818 # should be single values, but opt can be an array. We should probably
819 # build an array of parameters that can be multi-valued, but since for the time
820 # being it's only this one, we just single it out
821 sub evaluate_query_params {
822 our $cgi;
824 while (my ($name, $symbol) = each %cgi_param_mapping) {
825 if ($symbol eq 'opt') {
826 $input_params{$name} = [ map { decode_utf8($_) } $cgi->param($symbol) ];
827 } else {
828 $input_params{$name} = decode_utf8($cgi->param($symbol));
833 # now read PATH_INFO and update the parameter list for missing parameters
834 sub evaluate_path_info {
835 return if defined $input_params{'project'};
836 return if !$path_info;
837 $path_info =~ s,^/+,,;
838 return if !$path_info;
840 # find which part of PATH_INFO is project
841 my $project = $path_info;
842 $project =~ s,/+$,,;
843 while ($project && !check_head_link("$projectroot/$project")) {
844 $project =~ s,/*[^/]*$,,;
846 return unless $project;
847 $input_params{'project'} = $project;
849 # do not change any parameters if an action is given using the query string
850 return if $input_params{'action'};
851 $path_info =~ s,^\Q$project\E/*,,;
853 # next, check if we have an action
854 my $action = $path_info;
855 $action =~ s,/.*$,,;
856 if (exists $actions{$action}) {
857 $path_info =~ s,^$action/*,,;
858 $input_params{'action'} = $action;
861 # list of actions that want hash_base instead of hash, but can have no
862 # pathname (f) parameter
863 my @wants_base = (
864 'tree',
865 'history',
868 # we want to catch, among others
869 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
870 my ($parentrefname, $parentpathname, $refname, $pathname) =
871 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
873 # first, analyze the 'current' part
874 if (defined $pathname) {
875 # we got "branch:filename" or "branch:dir/"
876 # we could use git_get_type(branch:pathname), but:
877 # - it needs $git_dir
878 # - it does a git() call
879 # - the convention of terminating directories with a slash
880 # makes it superfluous
881 # - embedding the action in the PATH_INFO would make it even
882 # more superfluous
883 $pathname =~ s,^/+,,;
884 if (!$pathname || substr($pathname, -1) eq "/") {
885 $input_params{'action'} ||= "tree";
886 $pathname =~ s,/$,,;
887 } else {
888 # the default action depends on whether we had parent info
889 # or not
890 if ($parentrefname) {
891 $input_params{'action'} ||= "blobdiff_plain";
892 } else {
893 $input_params{'action'} ||= "blob_plain";
896 $input_params{'hash_base'} ||= $refname;
897 $input_params{'file_name'} ||= $pathname;
898 } elsif (defined $refname) {
899 # we got "branch". In this case we have to choose if we have to
900 # set hash or hash_base.
902 # Most of the actions without a pathname only want hash to be
903 # set, except for the ones specified in @wants_base that want
904 # hash_base instead. It should also be noted that hand-crafted
905 # links having 'history' as an action and no pathname or hash
906 # set will fail, but that happens regardless of PATH_INFO.
907 if (defined $parentrefname) {
908 # if there is parent let the default be 'shortlog' action
909 # (for http://git.example.com/repo.git/A..B links); if there
910 # is no parent, dispatch will detect type of object and set
911 # action appropriately if required (if action is not set)
912 $input_params{'action'} ||= "shortlog";
914 if ($input_params{'action'} &&
915 grep { $_ eq $input_params{'action'} } @wants_base) {
916 $input_params{'hash_base'} ||= $refname;
917 } else {
918 $input_params{'hash'} ||= $refname;
922 # next, handle the 'parent' part, if present
923 if (defined $parentrefname) {
924 # a missing pathspec defaults to the 'current' filename, allowing e.g.
925 # someproject/blobdiff/oldrev..newrev:/filename
926 if ($parentpathname) {
927 $parentpathname =~ s,^/+,,;
928 $parentpathname =~ s,/$,,;
929 $input_params{'file_parent'} ||= $parentpathname;
930 } else {
931 $input_params{'file_parent'} ||= $input_params{'file_name'};
933 # we assume that hash_parent_base is wanted if a path was specified,
934 # or if the action wants hash_base instead of hash
935 if (defined $input_params{'file_parent'} ||
936 grep { $_ eq $input_params{'action'} } @wants_base) {
937 $input_params{'hash_parent_base'} ||= $parentrefname;
938 } else {
939 $input_params{'hash_parent'} ||= $parentrefname;
943 # for the snapshot action, we allow URLs in the form
944 # $project/snapshot/$hash.ext
945 # where .ext determines the snapshot and gets removed from the
946 # passed $refname to provide the $hash.
948 # To be able to tell that $refname includes the format extension, we
949 # require the following two conditions to be satisfied:
950 # - the hash input parameter MUST have been set from the $refname part
951 # of the URL (i.e. they must be equal)
952 # - the snapshot format MUST NOT have been defined already (e.g. from
953 # CGI parameter sf)
954 # It's also useless to try any matching unless $refname has a dot,
955 # so we check for that too
956 if (defined $input_params{'action'} &&
957 $input_params{'action'} eq 'snapshot' &&
958 defined $refname && index($refname, '.') != -1 &&
959 $refname eq $input_params{'hash'} &&
960 !defined $input_params{'snapshot_format'}) {
961 # We loop over the known snapshot formats, checking for
962 # extensions. Allowed extensions are both the defined suffix
963 # (which includes the initial dot already) and the snapshot
964 # format key itself, with a prepended dot
965 while (my ($fmt, $opt) = each %known_snapshot_formats) {
966 my $hash = $refname;
967 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
968 next;
970 my $sfx = $1;
971 # a valid suffix was found, so set the snapshot format
972 # and reset the hash parameter
973 $input_params{'snapshot_format'} = $fmt;
974 $input_params{'hash'} = $hash;
975 # we also set the format suffix to the one requested
976 # in the URL: this way a request for e.g. .tgz returns
977 # a .tgz instead of a .tar.gz
978 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
979 last;
984 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
985 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
986 $searchtext, $search_regexp, $project_filter);
987 sub evaluate_and_validate_params {
988 our $action = $input_params{'action'};
989 if (defined $action) {
990 if (!validate_action($action)) {
991 die_error(400, "Invalid action parameter");
995 # parameters which are pathnames
996 our $project = $input_params{'project'};
997 if (defined $project) {
998 if (!validate_project($project)) {
999 undef $project;
1000 die_error(404, "No such project");
1004 our $project_filter = $input_params{'project_filter'};
1005 if (defined $project_filter) {
1006 if (!validate_pathname($project_filter)) {
1007 die_error(404, "Invalid project_filter parameter");
1011 our $file_name = $input_params{'file_name'};
1012 if (defined $file_name) {
1013 if (!validate_pathname($file_name)) {
1014 die_error(400, "Invalid file parameter");
1018 our $file_parent = $input_params{'file_parent'};
1019 if (defined $file_parent) {
1020 if (!validate_pathname($file_parent)) {
1021 die_error(400, "Invalid file parent parameter");
1025 # parameters which are refnames
1026 our $hash = $input_params{'hash'};
1027 if (defined $hash) {
1028 if (!validate_refname($hash)) {
1029 die_error(400, "Invalid hash parameter");
1033 our $hash_parent = $input_params{'hash_parent'};
1034 if (defined $hash_parent) {
1035 if (!validate_refname($hash_parent)) {
1036 die_error(400, "Invalid hash parent parameter");
1040 our $hash_base = $input_params{'hash_base'};
1041 if (defined $hash_base) {
1042 if (!validate_refname($hash_base)) {
1043 die_error(400, "Invalid hash base parameter");
1047 our @extra_options = @{$input_params{'extra_options'}};
1048 # @extra_options is always defined, since it can only be (currently) set from
1049 # CGI, and $cgi->param() returns the empty array in array context if the param
1050 # is not set
1051 foreach my $opt (@extra_options) {
1052 if (not exists $allowed_options{$opt}) {
1053 die_error(400, "Invalid option parameter");
1055 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1056 die_error(400, "Invalid option parameter for this action");
1060 our $hash_parent_base = $input_params{'hash_parent_base'};
1061 if (defined $hash_parent_base) {
1062 if (!validate_refname($hash_parent_base)) {
1063 die_error(400, "Invalid hash parent base parameter");
1067 # other parameters
1068 our $page = $input_params{'page'};
1069 if (defined $page) {
1070 if ($page =~ m/[^0-9]/) {
1071 die_error(400, "Invalid page parameter");
1075 our $searchtype = $input_params{'searchtype'};
1076 if (defined $searchtype) {
1077 if ($searchtype =~ m/[^a-z]/) {
1078 die_error(400, "Invalid searchtype parameter");
1082 our $search_use_regexp = $input_params{'search_use_regexp'};
1084 our $searchtext = $input_params{'searchtext'};
1085 our $search_regexp;
1086 if (defined $searchtext) {
1087 if (length($searchtext) < 2) {
1088 die_error(403, "At least two characters are required for search parameter");
1090 if ($search_use_regexp) {
1091 $search_regexp = $searchtext;
1092 if (!eval { qr/$search_regexp/; 1; }) {
1093 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1094 die_error(400, "Invalid search regexp '$search_regexp'",
1095 esc_html($error));
1097 } else {
1098 $search_regexp = quotemeta $searchtext;
1103 # path to the current git repository
1104 our $git_dir;
1105 sub evaluate_git_dir {
1106 our $git_dir = "$projectroot/$project" if $project;
1109 our (@snapshot_fmts, $git_avatar);
1110 sub configure_gitweb_features {
1111 # list of supported snapshot formats
1112 our @snapshot_fmts = gitweb_get_feature('snapshot');
1113 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1115 # check that the avatar feature is set to a known provider name,
1116 # and for each provider check if the dependencies are satisfied.
1117 # if the provider name is invalid or the dependencies are not met,
1118 # reset $git_avatar to the empty string.
1119 our ($git_avatar) = gitweb_get_feature('avatar');
1120 if ($git_avatar eq 'gravatar') {
1121 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1122 } elsif ($git_avatar eq 'picon') {
1123 # no dependencies
1124 } else {
1125 $git_avatar = '';
1129 # custom error handler: 'die <message>' is Internal Server Error
1130 sub handle_errors_html {
1131 my $msg = shift; # it is already HTML escaped
1133 # to avoid infinite loop where error occurs in die_error,
1134 # change handler to default handler, disabling handle_errors_html
1135 set_message("Error occured when inside die_error:\n$msg");
1137 # you cannot jump out of die_error when called as error handler;
1138 # the subroutine set via CGI::Carp::set_message is called _after_
1139 # HTTP headers are already written, so it cannot write them itself
1140 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1142 set_message(\&handle_errors_html);
1144 # dispatch
1145 sub dispatch {
1146 if (!defined $action) {
1147 if (defined $hash) {
1148 $action = git_get_type($hash);
1149 $action or die_error(404, "Object does not exist");
1150 } elsif (defined $hash_base && defined $file_name) {
1151 $action = git_get_type("$hash_base:$file_name");
1152 $action or die_error(404, "File or directory does not exist");
1153 } elsif (defined $project) {
1154 $action = 'summary';
1155 } else {
1156 $action = 'project_list';
1159 if (!defined($actions{$action})) {
1160 die_error(400, "Unknown action");
1162 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1163 !$project) {
1164 die_error(400, "Project needed");
1166 $actions{$action}->();
1169 sub reset_timer {
1170 our $t0 = [ gettimeofday() ]
1171 if defined $t0;
1172 our $number_of_git_cmds = 0;
1175 our $first_request = 1;
1176 sub run_request {
1177 reset_timer();
1179 evaluate_uri();
1180 if ($first_request) {
1181 evaluate_gitweb_config();
1182 evaluate_git_version();
1184 if ($per_request_config) {
1185 if (ref($per_request_config) eq 'CODE') {
1186 $per_request_config->();
1187 } elsif (!$first_request) {
1188 evaluate_gitweb_config();
1191 check_loadavg();
1193 # $projectroot and $projects_list might be set in gitweb config file
1194 $projects_list ||= $projectroot;
1196 evaluate_query_params();
1197 evaluate_path_info();
1198 evaluate_and_validate_params();
1199 evaluate_git_dir();
1201 configure_gitweb_features();
1203 dispatch();
1206 our $is_last_request = sub { 1 };
1207 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1208 our $CGI = 'CGI';
1209 our $cgi;
1210 sub configure_as_fcgi {
1211 require CGI::Fast;
1212 our $CGI = 'CGI::Fast';
1214 my $request_number = 0;
1215 # let each child service 100 requests
1216 our $is_last_request = sub { ++$request_number > 100 };
1218 sub evaluate_argv {
1219 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1220 configure_as_fcgi()
1221 if $script_name =~ /\.fcgi$/;
1223 return unless (@ARGV);
1225 require Getopt::Long;
1226 Getopt::Long::GetOptions(
1227 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1228 'nproc|n=i' => sub {
1229 my ($arg, $val) = @_;
1230 return unless eval { require FCGI::ProcManager; 1; };
1231 my $proc_manager = FCGI::ProcManager->new({
1232 n_processes => $val,
1234 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1235 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1236 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1241 sub run {
1242 evaluate_argv();
1244 $first_request = 1;
1245 $pre_listen_hook->()
1246 if $pre_listen_hook;
1248 REQUEST:
1249 while ($cgi = $CGI->new()) {
1250 $pre_dispatch_hook->()
1251 if $pre_dispatch_hook;
1253 run_request();
1255 $post_dispatch_hook->()
1256 if $post_dispatch_hook;
1257 $first_request = 0;
1259 last REQUEST if ($is_last_request->());
1262 DONE_GITWEB:
1266 run();
1268 if (defined caller) {
1269 # wrapped in a subroutine processing requests,
1270 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1271 return;
1272 } else {
1273 # pure CGI script, serving single request
1274 exit;
1277 ## ======================================================================
1278 ## action links
1280 # possible values of extra options
1281 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1282 # -replay => 1 - start from a current view (replay with modifications)
1283 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1284 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1285 sub href {
1286 my %params = @_;
1287 # default is to use -absolute url() i.e. $my_uri
1288 my $href = $params{-full} ? $my_url : $my_uri;
1290 # implicit -replay, must be first of implicit params
1291 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1293 $params{'project'} = $project unless exists $params{'project'};
1295 if ($params{-replay}) {
1296 while (my ($name, $symbol) = each %cgi_param_mapping) {
1297 if (!exists $params{$name}) {
1298 $params{$name} = $input_params{$name};
1303 my $use_pathinfo = gitweb_check_feature('pathinfo');
1304 if (defined $params{'project'} &&
1305 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1306 # try to put as many parameters as possible in PATH_INFO:
1307 # - project name
1308 # - action
1309 # - hash_parent or hash_parent_base:/file_parent
1310 # - hash or hash_base:/filename
1311 # - the snapshot_format as an appropriate suffix
1313 # When the script is the root DirectoryIndex for the domain,
1314 # $href here would be something like http://gitweb.example.com/
1315 # Thus, we strip any trailing / from $href, to spare us double
1316 # slashes in the final URL
1317 $href =~ s,/$,,;
1319 # Then add the project name, if present
1320 $href .= "/".esc_path_info($params{'project'});
1321 delete $params{'project'};
1323 # since we destructively absorb parameters, we keep this
1324 # boolean that remembers if we're handling a snapshot
1325 my $is_snapshot = $params{'action'} eq 'snapshot';
1327 # Summary just uses the project path URL, any other action is
1328 # added to the URL
1329 if (defined $params{'action'}) {
1330 $href .= "/".esc_path_info($params{'action'})
1331 unless $params{'action'} eq 'summary';
1332 delete $params{'action'};
1335 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1336 # stripping nonexistent or useless pieces
1337 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1338 || $params{'hash_parent'} || $params{'hash'});
1339 if (defined $params{'hash_base'}) {
1340 if (defined $params{'hash_parent_base'}) {
1341 $href .= esc_path_info($params{'hash_parent_base'});
1342 # skip the file_parent if it's the same as the file_name
1343 if (defined $params{'file_parent'}) {
1344 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1345 delete $params{'file_parent'};
1346 } elsif ($params{'file_parent'} !~ /\.\./) {
1347 $href .= ":/".esc_path_info($params{'file_parent'});
1348 delete $params{'file_parent'};
1351 $href .= "..";
1352 delete $params{'hash_parent'};
1353 delete $params{'hash_parent_base'};
1354 } elsif (defined $params{'hash_parent'}) {
1355 $href .= esc_path_info($params{'hash_parent'}). "..";
1356 delete $params{'hash_parent'};
1359 $href .= esc_path_info($params{'hash_base'});
1360 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1361 $href .= ":/".esc_path_info($params{'file_name'});
1362 delete $params{'file_name'};
1364 delete $params{'hash'};
1365 delete $params{'hash_base'};
1366 } elsif (defined $params{'hash'}) {
1367 $href .= esc_path_info($params{'hash'});
1368 delete $params{'hash'};
1371 # If the action was a snapshot, we can absorb the
1372 # snapshot_format parameter too
1373 if ($is_snapshot) {
1374 my $fmt = $params{'snapshot_format'};
1375 # snapshot_format should always be defined when href()
1376 # is called, but just in case some code forgets, we
1377 # fall back to the default
1378 $fmt ||= $snapshot_fmts[0];
1379 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1380 delete $params{'snapshot_format'};
1384 # now encode the parameters explicitly
1385 my @result = ();
1386 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1387 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1388 if (defined $params{$name}) {
1389 if (ref($params{$name}) eq "ARRAY") {
1390 foreach my $par (@{$params{$name}}) {
1391 push @result, $symbol . "=" . esc_param($par);
1393 } else {
1394 push @result, $symbol . "=" . esc_param($params{$name});
1398 $href .= "?" . join(';', @result) if scalar @result;
1400 # final transformation: trailing spaces must be escaped (URI-encoded)
1401 $href =~ s/(\s+)$/CGI::escape($1)/e;
1403 if ($params{-anchor}) {
1404 $href .= "#".esc_param($params{-anchor});
1407 return $href;
1411 ## ======================================================================
1412 ## validation, quoting/unquoting and escaping
1414 sub validate_action {
1415 my $input = shift || return undef;
1416 return undef unless exists $actions{$input};
1417 return $input;
1420 sub validate_project {
1421 my $input = shift || return undef;
1422 if (!validate_pathname($input) ||
1423 !(-d "$projectroot/$input") ||
1424 !check_export_ok("$projectroot/$input") ||
1425 ($strict_export && !project_in_list($input))) {
1426 return undef;
1427 } else {
1428 return $input;
1432 sub validate_pathname {
1433 my $input = shift || return undef;
1435 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1436 # at the beginning, at the end, and between slashes.
1437 # also this catches doubled slashes
1438 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1439 return undef;
1441 # no null characters
1442 if ($input =~ m!\0!) {
1443 return undef;
1445 return $input;
1448 sub validate_refname {
1449 my $input = shift || return undef;
1451 # textual hashes are O.K.
1452 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1453 return $input;
1455 # it must be correct pathname
1456 $input = validate_pathname($input)
1457 or return undef;
1458 # restrictions on ref name according to git-check-ref-format
1459 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1460 return undef;
1462 return $input;
1465 # decode sequences of octets in utf8 into Perl's internal form,
1466 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1467 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1468 sub to_utf8 {
1469 my $str = shift;
1470 return undef unless defined $str;
1472 if (utf8::is_utf8($str) || utf8::decode($str)) {
1473 return $str;
1474 } else {
1475 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1479 # quote unsafe chars, but keep the slash, even when it's not
1480 # correct, but quoted slashes look too horrible in bookmarks
1481 sub esc_param {
1482 my $str = shift;
1483 return undef unless defined $str;
1484 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1485 $str =~ s/ /\+/g;
1486 return $str;
1489 # the quoting rules for path_info fragment are slightly different
1490 sub esc_path_info {
1491 my $str = shift;
1492 return undef unless defined $str;
1494 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1495 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1497 return $str;
1500 # quote unsafe chars in whole URL, so some characters cannot be quoted
1501 sub esc_url {
1502 my $str = shift;
1503 return undef unless defined $str;
1504 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1505 $str =~ s/ /\+/g;
1506 return $str;
1509 # quote unsafe characters in HTML attributes
1510 sub esc_attr {
1512 # for XHTML conformance escaping '"' to '&quot;' is not enough
1513 return esc_html(@_);
1516 # replace invalid utf8 character with SUBSTITUTION sequence
1517 sub esc_html {
1518 my $str = shift;
1519 my %opts = @_;
1521 return undef unless defined $str;
1523 $str = to_utf8($str);
1524 $str = $cgi->escapeHTML($str);
1525 if ($opts{'-nbsp'}) {
1526 $str =~ s/ /&nbsp;/g;
1528 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1529 return $str;
1532 # quote control characters and escape filename to HTML
1533 sub esc_path {
1534 my $str = shift;
1535 my %opts = @_;
1537 return undef unless defined $str;
1539 $str = to_utf8($str);
1540 $str = $cgi->escapeHTML($str);
1541 if ($opts{'-nbsp'}) {
1542 $str =~ s/ /&nbsp;/g;
1544 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1545 return $str;
1548 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1549 sub sanitize {
1550 my $str = shift;
1552 return undef unless defined $str;
1554 $str = to_utf8($str);
1555 $str =~ s|([[:cntrl:]])|($1 =~ /[\t\n\r]/ ? $1 : quot_cec($1))|eg;
1556 return $str;
1559 # Make control characters "printable", using character escape codes (CEC)
1560 sub quot_cec {
1561 my $cntrl = shift;
1562 my %opts = @_;
1563 my %es = ( # character escape codes, aka escape sequences
1564 "\t" => '\t', # tab (HT)
1565 "\n" => '\n', # line feed (LF)
1566 "\r" => '\r', # carrige return (CR)
1567 "\f" => '\f', # form feed (FF)
1568 "\b" => '\b', # backspace (BS)
1569 "\a" => '\a', # alarm (bell) (BEL)
1570 "\e" => '\e', # escape (ESC)
1571 "\013" => '\v', # vertical tab (VT)
1572 "\000" => '\0', # nul character (NUL)
1574 my $chr = ( (exists $es{$cntrl})
1575 ? $es{$cntrl}
1576 : sprintf('\%2x', ord($cntrl)) );
1577 if ($opts{-nohtml}) {
1578 return $chr;
1579 } else {
1580 return "<span class=\"cntrl\">$chr</span>";
1584 # Alternatively use unicode control pictures codepoints,
1585 # Unicode "printable representation" (PR)
1586 sub quot_upr {
1587 my $cntrl = shift;
1588 my %opts = @_;
1590 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1591 if ($opts{-nohtml}) {
1592 return $chr;
1593 } else {
1594 return "<span class=\"cntrl\">$chr</span>";
1598 # git may return quoted and escaped filenames
1599 sub unquote {
1600 my $str = shift;
1602 sub unq {
1603 my $seq = shift;
1604 my %es = ( # character escape codes, aka escape sequences
1605 't' => "\t", # tab (HT, TAB)
1606 'n' => "\n", # newline (NL)
1607 'r' => "\r", # return (CR)
1608 'f' => "\f", # form feed (FF)
1609 'b' => "\b", # backspace (BS)
1610 'a' => "\a", # alarm (bell) (BEL)
1611 'e' => "\e", # escape (ESC)
1612 'v' => "\013", # vertical tab (VT)
1615 if ($seq =~ m/^[0-7]{1,3}$/) {
1616 # octal char sequence
1617 return chr(oct($seq));
1618 } elsif (exists $es{$seq}) {
1619 # C escape sequence, aka character escape code
1620 return $es{$seq};
1622 # quoted ordinary character
1623 return $seq;
1626 if ($str =~ m/^"(.*)"$/) {
1627 # needs unquoting
1628 $str = $1;
1629 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1631 return $str;
1634 # escape tabs (convert tabs to spaces)
1635 sub untabify {
1636 my $line = shift;
1638 while ((my $pos = index($line, "\t")) != -1) {
1639 if (my $count = (8 - ($pos % 8))) {
1640 my $spaces = ' ' x $count;
1641 $line =~ s/\t/$spaces/;
1645 return $line;
1648 sub project_in_list {
1649 my $project = shift;
1650 my @list = git_get_projects_list();
1651 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1654 ## ----------------------------------------------------------------------
1655 ## HTML aware string manipulation
1657 # Try to chop given string on a word boundary between position
1658 # $len and $len+$add_len. If there is no word boundary there,
1659 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1660 # (marking chopped part) would be longer than given string.
1661 sub chop_str {
1662 my $str = shift;
1663 my $len = shift;
1664 my $add_len = shift || 10;
1665 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1667 # Make sure perl knows it is utf8 encoded so we don't
1668 # cut in the middle of a utf8 multibyte char.
1669 $str = to_utf8($str);
1671 # allow only $len chars, but don't cut a word if it would fit in $add_len
1672 # if it doesn't fit, cut it if it's still longer than the dots we would add
1673 # remove chopped character entities entirely
1675 # when chopping in the middle, distribute $len into left and right part
1676 # return early if chopping wouldn't make string shorter
1677 if ($where eq 'center') {
1678 return $str if ($len + 5 >= length($str)); # filler is length 5
1679 $len = int($len/2);
1680 } else {
1681 return $str if ($len + 4 >= length($str)); # filler is length 4
1684 # regexps: ending and beginning with word part up to $add_len
1685 my $endre = qr/.{$len}\w{0,$add_len}/;
1686 my $begre = qr/\w{0,$add_len}.{$len}/;
1688 if ($where eq 'left') {
1689 $str =~ m/^(.*?)($begre)$/;
1690 my ($lead, $body) = ($1, $2);
1691 if (length($lead) > 4) {
1692 $lead = " ...";
1694 return "$lead$body";
1696 } elsif ($where eq 'center') {
1697 $str =~ m/^($endre)(.*)$/;
1698 my ($left, $str) = ($1, $2);
1699 $str =~ m/^(.*?)($begre)$/;
1700 my ($mid, $right) = ($1, $2);
1701 if (length($mid) > 5) {
1702 $mid = " ... ";
1704 return "$left$mid$right";
1706 } else {
1707 $str =~ m/^($endre)(.*)$/;
1708 my $body = $1;
1709 my $tail = $2;
1710 if (length($tail) > 4) {
1711 $tail = "... ";
1713 return "$body$tail";
1717 # takes the same arguments as chop_str, but also wraps a <span> around the
1718 # result with a title attribute if it does get chopped. Additionally, the
1719 # string is HTML-escaped.
1720 sub chop_and_escape_str {
1721 my ($str) = @_;
1723 my $chopped = chop_str(@_);
1724 $str = to_utf8($str);
1725 if ($chopped eq $str) {
1726 return esc_html($chopped);
1727 } else {
1728 $str =~ s/[[:cntrl:]]/?/g;
1729 return $cgi->span({-title=>$str}, esc_html($chopped));
1733 # Highlight selected fragments of string, using given CSS class,
1734 # and escape HTML. It is assumed that fragments do not overlap.
1735 # Regions are passed as list of pairs (array references).
1737 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1738 # '<span class="mark">foo</span>bar'
1739 sub esc_html_hl_regions {
1740 my ($str, $css_class, @sel) = @_;
1741 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1742 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1743 return esc_html($str, %opts) unless @sel;
1745 my $out = '';
1746 my $pos = 0;
1748 for my $s (@sel) {
1749 my ($begin, $end) = @$s;
1751 # Don't create empty <span> elements.
1752 next if $end <= $begin;
1754 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1755 %opts);
1757 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1758 if ($begin - $pos > 0);
1759 $out .= $cgi->span({-class => $css_class}, $escaped);
1761 $pos = $end;
1763 $out .= esc_html(substr($str, $pos), %opts)
1764 if ($pos < length($str));
1766 return $out;
1769 # return positions of beginning and end of each match
1770 sub matchpos_list {
1771 my ($str, $regexp) = @_;
1772 return unless (defined $str && defined $regexp);
1774 my @matches;
1775 while ($str =~ /$regexp/g) {
1776 push @matches, [$-[0], $+[0]];
1778 return @matches;
1781 # highlight match (if any), and escape HTML
1782 sub esc_html_match_hl {
1783 my ($str, $regexp) = @_;
1784 return esc_html($str) unless defined $regexp;
1786 my @matches = matchpos_list($str, $regexp);
1787 return esc_html($str) unless @matches;
1789 return esc_html_hl_regions($str, 'match', @matches);
1793 # highlight match (if any) of shortened string, and escape HTML
1794 sub esc_html_match_hl_chopped {
1795 my ($str, $chopped, $regexp) = @_;
1796 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1798 my @matches = matchpos_list($str, $regexp);
1799 return esc_html($chopped) unless @matches;
1801 # filter matches so that we mark chopped string
1802 my $tail = "... "; # see chop_str
1803 unless ($chopped =~ s/\Q$tail\E$//) {
1804 $tail = '';
1806 my $chop_len = length($chopped);
1807 my $tail_len = length($tail);
1808 my @filtered;
1810 for my $m (@matches) {
1811 if ($m->[0] > $chop_len) {
1812 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1813 last;
1814 } elsif ($m->[1] > $chop_len) {
1815 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1816 last;
1818 push @filtered, $m;
1821 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1824 ## ----------------------------------------------------------------------
1825 ## functions returning short strings
1827 # CSS class for given age value (in seconds)
1828 sub age_class {
1829 my $age = shift;
1831 if (!defined $age) {
1832 return "noage";
1833 } elsif ($age < 60*60*2) {
1834 return "age0";
1835 } elsif ($age < 60*60*24*2) {
1836 return "age1";
1837 } else {
1838 return "age2";
1842 # convert age in seconds to "nn units ago" string
1843 sub age_string {
1844 my $age = shift;
1845 my $age_str;
1847 if ($age > 60*60*24*365*2) {
1848 $age_str = (int $age/60/60/24/365);
1849 $age_str .= " years ago";
1850 } elsif ($age > 60*60*24*(365/12)*2) {
1851 $age_str = int $age/60/60/24/(365/12);
1852 $age_str .= " months ago";
1853 } elsif ($age > 60*60*24*7*2) {
1854 $age_str = int $age/60/60/24/7;
1855 $age_str .= " weeks ago";
1856 } elsif ($age > 60*60*24*2) {
1857 $age_str = int $age/60/60/24;
1858 $age_str .= " days ago";
1859 } elsif ($age > 60*60*2) {
1860 $age_str = int $age/60/60;
1861 $age_str .= " hours ago";
1862 } elsif ($age > 60*2) {
1863 $age_str = int $age/60;
1864 $age_str .= " min ago";
1865 } elsif ($age > 2) {
1866 $age_str = int $age;
1867 $age_str .= " sec ago";
1868 } else {
1869 $age_str .= " right now";
1871 return $age_str;
1874 use constant {
1875 S_IFINVALID => 0030000,
1876 S_IFGITLINK => 0160000,
1879 # submodule/subproject, a commit object reference
1880 sub S_ISGITLINK {
1881 my $mode = shift;
1883 return (($mode & S_IFMT) == S_IFGITLINK)
1886 # convert file mode in octal to symbolic file mode string
1887 sub mode_str {
1888 my $mode = oct shift;
1890 if (S_ISGITLINK($mode)) {
1891 return 'm---------';
1892 } elsif (S_ISDIR($mode & S_IFMT)) {
1893 return 'drwxr-xr-x';
1894 } elsif (S_ISLNK($mode)) {
1895 return 'lrwxrwxrwx';
1896 } elsif (S_ISREG($mode)) {
1897 # git cares only about the executable bit
1898 if ($mode & S_IXUSR) {
1899 return '-rwxr-xr-x';
1900 } else {
1901 return '-rw-r--r--';
1903 } else {
1904 return '----------';
1908 # convert file mode in octal to file type string
1909 sub file_type {
1910 my $mode = shift;
1912 if ($mode !~ m/^[0-7]+$/) {
1913 return $mode;
1914 } else {
1915 $mode = oct $mode;
1918 if (S_ISGITLINK($mode)) {
1919 return "submodule";
1920 } elsif (S_ISDIR($mode & S_IFMT)) {
1921 return "directory";
1922 } elsif (S_ISLNK($mode)) {
1923 return "symlink";
1924 } elsif (S_ISREG($mode)) {
1925 return "file";
1926 } else {
1927 return "unknown";
1931 # convert file mode in octal to file type description string
1932 sub file_type_long {
1933 my $mode = shift;
1935 if ($mode !~ m/^[0-7]+$/) {
1936 return $mode;
1937 } else {
1938 $mode = oct $mode;
1941 if (S_ISGITLINK($mode)) {
1942 return "submodule";
1943 } elsif (S_ISDIR($mode & S_IFMT)) {
1944 return "directory";
1945 } elsif (S_ISLNK($mode)) {
1946 return "symlink";
1947 } elsif (S_ISREG($mode)) {
1948 if ($mode & S_IXUSR) {
1949 return "executable";
1950 } else {
1951 return "file";
1953 } else {
1954 return "unknown";
1959 ## ----------------------------------------------------------------------
1960 ## functions returning short HTML fragments, or transforming HTML fragments
1961 ## which don't belong to other sections
1963 # format line of commit message.
1964 sub format_log_line_html {
1965 my $line = shift;
1967 $line = esc_html($line, -nbsp=>1);
1968 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1969 $cgi->a({-href => href(action=>"object", hash=>$1),
1970 -class => "text"}, $1);
1971 }eg;
1973 return $line;
1976 # format marker of refs pointing to given object
1978 # the destination action is chosen based on object type and current context:
1979 # - for annotated tags, we choose the tag view unless it's the current view
1980 # already, in which case we go to shortlog view
1981 # - for other refs, we keep the current view if we're in history, shortlog or
1982 # log view, and select shortlog otherwise
1983 sub format_ref_marker {
1984 my ($refs, $id) = @_;
1985 my $markers = '';
1987 if (defined $refs->{$id}) {
1988 foreach my $ref (@{$refs->{$id}}) {
1989 # this code exploits the fact that non-lightweight tags are the
1990 # only indirect objects, and that they are the only objects for which
1991 # we want to use tag instead of shortlog as action
1992 my ($type, $name) = qw();
1993 my $indirect = ($ref =~ s/\^\{\}$//);
1994 # e.g. tags/v2.6.11 or heads/next
1995 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1996 $type = $1;
1997 $name = $2;
1998 } else {
1999 $type = "ref";
2000 $name = $ref;
2003 my $class = $type;
2004 $class .= " indirect" if $indirect;
2006 my $dest_action = "shortlog";
2008 if ($indirect) {
2009 $dest_action = "tag" unless $action eq "tag";
2010 } elsif ($action =~ /^(history|(short)?log)$/) {
2011 $dest_action = $action;
2014 my $dest = "";
2015 $dest .= "refs/" unless $ref =~ m!^refs/!;
2016 $dest .= $ref;
2018 my $link = $cgi->a({
2019 -href => href(
2020 action=>$dest_action,
2021 hash=>$dest
2022 )}, $name);
2024 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2025 $link . "</span>";
2029 if ($markers) {
2030 return ' <span class="refs">'. $markers . '</span>';
2031 } else {
2032 return "";
2036 # format, perhaps shortened and with markers, title line
2037 sub format_subject_html {
2038 my ($long, $short, $href, $extra) = @_;
2039 $extra = '' unless defined($extra);
2041 if (length($short) < length($long)) {
2042 $long =~ s/[[:cntrl:]]/?/g;
2043 return $cgi->a({-href => $href, -class => "list subject",
2044 -title => to_utf8($long)},
2045 esc_html($short)) . $extra;
2046 } else {
2047 return $cgi->a({-href => $href, -class => "list subject"},
2048 esc_html($long)) . $extra;
2052 # Rather than recomputing the url for an email multiple times, we cache it
2053 # after the first hit. This gives a visible benefit in views where the avatar
2054 # for the same email is used repeatedly (e.g. shortlog).
2055 # The cache is shared by all avatar engines (currently gravatar only), which
2056 # are free to use it as preferred. Since only one avatar engine is used for any
2057 # given page, there's no risk for cache conflicts.
2058 our %avatar_cache = ();
2060 # Compute the picon url for a given email, by using the picon search service over at
2061 # http://www.cs.indiana.edu/picons/search.html
2062 sub picon_url {
2063 my $email = lc shift;
2064 if (!$avatar_cache{$email}) {
2065 my ($user, $domain) = split('@', $email);
2066 $avatar_cache{$email} =
2067 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2068 "$domain/$user/" .
2069 "users+domains+unknown/up/single";
2071 return $avatar_cache{$email};
2074 # Compute the gravatar url for a given email, if it's not in the cache already.
2075 # Gravatar stores only the part of the URL before the size, since that's the
2076 # one computationally more expensive. This also allows reuse of the cache for
2077 # different sizes (for this particular engine).
2078 sub gravatar_url {
2079 my $email = lc shift;
2080 my $size = shift;
2081 $avatar_cache{$email} ||=
2082 "http://www.gravatar.com/avatar/" .
2083 Digest::MD5::md5_hex($email) . "?s=";
2084 return $avatar_cache{$email} . $size;
2087 # Insert an avatar for the given $email at the given $size if the feature
2088 # is enabled.
2089 sub git_get_avatar {
2090 my ($email, %opts) = @_;
2091 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2092 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2093 $opts{-size} ||= 'default';
2094 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2095 my $url = "";
2096 if ($git_avatar eq 'gravatar') {
2097 $url = gravatar_url($email, $size);
2098 } elsif ($git_avatar eq 'picon') {
2099 $url = picon_url($email);
2101 # Other providers can be added by extending the if chain, defining $url
2102 # as needed. If no variant puts something in $url, we assume avatars
2103 # are completely disabled/unavailable.
2104 if ($url) {
2105 return $pre_white .
2106 "<img width=\"$size\" " .
2107 "class=\"avatar\" " .
2108 "src=\"".esc_url($url)."\" " .
2109 "alt=\"\" " .
2110 "/>" . $post_white;
2111 } else {
2112 return "";
2116 sub format_search_author {
2117 my ($author, $searchtype, $displaytext) = @_;
2118 my $have_search = gitweb_check_feature('search');
2120 if ($have_search) {
2121 my $performed = "";
2122 if ($searchtype eq 'author') {
2123 $performed = "authored";
2124 } elsif ($searchtype eq 'committer') {
2125 $performed = "committed";
2128 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2129 searchtext=>$author,
2130 searchtype=>$searchtype), class=>"list",
2131 title=>"Search for commits $performed by $author"},
2132 $displaytext);
2134 } else {
2135 return $displaytext;
2139 # format the author name of the given commit with the given tag
2140 # the author name is chopped and escaped according to the other
2141 # optional parameters (see chop_str).
2142 sub format_author_html {
2143 my $tag = shift;
2144 my $co = shift;
2145 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2146 return "<$tag class=\"author\">" .
2147 format_search_author($co->{'author_name'}, "author",
2148 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2149 $author) .
2150 "</$tag>";
2153 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2154 sub format_git_diff_header_line {
2155 my $line = shift;
2156 my $diffinfo = shift;
2157 my ($from, $to) = @_;
2159 if ($diffinfo->{'nparents'}) {
2160 # combined diff
2161 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2162 if ($to->{'href'}) {
2163 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2164 esc_path($to->{'file'}));
2165 } else { # file was deleted (no href)
2166 $line .= esc_path($to->{'file'});
2168 } else {
2169 # "ordinary" diff
2170 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2171 if ($from->{'href'}) {
2172 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2173 'a/' . esc_path($from->{'file'}));
2174 } else { # file was added (no href)
2175 $line .= 'a/' . esc_path($from->{'file'});
2177 $line .= ' ';
2178 if ($to->{'href'}) {
2179 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2180 'b/' . esc_path($to->{'file'}));
2181 } else { # file was deleted
2182 $line .= 'b/' . esc_path($to->{'file'});
2186 return "<div class=\"diff header\">$line</div>\n";
2189 # format extended diff header line, before patch itself
2190 sub format_extended_diff_header_line {
2191 my $line = shift;
2192 my $diffinfo = shift;
2193 my ($from, $to) = @_;
2195 # match <path>
2196 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2197 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2198 esc_path($from->{'file'}));
2200 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2201 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2202 esc_path($to->{'file'}));
2204 # match single <mode>
2205 if ($line =~ m/\s(\d{6})$/) {
2206 $line .= '<span class="info"> (' .
2207 file_type_long($1) .
2208 ')</span>';
2210 # match <hash>
2211 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2212 # can match only for combined diff
2213 $line = 'index ';
2214 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2215 if ($from->{'href'}[$i]) {
2216 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2217 -class=>"hash"},
2218 substr($diffinfo->{'from_id'}[$i],0,7));
2219 } else {
2220 $line .= '0' x 7;
2222 # separator
2223 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2225 $line .= '..';
2226 if ($to->{'href'}) {
2227 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2228 substr($diffinfo->{'to_id'},0,7));
2229 } else {
2230 $line .= '0' x 7;
2233 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2234 # can match only for ordinary diff
2235 my ($from_link, $to_link);
2236 if ($from->{'href'}) {
2237 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2238 substr($diffinfo->{'from_id'},0,7));
2239 } else {
2240 $from_link = '0' x 7;
2242 if ($to->{'href'}) {
2243 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2244 substr($diffinfo->{'to_id'},0,7));
2245 } else {
2246 $to_link = '0' x 7;
2248 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2249 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2252 return $line . "<br/>\n";
2255 # format from-file/to-file diff header
2256 sub format_diff_from_to_header {
2257 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2258 my $line;
2259 my $result = '';
2261 $line = $from_line;
2262 #assert($line =~ m/^---/) if DEBUG;
2263 # no extra formatting for "^--- /dev/null"
2264 if (! $diffinfo->{'nparents'}) {
2265 # ordinary (single parent) diff
2266 if ($line =~ m!^--- "?a/!) {
2267 if ($from->{'href'}) {
2268 $line = '--- a/' .
2269 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2270 esc_path($from->{'file'}));
2271 } else {
2272 $line = '--- a/' .
2273 esc_path($from->{'file'});
2276 $result .= qq!<div class="diff from_file">$line</div>\n!;
2278 } else {
2279 # combined diff (merge commit)
2280 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2281 if ($from->{'href'}[$i]) {
2282 $line = '--- ' .
2283 $cgi->a({-href=>href(action=>"blobdiff",
2284 hash_parent=>$diffinfo->{'from_id'}[$i],
2285 hash_parent_base=>$parents[$i],
2286 file_parent=>$from->{'file'}[$i],
2287 hash=>$diffinfo->{'to_id'},
2288 hash_base=>$hash,
2289 file_name=>$to->{'file'}),
2290 -class=>"path",
2291 -title=>"diff" . ($i+1)},
2292 $i+1) .
2293 '/' .
2294 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2295 esc_path($from->{'file'}[$i]));
2296 } else {
2297 $line = '--- /dev/null';
2299 $result .= qq!<div class="diff from_file">$line</div>\n!;
2303 $line = $to_line;
2304 #assert($line =~ m/^\+\+\+/) if DEBUG;
2305 # no extra formatting for "^+++ /dev/null"
2306 if ($line =~ m!^\+\+\+ "?b/!) {
2307 if ($to->{'href'}) {
2308 $line = '+++ b/' .
2309 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2310 esc_path($to->{'file'}));
2311 } else {
2312 $line = '+++ b/' .
2313 esc_path($to->{'file'});
2316 $result .= qq!<div class="diff to_file">$line</div>\n!;
2318 return $result;
2321 # create note for patch simplified by combined diff
2322 sub format_diff_cc_simplified {
2323 my ($diffinfo, @parents) = @_;
2324 my $result = '';
2326 $result .= "<div class=\"diff header\">" .
2327 "diff --cc ";
2328 if (!is_deleted($diffinfo)) {
2329 $result .= $cgi->a({-href => href(action=>"blob",
2330 hash_base=>$hash,
2331 hash=>$diffinfo->{'to_id'},
2332 file_name=>$diffinfo->{'to_file'}),
2333 -class => "path"},
2334 esc_path($diffinfo->{'to_file'}));
2335 } else {
2336 $result .= esc_path($diffinfo->{'to_file'});
2338 $result .= "</div>\n" . # class="diff header"
2339 "<div class=\"diff nodifferences\">" .
2340 "Simple merge" .
2341 "</div>\n"; # class="diff nodifferences"
2343 return $result;
2346 sub diff_line_class {
2347 my ($line, $from, $to) = @_;
2349 # ordinary diff
2350 my $num_sign = 1;
2351 # combined diff
2352 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2353 $num_sign = scalar @{$from->{'href'}};
2356 my @diff_line_classifier = (
2357 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2358 { regexp => qr/^\\/, class => "incomplete" },
2359 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2360 # classifier for context must come before classifier add/rem,
2361 # or we would have to use more complicated regexp, for example
2362 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2363 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2364 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2366 for my $clsfy (@diff_line_classifier) {
2367 return $clsfy->{'class'}
2368 if ($line =~ $clsfy->{'regexp'});
2371 # fallback
2372 return "";
2375 # assumes that $from and $to are defined and correctly filled,
2376 # and that $line holds a line of chunk header for unified diff
2377 sub format_unidiff_chunk_header {
2378 my ($line, $from, $to) = @_;
2380 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2381 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2383 $from_lines = 0 unless defined $from_lines;
2384 $to_lines = 0 unless defined $to_lines;
2386 if ($from->{'href'}) {
2387 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2388 -class=>"list"}, $from_text);
2390 if ($to->{'href'}) {
2391 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2392 -class=>"list"}, $to_text);
2394 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2395 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2396 return $line;
2399 # assumes that $from and $to are defined and correctly filled,
2400 # and that $line holds a line of chunk header for combined diff
2401 sub format_cc_diff_chunk_header {
2402 my ($line, $from, $to) = @_;
2404 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2405 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2407 @from_text = split(' ', $ranges);
2408 for (my $i = 0; $i < @from_text; ++$i) {
2409 ($from_start[$i], $from_nlines[$i]) =
2410 (split(',', substr($from_text[$i], 1)), 0);
2413 $to_text = pop @from_text;
2414 $to_start = pop @from_start;
2415 $to_nlines = pop @from_nlines;
2417 $line = "<span class=\"chunk_info\">$prefix ";
2418 for (my $i = 0; $i < @from_text; ++$i) {
2419 if ($from->{'href'}[$i]) {
2420 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2421 -class=>"list"}, $from_text[$i]);
2422 } else {
2423 $line .= $from_text[$i];
2425 $line .= " ";
2427 if ($to->{'href'}) {
2428 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2429 -class=>"list"}, $to_text);
2430 } else {
2431 $line .= $to_text;
2433 $line .= " $prefix</span>" .
2434 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2435 return $line;
2438 # process patch (diff) line (not to be used for diff headers),
2439 # returning HTML-formatted (but not wrapped) line.
2440 # If the line is passed as a reference, it is treated as HTML and not
2441 # esc_html()'ed.
2442 sub format_diff_line {
2443 my ($line, $diff_class, $from, $to) = @_;
2445 if (ref($line)) {
2446 $line = $$line;
2447 } else {
2448 chomp $line;
2449 $line = untabify($line);
2451 if ($from && $to && $line =~ m/^\@{2} /) {
2452 $line = format_unidiff_chunk_header($line, $from, $to);
2453 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2454 $line = format_cc_diff_chunk_header($line, $from, $to);
2455 } else {
2456 $line = esc_html($line, -nbsp=>1);
2460 my $diff_classes = "diff";
2461 $diff_classes .= " $diff_class" if ($diff_class);
2462 $line = "<div class=\"$diff_classes\">$line</div>\n";
2464 return $line;
2467 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2468 # linked. Pass the hash of the tree/commit to snapshot.
2469 sub format_snapshot_links {
2470 my ($hash) = @_;
2471 my $num_fmts = @snapshot_fmts;
2472 if ($num_fmts > 1) {
2473 # A parenthesized list of links bearing format names.
2474 # e.g. "snapshot (_tar.gz_ _zip_)"
2475 return "snapshot (" . join(' ', map
2476 $cgi->a({
2477 -href => href(
2478 action=>"snapshot",
2479 hash=>$hash,
2480 snapshot_format=>$_
2482 }, $known_snapshot_formats{$_}{'display'})
2483 , @snapshot_fmts) . ")";
2484 } elsif ($num_fmts == 1) {
2485 # A single "snapshot" link whose tooltip bears the format name.
2486 # i.e. "_snapshot_"
2487 my ($fmt) = @snapshot_fmts;
2488 return
2489 $cgi->a({
2490 -href => href(
2491 action=>"snapshot",
2492 hash=>$hash,
2493 snapshot_format=>$fmt
2495 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2496 }, "snapshot");
2497 } else { # $num_fmts == 0
2498 return undef;
2502 ## ......................................................................
2503 ## functions returning values to be passed, perhaps after some
2504 ## transformation, to other functions; e.g. returning arguments to href()
2506 # returns hash to be passed to href to generate gitweb URL
2507 # in -title key it returns description of link
2508 sub get_feed_info {
2509 my $format = shift || 'Atom';
2510 my %res = (action => lc($format));
2512 # feed links are possible only for project views
2513 return unless (defined $project);
2514 # some views should link to OPML, or to generic project feed,
2515 # or don't have specific feed yet (so they should use generic)
2516 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2518 my $branch;
2519 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2520 # from tag links; this also makes possible to detect branch links
2521 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2522 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2523 $branch = $1;
2525 # find log type for feed description (title)
2526 my $type = 'log';
2527 if (defined $file_name) {
2528 $type = "history of $file_name";
2529 $type .= "/" if ($action eq 'tree');
2530 $type .= " on '$branch'" if (defined $branch);
2531 } else {
2532 $type = "log of $branch" if (defined $branch);
2535 $res{-title} = $type;
2536 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2537 $res{'file_name'} = $file_name;
2539 return %res;
2542 ## ----------------------------------------------------------------------
2543 ## git utility subroutines, invoking git commands
2545 # returns path to the core git executable and the --git-dir parameter as list
2546 sub git_cmd {
2547 $number_of_git_cmds++;
2548 return $GIT, '--git-dir='.$git_dir;
2551 # quote the given arguments for passing them to the shell
2552 # quote_command("command", "arg 1", "arg with ' and ! characters")
2553 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2554 # Try to avoid using this function wherever possible.
2555 sub quote_command {
2556 return join(' ',
2557 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2560 # get HEAD ref of given project as hash
2561 sub git_get_head_hash {
2562 return git_get_full_hash(shift, 'HEAD');
2565 sub git_get_full_hash {
2566 return git_get_hash(@_);
2569 sub git_get_short_hash {
2570 return git_get_hash(@_, '--short=7');
2573 sub git_get_hash {
2574 my ($project, $hash, @options) = @_;
2575 my $o_git_dir = $git_dir;
2576 my $retval = undef;
2577 $git_dir = "$projectroot/$project";
2578 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2579 '--verify', '-q', @options, $hash) {
2580 $retval = <$fd>;
2581 chomp $retval if defined $retval;
2582 close $fd;
2584 if (defined $o_git_dir) {
2585 $git_dir = $o_git_dir;
2587 return $retval;
2590 # get type of given object
2591 sub git_get_type {
2592 my $hash = shift;
2594 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2595 my $type = <$fd>;
2596 close $fd or return;
2597 chomp $type;
2598 return $type;
2601 # repository configuration
2602 our $config_file = '';
2603 our %config;
2605 # store multiple values for single key as anonymous array reference
2606 # single values stored directly in the hash, not as [ <value> ]
2607 sub hash_set_multi {
2608 my ($hash, $key, $value) = @_;
2610 if (!exists $hash->{$key}) {
2611 $hash->{$key} = $value;
2612 } elsif (!ref $hash->{$key}) {
2613 $hash->{$key} = [ $hash->{$key}, $value ];
2614 } else {
2615 push @{$hash->{$key}}, $value;
2619 # return hash of git project configuration
2620 # optionally limited to some section, e.g. 'gitweb'
2621 sub git_parse_project_config {
2622 my $section_regexp = shift;
2623 my %config;
2625 local $/ = "\0";
2627 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2628 or return;
2630 while (my $keyval = <$fh>) {
2631 chomp $keyval;
2632 my ($key, $value) = split(/\n/, $keyval, 2);
2634 hash_set_multi(\%config, $key, $value)
2635 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2637 close $fh;
2639 return %config;
2642 # convert config value to boolean: 'true' or 'false'
2643 # no value, number > 0, 'true' and 'yes' values are true
2644 # rest of values are treated as false (never as error)
2645 sub config_to_bool {
2646 my $val = shift;
2648 return 1 if !defined $val; # section.key
2650 # strip leading and trailing whitespace
2651 $val =~ s/^\s+//;
2652 $val =~ s/\s+$//;
2654 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2655 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2658 # convert config value to simple decimal number
2659 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2660 # to be multiplied by 1024, 1048576, or 1073741824
2661 sub config_to_int {
2662 my $val = shift;
2664 # strip leading and trailing whitespace
2665 $val =~ s/^\s+//;
2666 $val =~ s/\s+$//;
2668 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2669 $unit = lc($unit);
2670 # unknown unit is treated as 1
2671 return $num * ($unit eq 'g' ? 1073741824 :
2672 $unit eq 'm' ? 1048576 :
2673 $unit eq 'k' ? 1024 : 1);
2675 return $val;
2678 # convert config value to array reference, if needed
2679 sub config_to_multi {
2680 my $val = shift;
2682 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2685 sub git_get_project_config {
2686 my ($key, $type) = @_;
2688 return unless defined $git_dir;
2690 # key sanity check
2691 return unless ($key);
2692 # only subsection, if exists, is case sensitive,
2693 # and not lowercased by 'git config -z -l'
2694 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2695 $key = join(".", lc($hi), $mi, lc($lo));
2696 } else {
2697 $key = lc($key);
2699 $key =~ s/^gitweb\.//;
2700 return if ($key =~ m/\W/);
2702 # type sanity check
2703 if (defined $type) {
2704 $type =~ s/^--//;
2705 $type = undef
2706 unless ($type eq 'bool' || $type eq 'int');
2709 # get config
2710 if (!defined $config_file ||
2711 $config_file ne "$git_dir/config") {
2712 %config = git_parse_project_config('gitweb');
2713 $config_file = "$git_dir/config";
2716 # check if config variable (key) exists
2717 return unless exists $config{"gitweb.$key"};
2719 # ensure given type
2720 if (!defined $type) {
2721 return $config{"gitweb.$key"};
2722 } elsif ($type eq 'bool') {
2723 # backward compatibility: 'git config --bool' returns true/false
2724 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2725 } elsif ($type eq 'int') {
2726 return config_to_int($config{"gitweb.$key"});
2728 return $config{"gitweb.$key"};
2731 # get hash of given path at given ref
2732 sub git_get_hash_by_path {
2733 my $base = shift;
2734 my $path = shift || return undef;
2735 my $type = shift;
2737 $path =~ s,/+$,,;
2739 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2740 or die_error(500, "Open git-ls-tree failed");
2741 my $line = <$fd>;
2742 close $fd or return undef;
2744 if (!defined $line) {
2745 # there is no tree or hash given by $path at $base
2746 return undef;
2749 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2750 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2751 if (defined $type && $type ne $2) {
2752 # type doesn't match
2753 return undef;
2755 return $3;
2758 # get path of entry with given hash at given tree-ish (ref)
2759 # used to get 'from' filename for combined diff (merge commit) for renames
2760 sub git_get_path_by_hash {
2761 my $base = shift || return;
2762 my $hash = shift || return;
2764 local $/ = "\0";
2766 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2767 or return undef;
2768 while (my $line = <$fd>) {
2769 chomp $line;
2771 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2772 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2773 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2774 close $fd;
2775 return $1;
2778 close $fd;
2779 return undef;
2782 ## ......................................................................
2783 ## git utility functions, directly accessing git repository
2785 # get the value of config variable either from file named as the variable
2786 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2787 # configuration variable in the repository config file.
2788 sub git_get_file_or_project_config {
2789 my ($path, $name) = @_;
2791 $git_dir = "$projectroot/$path";
2792 open my $fd, '<', "$git_dir/$name"
2793 or return git_get_project_config($name);
2794 my $conf = <$fd>;
2795 close $fd;
2796 if (defined $conf) {
2797 chomp $conf;
2799 return $conf;
2802 sub git_get_project_description {
2803 my $path = shift;
2804 return git_get_file_or_project_config($path, 'description');
2807 sub git_get_project_category {
2808 my $path = shift;
2809 return git_get_file_or_project_config($path, 'category');
2813 # supported formats:
2814 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2815 # - if its contents is a number, use it as tag weight,
2816 # - otherwise add a tag with weight 1
2817 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2818 # the same value multiple times increases tag weight
2819 # * `gitweb.ctag' multi-valued repo config variable
2820 sub git_get_project_ctags {
2821 my $project = shift;
2822 my $ctags = {};
2824 $git_dir = "$projectroot/$project";
2825 if (opendir my $dh, "$git_dir/ctags") {
2826 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2827 foreach my $tagfile (@files) {
2828 open my $ct, '<', $tagfile
2829 or next;
2830 my $val = <$ct>;
2831 chomp $val if $val;
2832 close $ct;
2834 (my $ctag = $tagfile) =~ s#.*/##;
2835 if ($val =~ /^\d+$/) {
2836 $ctags->{$ctag} = $val;
2837 } else {
2838 $ctags->{$ctag} = 1;
2841 closedir $dh;
2843 } elsif (open my $fh, '<', "$git_dir/ctags") {
2844 while (my $line = <$fh>) {
2845 chomp $line;
2846 $ctags->{$line}++ if $line;
2848 close $fh;
2850 } else {
2851 my $taglist = config_to_multi(git_get_project_config('ctag'));
2852 foreach my $tag (@$taglist) {
2853 $ctags->{$tag}++;
2857 return $ctags;
2860 # return hash, where keys are content tags ('ctags'),
2861 # and values are sum of weights of given tag in every project
2862 sub git_gather_all_ctags {
2863 my $projects = shift;
2864 my $ctags = {};
2866 foreach my $p (@$projects) {
2867 foreach my $ct (keys %{$p->{'ctags'}}) {
2868 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2872 return $ctags;
2875 sub git_populate_project_tagcloud {
2876 my $ctags = shift;
2878 # First, merge different-cased tags; tags vote on casing
2879 my %ctags_lc;
2880 foreach (keys %$ctags) {
2881 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2882 if (not $ctags_lc{lc $_}->{topcount}
2883 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2884 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2885 $ctags_lc{lc $_}->{topname} = $_;
2889 my $cloud;
2890 my $matched = $input_params{'ctag'};
2891 if (eval { require HTML::TagCloud; 1; }) {
2892 $cloud = HTML::TagCloud->new;
2893 foreach my $ctag (sort keys %ctags_lc) {
2894 # Pad the title with spaces so that the cloud looks
2895 # less crammed.
2896 my $title = esc_html($ctags_lc{$ctag}->{topname});
2897 $title =~ s/ /&nbsp;/g;
2898 $title =~ s/^/&nbsp;/g;
2899 $title =~ s/$/&nbsp;/g;
2900 if (defined $matched && $matched eq $ctag) {
2901 $title = qq(<span class="match">$title</span>);
2903 $cloud->add($title, href(project=>undef, ctag=>$ctag),
2904 $ctags_lc{$ctag}->{count});
2906 } else {
2907 $cloud = {};
2908 foreach my $ctag (keys %ctags_lc) {
2909 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
2910 if (defined $matched && $matched eq $ctag) {
2911 $title = qq(<span class="match">$title</span>);
2913 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
2914 $cloud->{$ctag}{ctag} =
2915 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
2918 return $cloud;
2921 sub git_show_project_tagcloud {
2922 my ($cloud, $count) = @_;
2923 if (ref $cloud eq 'HTML::TagCloud') {
2924 return $cloud->html_and_css($count);
2925 } else {
2926 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
2927 return
2928 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
2929 join (', ', map {
2930 $cloud->{$_}->{'ctag'}
2931 } splice(@tags, 0, $count)) .
2932 '</div>';
2936 sub git_get_project_url_list {
2937 my $path = shift;
2939 $git_dir = "$projectroot/$path";
2940 open my $fd, '<', "$git_dir/cloneurl"
2941 or return wantarray ?
2942 @{ config_to_multi(git_get_project_config('url')) } :
2943 config_to_multi(git_get_project_config('url'));
2944 my @git_project_url_list = map { chomp; $_ } <$fd>;
2945 close $fd;
2947 return wantarray ? @git_project_url_list : \@git_project_url_list;
2950 sub git_get_projects_list {
2951 my $filter = shift || '';
2952 my $paranoid = shift;
2953 my @list;
2955 if (-d $projects_list) {
2956 # search in directory
2957 my $dir = $projects_list;
2958 # remove the trailing "/"
2959 $dir =~ s!/+$!!;
2960 my $pfxlen = length("$dir");
2961 my $pfxdepth = ($dir =~ tr!/!!);
2962 # when filtering, search only given subdirectory
2963 if ($filter && !$paranoid) {
2964 $dir .= "/$filter";
2965 $dir =~ s!/+$!!;
2968 File::Find::find({
2969 follow_fast => 1, # follow symbolic links
2970 follow_skip => 2, # ignore duplicates
2971 dangling_symlinks => 0, # ignore dangling symlinks, silently
2972 wanted => sub {
2973 # global variables
2974 our $project_maxdepth;
2975 our $projectroot;
2976 # skip project-list toplevel, if we get it.
2977 return if (m!^[/.]$!);
2978 # only directories can be git repositories
2979 return unless (-d $_);
2980 # don't traverse too deep (Find is super slow on os x)
2981 # $project_maxdepth excludes depth of $projectroot
2982 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2983 $File::Find::prune = 1;
2984 return;
2987 my $path = substr($File::Find::name, $pfxlen + 1);
2988 # paranoidly only filter here
2989 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
2990 next;
2992 # we check related file in $projectroot
2993 if (check_export_ok("$projectroot/$path")) {
2994 push @list, { path => $path };
2995 $File::Find::prune = 1;
2998 }, "$dir");
3000 } elsif (-f $projects_list) {
3001 # read from file(url-encoded):
3002 # 'git%2Fgit.git Linus+Torvalds'
3003 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3004 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3005 open my $fd, '<', $projects_list or return;
3006 PROJECT:
3007 while (my $line = <$fd>) {
3008 chomp $line;
3009 my ($path, $owner) = split ' ', $line;
3010 $path = unescape($path);
3011 $owner = unescape($owner);
3012 if (!defined $path) {
3013 next;
3015 # if $filter is rpovided, check if $path begins with $filter
3016 if ($filter && $path !~ m!^\Q$filter\E/!) {
3017 next;
3019 if (check_export_ok("$projectroot/$path")) {
3020 my $pr = {
3021 path => $path
3023 if ($owner) {
3024 $pr->{'owner'} = to_utf8($owner);
3026 push @list, $pr;
3029 close $fd;
3031 return @list;
3034 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3035 # as side effects it sets 'forks' field to list of forks for forked projects
3036 sub filter_forks_from_projects_list {
3037 my $projects = shift;
3039 my %trie; # prefix tree of directories (path components)
3040 # generate trie out of those directories that might contain forks
3041 foreach my $pr (@$projects) {
3042 my $path = $pr->{'path'};
3043 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3044 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3045 next unless ($path); # skip '.git' repository: tests, git-instaweb
3046 next unless (-d "$projectroot/$path"); # containing directory exists
3047 $pr->{'forks'} = []; # there can be 0 or more forks of project
3049 # add to trie
3050 my @dirs = split('/', $path);
3051 # walk the trie, until either runs out of components or out of trie
3052 my $ref = \%trie;
3053 while (scalar @dirs &&
3054 exists($ref->{$dirs[0]})) {
3055 $ref = $ref->{shift @dirs};
3057 # create rest of trie structure from rest of components
3058 foreach my $dir (@dirs) {
3059 $ref = $ref->{$dir} = {};
3061 # create end marker, store $pr as a data
3062 $ref->{''} = $pr if (!exists $ref->{''});
3065 # filter out forks, by finding shortest prefix match for paths
3066 my @filtered;
3067 PROJECT:
3068 foreach my $pr (@$projects) {
3069 # trie lookup
3070 my $ref = \%trie;
3071 DIR:
3072 foreach my $dir (split('/', $pr->{'path'})) {
3073 if (exists $ref->{''}) {
3074 # found [shortest] prefix, is a fork - skip it
3075 push @{$ref->{''}{'forks'}}, $pr;
3076 next PROJECT;
3078 if (!exists $ref->{$dir}) {
3079 # not in trie, cannot have prefix, not a fork
3080 push @filtered, $pr;
3081 next PROJECT;
3083 # If the dir is there, we just walk one step down the trie.
3084 $ref = $ref->{$dir};
3086 # we ran out of trie
3087 # (shouldn't happen: it's either no match, or end marker)
3088 push @filtered, $pr;
3091 return @filtered;
3094 # note: fill_project_list_info must be run first,
3095 # for 'descr_long' and 'ctags' to be filled
3096 sub search_projects_list {
3097 my ($projlist, %opts) = @_;
3098 my $tagfilter = $opts{'tagfilter'};
3099 my $search_re = $opts{'search_regexp'};
3101 return @$projlist
3102 unless ($tagfilter || $search_re);
3104 # searching projects require filling to be run before it;
3105 fill_project_list_info($projlist,
3106 $tagfilter ? 'ctags' : (),
3107 $search_re ? ('path', 'descr') : ());
3108 my @projects;
3109 PROJECT:
3110 foreach my $pr (@$projlist) {
3112 if ($tagfilter) {
3113 next unless ref($pr->{'ctags'}) eq 'HASH';
3114 next unless
3115 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3118 if ($search_re) {
3119 next unless
3120 $pr->{'path'} =~ /$search_re/ ||
3121 $pr->{'descr_long'} =~ /$search_re/;
3124 push @projects, $pr;
3127 return @projects;
3130 our $gitweb_project_owner = undef;
3131 sub git_get_project_list_from_file {
3133 return if (defined $gitweb_project_owner);
3135 $gitweb_project_owner = {};
3136 # read from file (url-encoded):
3137 # 'git%2Fgit.git Linus+Torvalds'
3138 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3139 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3140 if (-f $projects_list) {
3141 open(my $fd, '<', $projects_list);
3142 while (my $line = <$fd>) {
3143 chomp $line;
3144 my ($pr, $ow) = split ' ', $line;
3145 $pr = unescape($pr);
3146 $ow = unescape($ow);
3147 $gitweb_project_owner->{$pr} = to_utf8($ow);
3149 close $fd;
3153 sub git_get_project_owner {
3154 my $project = shift;
3155 my $owner;
3157 return undef unless $project;
3158 $git_dir = "$projectroot/$project";
3160 if (!defined $gitweb_project_owner) {
3161 git_get_project_list_from_file();
3164 if (exists $gitweb_project_owner->{$project}) {
3165 $owner = $gitweb_project_owner->{$project};
3167 if (!defined $owner){
3168 $owner = git_get_project_config('owner');
3170 if (!defined $owner) {
3171 $owner = get_file_owner("$git_dir");
3174 return $owner;
3177 sub git_get_last_activity {
3178 my ($path) = @_;
3179 my $fd;
3181 $git_dir = "$projectroot/$path";
3182 open($fd, "-|", git_cmd(), 'for-each-ref',
3183 '--format=%(committer)',
3184 '--sort=-committerdate',
3185 '--count=1',
3186 'refs/heads') or return;
3187 my $most_recent = <$fd>;
3188 close $fd or return;
3189 if (defined $most_recent &&
3190 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3191 my $timestamp = $1;
3192 my $age = time - $timestamp;
3193 return ($age, age_string($age));
3195 return (undef, undef);
3198 # Implementation note: when a single remote is wanted, we cannot use 'git
3199 # remote show -n' because that command always work (assuming it's a remote URL
3200 # if it's not defined), and we cannot use 'git remote show' because that would
3201 # try to make a network roundtrip. So the only way to find if that particular
3202 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3203 # and when we find what we want.
3204 sub git_get_remotes_list {
3205 my $wanted = shift;
3206 my %remotes = ();
3208 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3209 return unless $fd;
3210 while (my $remote = <$fd>) {
3211 chomp $remote;
3212 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3213 next if $wanted and not $remote eq $wanted;
3214 my ($url, $key) = ($1, $2);
3216 $remotes{$remote} ||= { 'heads' => () };
3217 $remotes{$remote}{$key} = $url;
3219 close $fd or return;
3220 return wantarray ? %remotes : \%remotes;
3223 # Takes a hash of remotes as first parameter and fills it by adding the
3224 # available remote heads for each of the indicated remotes.
3225 sub fill_remote_heads {
3226 my $remotes = shift;
3227 my @heads = map { "remotes/$_" } keys %$remotes;
3228 my @remoteheads = git_get_heads_list(undef, @heads);
3229 foreach my $remote (keys %$remotes) {
3230 $remotes->{$remote}{'heads'} = [ grep {
3231 $_->{'name'} =~ s!^$remote/!!
3232 } @remoteheads ];
3236 sub git_get_references {
3237 my $type = shift || "";
3238 my %refs;
3239 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3240 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3241 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3242 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3243 or return;
3245 while (my $line = <$fd>) {
3246 chomp $line;
3247 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3248 if (defined $refs{$1}) {
3249 push @{$refs{$1}}, $2;
3250 } else {
3251 $refs{$1} = [ $2 ];
3255 close $fd or return;
3256 return \%refs;
3259 sub git_get_rev_name_tags {
3260 my $hash = shift || return undef;
3262 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3263 or return;
3264 my $name_rev = <$fd>;
3265 close $fd;
3267 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3268 return $1;
3269 } else {
3270 # catches also '$hash undefined' output
3271 return undef;
3275 ## ----------------------------------------------------------------------
3276 ## parse to hash functions
3278 sub parse_date {
3279 my $epoch = shift;
3280 my $tz = shift || "-0000";
3282 my %date;
3283 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3284 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3285 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3286 $date{'hour'} = $hour;
3287 $date{'minute'} = $min;
3288 $date{'mday'} = $mday;
3289 $date{'day'} = $days[$wday];
3290 $date{'month'} = $months[$mon];
3291 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3292 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3293 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3294 $mday, $months[$mon], $hour ,$min;
3295 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3296 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3298 my ($tz_sign, $tz_hour, $tz_min) =
3299 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3300 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3301 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3302 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3303 $date{'hour_local'} = $hour;
3304 $date{'minute_local'} = $min;
3305 $date{'tz_local'} = $tz;
3306 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3307 1900+$year, $mon+1, $mday,
3308 $hour, $min, $sec, $tz);
3309 return %date;
3312 sub parse_tag {
3313 my $tag_id = shift;
3314 my %tag;
3315 my @comment;
3317 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3318 $tag{'id'} = $tag_id;
3319 while (my $line = <$fd>) {
3320 chomp $line;
3321 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3322 $tag{'object'} = $1;
3323 } elsif ($line =~ m/^type (.+)$/) {
3324 $tag{'type'} = $1;
3325 } elsif ($line =~ m/^tag (.+)$/) {
3326 $tag{'name'} = $1;
3327 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3328 $tag{'author'} = $1;
3329 $tag{'author_epoch'} = $2;
3330 $tag{'author_tz'} = $3;
3331 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3332 $tag{'author_name'} = $1;
3333 $tag{'author_email'} = $2;
3334 } else {
3335 $tag{'author_name'} = $tag{'author'};
3337 } elsif ($line =~ m/--BEGIN/) {
3338 push @comment, $line;
3339 last;
3340 } elsif ($line eq "") {
3341 last;
3344 push @comment, <$fd>;
3345 $tag{'comment'} = \@comment;
3346 close $fd or return;
3347 if (!defined $tag{'name'}) {
3348 return
3350 return %tag
3353 sub parse_commit_text {
3354 my ($commit_text, $withparents) = @_;
3355 my @commit_lines = split '\n', $commit_text;
3356 my %co;
3358 pop @commit_lines; # Remove '\0'
3360 if (! @commit_lines) {
3361 return;
3364 my $header = shift @commit_lines;
3365 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3366 return;
3368 ($co{'id'}, my @parents) = split ' ', $header;
3369 while (my $line = shift @commit_lines) {
3370 last if $line eq "\n";
3371 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3372 $co{'tree'} = $1;
3373 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3374 push @parents, $1;
3375 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3376 $co{'author'} = to_utf8($1);
3377 $co{'author_epoch'} = $2;
3378 $co{'author_tz'} = $3;
3379 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3380 $co{'author_name'} = $1;
3381 $co{'author_email'} = $2;
3382 } else {
3383 $co{'author_name'} = $co{'author'};
3385 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3386 $co{'committer'} = to_utf8($1);
3387 $co{'committer_epoch'} = $2;
3388 $co{'committer_tz'} = $3;
3389 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3390 $co{'committer_name'} = $1;
3391 $co{'committer_email'} = $2;
3392 } else {
3393 $co{'committer_name'} = $co{'committer'};
3397 if (!defined $co{'tree'}) {
3398 return;
3400 $co{'parents'} = \@parents;
3401 $co{'parent'} = $parents[0];
3403 foreach my $title (@commit_lines) {
3404 $title =~ s/^ //;
3405 if ($title ne "") {
3406 $co{'title'} = chop_str($title, 80, 5);
3407 # remove leading stuff of merges to make the interesting part visible
3408 if (length($title) > 50) {
3409 $title =~ s/^Automatic //;
3410 $title =~ s/^merge (of|with) /Merge ... /i;
3411 if (length($title) > 50) {
3412 $title =~ s/(http|rsync):\/\///;
3414 if (length($title) > 50) {
3415 $title =~ s/(master|www|rsync)\.//;
3417 if (length($title) > 50) {
3418 $title =~ s/kernel.org:?//;
3420 if (length($title) > 50) {
3421 $title =~ s/\/pub\/scm//;
3424 $co{'title_short'} = chop_str($title, 50, 5);
3425 last;
3428 if (! defined $co{'title'} || $co{'title'} eq "") {
3429 $co{'title'} = $co{'title_short'} = '(no commit message)';
3431 # remove added spaces
3432 foreach my $line (@commit_lines) {
3433 $line =~ s/^ //;
3435 $co{'comment'} = \@commit_lines;
3437 my $age = time - $co{'committer_epoch'};
3438 $co{'age'} = $age;
3439 $co{'age_string'} = age_string($age);
3440 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3441 if ($age > 60*60*24*7*2) {
3442 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3443 $co{'age_string_age'} = $co{'age_string'};
3444 } else {
3445 $co{'age_string_date'} = $co{'age_string'};
3446 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3448 return %co;
3451 sub parse_commit {
3452 my ($commit_id) = @_;
3453 my %co;
3455 local $/ = "\0";
3457 open my $fd, "-|", git_cmd(), "rev-list",
3458 "--parents",
3459 "--header",
3460 "--max-count=1",
3461 $commit_id,
3462 "--",
3463 or die_error(500, "Open git-rev-list failed");
3464 %co = parse_commit_text(<$fd>, 1);
3465 close $fd;
3467 return %co;
3470 sub parse_commits {
3471 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3472 my @cos;
3474 $maxcount ||= 1;
3475 $skip ||= 0;
3477 local $/ = "\0";
3479 open my $fd, "-|", git_cmd(), "rev-list",
3480 "--header",
3481 @args,
3482 ("--max-count=" . $maxcount),
3483 ("--skip=" . $skip),
3484 @extra_options,
3485 $commit_id,
3486 "--",
3487 ($filename ? ($filename) : ())
3488 or die_error(500, "Open git-rev-list failed");
3489 while (my $line = <$fd>) {
3490 my %co = parse_commit_text($line);
3491 push @cos, \%co;
3493 close $fd;
3495 return wantarray ? @cos : \@cos;
3498 # parse line of git-diff-tree "raw" output
3499 sub parse_difftree_raw_line {
3500 my $line = shift;
3501 my %res;
3503 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3504 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3505 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3506 $res{'from_mode'} = $1;
3507 $res{'to_mode'} = $2;
3508 $res{'from_id'} = $3;
3509 $res{'to_id'} = $4;
3510 $res{'status'} = $5;
3511 $res{'similarity'} = $6;
3512 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3513 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3514 } else {
3515 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3518 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3519 # combined diff (for merge commit)
3520 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3521 $res{'nparents'} = length($1);
3522 $res{'from_mode'} = [ split(' ', $2) ];
3523 $res{'to_mode'} = pop @{$res{'from_mode'}};
3524 $res{'from_id'} = [ split(' ', $3) ];
3525 $res{'to_id'} = pop @{$res{'from_id'}};
3526 $res{'status'} = [ split('', $4) ];
3527 $res{'to_file'} = unquote($5);
3529 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3530 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3531 $res{'commit'} = $1;
3534 return wantarray ? %res : \%res;
3537 # wrapper: return parsed line of git-diff-tree "raw" output
3538 # (the argument might be raw line, or parsed info)
3539 sub parsed_difftree_line {
3540 my $line_or_ref = shift;
3542 if (ref($line_or_ref) eq "HASH") {
3543 # pre-parsed (or generated by hand)
3544 return $line_or_ref;
3545 } else {
3546 return parse_difftree_raw_line($line_or_ref);
3550 # parse line of git-ls-tree output
3551 sub parse_ls_tree_line {
3552 my $line = shift;
3553 my %opts = @_;
3554 my %res;
3556 if ($opts{'-l'}) {
3557 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3558 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3560 $res{'mode'} = $1;
3561 $res{'type'} = $2;
3562 $res{'hash'} = $3;
3563 $res{'size'} = $4;
3564 if ($opts{'-z'}) {
3565 $res{'name'} = $5;
3566 } else {
3567 $res{'name'} = unquote($5);
3569 } else {
3570 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3571 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3573 $res{'mode'} = $1;
3574 $res{'type'} = $2;
3575 $res{'hash'} = $3;
3576 if ($opts{'-z'}) {
3577 $res{'name'} = $4;
3578 } else {
3579 $res{'name'} = unquote($4);
3583 return wantarray ? %res : \%res;
3586 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3587 sub parse_from_to_diffinfo {
3588 my ($diffinfo, $from, $to, @parents) = @_;
3590 if ($diffinfo->{'nparents'}) {
3591 # combined diff
3592 $from->{'file'} = [];
3593 $from->{'href'} = [];
3594 fill_from_file_info($diffinfo, @parents)
3595 unless exists $diffinfo->{'from_file'};
3596 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3597 $from->{'file'}[$i] =
3598 defined $diffinfo->{'from_file'}[$i] ?
3599 $diffinfo->{'from_file'}[$i] :
3600 $diffinfo->{'to_file'};
3601 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3602 $from->{'href'}[$i] = href(action=>"blob",
3603 hash_base=>$parents[$i],
3604 hash=>$diffinfo->{'from_id'}[$i],
3605 file_name=>$from->{'file'}[$i]);
3606 } else {
3607 $from->{'href'}[$i] = undef;
3610 } else {
3611 # ordinary (not combined) diff
3612 $from->{'file'} = $diffinfo->{'from_file'};
3613 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3614 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3615 hash=>$diffinfo->{'from_id'},
3616 file_name=>$from->{'file'});
3617 } else {
3618 delete $from->{'href'};
3622 $to->{'file'} = $diffinfo->{'to_file'};
3623 if (!is_deleted($diffinfo)) { # file exists in result
3624 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3625 hash=>$diffinfo->{'to_id'},
3626 file_name=>$to->{'file'});
3627 } else {
3628 delete $to->{'href'};
3632 ## ......................................................................
3633 ## parse to array of hashes functions
3635 sub git_get_heads_list {
3636 my ($limit, @classes) = @_;
3637 @classes = ('heads') unless @classes;
3638 my @patterns = map { "refs/$_" } @classes;
3639 my @headslist;
3641 open my $fd, '-|', git_cmd(), 'for-each-ref',
3642 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3643 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3644 @patterns
3645 or return;
3646 while (my $line = <$fd>) {
3647 my %ref_item;
3649 chomp $line;
3650 my ($refinfo, $committerinfo) = split(/\0/, $line);
3651 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3652 my ($committer, $epoch, $tz) =
3653 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3654 $ref_item{'fullname'} = $name;
3655 $name =~ s!^refs/(?:head|remote)s/!!;
3657 $ref_item{'name'} = $name;
3658 $ref_item{'id'} = $hash;
3659 $ref_item{'title'} = $title || '(no commit message)';
3660 $ref_item{'epoch'} = $epoch;
3661 if ($epoch) {
3662 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3663 } else {
3664 $ref_item{'age'} = "unknown";
3667 push @headslist, \%ref_item;
3669 close $fd;
3671 return wantarray ? @headslist : \@headslist;
3674 sub git_get_tags_list {
3675 my $limit = shift;
3676 my @tagslist;
3678 open my $fd, '-|', git_cmd(), 'for-each-ref',
3679 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3680 '--format=%(objectname) %(objecttype) %(refname) '.
3681 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3682 'refs/tags'
3683 or return;
3684 while (my $line = <$fd>) {
3685 my %ref_item;
3687 chomp $line;
3688 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3689 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3690 my ($creator, $epoch, $tz) =
3691 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3692 $ref_item{'fullname'} = $name;
3693 $name =~ s!^refs/tags/!!;
3695 $ref_item{'type'} = $type;
3696 $ref_item{'id'} = $id;
3697 $ref_item{'name'} = $name;
3698 if ($type eq "tag") {
3699 $ref_item{'subject'} = $title;
3700 $ref_item{'reftype'} = $reftype;
3701 $ref_item{'refid'} = $refid;
3702 } else {
3703 $ref_item{'reftype'} = $type;
3704 $ref_item{'refid'} = $id;
3707 if ($type eq "tag" || $type eq "commit") {
3708 $ref_item{'epoch'} = $epoch;
3709 if ($epoch) {
3710 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3711 } else {
3712 $ref_item{'age'} = "unknown";
3716 push @tagslist, \%ref_item;
3718 close $fd;
3720 return wantarray ? @tagslist : \@tagslist;
3723 ## ----------------------------------------------------------------------
3724 ## filesystem-related functions
3726 sub get_file_owner {
3727 my $path = shift;
3729 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3730 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3731 if (!defined $gcos) {
3732 return undef;
3734 my $owner = $gcos;
3735 $owner =~ s/[,;].*$//;
3736 return to_utf8($owner);
3739 # assume that file exists
3740 sub insert_file {
3741 my $filename = shift;
3743 open my $fd, '<', $filename;
3744 print map { to_utf8($_) } <$fd>;
3745 close $fd;
3748 ## ......................................................................
3749 ## mimetype related functions
3751 sub mimetype_guess_file {
3752 my $filename = shift;
3753 my $mimemap = shift;
3754 -r $mimemap or return undef;
3756 my %mimemap;
3757 open(my $mh, '<', $mimemap) or return undef;
3758 while (<$mh>) {
3759 next if m/^#/; # skip comments
3760 my ($mimetype, @exts) = split(/\s+/);
3761 foreach my $ext (@exts) {
3762 $mimemap{$ext} = $mimetype;
3765 close($mh);
3767 $filename =~ /\.([^.]*)$/;
3768 return $mimemap{$1};
3771 sub mimetype_guess {
3772 my $filename = shift;
3773 my $mime;
3774 $filename =~ /\./ or return undef;
3776 if ($mimetypes_file) {
3777 my $file = $mimetypes_file;
3778 if ($file !~ m!^/!) { # if it is relative path
3779 # it is relative to project
3780 $file = "$projectroot/$project/$file";
3782 $mime = mimetype_guess_file($filename, $file);
3784 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3785 return $mime;
3788 sub blob_mimetype {
3789 my $fd = shift;
3790 my $filename = shift;
3792 if ($filename) {
3793 my $mime = mimetype_guess($filename);
3794 $mime and return $mime;
3797 # just in case
3798 return $default_blob_plain_mimetype unless $fd;
3800 if (-T $fd) {
3801 return 'text/plain';
3802 } elsif (! $filename) {
3803 return 'application/octet-stream';
3804 } elsif ($filename =~ m/\.png$/i) {
3805 return 'image/png';
3806 } elsif ($filename =~ m/\.gif$/i) {
3807 return 'image/gif';
3808 } elsif ($filename =~ m/\.jpe?g$/i) {
3809 return 'image/jpeg';
3810 } else {
3811 return 'application/octet-stream';
3815 sub blob_contenttype {
3816 my ($fd, $file_name, $type) = @_;
3818 $type ||= blob_mimetype($fd, $file_name);
3819 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3820 $type .= "; charset=$default_text_plain_charset";
3823 return $type;
3826 # guess file syntax for syntax highlighting; return undef if no highlighting
3827 # the name of syntax can (in the future) depend on syntax highlighter used
3828 sub guess_file_syntax {
3829 my ($highlight, $mimetype, $file_name) = @_;
3830 return undef unless ($highlight && defined $file_name);
3831 my $basename = basename($file_name, '.in');
3832 return $highlight_basename{$basename}
3833 if exists $highlight_basename{$basename};
3835 $basename =~ /\.([^.]*)$/;
3836 my $ext = $1 or return undef;
3837 return $highlight_ext{$ext}
3838 if exists $highlight_ext{$ext};
3840 return undef;
3843 # run highlighter and return FD of its output,
3844 # or return original FD if no highlighting
3845 sub run_highlighter {
3846 my ($fd, $highlight, $syntax) = @_;
3847 return $fd unless ($highlight && defined $syntax);
3849 close $fd;
3850 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3851 quote_command($highlight_bin).
3852 " --replace-tabs=8 --fragment --syntax $syntax |"
3853 or die_error(500, "Couldn't open file or run syntax highlighter");
3854 return $fd;
3857 ## ======================================================================
3858 ## functions printing HTML: header, footer, error page
3860 sub get_page_title {
3861 my $title = to_utf8($site_name);
3863 unless (defined $project) {
3864 if (defined $project_filter) {
3865 $title .= " - projects in '" . esc_path($project_filter) . "'";
3867 return $title;
3869 $title .= " - " . to_utf8($project);
3871 return $title unless (defined $action);
3872 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3874 return $title unless (defined $file_name);
3875 $title .= " - " . esc_path($file_name);
3876 if ($action eq "tree" && $file_name !~ m|/$|) {
3877 $title .= "/";
3880 return $title;
3883 sub get_content_type_html {
3884 # require explicit support from the UA if we are to send the page as
3885 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3886 # we have to do this because MSIE sometimes globs '*/*', pretending to
3887 # support xhtml+xml but choking when it gets what it asked for.
3888 if (defined $cgi->http('HTTP_ACCEPT') &&
3889 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3890 $cgi->Accept('application/xhtml+xml') != 0) {
3891 return 'application/xhtml+xml';
3892 } else {
3893 return 'text/html';
3897 sub print_feed_meta {
3898 if (defined $project) {
3899 my %href_params = get_feed_info();
3900 if (!exists $href_params{'-title'}) {
3901 $href_params{'-title'} = 'log';
3904 foreach my $format (qw(RSS Atom)) {
3905 my $type = lc($format);
3906 my %link_attr = (
3907 '-rel' => 'alternate',
3908 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
3909 '-type' => "application/$type+xml"
3912 $href_params{'extra_options'} = undef;
3913 $href_params{'action'} = $type;
3914 $link_attr{'-href'} = href(%href_params);
3915 print "<link ".
3916 "rel=\"$link_attr{'-rel'}\" ".
3917 "title=\"$link_attr{'-title'}\" ".
3918 "href=\"$link_attr{'-href'}\" ".
3919 "type=\"$link_attr{'-type'}\" ".
3920 "/>\n";
3922 $href_params{'extra_options'} = '--no-merges';
3923 $link_attr{'-href'} = href(%href_params);
3924 $link_attr{'-title'} .= ' (no merges)';
3925 print "<link ".
3926 "rel=\"$link_attr{'-rel'}\" ".
3927 "title=\"$link_attr{'-title'}\" ".
3928 "href=\"$link_attr{'-href'}\" ".
3929 "type=\"$link_attr{'-type'}\" ".
3930 "/>\n";
3933 } else {
3934 printf('<link rel="alternate" title="%s projects list" '.
3935 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3936 esc_attr($site_name), href(project=>undef, action=>"project_index"));
3937 printf('<link rel="alternate" title="%s projects feeds" '.
3938 'href="%s" type="text/x-opml" />'."\n",
3939 esc_attr($site_name), href(project=>undef, action=>"opml"));
3943 sub print_header_links {
3944 my $status = shift;
3946 # print out each stylesheet that exist, providing backwards capability
3947 # for those people who defined $stylesheet in a config file
3948 if (defined $stylesheet) {
3949 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3950 } else {
3951 foreach my $stylesheet (@stylesheets) {
3952 next unless $stylesheet;
3953 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3956 print_feed_meta()
3957 if ($status eq '200 OK');
3958 if (defined $favicon) {
3959 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
3963 sub print_nav_breadcrumbs_path {
3964 my $dirprefix = undef;
3965 while (my $part = shift) {
3966 $dirprefix .= "/" if defined $dirprefix;
3967 $dirprefix .= $part;
3968 print $cgi->a({-href => href(project => undef,
3969 project_filter => $dirprefix,
3970 action => "project_list")},
3971 esc_html($part)) . " / ";
3975 sub print_nav_breadcrumbs {
3976 my %opts = @_;
3978 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3979 if (defined $project) {
3980 my @dirname = split '/', $project;
3981 my $projectbasename = pop @dirname;
3982 print_nav_breadcrumbs_path(@dirname);
3983 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
3984 if (defined $action) {
3985 my $action_print = $action ;
3986 if (defined $opts{-action_extra}) {
3987 $action_print = $cgi->a({-href => href(action=>$action)},
3988 $action);
3990 print " / $action_print";
3992 if (defined $opts{-action_extra}) {
3993 print " / $opts{-action_extra}";
3995 print "\n";
3996 } elsif (defined $project_filter) {
3997 print_nav_breadcrumbs_path(split '/', $project_filter);
4001 sub print_search_form {
4002 if (!defined $searchtext) {
4003 $searchtext = "";
4005 my $search_hash;
4006 if (defined $hash_base) {
4007 $search_hash = $hash_base;
4008 } elsif (defined $hash) {
4009 $search_hash = $hash;
4010 } else {
4011 $search_hash = "HEAD";
4013 my $action = $my_uri;
4014 my $use_pathinfo = gitweb_check_feature('pathinfo');
4015 if ($use_pathinfo) {
4016 $action .= "/".esc_url($project);
4018 print $cgi->startform(-method => "get", -action => $action) .
4019 "<div class=\"search\">\n" .
4020 (!$use_pathinfo &&
4021 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4022 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4023 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4024 $cgi->popup_menu(-name => 'st', -default => 'commit',
4025 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4026 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
4027 " search:\n",
4028 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4029 "<span title=\"Extended regular expression\">" .
4030 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4031 -checked => $search_use_regexp) .
4032 "</span>" .
4033 "</div>" .
4034 $cgi->end_form() . "\n";
4037 sub git_header_html {
4038 my $status = shift || "200 OK";
4039 my $expires = shift;
4040 my %opts = @_;
4042 my $title = get_page_title();
4043 my $content_type = get_content_type_html();
4044 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4045 -status=> $status, -expires => $expires)
4046 unless ($opts{'-no_http_header'});
4047 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4048 print <<EOF;
4049 <?xml version="1.0" encoding="utf-8"?>
4050 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4051 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4052 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4053 <!-- git core binaries version $git_version -->
4054 <head>
4055 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4056 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4057 <meta name="robots" content="index, nofollow"/>
4058 <title>$title</title>
4060 # the stylesheet, favicon etc urls won't work correctly with path_info
4061 # unless we set the appropriate base URL
4062 if ($ENV{'PATH_INFO'}) {
4063 print "<base href=\"".esc_url($base_url)."\" />\n";
4065 print_header_links($status);
4067 if (defined $site_html_head_string) {
4068 print to_utf8($site_html_head_string);
4071 print "</head>\n" .
4072 "<body>\n";
4074 if (defined $site_header && -f $site_header) {
4075 insert_file($site_header);
4078 print "<div class=\"page_header\">\n";
4079 if (defined $logo) {
4080 print $cgi->a({-href => esc_url($logo_url),
4081 -title => $logo_label},
4082 $cgi->img({-src => esc_url($logo),
4083 -width => 72, -height => 27,
4084 -alt => "git",
4085 -class => "logo"}));
4087 print_nav_breadcrumbs(%opts);
4088 print "</div>\n";
4090 my $have_search = gitweb_check_feature('search');
4091 if (defined $project && $have_search) {
4092 print_search_form();
4096 sub git_footer_html {
4097 my $feed_class = 'rss_logo';
4099 print "<div class=\"page_footer\">\n";
4100 if (defined $project) {
4101 my $descr = git_get_project_description($project);
4102 if (defined $descr) {
4103 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4106 my %href_params = get_feed_info();
4107 if (!%href_params) {
4108 $feed_class .= ' generic';
4110 $href_params{'-title'} ||= 'log';
4112 foreach my $format (qw(RSS Atom)) {
4113 $href_params{'action'} = lc($format);
4114 print $cgi->a({-href => href(%href_params),
4115 -title => "$href_params{'-title'} $format feed",
4116 -class => $feed_class}, $format)."\n";
4119 } else {
4120 print $cgi->a({-href => href(project=>undef, action=>"opml",
4121 project_filter => $project_filter),
4122 -class => $feed_class}, "OPML") . " ";
4123 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4124 project_filter => $project_filter),
4125 -class => $feed_class}, "TXT") . "\n";
4127 print "</div>\n"; # class="page_footer"
4129 if (defined $t0 && gitweb_check_feature('timed')) {
4130 print "<div id=\"generating_info\">\n";
4131 print 'This page took '.
4132 '<span id="generating_time" class="time_span">'.
4133 tv_interval($t0, [ gettimeofday() ]).
4134 ' seconds </span>'.
4135 ' and '.
4136 '<span id="generating_cmd">'.
4137 $number_of_git_cmds.
4138 '</span> git commands '.
4139 " to generate.\n";
4140 print "</div>\n"; # class="page_footer"
4143 if (defined $site_footer && -f $site_footer) {
4144 insert_file($site_footer);
4147 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4148 if (defined $action &&
4149 $action eq 'blame_incremental') {
4150 print qq!<script type="text/javascript">\n!.
4151 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4152 qq! "!. href() .qq!");\n!.
4153 qq!</script>\n!;
4154 } else {
4155 my ($jstimezone, $tz_cookie, $datetime_class) =
4156 gitweb_get_feature('javascript-timezone');
4158 print qq!<script type="text/javascript">\n!.
4159 qq!window.onload = function () {\n!;
4160 if (gitweb_check_feature('javascript-actions')) {
4161 print qq! fixLinks();\n!;
4163 if ($jstimezone && $tz_cookie && $datetime_class) {
4164 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4165 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4167 print qq!};\n!.
4168 qq!</script>\n!;
4171 print "</body>\n" .
4172 "</html>";
4175 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4176 # Example: die_error(404, 'Hash not found')
4177 # By convention, use the following status codes (as defined in RFC 2616):
4178 # 400: Invalid or missing CGI parameters, or
4179 # requested object exists but has wrong type.
4180 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4181 # this server or project.
4182 # 404: Requested object/revision/project doesn't exist.
4183 # 500: The server isn't configured properly, or
4184 # an internal error occurred (e.g. failed assertions caused by bugs), or
4185 # an unknown error occurred (e.g. the git binary died unexpectedly).
4186 # 503: The server is currently unavailable (because it is overloaded,
4187 # or down for maintenance). Generally, this is a temporary state.
4188 sub die_error {
4189 my $status = shift || 500;
4190 my $error = esc_html(shift) || "Internal Server Error";
4191 my $extra = shift;
4192 my %opts = @_;
4194 my %http_responses = (
4195 400 => '400 Bad Request',
4196 403 => '403 Forbidden',
4197 404 => '404 Not Found',
4198 500 => '500 Internal Server Error',
4199 503 => '503 Service Unavailable',
4201 git_header_html($http_responses{$status}, undef, %opts);
4202 print <<EOF;
4203 <div class="page_body">
4204 <br /><br />
4205 $status - $error
4206 <br />
4208 if (defined $extra) {
4209 print "<hr />\n" .
4210 "$extra\n";
4212 print "</div>\n";
4214 git_footer_html();
4215 goto DONE_GITWEB
4216 unless ($opts{'-error_handler'});
4219 ## ----------------------------------------------------------------------
4220 ## functions printing or outputting HTML: navigation
4222 sub git_print_page_nav {
4223 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4224 $extra = '' if !defined $extra; # pager or formats
4226 my @navs = qw(summary shortlog log commit commitdiff tree);
4227 if ($suppress) {
4228 @navs = grep { $_ ne $suppress } @navs;
4231 my %arg = map { $_ => {action=>$_} } @navs;
4232 if (defined $head) {
4233 for (qw(commit commitdiff)) {
4234 $arg{$_}{'hash'} = $head;
4236 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4237 for (qw(shortlog log)) {
4238 $arg{$_}{'hash'} = $head;
4243 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4244 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4246 my @actions = gitweb_get_feature('actions');
4247 my %repl = (
4248 '%' => '%',
4249 'n' => $project, # project name
4250 'f' => $git_dir, # project path within filesystem
4251 'h' => $treehead || '', # current hash ('h' parameter)
4252 'b' => $treebase || '', # hash base ('hb' parameter)
4254 while (@actions) {
4255 my ($label, $link, $pos) = splice(@actions,0,3);
4256 # insert
4257 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4258 # munch munch
4259 $link =~ s/%([%nfhb])/$repl{$1}/g;
4260 $arg{$label}{'_href'} = $link;
4263 print "<div class=\"page_nav\">\n" .
4264 (join " | ",
4265 map { $_ eq $current ?
4266 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4267 } @navs);
4268 print "<br/>\n$extra<br/>\n" .
4269 "</div>\n";
4272 # returns a submenu for the nagivation of the refs views (tags, heads,
4273 # remotes) with the current view disabled and the remotes view only
4274 # available if the feature is enabled
4275 sub format_ref_views {
4276 my ($current) = @_;
4277 my @ref_views = qw{tags heads};
4278 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4279 return join " | ", map {
4280 $_ eq $current ? $_ :
4281 $cgi->a({-href => href(action=>$_)}, $_)
4282 } @ref_views
4285 sub format_paging_nav {
4286 my ($action, $page, $has_next_link) = @_;
4287 my $paging_nav;
4290 if ($page > 0) {
4291 $paging_nav .=
4292 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4293 " &sdot; " .
4294 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4295 -accesskey => "p", -title => "Alt-p"}, "prev");
4296 } else {
4297 $paging_nav .= "first &sdot; prev";
4300 if ($has_next_link) {
4301 $paging_nav .= " &sdot; " .
4302 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4303 -accesskey => "n", -title => "Alt-n"}, "next");
4304 } else {
4305 $paging_nav .= " &sdot; next";
4308 return $paging_nav;
4311 ## ......................................................................
4312 ## functions printing or outputting HTML: div
4314 sub git_print_header_div {
4315 my ($action, $title, $hash, $hash_base) = @_;
4316 my %args = ();
4318 $args{'action'} = $action;
4319 $args{'hash'} = $hash if $hash;
4320 $args{'hash_base'} = $hash_base if $hash_base;
4322 print "<div class=\"header\">\n" .
4323 $cgi->a({-href => href(%args), -class => "title"},
4324 $title ? $title : $action) .
4325 "\n</div>\n";
4328 sub format_repo_url {
4329 my ($name, $url) = @_;
4330 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4333 # Group output by placing it in a DIV element and adding a header.
4334 # Options for start_div() can be provided by passing a hash reference as the
4335 # first parameter to the function.
4336 # Options to git_print_header_div() can be provided by passing an array
4337 # reference. This must follow the options to start_div if they are present.
4338 # The content can be a scalar, which is output as-is, a scalar reference, which
4339 # is output after html escaping, an IO handle passed either as *handle or
4340 # *handle{IO}, or a function reference. In the latter case all following
4341 # parameters will be taken as argument to the content function call.
4342 sub git_print_section {
4343 my ($div_args, $header_args, $content);
4344 my $arg = shift;
4345 if (ref($arg) eq 'HASH') {
4346 $div_args = $arg;
4347 $arg = shift;
4349 if (ref($arg) eq 'ARRAY') {
4350 $header_args = $arg;
4351 $arg = shift;
4353 $content = $arg;
4355 print $cgi->start_div($div_args);
4356 git_print_header_div(@$header_args);
4358 if (ref($content) eq 'CODE') {
4359 $content->(@_);
4360 } elsif (ref($content) eq 'SCALAR') {
4361 print esc_html($$content);
4362 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4363 print <$content>;
4364 } elsif (!ref($content) && defined($content)) {
4365 print $content;
4368 print $cgi->end_div;
4371 sub format_timestamp_html {
4372 my $date = shift;
4373 my $strtime = $date->{'rfc2822'};
4375 my (undef, undef, $datetime_class) =
4376 gitweb_get_feature('javascript-timezone');
4377 if ($datetime_class) {
4378 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4381 my $localtime_format = '(%02d:%02d %s)';
4382 if ($date->{'hour_local'} < 6) {
4383 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4385 $strtime .= ' ' .
4386 sprintf($localtime_format,
4387 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4389 return $strtime;
4392 # Outputs the author name and date in long form
4393 sub git_print_authorship {
4394 my $co = shift;
4395 my %opts = @_;
4396 my $tag = $opts{-tag} || 'div';
4397 my $author = $co->{'author_name'};
4399 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4400 print "<$tag class=\"author_date\">" .
4401 format_search_author($author, "author", esc_html($author)) .
4402 " [".format_timestamp_html(\%ad)."]".
4403 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4404 "</$tag>\n";
4407 # Outputs table rows containing the full author or committer information,
4408 # in the format expected for 'commit' view (& similar).
4409 # Parameters are a commit hash reference, followed by the list of people
4410 # to output information for. If the list is empty it defaults to both
4411 # author and committer.
4412 sub git_print_authorship_rows {
4413 my $co = shift;
4414 # too bad we can't use @people = @_ || ('author', 'committer')
4415 my @people = @_;
4416 @people = ('author', 'committer') unless @people;
4417 foreach my $who (@people) {
4418 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4419 print "<tr><td>$who</td><td>" .
4420 format_search_author($co->{"${who}_name"}, $who,
4421 esc_html($co->{"${who}_name"})) . " " .
4422 format_search_author($co->{"${who}_email"}, $who,
4423 esc_html("<" . $co->{"${who}_email"} . ">")) .
4424 "</td><td rowspan=\"2\">" .
4425 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4426 "</td></tr>\n" .
4427 "<tr>" .
4428 "<td></td><td>" .
4429 format_timestamp_html(\%wd) .
4430 "</td>" .
4431 "</tr>\n";
4435 sub git_print_page_path {
4436 my $name = shift;
4437 my $type = shift;
4438 my $hb = shift;
4441 print "<div class=\"page_path\">";
4442 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4443 -title => 'tree root'}, to_utf8("[$project]"));
4444 print " / ";
4445 if (defined $name) {
4446 my @dirname = split '/', $name;
4447 my $basename = pop @dirname;
4448 my $fullname = '';
4450 foreach my $dir (@dirname) {
4451 $fullname .= ($fullname ? '/' : '') . $dir;
4452 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4453 hash_base=>$hb),
4454 -title => $fullname}, esc_path($dir));
4455 print " / ";
4457 if (defined $type && $type eq 'blob') {
4458 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4459 hash_base=>$hb),
4460 -title => $name}, esc_path($basename));
4461 if (gitweb_check_feature('highlight')) {
4462 print '&nbsp;&nbsp;&nbsp;&nbsp;
4463 <a id="lineNoToggle" href="#" onclick="toggleLineNumbers();"></a>
4464 <script>
4465 function toggleLineNumbers() {
4466 e = document.getElementById("lineNoStyle");
4467 e2 = document.getElementById("lineNoToggle");
4468 if (e2.innerHTML == "[Hide line numbers]") {
4469 e.innerHTML = ".linenr { display:none; }";
4470 e2.innerHTML = "[Show line numbers]";
4472 else {
4473 e.innerHTML = "";
4474 e2.innerHTML = "[Hide line numbers]";
4477 var style = document.createElement("style");
4478 style.setAttribute("id", "lineNoStyle");
4479 document.getElementsByTagName("head")[0].appendChild(style);
4480 toggleLineNumbers();
4481 </script>
4484 } elsif (defined $type && $type eq 'tree') {
4485 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4486 hash_base=>$hb),
4487 -title => $name}, esc_path($basename));
4488 print " / ";
4489 } else {
4490 print esc_path($basename);
4493 print "<br/></div>\n";
4496 sub git_print_log {
4497 my $log = shift;
4498 my %opts = @_;
4500 if ($opts{'-remove_title'}) {
4501 # remove title, i.e. first line of log
4502 shift @$log;
4504 # remove leading empty lines
4505 while (defined $log->[0] && $log->[0] eq "") {
4506 shift @$log;
4509 # print log
4510 my $signoff = 0;
4511 my $empty = 0;
4512 foreach my $line (@$log) {
4513 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4514 $signoff = 1;
4515 $empty = 0;
4516 if (! $opts{'-remove_signoff'}) {
4517 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4518 next;
4519 } else {
4520 # remove signoff lines
4521 next;
4523 } else {
4524 $signoff = 0;
4527 # print only one empty line
4528 # do not print empty line after signoff
4529 if ($line eq "") {
4530 next if ($empty || $signoff);
4531 $empty = 1;
4532 } else {
4533 $empty = 0;
4536 print format_log_line_html($line) . "<br/>\n";
4539 if ($opts{'-final_empty_line'}) {
4540 # end with single empty line
4541 print "<br/>\n" unless $empty;
4545 # return link target (what link points to)
4546 sub git_get_link_target {
4547 my $hash = shift;
4548 my $link_target;
4550 # read link
4551 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4552 or return;
4554 local $/ = undef;
4555 $link_target = <$fd>;
4557 close $fd
4558 or return;
4560 return $link_target;
4563 # given link target, and the directory (basedir) the link is in,
4564 # return target of link relative to top directory (top tree);
4565 # return undef if it is not possible (including absolute links).
4566 sub normalize_link_target {
4567 my ($link_target, $basedir) = @_;
4569 # absolute symlinks (beginning with '/') cannot be normalized
4570 return if (substr($link_target, 0, 1) eq '/');
4572 # normalize link target to path from top (root) tree (dir)
4573 my $path;
4574 if ($basedir) {
4575 $path = $basedir . '/' . $link_target;
4576 } else {
4577 # we are in top (root) tree (dir)
4578 $path = $link_target;
4581 # remove //, /./, and /../
4582 my @path_parts;
4583 foreach my $part (split('/', $path)) {
4584 # discard '.' and ''
4585 next if (!$part || $part eq '.');
4586 # handle '..'
4587 if ($part eq '..') {
4588 if (@path_parts) {
4589 pop @path_parts;
4590 } else {
4591 # link leads outside repository (outside top dir)
4592 return;
4594 } else {
4595 push @path_parts, $part;
4598 $path = join('/', @path_parts);
4600 return $path;
4603 # print tree entry (row of git_tree), but without encompassing <tr> element
4604 sub git_print_tree_entry {
4605 my ($t, $basedir, $hash_base, $have_blame) = @_;
4607 my %base_key = ();
4608 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4610 # The format of a table row is: mode list link. Where mode is
4611 # the mode of the entry, list is the name of the entry, an href,
4612 # and link is the action links of the entry.
4614 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4615 if (exists $t->{'size'}) {
4616 print "<td class=\"size\">$t->{'size'}</td>\n";
4618 if ($t->{'type'} eq "blob") {
4619 print "<td class=\"list\">" .
4620 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4621 file_name=>"$basedir$t->{'name'}", %base_key),
4622 -class => "list"}, esc_path($t->{'name'}));
4623 if (S_ISLNK(oct $t->{'mode'})) {
4624 my $link_target = git_get_link_target($t->{'hash'});
4625 if ($link_target) {
4626 my $norm_target = normalize_link_target($link_target, $basedir);
4627 if (defined $norm_target) {
4628 print " -> " .
4629 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4630 file_name=>$norm_target),
4631 -title => $norm_target}, esc_path($link_target));
4632 } else {
4633 print " -> " . esc_path($link_target);
4637 print "</td>\n";
4638 print "<td class=\"link\">";
4639 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4640 file_name=>"$basedir$t->{'name'}", %base_key)},
4641 "blob");
4642 if ($have_blame) {
4643 print " | " .
4644 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4645 file_name=>"$basedir$t->{'name'}", %base_key)},
4646 "blame");
4648 if (defined $hash_base) {
4649 print " | " .
4650 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4651 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4652 "history");
4654 print " | " .
4655 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4656 file_name=>"$basedir$t->{'name'}")},
4657 "raw");
4658 print "</td>\n";
4660 } elsif ($t->{'type'} eq "tree") {
4661 print "<td class=\"list\">";
4662 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4663 file_name=>"$basedir$t->{'name'}",
4664 %base_key)},
4665 esc_path($t->{'name'}));
4666 print "</td>\n";
4667 print "<td class=\"link\">";
4668 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4669 file_name=>"$basedir$t->{'name'}",
4670 %base_key)},
4671 "tree");
4672 if (defined $hash_base) {
4673 print " | " .
4674 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4675 file_name=>"$basedir$t->{'name'}")},
4676 "history");
4678 print "</td>\n";
4679 } else {
4680 # unknown object: we can only present history for it
4681 # (this includes 'commit' object, i.e. submodule support)
4682 print "<td class=\"list\">" .
4683 esc_path($t->{'name'}) .
4684 "</td>\n";
4685 print "<td class=\"link\">";
4686 if (defined $hash_base) {
4687 print $cgi->a({-href => href(action=>"history",
4688 hash_base=>$hash_base,
4689 file_name=>"$basedir$t->{'name'}")},
4690 "history");
4692 print "</td>\n";
4696 ## ......................................................................
4697 ## functions printing large fragments of HTML
4699 # get pre-image filenames for merge (combined) diff
4700 sub fill_from_file_info {
4701 my ($diff, @parents) = @_;
4703 $diff->{'from_file'} = [ ];
4704 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4705 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4706 if ($diff->{'status'}[$i] eq 'R' ||
4707 $diff->{'status'}[$i] eq 'C') {
4708 $diff->{'from_file'}[$i] =
4709 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4713 return $diff;
4716 # is current raw difftree line of file deletion
4717 sub is_deleted {
4718 my $diffinfo = shift;
4720 return $diffinfo->{'to_id'} eq ('0' x 40);
4723 # does patch correspond to [previous] difftree raw line
4724 # $diffinfo - hashref of parsed raw diff format
4725 # $patchinfo - hashref of parsed patch diff format
4726 # (the same keys as in $diffinfo)
4727 sub is_patch_split {
4728 my ($diffinfo, $patchinfo) = @_;
4730 return defined $diffinfo && defined $patchinfo
4731 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4735 sub git_difftree_body {
4736 my ($difftree, $hash, @parents) = @_;
4737 my ($parent) = $parents[0];
4738 my $have_blame = gitweb_check_feature('blame');
4739 print "<div class=\"list_head\">\n";
4740 if ($#{$difftree} > 10) {
4741 print(($#{$difftree} + 1) . " files changed:\n");
4743 print "</div>\n";
4745 print "<table class=\"" .
4746 (@parents > 1 ? "combined " : "") .
4747 "diff_tree\">\n";
4749 # header only for combined diff in 'commitdiff' view
4750 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4751 if ($has_header) {
4752 # table header
4753 print "<thead><tr>\n" .
4754 "<th></th><th></th>\n"; # filename, patchN link
4755 for (my $i = 0; $i < @parents; $i++) {
4756 my $par = $parents[$i];
4757 print "<th>" .
4758 $cgi->a({-href => href(action=>"commitdiff",
4759 hash=>$hash, hash_parent=>$par),
4760 -title => 'commitdiff to parent number ' .
4761 ($i+1) . ': ' . substr($par,0,7)},
4762 $i+1) .
4763 "&nbsp;</th>\n";
4765 print "</tr></thead>\n<tbody>\n";
4768 my $alternate = 1;
4769 my $patchno = 0;
4770 foreach my $line (@{$difftree}) {
4771 my $diff = parsed_difftree_line($line);
4773 if ($alternate) {
4774 print "<tr class=\"dark\">\n";
4775 } else {
4776 print "<tr class=\"light\">\n";
4778 $alternate ^= 1;
4780 if (exists $diff->{'nparents'}) { # combined diff
4782 fill_from_file_info($diff, @parents)
4783 unless exists $diff->{'from_file'};
4785 if (!is_deleted($diff)) {
4786 # file exists in the result (child) commit
4787 print "<td>" .
4788 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4789 file_name=>$diff->{'to_file'},
4790 hash_base=>$hash),
4791 -class => "list"}, esc_path($diff->{'to_file'})) .
4792 "</td>\n";
4793 } else {
4794 print "<td>" .
4795 esc_path($diff->{'to_file'}) .
4796 "</td>\n";
4799 if ($action eq 'commitdiff') {
4800 # link to patch
4801 $patchno++;
4802 print "<td class=\"link\">" .
4803 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4804 "patch") .
4805 " | " .
4806 "</td>\n";
4809 my $has_history = 0;
4810 my $not_deleted = 0;
4811 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4812 my $hash_parent = $parents[$i];
4813 my $from_hash = $diff->{'from_id'}[$i];
4814 my $from_path = $diff->{'from_file'}[$i];
4815 my $status = $diff->{'status'}[$i];
4817 $has_history ||= ($status ne 'A');
4818 $not_deleted ||= ($status ne 'D');
4820 if ($status eq 'A') {
4821 print "<td class=\"link\" align=\"right\"> | </td>\n";
4822 } elsif ($status eq 'D') {
4823 print "<td class=\"link\">" .
4824 $cgi->a({-href => href(action=>"blob",
4825 hash_base=>$hash,
4826 hash=>$from_hash,
4827 file_name=>$from_path)},
4828 "blob" . ($i+1)) .
4829 " | </td>\n";
4830 } else {
4831 if ($diff->{'to_id'} eq $from_hash) {
4832 print "<td class=\"link nochange\">";
4833 } else {
4834 print "<td class=\"link\">";
4836 print $cgi->a({-href => href(action=>"blobdiff",
4837 hash=>$diff->{'to_id'},
4838 hash_parent=>$from_hash,
4839 hash_base=>$hash,
4840 hash_parent_base=>$hash_parent,
4841 file_name=>$diff->{'to_file'},
4842 file_parent=>$from_path)},
4843 "diff" . ($i+1)) .
4844 " | </td>\n";
4848 print "<td class=\"link\">";
4849 if ($not_deleted) {
4850 print $cgi->a({-href => href(action=>"blob",
4851 hash=>$diff->{'to_id'},
4852 file_name=>$diff->{'to_file'},
4853 hash_base=>$hash)},
4854 "blob");
4855 print " | " if ($has_history);
4857 if ($has_history) {
4858 print $cgi->a({-href => href(action=>"history",
4859 file_name=>$diff->{'to_file'},
4860 hash_base=>$hash)},
4861 "history");
4863 print "</td>\n";
4865 print "</tr>\n";
4866 next; # instead of 'else' clause, to avoid extra indent
4868 # else ordinary diff
4870 my ($to_mode_oct, $to_mode_str, $to_file_type);
4871 my ($from_mode_oct, $from_mode_str, $from_file_type);
4872 if ($diff->{'to_mode'} ne ('0' x 6)) {
4873 $to_mode_oct = oct $diff->{'to_mode'};
4874 if (S_ISREG($to_mode_oct)) { # only for regular file
4875 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4877 $to_file_type = file_type($diff->{'to_mode'});
4879 if ($diff->{'from_mode'} ne ('0' x 6)) {
4880 $from_mode_oct = oct $diff->{'from_mode'};
4881 if (S_ISREG($from_mode_oct)) { # only for regular file
4882 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4884 $from_file_type = file_type($diff->{'from_mode'});
4887 if ($diff->{'status'} eq "A") { # created
4888 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4889 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4890 $mode_chng .= "]</span>";
4891 print "<td>";
4892 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4893 hash_base=>$hash, file_name=>$diff->{'file'}),
4894 -class => "list"}, esc_path($diff->{'file'}));
4895 print "</td>\n";
4896 print "<td>$mode_chng</td>\n";
4897 print "<td class=\"link\">";
4898 if ($action eq 'commitdiff') {
4899 # link to patch
4900 $patchno++;
4901 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4902 "patch") .
4903 " | ";
4905 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4906 hash_base=>$hash, file_name=>$diff->{'file'})},
4907 "blob");
4908 print "</td>\n";
4910 } elsif ($diff->{'status'} eq "D") { # deleted
4911 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4912 print "<td>";
4913 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4914 hash_base=>$parent, file_name=>$diff->{'file'}),
4915 -class => "list"}, esc_path($diff->{'file'}));
4916 print "</td>\n";
4917 print "<td>$mode_chng</td>\n";
4918 print "<td class=\"link\">";
4919 if ($action eq 'commitdiff') {
4920 # link to patch
4921 $patchno++;
4922 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4923 "patch") .
4924 " | ";
4926 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4927 hash_base=>$parent, file_name=>$diff->{'file'})},
4928 "blob") . " | ";
4929 if ($have_blame) {
4930 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4931 file_name=>$diff->{'file'})},
4932 "blame") . " | ";
4934 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4935 file_name=>$diff->{'file'})},
4936 "history");
4937 print "</td>\n";
4939 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4940 my $mode_chnge = "";
4941 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4942 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4943 if ($from_file_type ne $to_file_type) {
4944 $mode_chnge .= " from $from_file_type to $to_file_type";
4946 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4947 if ($from_mode_str && $to_mode_str) {
4948 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4949 } elsif ($to_mode_str) {
4950 $mode_chnge .= " mode: $to_mode_str";
4953 $mode_chnge .= "]</span>\n";
4955 print "<td>";
4956 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4957 hash_base=>$hash, file_name=>$diff->{'file'}),
4958 -class => "list"}, esc_path($diff->{'file'}));
4959 print "</td>\n";
4960 print "<td>$mode_chnge</td>\n";
4961 print "<td class=\"link\">";
4962 if ($action eq 'commitdiff') {
4963 # link to patch
4964 $patchno++;
4965 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4966 "patch") .
4967 " | ";
4968 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4969 # "commit" view and modified file (not onlu mode changed)
4970 print $cgi->a({-href => href(action=>"blobdiff",
4971 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4972 hash_base=>$hash, hash_parent_base=>$parent,
4973 file_name=>$diff->{'file'})},
4974 "diff") .
4975 " | ";
4977 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4978 hash_base=>$hash, file_name=>$diff->{'file'})},
4979 "blob") . " | ";
4980 if ($have_blame) {
4981 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4982 file_name=>$diff->{'file'})},
4983 "blame") . " | ";
4985 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4986 file_name=>$diff->{'file'})},
4987 "history");
4988 print "</td>\n";
4990 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4991 my %status_name = ('R' => 'moved', 'C' => 'copied');
4992 my $nstatus = $status_name{$diff->{'status'}};
4993 my $mode_chng = "";
4994 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4995 # mode also for directories, so we cannot use $to_mode_str
4996 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4998 print "<td>" .
4999 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5000 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5001 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5002 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5003 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5004 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5005 -class => "list"}, esc_path($diff->{'from_file'})) .
5006 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5007 "<td class=\"link\">";
5008 if ($action eq 'commitdiff') {
5009 # link to patch
5010 $patchno++;
5011 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5012 "patch") .
5013 " | ";
5014 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5015 # "commit" view and modified file (not only pure rename or copy)
5016 print $cgi->a({-href => href(action=>"blobdiff",
5017 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5018 hash_base=>$hash, hash_parent_base=>$parent,
5019 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5020 "diff") .
5021 " | ";
5023 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5024 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5025 "blob") . " | ";
5026 if ($have_blame) {
5027 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5028 file_name=>$diff->{'to_file'})},
5029 "blame") . " | ";
5031 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5032 file_name=>$diff->{'to_file'})},
5033 "history");
5034 print "</td>\n";
5036 } # we should not encounter Unmerged (U) or Unknown (X) status
5037 print "</tr>\n";
5039 print "</tbody>" if $has_header;
5040 print "</table>\n";
5043 # Print context lines and then rem/add lines in a side-by-side manner.
5044 sub print_sidebyside_diff_lines {
5045 my ($ctx, $rem, $add) = @_;
5047 # print context block before add/rem block
5048 if (@$ctx) {
5049 print join '',
5050 '<div class="chunk_block ctx">',
5051 '<div class="old">',
5052 @$ctx,
5053 '</div>',
5054 '<div class="new">',
5055 @$ctx,
5056 '</div>',
5057 '</div>';
5060 if (!@$add) {
5061 # pure removal
5062 print join '',
5063 '<div class="chunk_block rem">',
5064 '<div class="old">',
5065 @$rem,
5066 '</div>',
5067 '</div>';
5068 } elsif (!@$rem) {
5069 # pure addition
5070 print join '',
5071 '<div class="chunk_block add">',
5072 '<div class="new">',
5073 @$add,
5074 '</div>',
5075 '</div>';
5076 } else {
5077 print join '',
5078 '<div class="chunk_block chg">',
5079 '<div class="old">',
5080 @$rem,
5081 '</div>',
5082 '<div class="new">',
5083 @$add,
5084 '</div>',
5085 '</div>';
5089 # Print context lines and then rem/add lines in inline manner.
5090 sub print_inline_diff_lines {
5091 my ($ctx, $rem, $add) = @_;
5093 print @$ctx, @$rem, @$add;
5096 # Format removed and added line, mark changed part and HTML-format them.
5097 # Implementation is based on contrib/diff-highlight
5098 sub format_rem_add_lines_pair {
5099 my ($rem, $add, $num_parents) = @_;
5101 # We need to untabify lines before split()'ing them;
5102 # otherwise offsets would be invalid.
5103 chomp $rem;
5104 chomp $add;
5105 $rem = untabify($rem);
5106 $add = untabify($add);
5108 my @rem = split(//, $rem);
5109 my @add = split(//, $add);
5110 my ($esc_rem, $esc_add);
5111 # Ignore leading +/- characters for each parent.
5112 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5113 my ($prefix_has_nonspace, $suffix_has_nonspace);
5115 my $shorter = (@rem < @add) ? @rem : @add;
5116 while ($prefix_len < $shorter) {
5117 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5119 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5120 $prefix_len++;
5123 while ($prefix_len + $suffix_len < $shorter) {
5124 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5126 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5127 $suffix_len++;
5130 # Mark lines that are different from each other, but have some common
5131 # part that isn't whitespace. If lines are completely different, don't
5132 # mark them because that would make output unreadable, especially if
5133 # diff consists of multiple lines.
5134 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5135 $esc_rem = esc_html_hl_regions($rem, 'marked',
5136 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5137 $esc_add = esc_html_hl_regions($add, 'marked',
5138 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5139 } else {
5140 $esc_rem = esc_html($rem, -nbsp=>1);
5141 $esc_add = esc_html($add, -nbsp=>1);
5144 return format_diff_line(\$esc_rem, 'rem'),
5145 format_diff_line(\$esc_add, 'add');
5148 # HTML-format diff context, removed and added lines.
5149 sub format_ctx_rem_add_lines {
5150 my ($ctx, $rem, $add, $num_parents) = @_;
5151 my (@new_ctx, @new_rem, @new_add);
5152 my $can_highlight = 0;
5153 my $is_combined = ($num_parents > 1);
5155 # Highlight if every removed line has a corresponding added line.
5156 if (@$add > 0 && @$add == @$rem) {
5157 $can_highlight = 1;
5159 # Highlight lines in combined diff only if the chunk contains
5160 # diff between the same version, e.g.
5162 # - a
5163 # - b
5164 # + c
5165 # + d
5167 # Otherwise the highlightling would be confusing.
5168 if ($is_combined) {
5169 for (my $i = 0; $i < @$add; $i++) {
5170 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5171 my $prefix_add = substr($add->[$i], 0, $num_parents);
5173 $prefix_rem =~ s/-/+/g;
5175 if ($prefix_rem ne $prefix_add) {
5176 $can_highlight = 0;
5177 last;
5183 if ($can_highlight) {
5184 for (my $i = 0; $i < @$add; $i++) {
5185 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5186 $rem->[$i], $add->[$i], $num_parents);
5187 push @new_rem, $line_rem;
5188 push @new_add, $line_add;
5190 } else {
5191 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5192 @new_add = map { format_diff_line($_, 'add') } @$add;
5195 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5197 return (\@new_ctx, \@new_rem, \@new_add);
5200 # Print context lines and then rem/add lines.
5201 sub print_diff_lines {
5202 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5203 my $is_combined = $num_parents > 1;
5205 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5206 $num_parents);
5208 if ($diff_style eq 'sidebyside' && !$is_combined) {
5209 print_sidebyside_diff_lines($ctx, $rem, $add);
5210 } else {
5211 # default 'inline' style and unknown styles
5212 print_inline_diff_lines($ctx, $rem, $add);
5216 sub print_diff_chunk {
5217 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5218 my (@ctx, @rem, @add);
5220 # The class of the previous line.
5221 my $prev_class = '';
5223 return unless @chunk;
5225 # incomplete last line might be among removed or added lines,
5226 # or both, or among context lines: find which
5227 for (my $i = 1; $i < @chunk; $i++) {
5228 if ($chunk[$i][0] eq 'incomplete') {
5229 $chunk[$i][0] = $chunk[$i-1][0];
5233 # guardian
5234 push @chunk, ["", ""];
5236 foreach my $line_info (@chunk) {
5237 my ($class, $line) = @$line_info;
5239 # print chunk headers
5240 if ($class && $class eq 'chunk_header') {
5241 print format_diff_line($line, $class, $from, $to);
5242 next;
5245 ## print from accumulator when have some add/rem lines or end
5246 # of chunk (flush context lines), or when have add and rem
5247 # lines and new block is reached (otherwise add/rem lines could
5248 # be reordered)
5249 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5250 (@rem && @add && $class ne $prev_class)) {
5251 print_diff_lines(\@ctx, \@rem, \@add,
5252 $diff_style, $num_parents);
5253 @ctx = @rem = @add = ();
5256 ## adding lines to accumulator
5257 # guardian value
5258 last unless $line;
5259 # rem, add or change
5260 if ($class eq 'rem') {
5261 push @rem, $line;
5262 } elsif ($class eq 'add') {
5263 push @add, $line;
5265 # context line
5266 if ($class eq 'ctx') {
5267 push @ctx, $line;
5270 $prev_class = $class;
5274 sub git_patchset_body {
5275 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5276 my ($hash_parent) = $hash_parents[0];
5278 my $is_combined = (@hash_parents > 1);
5279 my $patch_idx = 0;
5280 my $patch_number = 0;
5281 my $patch_line;
5282 my $diffinfo;
5283 my $to_name;
5284 my (%from, %to);
5285 my @chunk; # for side-by-side diff
5287 print "<div class=\"patchset\">\n";
5289 # skip to first patch
5290 while ($patch_line = <$fd>) {
5291 chomp $patch_line;
5293 last if ($patch_line =~ m/^diff /);
5296 PATCH:
5297 while ($patch_line) {
5299 # parse "git diff" header line
5300 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5301 # $1 is from_name, which we do not use
5302 $to_name = unquote($2);
5303 $to_name =~ s!^b/!!;
5304 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5305 # $1 is 'cc' or 'combined', which we do not use
5306 $to_name = unquote($2);
5307 } else {
5308 $to_name = undef;
5311 # check if current patch belong to current raw line
5312 # and parse raw git-diff line if needed
5313 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5314 # this is continuation of a split patch
5315 print "<div class=\"patch cont\">\n";
5316 } else {
5317 # advance raw git-diff output if needed
5318 $patch_idx++ if defined $diffinfo;
5320 # read and prepare patch information
5321 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5323 # compact combined diff output can have some patches skipped
5324 # find which patch (using pathname of result) we are at now;
5325 if ($is_combined) {
5326 while ($to_name ne $diffinfo->{'to_file'}) {
5327 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5328 format_diff_cc_simplified($diffinfo, @hash_parents) .
5329 "</div>\n"; # class="patch"
5331 $patch_idx++;
5332 $patch_number++;
5334 last if $patch_idx > $#$difftree;
5335 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5339 # modifies %from, %to hashes
5340 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5342 # this is first patch for raw difftree line with $patch_idx index
5343 # we index @$difftree array from 0, but number patches from 1
5344 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5347 # git diff header
5348 #assert($patch_line =~ m/^diff /) if DEBUG;
5349 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5350 $patch_number++;
5351 # print "git diff" header
5352 print format_git_diff_header_line($patch_line, $diffinfo,
5353 \%from, \%to);
5355 # print extended diff header
5356 print "<div class=\"diff extended_header\">\n";
5357 EXTENDED_HEADER:
5358 while ($patch_line = <$fd>) {
5359 chomp $patch_line;
5361 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5363 print format_extended_diff_header_line($patch_line, $diffinfo,
5364 \%from, \%to);
5366 print "</div>\n"; # class="diff extended_header"
5368 # from-file/to-file diff header
5369 if (! $patch_line) {
5370 print "</div>\n"; # class="patch"
5371 last PATCH;
5373 next PATCH if ($patch_line =~ m/^diff /);
5374 #assert($patch_line =~ m/^---/) if DEBUG;
5376 my $last_patch_line = $patch_line;
5377 $patch_line = <$fd>;
5378 chomp $patch_line;
5379 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5381 print format_diff_from_to_header($last_patch_line, $patch_line,
5382 $diffinfo, \%from, \%to,
5383 @hash_parents);
5385 # the patch itself
5386 LINE:
5387 while ($patch_line = <$fd>) {
5388 chomp $patch_line;
5390 next PATCH if ($patch_line =~ m/^diff /);
5392 my $class = diff_line_class($patch_line, \%from, \%to);
5394 if ($class eq 'chunk_header') {
5395 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5396 @chunk = ();
5399 push @chunk, [ $class, $patch_line ];
5402 } continue {
5403 if (@chunk) {
5404 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5405 @chunk = ();
5407 print "</div>\n"; # class="patch"
5410 # for compact combined (--cc) format, with chunk and patch simplification
5411 # the patchset might be empty, but there might be unprocessed raw lines
5412 for (++$patch_idx if $patch_number > 0;
5413 $patch_idx < @$difftree;
5414 ++$patch_idx) {
5415 # read and prepare patch information
5416 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5418 # generate anchor for "patch" links in difftree / whatchanged part
5419 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5420 format_diff_cc_simplified($diffinfo, @hash_parents) .
5421 "</div>\n"; # class="patch"
5423 $patch_number++;
5426 if ($patch_number == 0) {
5427 if (@hash_parents > 1) {
5428 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5429 } else {
5430 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5434 print "</div>\n"; # class="patchset"
5437 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5439 sub git_project_search_form {
5440 my ($searchtext, $search_use_regexp) = @_;
5442 my $limit = '';
5443 if ($project_filter) {
5444 $limit = " in '$project_filter/'";
5447 print "<div class=\"projsearch\">\n";
5448 print $cgi->startform(-method => 'get', -action => $my_uri) .
5449 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5450 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5451 if (defined $project_filter);
5452 print $cgi->textfield(-name => 's', -value => $searchtext,
5453 -title => "Search project by name and description$limit",
5454 -size => 60) . "\n" .
5455 "<span title=\"Extended regular expression\">" .
5456 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5457 -checked => $search_use_regexp) .
5458 "</span>\n" .
5459 $cgi->submit(-name => 'btnS', -value => 'Search') .
5460 $cgi->end_form() . "\n" .
5461 $cgi->a({-href => href(project => undef, searchtext => undef,
5462 project_filter => $project_filter)},
5463 esc_html("List all projects$limit")) . "<br />\n";
5464 print "</div>\n";
5467 # entry for given @keys needs filling if at least one of keys in list
5468 # is not present in %$project_info
5469 sub project_info_needs_filling {
5470 my ($project_info, @keys) = @_;
5472 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5473 foreach my $key (@keys) {
5474 if (!exists $project_info->{$key}) {
5475 return 1;
5478 return;
5481 # fills project list info (age, description, owner, category, forks, etc.)
5482 # for each project in the list, removing invalid projects from
5483 # returned list, or fill only specified info.
5485 # Invalid projects are removed from the returned list if and only if you
5486 # ask 'age' or 'age_string' to be filled, because they are the only fields
5487 # that run unconditionally git command that requires repository, and
5488 # therefore do always check if project repository is invalid.
5490 # USAGE:
5491 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5492 # ensures that 'descr_long' and 'ctags' fields are filled
5493 # * @project_list = fill_project_list_info(\@project_list)
5494 # ensures that all fields are filled (and invalid projects removed)
5496 # NOTE: modifies $projlist, but does not remove entries from it
5497 sub fill_project_list_info {
5498 my ($projlist, @wanted_keys) = @_;
5499 my @projects;
5500 my $filter_set = sub { return @_; };
5501 if (@wanted_keys) {
5502 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5503 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5506 my $show_ctags = gitweb_check_feature('ctags');
5507 PROJECT:
5508 foreach my $pr (@$projlist) {
5509 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5510 my (@activity) = git_get_last_activity($pr->{'path'});
5511 unless (@activity) {
5512 next PROJECT;
5514 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5516 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5517 my $descr = git_get_project_description($pr->{'path'}) || "";
5518 $descr = to_utf8($descr);
5519 $pr->{'descr_long'} = $descr;
5520 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5522 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5523 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5525 if ($show_ctags &&
5526 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5527 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5529 if ($projects_list_group_categories &&
5530 project_info_needs_filling($pr, $filter_set->('category'))) {
5531 my $cat = git_get_project_category($pr->{'path'}) ||
5532 $project_list_default_category;
5533 $pr->{'category'} = to_utf8($cat);
5536 push @projects, $pr;
5539 return @projects;
5542 sub sort_projects_list {
5543 my ($projlist, $order) = @_;
5544 my @projects;
5546 my %order_info = (
5547 project => { key => 'path', type => 'str' },
5548 descr => { key => 'descr_long', type => 'str' },
5549 owner => { key => 'owner', type => 'str' },
5550 age => { key => 'age', type => 'num' }
5552 my $oi = $order_info{$order};
5553 return @$projlist unless defined $oi;
5554 if ($oi->{'type'} eq 'str') {
5555 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @$projlist;
5556 } else {
5557 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @$projlist;
5560 return @projects;
5563 # returns a hash of categories, containing the list of project
5564 # belonging to each category
5565 sub build_projlist_by_category {
5566 my ($projlist, $from, $to) = @_;
5567 my %categories;
5569 $from = 0 unless defined $from;
5570 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5572 for (my $i = $from; $i <= $to; $i++) {
5573 my $pr = $projlist->[$i];
5574 push @{$categories{ $pr->{'category'} }}, $pr;
5577 return wantarray ? %categories : \%categories;
5580 # print 'sort by' <th> element, generating 'sort by $name' replay link
5581 # if that order is not selected
5582 sub print_sort_th {
5583 print format_sort_th(@_);
5586 sub format_sort_th {
5587 my ($name, $order, $header) = @_;
5588 my $sort_th = "";
5589 $header ||= ucfirst($name);
5591 if ($order eq $name) {
5592 $sort_th .= "<th>$header</th>\n";
5593 } else {
5594 $sort_th .= "<th>" .
5595 $cgi->a({-href => href(-replay=>1, order=>$name),
5596 -class => "header"}, $header) .
5597 "</th>\n";
5600 return $sort_th;
5603 sub git_project_list_rows {
5604 my ($projlist, $from, $to, $check_forks) = @_;
5606 $from = 0 unless defined $from;
5607 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5609 my $alternate = 1;
5610 for (my $i = $from; $i <= $to; $i++) {
5611 my $pr = $projlist->[$i];
5613 if ($alternate) {
5614 print "<tr class=\"dark\">\n";
5615 } else {
5616 print "<tr class=\"light\">\n";
5618 $alternate ^= 1;
5620 if ($check_forks) {
5621 print "<td>";
5622 if ($pr->{'forks'}) {
5623 my $nforks = scalar @{$pr->{'forks'}};
5624 if ($nforks > 0) {
5625 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5626 -title => "$nforks forks"}, "+");
5627 } else {
5628 print $cgi->span({-title => "$nforks forks"}, "+");
5631 print "</td>\n";
5633 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5634 -class => "list"},
5635 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5636 "</td>\n" .
5637 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5638 -class => "list",
5639 -title => $pr->{'descr_long'}},
5640 $search_regexp
5641 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5642 $pr->{'descr'}, $search_regexp)
5643 : esc_html($pr->{'descr'})) .
5644 "</td>\n";
5645 unless ($omit_owner) {
5646 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5648 unless ($omit_age_column) {
5649 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5650 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5652 print"<td class=\"link\">" .
5653 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5654 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5655 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5656 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5657 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5658 "</td>\n" .
5659 "</tr>\n";
5663 sub git_project_list_body {
5664 # actually uses global variable $project
5665 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5666 my @projects = @$projlist;
5668 my $check_forks = gitweb_check_feature('forks');
5669 my $show_ctags = gitweb_check_feature('ctags');
5670 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5671 $check_forks = undef
5672 if ($tagfilter || $search_regexp);
5674 # filtering out forks before filling info allows to do less work
5675 @projects = filter_forks_from_projects_list(\@projects)
5676 if ($check_forks);
5677 # search_projects_list pre-fills required info
5678 @projects = search_projects_list(\@projects,
5679 'search_regexp' => $search_regexp,
5680 'tagfilter' => $tagfilter)
5681 if ($tagfilter || $search_regexp);
5682 # fill the rest
5683 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5684 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5685 push @all_fields, 'owner' unless($omit_owner);
5686 @projects = fill_project_list_info(\@projects, @all_fields);
5688 $order ||= $default_projects_order;
5689 $from = 0 unless defined $from;
5690 $to = $#projects if (!defined $to || $#projects < $to);
5692 # short circuit
5693 if ($from > $to) {
5694 print "<center>\n".
5695 "<b>No such projects found</b><br />\n".
5696 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5697 "</center>\n<br />\n";
5698 return;
5701 @projects = sort_projects_list(\@projects, $order);
5703 if ($show_ctags) {
5704 my $ctags = git_gather_all_ctags(\@projects);
5705 my $cloud = git_populate_project_tagcloud($ctags);
5706 print git_show_project_tagcloud($cloud, 64);
5709 print "<table class=\"project_list\">\n";
5710 unless ($no_header) {
5711 print "<tr>\n";
5712 if ($check_forks) {
5713 print "<th></th>\n";
5715 print_sort_th('project', $order, 'Project');
5716 print_sort_th('descr', $order, 'Description');
5717 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5718 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5719 print "<th></th>\n" . # for links
5720 "</tr>\n";
5723 if ($projects_list_group_categories) {
5724 # only display categories with projects in the $from-$to window
5725 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5726 my %categories = build_projlist_by_category(\@projects, $from, $to);
5727 foreach my $cat (sort keys %categories) {
5728 unless ($cat eq "") {
5729 print "<tr>\n";
5730 if ($check_forks) {
5731 print "<td></td>\n";
5733 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5734 print "</tr>\n";
5737 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5739 } else {
5740 git_project_list_rows(\@projects, $from, $to, $check_forks);
5743 if (defined $extra) {
5744 print "<tr>\n";
5745 if ($check_forks) {
5746 print "<td></td>\n";
5748 print "<td colspan=\"5\">$extra</td>\n" .
5749 "</tr>\n";
5751 print "</table>\n";
5754 sub git_log_body {
5755 # uses global variable $project
5756 my ($commitlist, $from, $to, $refs, $extra) = @_;
5758 $from = 0 unless defined $from;
5759 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5761 for (my $i = 0; $i <= $to; $i++) {
5762 my %co = %{$commitlist->[$i]};
5763 next if !%co;
5764 my $commit = $co{'id'};
5765 my $ref = format_ref_marker($refs, $commit);
5766 git_print_header_div('commit',
5767 "<span class=\"age\">$co{'age_string'}</span>" .
5768 esc_html($co{'title'}) . $ref,
5769 $commit);
5770 print "<div class=\"title_text\">\n" .
5771 "<div class=\"log_link\">\n" .
5772 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5773 " | " .
5774 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5775 " | " .
5776 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5777 "<br/>\n" .
5778 "</div>\n";
5779 git_print_authorship(\%co, -tag => 'span');
5780 print "<br/>\n</div>\n";
5782 print "<div class=\"log_body\">\n";
5783 git_print_log($co{'comment'}, -final_empty_line=> 1);
5784 print "</div>\n";
5786 if ($extra) {
5787 print "<div class=\"page_nav\">\n";
5788 print "$extra\n";
5789 print "</div>\n";
5793 sub git_shortlog_body {
5794 # uses global variable $project
5795 my ($commitlist, $from, $to, $refs, $extra) = @_;
5797 $from = 0 unless defined $from;
5798 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5800 print "<table class=\"shortlog\">\n";
5801 my $alternate = 1;
5802 for (my $i = $from; $i <= $to; $i++) {
5803 my %co = %{$commitlist->[$i]};
5804 my $commit = $co{'id'};
5805 my $ref = format_ref_marker($refs, $commit);
5806 if ($alternate) {
5807 print "<tr class=\"dark\">\n";
5808 } else {
5809 print "<tr class=\"light\">\n";
5811 $alternate ^= 1;
5812 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5813 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5814 format_author_html('td', \%co, 10) . "<td>";
5815 print format_subject_html($co{'title'}, $co{'title_short'},
5816 href(action=>"commit", hash=>$commit), $ref);
5817 print "</td>\n" .
5818 "<td class=\"link\">" .
5819 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5820 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5821 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5822 my $snapshot_links = format_snapshot_links($commit);
5823 if (defined $snapshot_links) {
5824 print " | " . $snapshot_links;
5826 print "</td>\n" .
5827 "</tr>\n";
5829 if (defined $extra) {
5830 print "<tr>\n" .
5831 "<td colspan=\"4\">$extra</td>\n" .
5832 "</tr>\n";
5834 print "</table>\n";
5837 sub git_history_body {
5838 # Warning: assumes constant type (blob or tree) during history
5839 my ($commitlist, $from, $to, $refs, $extra,
5840 $file_name, $file_hash, $ftype) = @_;
5842 $from = 0 unless defined $from;
5843 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5845 print "<table class=\"history\">\n";
5846 my $alternate = 1;
5847 for (my $i = $from; $i <= $to; $i++) {
5848 my %co = %{$commitlist->[$i]};
5849 if (!%co) {
5850 next;
5852 my $commit = $co{'id'};
5854 my $ref = format_ref_marker($refs, $commit);
5856 if ($alternate) {
5857 print "<tr class=\"dark\">\n";
5858 } else {
5859 print "<tr class=\"light\">\n";
5861 $alternate ^= 1;
5862 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5863 # shortlog: format_author_html('td', \%co, 10)
5864 format_author_html('td', \%co, 15, 3) . "<td>";
5865 # originally git_history used chop_str($co{'title'}, 50)
5866 print format_subject_html($co{'title'}, $co{'title_short'},
5867 href(action=>"commit", hash=>$commit), $ref);
5868 print "</td>\n" .
5869 "<td class=\"link\">" .
5870 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5871 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5873 if ($ftype eq 'blob') {
5874 my $blob_current = $file_hash;
5875 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5876 if (defined $blob_current && defined $blob_parent &&
5877 $blob_current ne $blob_parent) {
5878 print " | " .
5879 $cgi->a({-href => href(action=>"blobdiff",
5880 hash=>$blob_current, hash_parent=>$blob_parent,
5881 hash_base=>$hash_base, hash_parent_base=>$commit,
5882 file_name=>$file_name)},
5883 "diff to current");
5886 print "</td>\n" .
5887 "</tr>\n";
5889 if (defined $extra) {
5890 print "<tr>\n" .
5891 "<td colspan=\"4\">$extra</td>\n" .
5892 "</tr>\n";
5894 print "</table>\n";
5897 sub git_tags_body {
5898 # uses global variable $project
5899 my ($taglist, $from, $to, $extra) = @_;
5900 $from = 0 unless defined $from;
5901 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5903 print "<table class=\"tags\">\n";
5904 my $alternate = 1;
5905 for (my $i = $from; $i <= $to; $i++) {
5906 my $entry = $taglist->[$i];
5907 my %tag = %$entry;
5908 my $comment = $tag{'subject'};
5909 my $comment_short;
5910 if (defined $comment) {
5911 $comment_short = chop_str($comment, 30, 5);
5913 if ($alternate) {
5914 print "<tr class=\"dark\">\n";
5915 } else {
5916 print "<tr class=\"light\">\n";
5918 $alternate ^= 1;
5919 if (defined $tag{'age'}) {
5920 print "<td><i>$tag{'age'}</i></td>\n";
5921 } else {
5922 print "<td></td>\n";
5924 print "<td>" .
5925 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5926 -class => "list name"}, esc_html($tag{'name'})) .
5927 "</td>\n" .
5928 "<td>";
5929 if (defined $comment) {
5930 print format_subject_html($comment, $comment_short,
5931 href(action=>"tag", hash=>$tag{'id'}));
5933 print "</td>\n" .
5934 "<td class=\"selflink\">";
5935 if ($tag{'type'} eq "tag") {
5936 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5937 } else {
5938 print "&nbsp;";
5940 print "</td>\n" .
5941 "<td class=\"link\">" . " | " .
5942 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5943 if ($tag{'reftype'} eq "commit") {
5944 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5945 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5946 } elsif ($tag{'reftype'} eq "blob") {
5947 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5949 print "</td>\n" .
5950 "</tr>";
5952 if (defined $extra) {
5953 print "<tr>\n" .
5954 "<td colspan=\"5\">$extra</td>\n" .
5955 "</tr>\n";
5957 print "</table>\n";
5960 sub git_heads_body {
5961 # uses global variable $project
5962 my ($headlist, $head_at, $from, $to, $extra) = @_;
5963 $from = 0 unless defined $from;
5964 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5966 print "<table class=\"heads\">\n";
5967 my $alternate = 1;
5968 for (my $i = $from; $i <= $to; $i++) {
5969 my $entry = $headlist->[$i];
5970 my %ref = %$entry;
5971 my $curr = defined $head_at && $ref{'id'} eq $head_at;
5972 if ($alternate) {
5973 print "<tr class=\"dark\">\n";
5974 } else {
5975 print "<tr class=\"light\">\n";
5977 $alternate ^= 1;
5978 print "<td><i>$ref{'age'}</i></td>\n" .
5979 ($curr ? "<td class=\"current_head\">" : "<td>") .
5980 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5981 -class => "list name"},esc_html($ref{'name'})) .
5982 "</td>\n" .
5983 "<td class=\"link\">" .
5984 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5985 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5986 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
5987 "</td>\n" .
5988 "</tr>";
5990 if (defined $extra) {
5991 print "<tr>\n" .
5992 "<td colspan=\"3\">$extra</td>\n" .
5993 "</tr>\n";
5995 print "</table>\n";
5998 # Display a single remote block
5999 sub git_remote_block {
6000 my ($remote, $rdata, $limit, $head) = @_;
6002 my $heads = $rdata->{'heads'};
6003 my $fetch = $rdata->{'fetch'};
6004 my $push = $rdata->{'push'};
6006 my $urls_table = "<table class=\"projects_list\">\n" ;
6008 if (defined $fetch) {
6009 if ($fetch eq $push) {
6010 $urls_table .= format_repo_url("URL", $fetch);
6011 } else {
6012 $urls_table .= format_repo_url("Fetch URL", $fetch);
6013 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6015 } elsif (defined $push) {
6016 $urls_table .= format_repo_url("Push URL", $push);
6017 } else {
6018 $urls_table .= format_repo_url("", "No remote URL");
6021 $urls_table .= "</table>\n";
6023 my $dots;
6024 if (defined $limit && $limit < @$heads) {
6025 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6028 print $urls_table;
6029 git_heads_body($heads, $head, 0, $limit, $dots);
6032 # Display a list of remote names with the respective fetch and push URLs
6033 sub git_remotes_list {
6034 my ($remotedata, $limit) = @_;
6035 print "<table class=\"heads\">\n";
6036 my $alternate = 1;
6037 my @remotes = sort keys %$remotedata;
6039 my $limited = $limit && $limit < @remotes;
6041 $#remotes = $limit - 1 if $limited;
6043 while (my $remote = shift @remotes) {
6044 my $rdata = $remotedata->{$remote};
6045 my $fetch = $rdata->{'fetch'};
6046 my $push = $rdata->{'push'};
6047 if ($alternate) {
6048 print "<tr class=\"dark\">\n";
6049 } else {
6050 print "<tr class=\"light\">\n";
6052 $alternate ^= 1;
6053 print "<td>" .
6054 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6055 -class=> "list name"},esc_html($remote)) .
6056 "</td>";
6057 print "<td class=\"link\">" .
6058 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6059 " | " .
6060 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6061 "</td>";
6063 print "</tr>\n";
6066 if ($limited) {
6067 print "<tr>\n" .
6068 "<td colspan=\"3\">" .
6069 $cgi->a({-href => href(action=>"remotes")}, "...") .
6070 "</td>\n" . "</tr>\n";
6073 print "</table>";
6076 # Display remote heads grouped by remote, unless there are too many
6077 # remotes, in which case we only display the remote names
6078 sub git_remotes_body {
6079 my ($remotedata, $limit, $head) = @_;
6080 if ($limit and $limit < keys %$remotedata) {
6081 git_remotes_list($remotedata, $limit);
6082 } else {
6083 fill_remote_heads($remotedata);
6084 while (my ($remote, $rdata) = each %$remotedata) {
6085 git_print_section({-class=>"remote", -id=>$remote},
6086 ["remotes", $remote, $remote], sub {
6087 git_remote_block($remote, $rdata, $limit, $head);
6093 sub git_search_message {
6094 my %co = @_;
6096 my $greptype;
6097 if ($searchtype eq 'commit') {
6098 $greptype = "--grep=";
6099 } elsif ($searchtype eq 'author') {
6100 $greptype = "--author=";
6101 } elsif ($searchtype eq 'committer') {
6102 $greptype = "--committer=";
6104 $greptype .= $searchtext;
6105 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6106 $greptype, '--regexp-ignore-case',
6107 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6109 my $paging_nav = '';
6110 if ($page > 0) {
6111 $paging_nav .=
6112 $cgi->a({-href => href(-replay=>1, page=>undef)},
6113 "first") .
6114 " &sdot; " .
6115 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6116 -accesskey => "p", -title => "Alt-p"}, "prev");
6117 } else {
6118 $paging_nav .= "first &sdot; prev";
6120 my $next_link = '';
6121 if ($#commitlist >= 100) {
6122 $next_link =
6123 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6124 -accesskey => "n", -title => "Alt-n"}, "next");
6125 $paging_nav .= " &sdot; $next_link";
6126 } else {
6127 $paging_nav .= " &sdot; next";
6130 git_header_html();
6132 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6133 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6134 if ($page == 0 && !@commitlist) {
6135 print "<p>No match.</p>\n";
6136 } else {
6137 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6140 git_footer_html();
6143 sub git_search_changes {
6144 my %co = @_;
6146 local $/ = "\n";
6147 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6148 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6149 ($search_use_regexp ? '--pickaxe-regex' : ())
6150 or die_error(500, "Open git-log failed");
6152 git_header_html();
6154 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6155 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6157 print "<table class=\"pickaxe search\">\n";
6158 my $alternate = 1;
6159 undef %co;
6160 my @files;
6161 while (my $line = <$fd>) {
6162 chomp $line;
6163 next unless $line;
6165 my %set = parse_difftree_raw_line($line);
6166 if (defined $set{'commit'}) {
6167 # finish previous commit
6168 if (%co) {
6169 print "</td>\n" .
6170 "<td class=\"link\">" .
6171 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6172 "commit") .
6173 " | " .
6174 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6175 hash_base=>$co{'id'})},
6176 "tree") .
6177 "</td>\n" .
6178 "</tr>\n";
6181 if ($alternate) {
6182 print "<tr class=\"dark\">\n";
6183 } else {
6184 print "<tr class=\"light\">\n";
6186 $alternate ^= 1;
6187 %co = parse_commit($set{'commit'});
6188 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6189 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6190 "<td><i>$author</i></td>\n" .
6191 "<td>" .
6192 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6193 -class => "list subject"},
6194 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6195 } elsif (defined $set{'to_id'}) {
6196 next if ($set{'to_id'} =~ m/^0{40}$/);
6198 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6199 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6200 -class => "list"},
6201 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6202 "<br/>\n";
6205 close $fd;
6207 # finish last commit (warning: repetition!)
6208 if (%co) {
6209 print "</td>\n" .
6210 "<td class=\"link\">" .
6211 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6212 "commit") .
6213 " | " .
6214 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6215 hash_base=>$co{'id'})},
6216 "tree") .
6217 "</td>\n" .
6218 "</tr>\n";
6221 print "</table>\n";
6223 git_footer_html();
6226 sub git_search_files {
6227 my %co = @_;
6229 local $/ = "\n";
6230 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6231 $search_use_regexp ? ('-E', '-i') : '-F',
6232 $searchtext, $co{'tree'}
6233 or die_error(500, "Open git-grep failed");
6235 git_header_html();
6237 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6238 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6240 print "<table class=\"grep_search\">\n";
6241 my $alternate = 1;
6242 my $matches = 0;
6243 my $lastfile = '';
6244 my $file_href;
6245 while (my $line = <$fd>) {
6246 chomp $line;
6247 my ($file, $lno, $ltext, $binary);
6248 last if ($matches++ > 1000);
6249 if ($line =~ /^Binary file (.+) matches$/) {
6250 $file = $1;
6251 $binary = 1;
6252 } else {
6253 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6254 $file =~ s/^$co{'tree'}://;
6256 if ($file ne $lastfile) {
6257 $lastfile and print "</td></tr>\n";
6258 if ($alternate++) {
6259 print "<tr class=\"dark\">\n";
6260 } else {
6261 print "<tr class=\"light\">\n";
6263 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6264 file_name=>$file);
6265 print "<td class=\"list\">".
6266 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6267 print "</td><td>\n";
6268 $lastfile = $file;
6270 if ($binary) {
6271 print "<div class=\"binary\">Binary file</div>\n";
6272 } else {
6273 $ltext = untabify($ltext);
6274 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6275 $ltext = esc_html($1, -nbsp=>1);
6276 $ltext .= '<span class="match">';
6277 $ltext .= esc_html($2, -nbsp=>1);
6278 $ltext .= '</span>';
6279 $ltext .= esc_html($3, -nbsp=>1);
6280 } else {
6281 $ltext = esc_html($ltext, -nbsp=>1);
6283 print "<div class=\"pre\">" .
6284 $cgi->a({-href => $file_href.'#l'.$lno,
6285 -class => "linenr"}, sprintf('%4i', $lno)) .
6286 ' ' . $ltext . "</div>\n";
6289 if ($lastfile) {
6290 print "</td></tr>\n";
6291 if ($matches > 1000) {
6292 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6294 } else {
6295 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6297 close $fd;
6299 print "</table>\n";
6301 git_footer_html();
6304 sub git_search_grep_body {
6305 my ($commitlist, $from, $to, $extra) = @_;
6306 $from = 0 unless defined $from;
6307 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6309 print "<table class=\"commit_search\">\n";
6310 my $alternate = 1;
6311 for (my $i = $from; $i <= $to; $i++) {
6312 my %co = %{$commitlist->[$i]};
6313 if (!%co) {
6314 next;
6316 my $commit = $co{'id'};
6317 if ($alternate) {
6318 print "<tr class=\"dark\">\n";
6319 } else {
6320 print "<tr class=\"light\">\n";
6322 $alternate ^= 1;
6323 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6324 format_author_html('td', \%co, 15, 5) .
6325 "<td>" .
6326 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6327 -class => "list subject"},
6328 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6329 my $comment = $co{'comment'};
6330 foreach my $line (@$comment) {
6331 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6332 my ($lead, $match, $trail) = ($1, $2, $3);
6333 $match = chop_str($match, 70, 5, 'center');
6334 my $contextlen = int((80 - length($match))/2);
6335 $contextlen = 30 if ($contextlen > 30);
6336 $lead = chop_str($lead, $contextlen, 10, 'left');
6337 $trail = chop_str($trail, $contextlen, 10, 'right');
6339 $lead = esc_html($lead);
6340 $match = esc_html($match);
6341 $trail = esc_html($trail);
6343 print "$lead<span class=\"match\">$match</span>$trail<br />";
6346 print "</td>\n" .
6347 "<td class=\"link\">" .
6348 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6349 " | " .
6350 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6351 " | " .
6352 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6353 print "</td>\n" .
6354 "</tr>\n";
6356 if (defined $extra) {
6357 print "<tr>\n" .
6358 "<td colspan=\"3\">$extra</td>\n" .
6359 "</tr>\n";
6361 print "</table>\n";
6364 ## ======================================================================
6365 ## ======================================================================
6366 ## actions
6368 sub git_project_list {
6369 my $order = $input_params{'order'};
6370 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6371 die_error(400, "Unknown order parameter");
6374 my @list = git_get_projects_list($project_filter, $strict_export);
6375 if (!@list) {
6376 die_error(404, "No projects found");
6379 git_header_html();
6380 if (defined $home_text && -f $home_text) {
6381 print "<div class=\"index_include\">\n";
6382 insert_file($home_text);
6383 print "</div>\n";
6386 git_project_search_form($searchtext, $search_use_regexp);
6387 git_project_list_body(\@list, $order);
6388 git_footer_html();
6391 sub git_forks {
6392 my $order = $input_params{'order'};
6393 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6394 die_error(400, "Unknown order parameter");
6397 my $filter = $project;
6398 $filter =~ s/\.git$//;
6399 my @list = git_get_projects_list($filter);
6400 if (!@list) {
6401 die_error(404, "No forks found");
6404 git_header_html();
6405 git_print_page_nav('','');
6406 git_print_header_div('summary', "$project forks");
6407 git_project_list_body(\@list, $order);
6408 git_footer_html();
6411 sub git_project_index {
6412 my @projects = git_get_projects_list($project_filter, $strict_export);
6413 if (!@projects) {
6414 die_error(404, "No projects found");
6417 print $cgi->header(
6418 -type => 'text/plain',
6419 -charset => 'utf-8',
6420 -content_disposition => 'inline; filename="index.aux"');
6422 foreach my $pr (@projects) {
6423 if (!exists $pr->{'owner'}) {
6424 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6427 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6428 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6429 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6430 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6431 $path =~ s/ /\+/g;
6432 $owner =~ s/ /\+/g;
6434 print "$path $owner\n";
6438 sub git_summary {
6439 my $descr = git_get_project_description($project) || "none";
6440 my %co = parse_commit("HEAD");
6441 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6442 my $head = $co{'id'};
6443 my $remote_heads = gitweb_check_feature('remote_heads');
6445 my $owner = git_get_project_owner($project);
6447 my $refs = git_get_references();
6448 # These get_*_list functions return one more to allow us to see if
6449 # there are more ...
6450 my @taglist = git_get_tags_list(16);
6451 my @headlist = git_get_heads_list(16);
6452 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6453 my @forklist;
6454 my $check_forks = gitweb_check_feature('forks');
6456 if ($check_forks) {
6457 # find forks of a project
6458 my $filter = $project;
6459 $filter =~ s/\.git$//;
6460 @forklist = git_get_projects_list($filter);
6461 # filter out forks of forks
6462 @forklist = filter_forks_from_projects_list(\@forklist)
6463 if (@forklist);
6466 git_header_html();
6467 git_print_page_nav('summary','', $head);
6469 print "<div class=\"title\">&nbsp;</div>\n";
6470 print "<table class=\"projects_list\">\n" .
6471 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6472 unless ($omit_owner) {
6473 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6475 if (defined $cd{'rfc2822'}) {
6476 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6477 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6480 # use per project git URL list in $projectroot/$project/cloneurl
6481 # or make project git URL from git base URL and project name
6482 my $url_tag = "URL";
6483 my @url_list = git_get_project_url_list($project);
6484 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6485 foreach my $git_url (@url_list) {
6486 next unless $git_url;
6487 print format_repo_url($url_tag, $git_url);
6488 $url_tag = "";
6491 # Tag cloud
6492 my $show_ctags = gitweb_check_feature('ctags');
6493 if ($show_ctags) {
6494 my $ctags = git_get_project_ctags($project);
6495 if (%$ctags) {
6496 # without ability to add tags, don't show if there are none
6497 my $cloud = git_populate_project_tagcloud($ctags);
6498 print "<tr id=\"metadata_ctags\">" .
6499 "<td>content tags</td>" .
6500 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6501 "</tr>\n";
6505 print "</table>\n";
6507 # If XSS prevention is on, we don't include README.html.
6508 # TODO: Allow a readme in some safe format.
6509 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6510 print "<div class=\"title\">readme</div>\n" .
6511 "<div class=\"readme\">\n";
6512 insert_file("$projectroot/$project/README.html");
6513 print "\n</div>\n"; # class="readme"
6516 # we need to request one more than 16 (0..15) to check if
6517 # those 16 are all
6518 my @commitlist = $head ? parse_commits($head, 17) : ();
6519 if (@commitlist) {
6520 git_print_header_div('shortlog');
6521 git_shortlog_body(\@commitlist, 0, 15, $refs,
6522 $#commitlist <= 15 ? undef :
6523 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6526 if (@taglist) {
6527 git_print_header_div('tags');
6528 git_tags_body(\@taglist, 0, 15,
6529 $#taglist <= 15 ? undef :
6530 $cgi->a({-href => href(action=>"tags")}, "..."));
6533 if (@headlist) {
6534 git_print_header_div('heads');
6535 git_heads_body(\@headlist, $head, 0, 15,
6536 $#headlist <= 15 ? undef :
6537 $cgi->a({-href => href(action=>"heads")}, "..."));
6540 if (%remotedata) {
6541 git_print_header_div('remotes');
6542 git_remotes_body(\%remotedata, 15, $head);
6545 if (@forklist) {
6546 git_print_header_div('forks');
6547 git_project_list_body(\@forklist, 'age', 0, 15,
6548 $#forklist <= 15 ? undef :
6549 $cgi->a({-href => href(action=>"forks")}, "..."),
6550 'no_header');
6553 git_footer_html();
6556 sub git_tag {
6557 my %tag = parse_tag($hash);
6559 if (! %tag) {
6560 die_error(404, "Unknown tag object");
6563 my $head = git_get_head_hash($project);
6564 git_header_html();
6565 git_print_page_nav('','', $head,undef,$head);
6566 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6567 print "<div class=\"title_text\">\n" .
6568 "<table class=\"object_header\">\n" .
6569 "<tr>\n" .
6570 "<td>object</td>\n" .
6571 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6572 $tag{'object'}) . "</td>\n" .
6573 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6574 $tag{'type'}) . "</td>\n" .
6575 "</tr>\n";
6576 if (defined($tag{'author'})) {
6577 git_print_authorship_rows(\%tag, 'author');
6579 print "</table>\n\n" .
6580 "</div>\n";
6581 print "<div class=\"page_body\">";
6582 my $comment = $tag{'comment'};
6583 foreach my $line (@$comment) {
6584 chomp $line;
6585 print esc_html($line, -nbsp=>1) . "<br/>\n";
6587 print "</div>\n";
6588 git_footer_html();
6591 sub git_blame_common {
6592 my $format = shift || 'porcelain';
6593 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6594 $format = 'incremental';
6595 $action = 'blame_incremental'; # for page title etc
6598 # permissions
6599 gitweb_check_feature('blame')
6600 or die_error(403, "Blame view not allowed");
6602 # error checking
6603 die_error(400, "No file name given") unless $file_name;
6604 $hash_base ||= git_get_head_hash($project);
6605 die_error(404, "Couldn't find base commit") unless $hash_base;
6606 my %co = parse_commit($hash_base)
6607 or die_error(404, "Commit not found");
6608 my $ftype = "blob";
6609 if (!defined $hash) {
6610 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6611 or die_error(404, "Error looking up file");
6612 } else {
6613 $ftype = git_get_type($hash);
6614 if ($ftype !~ "blob") {
6615 die_error(400, "Object is not a blob");
6619 my $fd;
6620 if ($format eq 'incremental') {
6621 # get file contents (as base)
6622 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6623 or die_error(500, "Open git-cat-file failed");
6624 } elsif ($format eq 'data') {
6625 # run git-blame --incremental
6626 open $fd, "-|", git_cmd(), "blame", "--incremental",
6627 $hash_base, "--", $file_name
6628 or die_error(500, "Open git-blame --incremental failed");
6629 } else {
6630 # run git-blame --porcelain
6631 open $fd, "-|", git_cmd(), "blame", '-p',
6632 $hash_base, '--', $file_name
6633 or die_error(500, "Open git-blame --porcelain failed");
6636 # incremental blame data returns early
6637 if ($format eq 'data') {
6638 print $cgi->header(
6639 -type=>"text/plain", -charset => "utf-8",
6640 -status=> "200 OK");
6641 local $| = 1; # output autoflush
6642 while (my $line = <$fd>) {
6643 print to_utf8($line);
6645 close $fd
6646 or print "ERROR $!\n";
6648 print 'END';
6649 if (defined $t0 && gitweb_check_feature('timed')) {
6650 print ' '.
6651 tv_interval($t0, [ gettimeofday() ]).
6652 ' '.$number_of_git_cmds;
6654 print "\n";
6656 return;
6659 # page header
6660 git_header_html();
6661 my $formats_nav =
6662 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6663 "blob") .
6664 " | ";
6665 if ($format eq 'incremental') {
6666 $formats_nav .=
6667 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6668 "blame") . " (non-incremental)";
6669 } else {
6670 $formats_nav .=
6671 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6672 "blame") . " (incremental)";
6674 $formats_nav .=
6675 " | " .
6676 $cgi->a({-href => href(action=>"history", -replay=>1)},
6677 "history") .
6678 " | " .
6679 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6680 "HEAD");
6681 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6682 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6683 git_print_page_path($file_name, $ftype, $hash_base);
6685 # page body
6686 if ($format eq 'incremental') {
6687 print "<noscript>\n<div class=\"error\"><center><b>\n".
6688 "This page requires JavaScript to run.\n Use ".
6689 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6690 'this page').
6691 " instead.\n".
6692 "</b></center></div>\n</noscript>\n";
6694 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6697 print qq!<div class="page_body">\n!;
6698 print qq!<div id="progress_info">... / ...</div>\n!
6699 if ($format eq 'incremental');
6700 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6701 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6702 qq!<thead>\n!.
6703 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6704 qq!</thead>\n!.
6705 qq!<tbody>\n!;
6707 my @rev_color = qw(light dark);
6708 my $num_colors = scalar(@rev_color);
6709 my $current_color = 0;
6711 if ($format eq 'incremental') {
6712 my $color_class = $rev_color[$current_color];
6714 #contents of a file
6715 my $linenr = 0;
6716 LINE:
6717 while (my $line = <$fd>) {
6718 chomp $line;
6719 $linenr++;
6721 print qq!<tr id="l$linenr" class="$color_class">!.
6722 qq!<td class="sha1"><a href=""> </a></td>!.
6723 qq!<td class="linenr">!.
6724 qq!<a class="linenr" href="">$linenr</a></td>!;
6725 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6726 print qq!</tr>\n!;
6729 } else { # porcelain, i.e. ordinary blame
6730 my %metainfo = (); # saves information about commits
6732 # blame data
6733 LINE:
6734 while (my $line = <$fd>) {
6735 chomp $line;
6736 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6737 # no <lines in group> for subsequent lines in group of lines
6738 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6739 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6740 if (!exists $metainfo{$full_rev}) {
6741 $metainfo{$full_rev} = { 'nprevious' => 0 };
6743 my $meta = $metainfo{$full_rev};
6744 my $data;
6745 while ($data = <$fd>) {
6746 chomp $data;
6747 last if ($data =~ s/^\t//); # contents of line
6748 if ($data =~ /^(\S+)(?: (.*))?$/) {
6749 $meta->{$1} = $2 unless exists $meta->{$1};
6751 if ($data =~ /^previous /) {
6752 $meta->{'nprevious'}++;
6755 my $short_rev = substr($full_rev, 0, 8);
6756 my $author = $meta->{'author'};
6757 my %date =
6758 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6759 my $date = $date{'iso-tz'};
6760 if ($group_size) {
6761 $current_color = ($current_color + 1) % $num_colors;
6763 my $tr_class = $rev_color[$current_color];
6764 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6765 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6766 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6767 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6768 if ($group_size) {
6769 print "<td class=\"sha1\"";
6770 print " title=\"". esc_html($author) . ", $date\"";
6771 print " rowspan=\"$group_size\"" if ($group_size > 1);
6772 print ">";
6773 print $cgi->a({-href => href(action=>"commit",
6774 hash=>$full_rev,
6775 file_name=>$file_name)},
6776 esc_html($short_rev));
6777 if ($group_size >= 2) {
6778 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6779 if (@author_initials) {
6780 print "<br />" .
6781 esc_html(join('', @author_initials));
6782 # or join('.', ...)
6785 print "</td>\n";
6787 # 'previous' <sha1 of parent commit> <filename at commit>
6788 if (exists $meta->{'previous'} &&
6789 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6790 $meta->{'parent'} = $1;
6791 $meta->{'file_parent'} = unquote($2);
6793 my $linenr_commit =
6794 exists($meta->{'parent'}) ?
6795 $meta->{'parent'} : $full_rev;
6796 my $linenr_filename =
6797 exists($meta->{'file_parent'}) ?
6798 $meta->{'file_parent'} : unquote($meta->{'filename'});
6799 my $blamed = href(action => 'blame',
6800 file_name => $linenr_filename,
6801 hash_base => $linenr_commit);
6802 print "<td class=\"linenr\">";
6803 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6804 -class => "linenr" },
6805 esc_html($lineno));
6806 print "</td>";
6807 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6808 print "</tr>\n";
6809 } # end while
6813 # footer
6814 print "</tbody>\n".
6815 "</table>\n"; # class="blame"
6816 print "</div>\n"; # class="blame_body"
6817 close $fd
6818 or print "Reading blob failed\n";
6820 git_footer_html();
6823 sub git_blame {
6824 git_blame_common();
6827 sub git_blame_incremental {
6828 git_blame_common('incremental');
6831 sub git_blame_data {
6832 git_blame_common('data');
6835 sub git_tags {
6836 my $head = git_get_head_hash($project);
6837 git_header_html();
6838 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6839 git_print_header_div('summary', $project);
6841 my @tagslist = git_get_tags_list();
6842 if (@tagslist) {
6843 git_tags_body(\@tagslist);
6845 git_footer_html();
6848 sub git_heads {
6849 my $head = git_get_head_hash($project);
6850 git_header_html();
6851 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6852 git_print_header_div('summary', $project);
6854 my @headslist = git_get_heads_list();
6855 if (@headslist) {
6856 git_heads_body(\@headslist, $head);
6858 git_footer_html();
6861 # used both for single remote view and for list of all the remotes
6862 sub git_remotes {
6863 gitweb_check_feature('remote_heads')
6864 or die_error(403, "Remote heads view is disabled");
6866 my $head = git_get_head_hash($project);
6867 my $remote = $input_params{'hash'};
6869 my $remotedata = git_get_remotes_list($remote);
6870 die_error(500, "Unable to get remote information") unless defined $remotedata;
6872 unless (%$remotedata) {
6873 die_error(404, defined $remote ?
6874 "Remote $remote not found" :
6875 "No remotes found");
6878 git_header_html(undef, undef, -action_extra => $remote);
6879 git_print_page_nav('', '', $head, undef, $head,
6880 format_ref_views($remote ? '' : 'remotes'));
6882 fill_remote_heads($remotedata);
6883 if (defined $remote) {
6884 git_print_header_div('remotes', "$remote remote for $project");
6885 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6886 } else {
6887 git_print_header_div('summary', "$project remotes");
6888 git_remotes_body($remotedata, undef, $head);
6891 git_footer_html();
6894 sub git_blob_plain {
6895 my $type = shift;
6896 my $expires;
6898 if (!defined $hash) {
6899 if (defined $file_name) {
6900 my $base = $hash_base || git_get_head_hash($project);
6901 $hash = git_get_hash_by_path($base, $file_name, "blob")
6902 or die_error(404, "Cannot find file");
6903 } else {
6904 die_error(400, "No file name defined");
6906 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6907 # blobs defined by non-textual hash id's can be cached
6908 $expires = "+1d";
6911 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6912 or die_error(500, "Open git-cat-file blob '$hash' failed");
6914 # content-type (can include charset)
6915 $type = blob_contenttype($fd, $file_name, $type);
6917 # "save as" filename, even when no $file_name is given
6918 my $save_as = "$hash";
6919 if (defined $file_name) {
6920 $save_as = $file_name;
6921 } elsif ($type =~ m/^text\//) {
6922 $save_as .= '.txt';
6925 # With XSS prevention on, blobs of all types except a few known safe
6926 # ones are served with "Content-Disposition: attachment" to make sure
6927 # they don't run in our security domain. For certain image types,
6928 # blob view writes an <img> tag referring to blob_plain view, and we
6929 # want to be sure not to break that by serving the image as an
6930 # attachment (though Firefox 3 doesn't seem to care).
6931 my $sandbox = $prevent_xss &&
6932 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
6934 # serve text/* as text/plain
6935 if ($prevent_xss &&
6936 ($type =~ m!^text/[a-z]+\b(.*)$! ||
6937 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
6938 my $rest = $1;
6939 $rest = defined $rest ? $rest : '';
6940 $type = "text/plain$rest";
6943 print $cgi->header(
6944 -type => $type,
6945 -expires => $expires,
6946 -content_disposition =>
6947 ($sandbox ? 'attachment' : 'inline')
6948 . '; filename="' . $save_as . '"');
6949 local $/ = undef;
6950 binmode STDOUT, ':raw';
6951 print <$fd>;
6952 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6953 close $fd;
6956 sub git_blob {
6957 my $expires;
6959 if (!defined $hash) {
6960 if (defined $file_name) {
6961 my $base = $hash_base || git_get_head_hash($project);
6962 $hash = git_get_hash_by_path($base, $file_name, "blob")
6963 or die_error(404, "Cannot find file");
6964 } else {
6965 die_error(400, "No file name defined");
6967 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6968 # blobs defined by non-textual hash id's can be cached
6969 $expires = "+1d";
6972 my $have_blame = gitweb_check_feature('blame');
6973 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6974 or die_error(500, "Couldn't cat $file_name, $hash");
6975 my $mimetype = blob_mimetype($fd, $file_name);
6976 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
6977 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
6978 close $fd;
6979 return git_blob_plain($mimetype);
6981 # we can have blame only for text/* mimetype
6982 $have_blame &&= ($mimetype =~ m!^text/!);
6984 my $highlight_js = gitweb_check_feature('syntaxhighlighter_js');
6985 if ($highlight_js) {
6986 push @stylesheets, $highlight_js->{url} . '/styles/shCore'
6987 . $highlight_js->{style} . '.css';
6988 push @stylesheets, $highlight_js->{url} . '/styles/shTheme'
6989 . $highlight_js->{theme} . '.css';
6992 my $highlight = gitweb_check_feature('highlight');
6993 if ($highlight_js && $highlight) {
6994 die_error(500, 'The highlight and syntaxhighlighter_js are'
6995 . 'mutually exclusive');
6997 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
6998 $fd = run_highlighter($fd, $highlight, $syntax)
6999 if $syntax;
7001 git_header_html(undef, $expires);
7002 my $formats_nav = '';
7003 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7004 if (defined $file_name) {
7005 if ($have_blame) {
7006 $formats_nav .=
7007 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7008 "blame") .
7009 " | ";
7011 $formats_nav .=
7012 $cgi->a({-href => href(action=>"history", -replay=>1)},
7013 "history") .
7014 " | " .
7015 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7016 "raw") .
7017 " | " .
7018 $cgi->a({-href => href(action=>"blob",
7019 hash_base=>"HEAD", file_name=>$file_name)},
7020 "HEAD");
7021 } else {
7022 $formats_nav .=
7023 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7024 "raw");
7026 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7027 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7028 } else {
7029 print "<div class=\"page_nav\">\n" .
7030 "<br/><br/></div>\n" .
7031 "<div class=\"title\">".esc_html($hash)."</div>\n";
7033 git_print_page_path($file_name, "blob", $hash_base);
7034 print "<div class=\"page_body\">\n";
7035 if ($mimetype =~ m!^image/!) {
7036 print qq!<img type="!.esc_attr($mimetype).qq!"!;
7037 if ($file_name) {
7038 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7040 print qq! src="! .
7041 href(action=>"blob_plain", hash=>$hash,
7042 hash_base=>$hash_base, file_name=>$file_name) .
7043 qq!" />\n!;
7044 } elsif ($highlight_js) {
7045 my $ext = $file_name;
7046 $ext =~ s/.*\.//;
7047 print qq!<pre class="brush:!.$ext.qq!">!;
7048 while (my $line = <$fd>) {
7049 $line =~ s!&!\&#38;!g;
7050 $line =~ s!<!\&#60;!g;
7051 print $line;
7053 print qq!</pre>!;
7054 foreach my $name ('Core', 'Autoloader') {
7055 print qq!<script src="!.$highlight_js->{url}
7056 .qq!/scripts/sh!.$name
7057 .qq!.js" type="text/javascript"></script>!;
7059 print qq!<script type="text/javascript">!;
7060 print qq!SyntaxHighlighter.defaults["pad-line-numbers"] = 3;!;
7061 print qq!SyntaxHighlighter.defaults["toolbar"] = false;!;
7062 # for XHTML compliance
7063 print qq!SyntaxHighlighter.config["space"] = '&#160;';!;
7064 print qq!SyntaxHighlighter.autoloader(!;
7065 my $brush_prefix = $highlight_js->{url} . '/scripts/shBrush';
7066 foreach my $language ('applescript AppleScript',
7067 'actionscript3 as3 AS3',
7068 'bash shell Bash',
7069 'clj Clojure',
7070 'coldfusion cf ColdFusion',
7071 'cpp c Cpp',
7072 'c# c-sharp csharp CSharp',
7073 'css Css',
7074 'delphi pascal Delphi',
7075 'diff patch pas Diff',
7076 'erl erlang Erlang',
7077 'groovy Groovy',
7078 'java Java',
7079 'jfx javafx JavaFX',
7080 'js jscript javascript JScript',
7081 'perl pl Perl',
7082 'php Php',
7083 'text plain Plain',
7084 'py python Python',
7085 'ruby rails ror rb Ruby',
7086 'scala Scala',
7087 'scm Scheme',
7088 'sql Sql',
7089 'vb vbnet Vb',
7090 'xml xhtml xslt html Xml') {
7091 my $lang = $language;
7092 $lang =~ s! (\S+)$! $brush_prefix$1!;
7093 print "'".$lang.qq!.js',!;
7095 print qq!''); SyntaxHighlighter.all();!
7096 .qq!function scrollTo(number) {!
7097 .qq! var elements = document.getElementsByClassName(number);!
7098 .qq! if (elements.length == 0) setTimeout('scrollTo("' + number + '");', 50);!
7099 .qq! else {!
7100 .qq! window.scroll(0, elements[0].offsetTop);!
7101 .qq! window.scrollTo(0, elements[0].offsetTop);!
7102 .qq! elements[0].style.color = '#ff0000';!
7103 .qq! }!
7104 .qq!}!
7105 .qq!var lineRegex = /#l(\\d+)\$/;!
7106 .qq!var lineNumber = lineRegex.exec(document.URL);!
7107 .qq!if (lineNumber)!
7108 .qq! scrollTo('number' + lineNumber[1]);!
7109 .qq!</script>!;
7110 } else {
7111 my $nr;
7112 while (my $line = <$fd>) {
7113 chomp $line;
7114 $nr++;
7115 $line = untabify($line);
7116 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7117 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7118 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7121 close $fd
7122 or print "Reading blob failed.\n";
7123 print "</div>";
7124 git_footer_html();
7127 sub git_tree {
7128 if (!defined $hash_base) {
7129 $hash_base = "HEAD";
7131 if (!defined $hash) {
7132 if (defined $file_name) {
7133 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7134 } else {
7135 $hash = $hash_base;
7138 die_error(404, "No such tree") unless defined($hash);
7140 my $show_sizes = gitweb_check_feature('show-sizes');
7141 my $have_blame = gitweb_check_feature('blame');
7143 my @entries = ();
7145 local $/ = "\0";
7146 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7147 ($show_sizes ? '-l' : ()), @extra_options, $hash
7148 or die_error(500, "Open git-ls-tree failed");
7149 @entries = map { chomp; $_ } <$fd>;
7150 close $fd
7151 or die_error(404, "Reading tree failed");
7154 my $refs = git_get_references();
7155 my $ref = format_ref_marker($refs, $hash_base);
7156 git_header_html();
7157 my $basedir = '';
7158 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7159 my @views_nav = ();
7160 if (defined $file_name) {
7161 push @views_nav,
7162 $cgi->a({-href => href(action=>"history", -replay=>1)},
7163 "history"),
7164 $cgi->a({-href => href(action=>"tree",
7165 hash_base=>"HEAD", file_name=>$file_name)},
7166 "HEAD"),
7168 my $snapshot_links = format_snapshot_links($hash);
7169 if (defined $snapshot_links) {
7170 # FIXME: Should be available when we have no hash base as well.
7171 push @views_nav, $snapshot_links;
7173 git_print_page_nav('tree','', $hash_base, undef, undef,
7174 join(' | ', @views_nav));
7175 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7176 } else {
7177 undef $hash_base;
7178 print "<div class=\"page_nav\">\n";
7179 print "<br/><br/></div>\n";
7180 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7182 if (defined $file_name) {
7183 $basedir = $file_name;
7184 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7185 $basedir .= '/';
7187 git_print_page_path($file_name, 'tree', $hash_base);
7189 print "<div class=\"page_body\">\n";
7190 print "<table class=\"tree\">\n";
7191 my $alternate = 1;
7192 # '..' (top directory) link if possible
7193 if (defined $hash_base &&
7194 defined $file_name && $file_name =~ m![^/]+$!) {
7195 if ($alternate) {
7196 print "<tr class=\"dark\">\n";
7197 } else {
7198 print "<tr class=\"light\">\n";
7200 $alternate ^= 1;
7202 my $up = $file_name;
7203 $up =~ s!/?[^/]+$!!;
7204 undef $up unless $up;
7205 # based on git_print_tree_entry
7206 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7207 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7208 print '<td class="list">';
7209 print $cgi->a({-href => href(action=>"tree",
7210 hash_base=>$hash_base,
7211 file_name=>$up)},
7212 "..");
7213 print "</td>\n";
7214 print "<td class=\"link\"></td>\n";
7216 print "</tr>\n";
7218 foreach my $line (@entries) {
7219 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7221 if ($alternate) {
7222 print "<tr class=\"dark\">\n";
7223 } else {
7224 print "<tr class=\"light\">\n";
7226 $alternate ^= 1;
7228 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7230 print "</tr>\n";
7232 print "</table>\n" .
7233 "</div>";
7234 git_footer_html();
7237 sub snapshot_name {
7238 my ($project, $hash) = @_;
7240 # path/to/project.git -> project
7241 # path/to/project/.git -> project
7242 my $name = to_utf8($project);
7243 $name =~ s,([^/])/*\.git$,$1,;
7244 $name = basename($name);
7245 # sanitize name
7246 $name =~ s/[[:cntrl:]]/?/g;
7248 my $ver = $hash;
7249 if ($hash =~ /^[0-9a-fA-F]+$/) {
7250 # shorten SHA-1 hash
7251 my $full_hash = git_get_full_hash($project, $hash);
7252 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7253 $ver = git_get_short_hash($project, $hash);
7255 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7256 # tags don't need shortened SHA-1 hash
7257 $ver = $1;
7258 } else {
7259 # branches and other need shortened SHA-1 hash
7260 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
7261 $ver = $1;
7263 $ver .= '-' . git_get_short_hash($project, $hash);
7265 # in case of hierarchical branch names
7266 $ver =~ s!/!.!g;
7268 # name = project-version_string
7269 $name = "$name-$ver";
7271 return wantarray ? ($name, $name) : $name;
7274 sub exit_if_unmodified_since {
7275 my ($latest_epoch) = @_;
7276 our $cgi;
7278 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7279 if (defined $if_modified) {
7280 my $since;
7281 if (eval { require HTTP::Date; 1; }) {
7282 $since = HTTP::Date::str2time($if_modified);
7283 } elsif (eval { require Time::ParseDate; 1; }) {
7284 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7286 if (defined $since && $latest_epoch <= $since) {
7287 my %latest_date = parse_date($latest_epoch);
7288 print $cgi->header(
7289 -last_modified => $latest_date{'rfc2822'},
7290 -status => '304 Not Modified');
7291 goto DONE_GITWEB;
7296 sub git_snapshot {
7297 my $format = $input_params{'snapshot_format'};
7298 if (!@snapshot_fmts) {
7299 die_error(403, "Snapshots not allowed");
7301 # default to first supported snapshot format
7302 $format ||= $snapshot_fmts[0];
7303 if ($format !~ m/^[a-z0-9]+$/) {
7304 die_error(400, "Invalid snapshot format parameter");
7305 } elsif (!exists($known_snapshot_formats{$format})) {
7306 die_error(400, "Unknown snapshot format");
7307 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7308 die_error(403, "Snapshot format not allowed");
7309 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7310 die_error(403, "Unsupported snapshot format");
7313 my $type = git_get_type("$hash^{}");
7314 if (!$type) {
7315 die_error(404, 'Object does not exist');
7316 } elsif ($type eq 'blob') {
7317 die_error(400, 'Object is not a tree-ish');
7320 my ($name, $prefix) = snapshot_name($project, $hash);
7321 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7323 my %co = parse_commit($hash);
7324 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7326 my $cmd = quote_command(
7327 git_cmd(), 'archive',
7328 "--format=$known_snapshot_formats{$format}{'format'}",
7329 "--prefix=$prefix/", $hash);
7330 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7331 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7334 $filename =~ s/(["\\])/\\$1/g;
7335 my %latest_date;
7336 if (%co) {
7337 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7340 print $cgi->header(
7341 -type => $known_snapshot_formats{$format}{'type'},
7342 -content_disposition => 'inline; filename="' . $filename . '"',
7343 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7344 -status => '200 OK');
7346 open my $fd, "-|", $cmd
7347 or die_error(500, "Execute git-archive failed");
7348 binmode STDOUT, ':raw';
7349 print <$fd>;
7350 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7351 close $fd;
7354 sub git_log_generic {
7355 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7357 my $head = git_get_head_hash($project);
7358 if (!defined $base) {
7359 $base = $head;
7361 if (!defined $page) {
7362 $page = 0;
7364 my $refs = git_get_references();
7366 my $commit_hash = $base;
7367 if (defined $parent) {
7368 $commit_hash = "$parent..$base";
7370 my @commitlist =
7371 parse_commits($commit_hash, 101, (100 * $page),
7372 defined $file_name ? ($file_name, "--full-history") : ());
7374 my $ftype;
7375 if (!defined $file_hash && defined $file_name) {
7376 # some commits could have deleted file in question,
7377 # and not have it in tree, but one of them has to have it
7378 for (my $i = 0; $i < @commitlist; $i++) {
7379 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7380 last if defined $file_hash;
7383 if (defined $file_hash) {
7384 $ftype = git_get_type($file_hash);
7386 if (defined $file_name && !defined $ftype) {
7387 die_error(500, "Unknown type of object");
7389 my %co;
7390 if (defined $file_name) {
7391 %co = parse_commit($base)
7392 or die_error(404, "Unknown commit object");
7396 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7397 my $next_link = '';
7398 if ($#commitlist >= 100) {
7399 $next_link =
7400 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7401 -accesskey => "n", -title => "Alt-n"}, "next");
7403 my $patch_max = gitweb_get_feature('patches');
7404 if ($patch_max && !defined $file_name) {
7405 if ($patch_max < 0 || @commitlist <= $patch_max) {
7406 $paging_nav .= " &sdot; " .
7407 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7408 "patches");
7412 git_header_html();
7413 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7414 if (defined $file_name) {
7415 git_print_header_div('commit', esc_html($co{'title'}), $base);
7416 } else {
7417 git_print_header_div('summary', $project)
7419 git_print_page_path($file_name, $ftype, $hash_base)
7420 if (defined $file_name);
7422 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7423 $file_name, $file_hash, $ftype);
7425 git_footer_html();
7428 sub git_log {
7429 git_log_generic('log', \&git_log_body,
7430 $hash, $hash_parent);
7433 sub git_commit {
7434 $hash ||= $hash_base || "HEAD";
7435 my %co = parse_commit($hash)
7436 or die_error(404, "Unknown commit object");
7438 my $parent = $co{'parent'};
7439 my $parents = $co{'parents'}; # listref
7441 # we need to prepare $formats_nav before any parameter munging
7442 my $formats_nav;
7443 if (!defined $parent) {
7444 # --root commitdiff
7445 $formats_nav .= '(initial)';
7446 } elsif (@$parents == 1) {
7447 # single parent commit
7448 $formats_nav .=
7449 '(parent: ' .
7450 $cgi->a({-href => href(action=>"commit",
7451 hash=>$parent)},
7452 esc_html(substr($parent, 0, 7))) .
7453 ')';
7454 } else {
7455 # merge commit
7456 $formats_nav .=
7457 '(merge: ' .
7458 join(' ', map {
7459 $cgi->a({-href => href(action=>"commit",
7460 hash=>$_)},
7461 esc_html(substr($_, 0, 7)));
7462 } @$parents ) .
7463 ')';
7465 if (gitweb_check_feature('patches') && @$parents <= 1) {
7466 $formats_nav .= " | " .
7467 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7468 "patch");
7471 if (!defined $parent) {
7472 $parent = "--root";
7474 my @difftree;
7475 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7476 @diff_opts,
7477 (@$parents <= 1 ? $parent : '-c'),
7478 $hash, "--"
7479 or die_error(500, "Open git-diff-tree failed");
7480 @difftree = map { chomp; $_ } <$fd>;
7481 close $fd or die_error(404, "Reading git-diff-tree failed");
7483 # non-textual hash id's can be cached
7484 my $expires;
7485 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7486 $expires = "+1d";
7488 my $refs = git_get_references();
7489 my $ref = format_ref_marker($refs, $co{'id'});
7491 git_header_html(undef, $expires);
7492 git_print_page_nav('commit', '',
7493 $hash, $co{'tree'}, $hash,
7494 $formats_nav);
7496 if (defined $co{'parent'}) {
7497 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7498 } else {
7499 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7501 print "<div class=\"title_text\">\n" .
7502 "<table class=\"object_header\">\n";
7503 git_print_authorship_rows(\%co);
7504 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7505 print "<tr>" .
7506 "<td>tree</td>" .
7507 "<td class=\"sha1\">" .
7508 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7509 class => "list"}, $co{'tree'}) .
7510 "</td>" .
7511 "<td class=\"link\">" .
7512 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7513 "tree");
7514 my $snapshot_links = format_snapshot_links($hash);
7515 if (defined $snapshot_links) {
7516 print " | " . $snapshot_links;
7518 print "</td>" .
7519 "</tr>\n";
7521 foreach my $par (@$parents) {
7522 print "<tr>" .
7523 "<td>parent</td>" .
7524 "<td class=\"sha1\">" .
7525 $cgi->a({-href => href(action=>"commit", hash=>$par),
7526 class => "list"}, $par) .
7527 "</td>" .
7528 "<td class=\"link\">" .
7529 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7530 " | " .
7531 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7532 "</td>" .
7533 "</tr>\n";
7535 print "</table>".
7536 "</div>\n";
7538 print "<div class=\"page_body\">\n";
7539 git_print_log($co{'comment'});
7540 print "</div>\n";
7542 git_difftree_body(\@difftree, $hash, @$parents);
7544 git_footer_html();
7547 sub git_object {
7548 # object is defined by:
7549 # - hash or hash_base alone
7550 # - hash_base and file_name
7551 my $type;
7553 # - hash or hash_base alone
7554 if ($hash || ($hash_base && !defined $file_name)) {
7555 my $object_id = $hash || $hash_base;
7557 open my $fd, "-|", quote_command(
7558 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7559 or die_error(404, "Object does not exist");
7560 $type = <$fd>;
7561 chomp $type;
7562 close $fd
7563 or die_error(404, "Object does not exist");
7565 # - hash_base and file_name
7566 } elsif ($hash_base && defined $file_name) {
7567 $file_name =~ s,/+$,,;
7569 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7570 or die_error(404, "Base object does not exist");
7572 # here errors should not hapen
7573 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7574 or die_error(500, "Open git-ls-tree failed");
7575 my $line = <$fd>;
7576 close $fd;
7578 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7579 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7580 die_error(404, "File or directory for given base does not exist");
7582 $type = $2;
7583 $hash = $3;
7584 } else {
7585 die_error(400, "Not enough information to find object");
7588 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7589 hash=>$hash, hash_base=>$hash_base,
7590 file_name=>$file_name),
7591 -status => '302 Found');
7594 sub git_blobdiff {
7595 my $format = shift || 'html';
7596 my $diff_style = $input_params{'diff_style'} || 'inline';
7598 my $fd;
7599 my @difftree;
7600 my %diffinfo;
7601 my $expires;
7603 # preparing $fd and %diffinfo for git_patchset_body
7604 # new style URI
7605 if (defined $hash_base && defined $hash_parent_base) {
7606 if (defined $file_name) {
7607 # read raw output
7608 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7609 $hash_parent_base, $hash_base,
7610 "--", (defined $file_parent ? $file_parent : ()), $file_name
7611 or die_error(500, "Open git-diff-tree failed");
7612 @difftree = map { chomp; $_ } <$fd>;
7613 close $fd
7614 or die_error(404, "Reading git-diff-tree failed");
7615 @difftree
7616 or die_error(404, "Blob diff not found");
7618 } elsif (defined $hash &&
7619 $hash =~ /[0-9a-fA-F]{40}/) {
7620 # try to find filename from $hash
7622 # read filtered raw output
7623 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7624 $hash_parent_base, $hash_base, "--"
7625 or die_error(500, "Open git-diff-tree failed");
7626 @difftree =
7627 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7628 # $hash == to_id
7629 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7630 map { chomp; $_ } <$fd>;
7631 close $fd
7632 or die_error(404, "Reading git-diff-tree failed");
7633 @difftree
7634 or die_error(404, "Blob diff not found");
7636 } else {
7637 die_error(400, "Missing one of the blob diff parameters");
7640 if (@difftree > 1) {
7641 die_error(400, "Ambiguous blob diff specification");
7644 %diffinfo = parse_difftree_raw_line($difftree[0]);
7645 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7646 $file_name ||= $diffinfo{'to_file'};
7648 $hash_parent ||= $diffinfo{'from_id'};
7649 $hash ||= $diffinfo{'to_id'};
7651 # non-textual hash id's can be cached
7652 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7653 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7654 $expires = '+1d';
7657 # open patch output
7658 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7659 '-p', ($format eq 'html' ? "--full-index" : ()),
7660 $hash_parent_base, $hash_base,
7661 "--", (defined $file_parent ? $file_parent : ()), $file_name
7662 or die_error(500, "Open git-diff-tree failed");
7665 # old/legacy style URI -- not generated anymore since 1.4.3.
7666 if (!%diffinfo) {
7667 die_error('404 Not Found', "Missing one of the blob diff parameters")
7670 # header
7671 if ($format eq 'html') {
7672 my $formats_nav =
7673 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7674 "raw");
7675 $formats_nav .= diff_style_nav($diff_style);
7676 git_header_html(undef, $expires);
7677 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7678 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7679 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7680 } else {
7681 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7682 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7684 if (defined $file_name) {
7685 git_print_page_path($file_name, "blob", $hash_base);
7686 } else {
7687 print "<div class=\"page_path\"></div>\n";
7690 } elsif ($format eq 'plain') {
7691 print $cgi->header(
7692 -type => 'text/plain',
7693 -charset => 'utf-8',
7694 -expires => $expires,
7695 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7697 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7699 } else {
7700 die_error(400, "Unknown blobdiff format");
7703 # patch
7704 if ($format eq 'html') {
7705 print "<div class=\"page_body\">\n";
7707 git_patchset_body($fd, $diff_style,
7708 [ \%diffinfo ], $hash_base, $hash_parent_base);
7709 close $fd;
7711 print "</div>\n"; # class="page_body"
7712 git_footer_html();
7714 } else {
7715 while (my $line = <$fd>) {
7716 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7717 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7719 print $line;
7721 last if $line =~ m!^\+\+\+!;
7723 local $/ = undef;
7724 print <$fd>;
7725 close $fd;
7729 sub git_blobdiff_plain {
7730 git_blobdiff('plain');
7733 # assumes that it is added as later part of already existing navigation,
7734 # so it returns "| foo | bar" rather than just "foo | bar"
7735 sub diff_style_nav {
7736 my ($diff_style, $is_combined) = @_;
7737 $diff_style ||= 'inline';
7739 return "" if ($is_combined);
7741 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7742 my %styles = @styles;
7743 @styles =
7744 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7746 return join '',
7747 map { " | ".$_ }
7748 map {
7749 $_ eq $diff_style ? $styles{$_} :
7750 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7751 } @styles;
7754 sub git_commitdiff {
7755 my %params = @_;
7756 my $format = $params{-format} || 'html';
7757 my $diff_style = $input_params{'diff_style'} || 'inline';
7759 my ($patch_max) = gitweb_get_feature('patches');
7760 if ($format eq 'patch') {
7761 die_error(403, "Patch view not allowed") unless $patch_max;
7764 $hash ||= $hash_base || "HEAD";
7765 my %co = parse_commit($hash)
7766 or die_error(404, "Unknown commit object");
7768 # choose format for commitdiff for merge
7769 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7770 $hash_parent = '--cc';
7772 # we need to prepare $formats_nav before almost any parameter munging
7773 my $formats_nav;
7774 if ($format eq 'html') {
7775 $formats_nav =
7776 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7777 "raw");
7778 if ($patch_max && @{$co{'parents'}} <= 1) {
7779 $formats_nav .= " | " .
7780 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7781 "patch");
7783 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7785 if (defined $hash_parent &&
7786 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7787 # commitdiff with two commits given
7788 my $hash_parent_short = $hash_parent;
7789 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7790 $hash_parent_short = substr($hash_parent, 0, 7);
7792 $formats_nav .=
7793 ' (from';
7794 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7795 if ($co{'parents'}[$i] eq $hash_parent) {
7796 $formats_nav .= ' parent ' . ($i+1);
7797 last;
7800 $formats_nav .= ': ' .
7801 $cgi->a({-href => href(-replay=>1,
7802 hash=>$hash_parent, hash_base=>undef)},
7803 esc_html($hash_parent_short)) .
7804 ')';
7805 } elsif (!$co{'parent'}) {
7806 # --root commitdiff
7807 $formats_nav .= ' (initial)';
7808 } elsif (scalar @{$co{'parents'}} == 1) {
7809 # single parent commit
7810 $formats_nav .=
7811 ' (parent: ' .
7812 $cgi->a({-href => href(-replay=>1,
7813 hash=>$co{'parent'}, hash_base=>undef)},
7814 esc_html(substr($co{'parent'}, 0, 7))) .
7815 ')';
7816 } else {
7817 # merge commit
7818 if ($hash_parent eq '--cc') {
7819 $formats_nav .= ' | ' .
7820 $cgi->a({-href => href(-replay=>1,
7821 hash=>$hash, hash_parent=>'-c')},
7822 'combined');
7823 } else { # $hash_parent eq '-c'
7824 $formats_nav .= ' | ' .
7825 $cgi->a({-href => href(-replay=>1,
7826 hash=>$hash, hash_parent=>'--cc')},
7827 'compact');
7829 $formats_nav .=
7830 ' (merge: ' .
7831 join(' ', map {
7832 $cgi->a({-href => href(-replay=>1,
7833 hash=>$_, hash_base=>undef)},
7834 esc_html(substr($_, 0, 7)));
7835 } @{$co{'parents'}} ) .
7836 ')';
7840 my $hash_parent_param = $hash_parent;
7841 if (!defined $hash_parent_param) {
7842 # --cc for multiple parents, --root for parentless
7843 $hash_parent_param =
7844 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7847 # read commitdiff
7848 my $fd;
7849 my @difftree;
7850 if ($format eq 'html') {
7851 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7852 "--no-commit-id", "--patch-with-raw", "--full-index",
7853 $hash_parent_param, $hash, "--"
7854 or die_error(500, "Open git-diff-tree failed");
7856 while (my $line = <$fd>) {
7857 chomp $line;
7858 # empty line ends raw part of diff-tree output
7859 last unless $line;
7860 push @difftree, scalar parse_difftree_raw_line($line);
7863 } elsif ($format eq 'plain') {
7864 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7865 '-p', $hash_parent_param, $hash, "--"
7866 or die_error(500, "Open git-diff-tree failed");
7867 } elsif ($format eq 'patch') {
7868 # For commit ranges, we limit the output to the number of
7869 # patches specified in the 'patches' feature.
7870 # For single commits, we limit the output to a single patch,
7871 # diverging from the git-format-patch default.
7872 my @commit_spec = ();
7873 if ($hash_parent) {
7874 if ($patch_max > 0) {
7875 push @commit_spec, "-$patch_max";
7877 push @commit_spec, '-n', "$hash_parent..$hash";
7878 } else {
7879 if ($params{-single}) {
7880 push @commit_spec, '-1';
7881 } else {
7882 if ($patch_max > 0) {
7883 push @commit_spec, "-$patch_max";
7885 push @commit_spec, "-n";
7887 push @commit_spec, '--root', $hash;
7889 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7890 '--encoding=utf8', '--stdout', @commit_spec
7891 or die_error(500, "Open git-format-patch failed");
7892 } else {
7893 die_error(400, "Unknown commitdiff format");
7896 # non-textual hash id's can be cached
7897 my $expires;
7898 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7899 $expires = "+1d";
7902 # write commit message
7903 if ($format eq 'html') {
7904 my $refs = git_get_references();
7905 my $ref = format_ref_marker($refs, $co{'id'});
7907 git_header_html(undef, $expires);
7908 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7909 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7910 print "<div class=\"title_text\">\n" .
7911 "<table class=\"object_header\">\n";
7912 git_print_authorship_rows(\%co);
7913 print "</table>".
7914 "</div>\n";
7915 print "<div class=\"page_body\">\n";
7916 if (@{$co{'comment'}} > 1) {
7917 print "<div class=\"log\">\n";
7918 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7919 print "</div>\n"; # class="log"
7922 } elsif ($format eq 'plain') {
7923 my $refs = git_get_references("tags");
7924 my $tagname = git_get_rev_name_tags($hash);
7925 my $filename = basename($project) . "-$hash.patch";
7927 print $cgi->header(
7928 -type => 'text/plain',
7929 -charset => 'utf-8',
7930 -expires => $expires,
7931 -content_disposition => 'inline; filename="' . "$filename" . '"');
7932 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7933 print "From: " . to_utf8($co{'author'}) . "\n";
7934 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7935 print "Subject: " . to_utf8($co{'title'}) . "\n";
7937 print "X-Git-Tag: $tagname\n" if $tagname;
7938 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7940 foreach my $line (@{$co{'comment'}}) {
7941 print to_utf8($line) . "\n";
7943 print "---\n\n";
7944 } elsif ($format eq 'patch') {
7945 my $filename = basename($project) . "-$hash.patch";
7947 print $cgi->header(
7948 -type => 'text/plain',
7949 -charset => 'utf-8',
7950 -expires => $expires,
7951 -content_disposition => 'inline; filename="' . "$filename" . '"');
7954 # write patch
7955 if ($format eq 'html') {
7956 my $use_parents = !defined $hash_parent ||
7957 $hash_parent eq '-c' || $hash_parent eq '--cc';
7958 git_difftree_body(\@difftree, $hash,
7959 $use_parents ? @{$co{'parents'}} : $hash_parent);
7960 print "<br/>\n";
7962 git_patchset_body($fd, $diff_style,
7963 \@difftree, $hash,
7964 $use_parents ? @{$co{'parents'}} : $hash_parent);
7965 close $fd;
7966 print "</div>\n"; # class="page_body"
7967 git_footer_html();
7969 } elsif ($format eq 'plain') {
7970 local $/ = undef;
7971 print <$fd>;
7972 close $fd
7973 or print "Reading git-diff-tree failed\n";
7974 } elsif ($format eq 'patch') {
7975 local $/ = undef;
7976 print <$fd>;
7977 close $fd
7978 or print "Reading git-format-patch failed\n";
7982 sub git_commitdiff_plain {
7983 git_commitdiff(-format => 'plain');
7986 # format-patch-style patches
7987 sub git_patch {
7988 git_commitdiff(-format => 'patch', -single => 1);
7991 sub git_patches {
7992 git_commitdiff(-format => 'patch');
7995 sub git_history {
7996 git_log_generic('history', \&git_history_body,
7997 $hash_base, $hash_parent_base,
7998 $file_name, $hash);
8001 sub git_search {
8002 $searchtype ||= 'commit';
8004 # check if appropriate features are enabled
8005 gitweb_check_feature('search')
8006 or die_error(403, "Search is disabled");
8007 if ($searchtype eq 'pickaxe') {
8008 # pickaxe may take all resources of your box and run for several minutes
8009 # with every query - so decide by yourself how public you make this feature
8010 gitweb_check_feature('pickaxe')
8011 or die_error(403, "Pickaxe search is disabled");
8013 if ($searchtype eq 'grep') {
8014 # grep search might be potentially CPU-intensive, too
8015 gitweb_check_feature('grep')
8016 or die_error(403, "Grep search is disabled");
8019 if (!defined $searchtext) {
8020 die_error(400, "Text field is empty");
8022 if (!defined $hash) {
8023 $hash = git_get_head_hash($project);
8025 my %co = parse_commit($hash);
8026 if (!%co) {
8027 die_error(404, "Unknown commit object");
8029 if (!defined $page) {
8030 $page = 0;
8033 if ($searchtype eq 'commit' ||
8034 $searchtype eq 'author' ||
8035 $searchtype eq 'committer') {
8036 git_search_message(%co);
8037 } elsif ($searchtype eq 'pickaxe') {
8038 git_search_changes(%co);
8039 } elsif ($searchtype eq 'grep') {
8040 git_search_files(%co);
8041 } else {
8042 die_error(400, "Unknown search type");
8046 sub git_search_help {
8047 git_header_html();
8048 git_print_page_nav('','', $hash,$hash,$hash);
8049 print <<EOT;
8050 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8051 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8052 the pattern entered is recognized as the POSIX extended
8053 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8054 insensitive).</p>
8055 <dl>
8056 <dt><b>commit</b></dt>
8057 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8059 my $have_grep = gitweb_check_feature('grep');
8060 if ($have_grep) {
8061 print <<EOT;
8062 <dt><b>grep</b></dt>
8063 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8064 a different one) are searched for the given pattern. On large trees, this search can take
8065 a while and put some strain on the server, so please use it with some consideration. Note that
8066 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8067 case-sensitive.</dd>
8070 print <<EOT;
8071 <dt><b>author</b></dt>
8072 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8073 <dt><b>committer</b></dt>
8074 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8076 my $have_pickaxe = gitweb_check_feature('pickaxe');
8077 if ($have_pickaxe) {
8078 print <<EOT;
8079 <dt><b>pickaxe</b></dt>
8080 <dd>All commits that caused the string to appear or disappear from any file (changes that
8081 added, removed or "modified" the string) will be listed. This search can take a while and
8082 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8083 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8086 print "</dl>\n";
8087 git_footer_html();
8090 sub git_shortlog {
8091 git_log_generic('shortlog', \&git_shortlog_body,
8092 $hash, $hash_parent);
8095 ## ......................................................................
8096 ## feeds (RSS, Atom; OPML)
8098 sub git_feed {
8099 my $format = shift || 'atom';
8100 my $have_blame = gitweb_check_feature('blame');
8102 # Atom: http://www.atomenabled.org/developers/syndication/
8103 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8104 if ($format ne 'rss' && $format ne 'atom') {
8105 die_error(400, "Unknown web feed format");
8108 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8109 my $head = $hash || 'HEAD';
8110 my @commitlist = parse_commits($head, 150, 0, $file_name);
8112 my %latest_commit;
8113 my %latest_date;
8114 my $content_type = "application/$format+xml";
8115 if (defined $cgi->http('HTTP_ACCEPT') &&
8116 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8117 # browser (feed reader) prefers text/xml
8118 $content_type = 'text/xml';
8120 if (defined($commitlist[0])) {
8121 %latest_commit = %{$commitlist[0]};
8122 my $latest_epoch = $latest_commit{'committer_epoch'};
8123 exit_if_unmodified_since($latest_epoch);
8124 %latest_date = parse_date($latest_epoch, $latest_commit{'comitter_tz'});
8126 print $cgi->header(
8127 -type => $content_type,
8128 -charset => 'utf-8',
8129 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8130 -status => '200 OK');
8132 # Optimization: skip generating the body if client asks only
8133 # for Last-Modified date.
8134 return if ($cgi->request_method() eq 'HEAD');
8136 # header variables
8137 my $title = "$site_name - $project/$action";
8138 my $feed_type = 'log';
8139 if (defined $hash) {
8140 $title .= " - '$hash'";
8141 $feed_type = 'branch log';
8142 if (defined $file_name) {
8143 $title .= " :: $file_name";
8144 $feed_type = 'history';
8146 } elsif (defined $file_name) {
8147 $title .= " - $file_name";
8148 $feed_type = 'history';
8150 $title .= " $feed_type";
8151 my $descr = git_get_project_description($project);
8152 if (defined $descr) {
8153 $descr = esc_html($descr);
8154 } else {
8155 $descr = "$project " .
8156 ($format eq 'rss' ? 'RSS' : 'Atom') .
8157 " feed";
8159 my $owner = git_get_project_owner($project);
8160 $owner = esc_html($owner);
8162 #header
8163 my $alt_url;
8164 if (defined $file_name) {
8165 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8166 } elsif (defined $hash) {
8167 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8168 } else {
8169 $alt_url = href(-full=>1, action=>"summary");
8171 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8172 if ($format eq 'rss') {
8173 print <<XML;
8174 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8175 <channel>
8177 print "<title>$title</title>\n" .
8178 "<link>$alt_url</link>\n" .
8179 "<description>$descr</description>\n" .
8180 "<language>en</language>\n" .
8181 # project owner is responsible for 'editorial' content
8182 "<managingEditor>$owner</managingEditor>\n";
8183 if (defined $logo || defined $favicon) {
8184 # prefer the logo to the favicon, since RSS
8185 # doesn't allow both
8186 my $img = esc_url($logo || $favicon);
8187 print "<image>\n" .
8188 "<url>$img</url>\n" .
8189 "<title>$title</title>\n" .
8190 "<link>$alt_url</link>\n" .
8191 "</image>\n";
8193 if (%latest_date) {
8194 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8195 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8197 print "<generator>gitweb v.$version/$git_version</generator>\n";
8198 } elsif ($format eq 'atom') {
8199 print <<XML;
8200 <feed xmlns="http://www.w3.org/2005/Atom">
8202 print "<title>$title</title>\n" .
8203 "<subtitle>$descr</subtitle>\n" .
8204 '<link rel="alternate" type="text/html" href="' .
8205 $alt_url . '" />' . "\n" .
8206 '<link rel="self" type="' . $content_type . '" href="' .
8207 $cgi->self_url() . '" />' . "\n" .
8208 "<id>" . href(-full=>1) . "</id>\n" .
8209 # use project owner for feed author
8210 "<author><name>$owner</name></author>\n";
8211 if (defined $favicon) {
8212 print "<icon>" . esc_url($favicon) . "</icon>\n";
8214 if (defined $logo) {
8215 # not twice as wide as tall: 72 x 27 pixels
8216 print "<logo>" . esc_url($logo) . "</logo>\n";
8218 if (! %latest_date) {
8219 # dummy date to keep the feed valid until commits trickle in:
8220 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8221 } else {
8222 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8224 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8227 # contents
8228 for (my $i = 0; $i <= $#commitlist; $i++) {
8229 my %co = %{$commitlist[$i]};
8230 my $commit = $co{'id'};
8231 # we read 150, we always show 30 and the ones more recent than 48 hours
8232 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8233 last;
8235 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8237 # get list of changed files
8238 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8239 $co{'parent'} || "--root",
8240 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8241 or next;
8242 my @difftree = map { chomp; $_ } <$fd>;
8243 close $fd
8244 or next;
8246 # print element (entry, item)
8247 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8248 if ($format eq 'rss') {
8249 print "<item>\n" .
8250 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8251 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8252 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8253 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8254 "<link>$co_url</link>\n" .
8255 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8256 "<content:encoded>" .
8257 "<![CDATA[\n";
8258 } elsif ($format eq 'atom') {
8259 print "<entry>\n" .
8260 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8261 "<updated>$cd{'iso-8601'}</updated>\n" .
8262 "<author>\n" .
8263 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8264 if ($co{'author_email'}) {
8265 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8267 print "</author>\n" .
8268 # use committer for contributor
8269 "<contributor>\n" .
8270 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8271 if ($co{'committer_email'}) {
8272 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8274 print "</contributor>\n" .
8275 "<published>$cd{'iso-8601'}</published>\n" .
8276 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8277 "<id>$co_url</id>\n" .
8278 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8279 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8281 my $comment = $co{'comment'};
8282 print "<pre>\n";
8283 foreach my $line (@$comment) {
8284 $line = esc_html($line);
8285 print "$line\n";
8287 print "</pre><ul>\n";
8288 foreach my $difftree_line (@difftree) {
8289 my %difftree = parse_difftree_raw_line($difftree_line);
8290 next if !$difftree{'from_id'};
8292 my $file = $difftree{'file'} || $difftree{'to_file'};
8294 print "<li>" .
8295 "[" .
8296 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8297 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8298 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8299 file_name=>$file, file_parent=>$difftree{'from_file'}),
8300 -title => "diff"}, 'D');
8301 if ($have_blame) {
8302 print $cgi->a({-href => href(-full=>1, action=>"blame",
8303 file_name=>$file, hash_base=>$commit),
8304 -title => "blame"}, 'B');
8306 # if this is not a feed of a file history
8307 if (!defined $file_name || $file_name ne $file) {
8308 print $cgi->a({-href => href(-full=>1, action=>"history",
8309 file_name=>$file, hash=>$commit),
8310 -title => "history"}, 'H');
8312 $file = esc_path($file);
8313 print "] ".
8314 "$file</li>\n";
8316 if ($format eq 'rss') {
8317 print "</ul>]]>\n" .
8318 "</content:encoded>\n" .
8319 "</item>\n";
8320 } elsif ($format eq 'atom') {
8321 print "</ul>\n</div>\n" .
8322 "</content>\n" .
8323 "</entry>\n";
8327 # end of feed
8328 if ($format eq 'rss') {
8329 print "</channel>\n</rss>\n";
8330 } elsif ($format eq 'atom') {
8331 print "</feed>\n";
8335 sub git_rss {
8336 git_feed('rss');
8339 sub git_atom {
8340 git_feed('atom');
8343 sub git_opml {
8344 my @list = git_get_projects_list($project_filter, $strict_export);
8345 if (!@list) {
8346 die_error(404, "No projects found");
8349 print $cgi->header(
8350 -type => 'text/xml',
8351 -charset => 'utf-8',
8352 -content_disposition => 'inline; filename="opml.xml"');
8354 my $title = esc_html($site_name);
8355 my $filter = " within subdirectory ";
8356 if (defined $project_filter) {
8357 $filter .= esc_html($project_filter);
8358 } else {
8359 $filter = "";
8361 print <<XML;
8362 <?xml version="1.0" encoding="utf-8"?>
8363 <opml version="1.0">
8364 <head>
8365 <title>$title OPML Export$filter</title>
8366 </head>
8367 <body>
8368 <outline text="git RSS feeds">
8371 foreach my $pr (@list) {
8372 my %proj = %$pr;
8373 my $head = git_get_head_hash($proj{'path'});
8374 if (!defined $head) {
8375 next;
8377 $git_dir = "$projectroot/$proj{'path'}";
8378 my %co = parse_commit($head);
8379 if (!%co) {
8380 next;
8383 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8384 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8385 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8386 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8388 print <<XML;
8389 </outline>
8390 </body>
8391 </opml>