Merge branch 'jn/maint-gitweb-pathinfo-fix' into next
[git/srabbelier.git] / gitweb / gitweb.perl
blob608d0dd21204a9f3111843521fe09c9dcd85f699
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use 5.008;
11 use strict;
12 use warnings;
13 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
16 use Encode;
17 use Fcntl ':mode';
18 use File::Find qw();
19 use File::Basename qw(basename);
20 use Time::HiRes qw(gettimeofday tv_interval);
21 binmode STDOUT, ':utf8';
23 our $t0 = [ gettimeofday() ];
24 our $number_of_git_cmds = 0;
26 BEGIN {
27 CGI->compile() if $ENV{'MOD_PERL'};
30 our $version = "++GIT_VERSION++";
32 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
33 sub evaluate_uri {
34 our $cgi;
36 our $my_url = $cgi->url();
37 our $my_uri = $cgi->url(-absolute => 1);
39 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
40 # needed and used only for URLs with nonempty PATH_INFO
41 our $base_url = $my_url;
43 # When the script is used as DirectoryIndex, the URL does not contain the name
44 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
45 # have to do it ourselves. We make $path_info global because it's also used
46 # later on.
48 # Another issue with the script being the DirectoryIndex is that the resulting
49 # $my_url data is not the full script URL: this is good, because we want
50 # generated links to keep implying the script name if it wasn't explicitly
51 # indicated in the URL we're handling, but it means that $my_url cannot be used
52 # as base URL.
53 # Therefore, if we needed to strip PATH_INFO, then we know that we have
54 # to build the base URL ourselves:
55 our $path_info = $ENV{"PATH_INFO"};
56 if ($path_info) {
57 if ($my_url =~ s,\Q$path_info\E$,, &&
58 $my_uri =~ s,\Q$path_info\E$,, &&
59 defined $ENV{'SCRIPT_NAME'}) {
60 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
64 # target of the home link on top of all pages
65 our $home_link = $my_uri || "/";
68 # core git executable to use
69 # this can just be "git" if your webserver has a sensible PATH
70 our $GIT = "++GIT_BINDIR++/git";
72 # absolute fs-path which will be prepended to the project path
73 #our $projectroot = "/pub/scm";
74 our $projectroot = "++GITWEB_PROJECTROOT++";
76 # fs traversing limit for getting project list
77 # the number is relative to the projectroot
78 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
80 # string of the home link on top of all pages
81 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
83 # name of your site or organization to appear in page titles
84 # replace this with something more descriptive for clearer bookmarks
85 our $site_name = "++GITWEB_SITENAME++"
86 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
88 # filename of html text to include at top of each page
89 our $site_header = "++GITWEB_SITE_HEADER++";
90 # html text to include at home page
91 our $home_text = "++GITWEB_HOMETEXT++";
92 # filename of html text to include at bottom of each page
93 our $site_footer = "++GITWEB_SITE_FOOTER++";
95 # URI of stylesheets
96 our @stylesheets = ("++GITWEB_CSS++");
97 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
98 our $stylesheet = undef;
99 # URI of GIT logo (72x27 size)
100 our $logo = "++GITWEB_LOGO++";
101 # URI of GIT favicon, assumed to be image/png type
102 our $favicon = "++GITWEB_FAVICON++";
103 # URI of gitweb.js (JavaScript code for gitweb)
104 our $javascript = "++GITWEB_JS++";
106 # URI and label (title) of GIT logo link
107 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
108 #our $logo_label = "git documentation";
109 our $logo_url = "http://git-scm.com/";
110 our $logo_label = "git homepage";
112 # source of projects list
113 our $projects_list = "++GITWEB_LIST++";
115 # the width (in characters) of the projects list "Description" column
116 our $projects_list_description_width = 25;
118 # default order of projects list
119 # valid values are none, project, descr, owner, and age
120 our $default_projects_order = "project";
122 # show repository only if this file exists
123 # (only effective if this variable evaluates to true)
124 our $export_ok = "++GITWEB_EXPORT_OK++";
126 # show repository only if this subroutine returns true
127 # when given the path to the project, for example:
128 # sub { return -e "$_[0]/git-daemon-export-ok"; }
129 our $export_auth_hook = undef;
131 # only allow viewing of repositories also shown on the overview page
132 our $strict_export = "++GITWEB_STRICT_EXPORT++";
134 # list of git base URLs used for URL to where fetch project from,
135 # i.e. full URL is "$git_base_url/$project"
136 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
138 # default blob_plain mimetype and default charset for text/plain blob
139 our $default_blob_plain_mimetype = 'text/plain';
140 our $default_text_plain_charset = undef;
142 # file to use for guessing MIME types before trying /etc/mime.types
143 # (relative to the current git repository)
144 our $mimetypes_file = undef;
146 # assume this charset if line contains non-UTF-8 characters;
147 # it should be valid encoding (see Encoding::Supported(3pm) for list),
148 # for which encoding all byte sequences are valid, for example
149 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
150 # could be even 'utf-8' for the old behavior)
151 our $fallback_encoding = 'latin1';
153 # rename detection options for git-diff and git-diff-tree
154 # - default is '-M', with the cost proportional to
155 # (number of removed files) * (number of new files).
156 # - more costly is '-C' (which implies '-M'), with the cost proportional to
157 # (number of changed files + number of removed files) * (number of new files)
158 # - even more costly is '-C', '--find-copies-harder' with cost
159 # (number of files in the original tree) * (number of new files)
160 # - one might want to include '-B' option, e.g. '-B', '-M'
161 our @diff_opts = ('-M'); # taken from git_commit
163 # Disables features that would allow repository owners to inject script into
164 # the gitweb domain.
165 our $prevent_xss = 0;
167 # Path to the highlight executable to use (must be the one from
168 # http://www.andre-simon.de due to assumptions about parameters and output).
169 # Useful if highlight is not installed on your webserver's PATH.
170 # [Default: highlight]
171 our $highlight_bin = "++HIGHLIGHT_BIN++";
173 # information about snapshot formats that gitweb is capable of serving
174 our %known_snapshot_formats = (
175 # name => {
176 # 'display' => display name,
177 # 'type' => mime type,
178 # 'suffix' => filename suffix,
179 # 'format' => --format for git-archive,
180 # 'compressor' => [compressor command and arguments]
181 # (array reference, optional)
182 # 'disabled' => boolean (optional)}
184 'tgz' => {
185 'display' => 'tar.gz',
186 'type' => 'application/x-gzip',
187 'suffix' => '.tar.gz',
188 'format' => 'tar',
189 'compressor' => ['gzip']},
191 'tbz2' => {
192 'display' => 'tar.bz2',
193 'type' => 'application/x-bzip2',
194 'suffix' => '.tar.bz2',
195 'format' => 'tar',
196 'compressor' => ['bzip2']},
198 'txz' => {
199 'display' => 'tar.xz',
200 'type' => 'application/x-xz',
201 'suffix' => '.tar.xz',
202 'format' => 'tar',
203 'compressor' => ['xz'],
204 'disabled' => 1},
206 'zip' => {
207 'display' => 'zip',
208 'type' => 'application/x-zip',
209 'suffix' => '.zip',
210 'format' => 'zip'},
213 # Aliases so we understand old gitweb.snapshot values in repository
214 # configuration.
215 our %known_snapshot_format_aliases = (
216 'gzip' => 'tgz',
217 'bzip2' => 'tbz2',
218 'xz' => 'txz',
220 # backward compatibility: legacy gitweb config support
221 'x-gzip' => undef, 'gz' => undef,
222 'x-bzip2' => undef, 'bz2' => undef,
223 'x-zip' => undef, '' => undef,
226 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
227 # are changed, it may be appropriate to change these values too via
228 # $GITWEB_CONFIG.
229 our %avatar_size = (
230 'default' => 16,
231 'double' => 32
234 # Used to set the maximum load that we will still respond to gitweb queries.
235 # If server load exceed this value then return "503 server busy" error.
236 # If gitweb cannot determined server load, it is taken to be 0.
237 # Leave it undefined (or set to 'undef') to turn off load checking.
238 our $maxload = 300;
240 # configuration for 'highlight' (http://www.andre-simon.de/)
241 # match by basename
242 our %highlight_basename = (
243 #'Program' => 'py',
244 #'Library' => 'py',
245 'SConstruct' => 'py', # SCons equivalent of Makefile
246 'Makefile' => 'make',
248 # match by extension
249 our %highlight_ext = (
250 # main extensions, defining name of syntax;
251 # see files in /usr/share/highlight/langDefs/ directory
252 map { $_ => $_ }
253 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl),
254 # alternate extensions, see /etc/highlight/filetypes.conf
255 'h' => 'c',
256 map { $_ => 'cpp' } qw(cxx c++ cc),
257 map { $_ => 'php' } qw(php3 php4),
258 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
259 'mak' => 'make',
260 map { $_ => 'xml' } qw(xhtml html htm),
263 # You define site-wide feature defaults here; override them with
264 # $GITWEB_CONFIG as necessary.
265 our %feature = (
266 # feature => {
267 # 'sub' => feature-sub (subroutine),
268 # 'override' => allow-override (boolean),
269 # 'default' => [ default options...] (array reference)}
271 # if feature is overridable (it means that allow-override has true value),
272 # then feature-sub will be called with default options as parameters;
273 # return value of feature-sub indicates if to enable specified feature
275 # if there is no 'sub' key (no feature-sub), then feature cannot be
276 # overridden
278 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
279 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
280 # is enabled
282 # Enable the 'blame' blob view, showing the last commit that modified
283 # each line in the file. This can be very CPU-intensive.
285 # To enable system wide have in $GITWEB_CONFIG
286 # $feature{'blame'}{'default'} = [1];
287 # To have project specific config enable override in $GITWEB_CONFIG
288 # $feature{'blame'}{'override'} = 1;
289 # and in project config gitweb.blame = 0|1;
290 'blame' => {
291 'sub' => sub { feature_bool('blame', @_) },
292 'override' => 0,
293 'default' => [0]},
295 # Enable the 'snapshot' link, providing a compressed archive of any
296 # tree. This can potentially generate high traffic if you have large
297 # project.
299 # Value is a list of formats defined in %known_snapshot_formats that
300 # you wish to offer.
301 # To disable system wide have in $GITWEB_CONFIG
302 # $feature{'snapshot'}{'default'} = [];
303 # To have project specific config enable override in $GITWEB_CONFIG
304 # $feature{'snapshot'}{'override'} = 1;
305 # and in project config, a comma-separated list of formats or "none"
306 # to disable. Example: gitweb.snapshot = tbz2,zip;
307 'snapshot' => {
308 'sub' => \&feature_snapshot,
309 'override' => 0,
310 'default' => ['tgz']},
312 # Enable text search, which will list the commits which match author,
313 # committer or commit text to a given string. Enabled by default.
314 # Project specific override is not supported.
315 'search' => {
316 'override' => 0,
317 'default' => [1]},
319 # Enable grep search, which will list the files in currently selected
320 # tree containing the given string. Enabled by default. This can be
321 # potentially CPU-intensive, of course.
323 # To enable system wide have in $GITWEB_CONFIG
324 # $feature{'grep'}{'default'} = [1];
325 # To have project specific config enable override in $GITWEB_CONFIG
326 # $feature{'grep'}{'override'} = 1;
327 # and in project config gitweb.grep = 0|1;
328 'grep' => {
329 'sub' => sub { feature_bool('grep', @_) },
330 'override' => 0,
331 'default' => [1]},
333 # Enable the pickaxe search, which will list the commits that modified
334 # a given string in a file. This can be practical and quite faster
335 # alternative to 'blame', but still potentially CPU-intensive.
337 # To enable system wide have in $GITWEB_CONFIG
338 # $feature{'pickaxe'}{'default'} = [1];
339 # To have project specific config enable override in $GITWEB_CONFIG
340 # $feature{'pickaxe'}{'override'} = 1;
341 # and in project config gitweb.pickaxe = 0|1;
342 'pickaxe' => {
343 'sub' => sub { feature_bool('pickaxe', @_) },
344 'override' => 0,
345 'default' => [1]},
347 # Enable showing size of blobs in a 'tree' view, in a separate
348 # column, similar to what 'ls -l' does. This cost a bit of IO.
350 # To disable system wide have in $GITWEB_CONFIG
351 # $feature{'show-sizes'}{'default'} = [0];
352 # To have project specific config enable override in $GITWEB_CONFIG
353 # $feature{'show-sizes'}{'override'} = 1;
354 # and in project config gitweb.showsizes = 0|1;
355 'show-sizes' => {
356 'sub' => sub { feature_bool('showsizes', @_) },
357 'override' => 0,
358 'default' => [1]},
360 # Make gitweb use an alternative format of the URLs which can be
361 # more readable and natural-looking: project name is embedded
362 # directly in the path and the query string contains other
363 # auxiliary information. All gitweb installations recognize
364 # URL in either format; this configures in which formats gitweb
365 # generates links.
367 # To enable system wide have in $GITWEB_CONFIG
368 # $feature{'pathinfo'}{'default'} = [1];
369 # Project specific override is not supported.
371 # Note that you will need to change the default location of CSS,
372 # favicon, logo and possibly other files to an absolute URL. Also,
373 # if gitweb.cgi serves as your indexfile, you will need to force
374 # $my_uri to contain the script name in your $GITWEB_CONFIG.
375 'pathinfo' => {
376 'override' => 0,
377 'default' => [0]},
379 # Make gitweb consider projects in project root subdirectories
380 # to be forks of existing projects. Given project $projname.git,
381 # projects matching $projname/*.git will not be shown in the main
382 # projects list, instead a '+' mark will be added to $projname
383 # there and a 'forks' view will be enabled for the project, listing
384 # all the forks. If project list is taken from a file, forks have
385 # to be listed after the main project.
387 # To enable system wide have in $GITWEB_CONFIG
388 # $feature{'forks'}{'default'} = [1];
389 # Project specific override is not supported.
390 'forks' => {
391 'override' => 0,
392 'default' => [0]},
394 # Insert custom links to the action bar of all project pages.
395 # This enables you mainly to link to third-party scripts integrating
396 # into gitweb; e.g. git-browser for graphical history representation
397 # or custom web-based repository administration interface.
399 # The 'default' value consists of a list of triplets in the form
400 # (label, link, position) where position is the label after which
401 # to insert the link and link is a format string where %n expands
402 # to the project name, %f to the project path within the filesystem,
403 # %h to the current hash (h gitweb parameter) and %b to the current
404 # hash base (hb gitweb parameter); %% expands to %.
406 # To enable system wide have in $GITWEB_CONFIG e.g.
407 # $feature{'actions'}{'default'} = [('graphiclog',
408 # '/git-browser/by-commit.html?r=%n', 'summary')];
409 # Project specific override is not supported.
410 'actions' => {
411 'override' => 0,
412 'default' => []},
414 # Allow gitweb scan project content tags described in ctags/
415 # of project repository, and display the popular Web 2.0-ish
416 # "tag cloud" near the project list. Note that this is something
417 # COMPLETELY different from the normal Git tags.
419 # gitweb by itself can show existing tags, but it does not handle
420 # tagging itself; you need an external application for that.
421 # For an example script, check Girocco's cgi/tagproj.cgi.
422 # You may want to install the HTML::TagCloud Perl module to get
423 # a pretty tag cloud instead of just a list of tags.
425 # To enable system wide have in $GITWEB_CONFIG
426 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
427 # Project specific override is not supported.
428 'ctags' => {
429 'override' => 0,
430 'default' => [0]},
432 # The maximum number of patches in a patchset generated in patch
433 # view. Set this to 0 or undef to disable patch view, or to a
434 # negative number to remove any limit.
436 # To disable system wide have in $GITWEB_CONFIG
437 # $feature{'patches'}{'default'} = [0];
438 # To have project specific config enable override in $GITWEB_CONFIG
439 # $feature{'patches'}{'override'} = 1;
440 # and in project config gitweb.patches = 0|n;
441 # where n is the maximum number of patches allowed in a patchset.
442 'patches' => {
443 'sub' => \&feature_patches,
444 'override' => 0,
445 'default' => [16]},
447 # Avatar support. When this feature is enabled, views such as
448 # shortlog or commit will display an avatar associated with
449 # the email of the committer(s) and/or author(s).
451 # Currently available providers are gravatar and picon.
452 # If an unknown provider is specified, the feature is disabled.
454 # Gravatar depends on Digest::MD5.
455 # Picon currently relies on the indiana.edu database.
457 # To enable system wide have in $GITWEB_CONFIG
458 # $feature{'avatar'}{'default'} = ['<provider>'];
459 # where <provider> is either gravatar or picon.
460 # To have project specific config enable override in $GITWEB_CONFIG
461 # $feature{'avatar'}{'override'} = 1;
462 # and in project config gitweb.avatar = <provider>;
463 'avatar' => {
464 'sub' => \&feature_avatar,
465 'override' => 0,
466 'default' => ['']},
468 # Enable displaying how much time and how many git commands
469 # it took to generate and display page. Disabled by default.
470 # Project specific override is not supported.
471 'timed' => {
472 'override' => 0,
473 'default' => [0]},
475 # Enable turning some links into links to actions which require
476 # JavaScript to run (like 'blame_incremental'). Not enabled by
477 # default. Project specific override is currently not supported.
478 'javascript-actions' => {
479 'override' => 0,
480 'default' => [0]},
482 # Syntax highlighting support. This is based on Daniel Svensson's
483 # and Sham Chukoury's work in gitweb-xmms2.git.
484 # It requires the 'highlight' program present in $PATH,
485 # and therefore is disabled by default.
487 # To enable system wide have in $GITWEB_CONFIG
488 # $feature{'highlight'}{'default'} = [1];
490 'highlight' => {
491 'sub' => sub { feature_bool('highlight', @_) },
492 'override' => 0,
493 'default' => [0]},
495 # Enable displaying of remote heads in the heads list
497 # To enable system wide have in $GITWEB_CONFIG
498 # $feature{'remote_heads'}{'default'} = [1];
499 # To have project specific config enable override in $GITWEB_CONFIG
500 # $feature{'remote_heads'}{'override'} = 1;
501 # and in project config gitweb.remote_heads = 0|1;
502 'remote_heads' => {
503 'sub' => sub { feature_bool('remote_heads', @_) },
504 'override' => 0,
505 'default' => [0]},
508 sub gitweb_get_feature {
509 my ($name) = @_;
510 return unless exists $feature{$name};
511 my ($sub, $override, @defaults) = (
512 $feature{$name}{'sub'},
513 $feature{$name}{'override'},
514 @{$feature{$name}{'default'}});
515 # project specific override is possible only if we have project
516 our $git_dir; # global variable, declared later
517 if (!$override || !defined $git_dir) {
518 return @defaults;
520 if (!defined $sub) {
521 warn "feature $name is not overridable";
522 return @defaults;
524 return $sub->(@defaults);
527 # A wrapper to check if a given feature is enabled.
528 # With this, you can say
530 # my $bool_feat = gitweb_check_feature('bool_feat');
531 # gitweb_check_feature('bool_feat') or somecode;
533 # instead of
535 # my ($bool_feat) = gitweb_get_feature('bool_feat');
536 # (gitweb_get_feature('bool_feat'))[0] or somecode;
538 sub gitweb_check_feature {
539 return (gitweb_get_feature(@_))[0];
543 sub feature_bool {
544 my $key = shift;
545 my ($val) = git_get_project_config($key, '--bool');
547 if (!defined $val) {
548 return ($_[0]);
549 } elsif ($val eq 'true') {
550 return (1);
551 } elsif ($val eq 'false') {
552 return (0);
556 sub feature_snapshot {
557 my (@fmts) = @_;
559 my ($val) = git_get_project_config('snapshot');
561 if ($val) {
562 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
565 return @fmts;
568 sub feature_patches {
569 my @val = (git_get_project_config('patches', '--int'));
571 if (@val) {
572 return @val;
575 return ($_[0]);
578 sub feature_avatar {
579 my @val = (git_get_project_config('avatar'));
581 return @val ? @val : @_;
584 # checking HEAD file with -e is fragile if the repository was
585 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
586 # and then pruned.
587 sub check_head_link {
588 my ($dir) = @_;
589 my $headfile = "$dir/HEAD";
590 return ((-e $headfile) ||
591 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
594 sub check_export_ok {
595 my ($dir) = @_;
596 return (check_head_link($dir) &&
597 (!$export_ok || -e "$dir/$export_ok") &&
598 (!$export_auth_hook || $export_auth_hook->($dir)));
601 # process alternate names for backward compatibility
602 # filter out unsupported (unknown) snapshot formats
603 sub filter_snapshot_fmts {
604 my @fmts = @_;
606 @fmts = map {
607 exists $known_snapshot_format_aliases{$_} ?
608 $known_snapshot_format_aliases{$_} : $_} @fmts;
609 @fmts = grep {
610 exists $known_snapshot_formats{$_} &&
611 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
614 # If it is set to code reference, it is code that it is to be run once per
615 # request, allowing updating configurations that change with each request,
616 # while running other code in config file only once.
618 # Otherwise, if it is false then gitweb would process config file only once;
619 # if it is true then gitweb config would be run for each request.
620 our $per_request_config = 1;
622 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
623 sub evaluate_gitweb_config {
624 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
625 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
626 # die if there are errors parsing config file
627 if (-e $GITWEB_CONFIG) {
628 do $GITWEB_CONFIG;
629 die $@ if $@;
630 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
631 do $GITWEB_CONFIG_SYSTEM;
632 die $@ if $@;
636 # Get loadavg of system, to compare against $maxload.
637 # Currently it requires '/proc/loadavg' present to get loadavg;
638 # if it is not present it returns 0, which means no load checking.
639 sub get_loadavg {
640 if( -e '/proc/loadavg' ){
641 open my $fd, '<', '/proc/loadavg'
642 or return 0;
643 my @load = split(/\s+/, scalar <$fd>);
644 close $fd;
646 # The first three columns measure CPU and IO utilization of the last one,
647 # five, and 10 minute periods. The fourth column shows the number of
648 # currently running processes and the total number of processes in the m/n
649 # format. The last column displays the last process ID used.
650 return $load[0] || 0;
652 # additional checks for load average should go here for things that don't export
653 # /proc/loadavg
655 return 0;
658 # version of the core git binary
659 our $git_version;
660 sub evaluate_git_version {
661 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
662 $number_of_git_cmds++;
665 sub check_loadavg {
666 if (defined $maxload && get_loadavg() > $maxload) {
667 die_error(503, "The load average on the server is too high");
671 # ======================================================================
672 # input validation and dispatch
674 # input parameters can be collected from a variety of sources (presently, CGI
675 # and PATH_INFO), so we define an %input_params hash that collects them all
676 # together during validation: this allows subsequent uses (e.g. href()) to be
677 # agnostic of the parameter origin
679 our %input_params = ();
681 # input parameters are stored with the long parameter name as key. This will
682 # also be used in the href subroutine to convert parameters to their CGI
683 # equivalent, and since the href() usage is the most frequent one, we store
684 # the name -> CGI key mapping here, instead of the reverse.
686 # XXX: Warning: If you touch this, check the search form for updating,
687 # too.
689 our @cgi_param_mapping = (
690 project => "p",
691 action => "a",
692 file_name => "f",
693 file_parent => "fp",
694 hash => "h",
695 hash_parent => "hp",
696 hash_base => "hb",
697 hash_parent_base => "hpb",
698 page => "pg",
699 order => "o",
700 searchtext => "s",
701 searchtype => "st",
702 snapshot_format => "sf",
703 extra_options => "opt",
704 search_use_regexp => "sr",
705 # this must be last entry (for manipulation from JavaScript)
706 javascript => "js"
708 our %cgi_param_mapping = @cgi_param_mapping;
710 # we will also need to know the possible actions, for validation
711 our %actions = (
712 "blame" => \&git_blame,
713 "blame_incremental" => \&git_blame_incremental,
714 "blame_data" => \&git_blame_data,
715 "blobdiff" => \&git_blobdiff,
716 "blobdiff_plain" => \&git_blobdiff_plain,
717 "blob" => \&git_blob,
718 "blob_plain" => \&git_blob_plain,
719 "commitdiff" => \&git_commitdiff,
720 "commitdiff_plain" => \&git_commitdiff_plain,
721 "commit" => \&git_commit,
722 "forks" => \&git_forks,
723 "heads" => \&git_heads,
724 "history" => \&git_history,
725 "log" => \&git_log,
726 "patch" => \&git_patch,
727 "patches" => \&git_patches,
728 "remotes" => \&git_remotes,
729 "rss" => \&git_rss,
730 "atom" => \&git_atom,
731 "search" => \&git_search,
732 "search_help" => \&git_search_help,
733 "shortlog" => \&git_shortlog,
734 "summary" => \&git_summary,
735 "tag" => \&git_tag,
736 "tags" => \&git_tags,
737 "tree" => \&git_tree,
738 "snapshot" => \&git_snapshot,
739 "object" => \&git_object,
740 # those below don't need $project
741 "opml" => \&git_opml,
742 "project_list" => \&git_project_list,
743 "project_index" => \&git_project_index,
746 # finally, we have the hash of allowed extra_options for the commands that
747 # allow them
748 our %allowed_options = (
749 "--no-merges" => [ qw(rss atom log shortlog history) ],
752 # fill %input_params with the CGI parameters. All values except for 'opt'
753 # should be single values, but opt can be an array. We should probably
754 # build an array of parameters that can be multi-valued, but since for the time
755 # being it's only this one, we just single it out
756 sub evaluate_query_params {
757 our $cgi;
759 while (my ($name, $symbol) = each %cgi_param_mapping) {
760 if ($symbol eq 'opt') {
761 $input_params{$name} = [ $cgi->param($symbol) ];
762 } else {
763 $input_params{$name} = $cgi->param($symbol);
768 # now read PATH_INFO and update the parameter list for missing parameters
769 sub evaluate_path_info {
770 return if defined $input_params{'project'};
771 return if !$path_info;
772 $path_info =~ s,^/+,,;
773 return if !$path_info;
775 # find which part of PATH_INFO is project
776 my $project = $path_info;
777 $project =~ s,/+$,,;
778 while ($project && !check_head_link("$projectroot/$project")) {
779 $project =~ s,/*[^/]*$,,;
781 return unless $project;
782 $input_params{'project'} = $project;
784 # do not change any parameters if an action is given using the query string
785 return if $input_params{'action'};
786 $path_info =~ s,^\Q$project\E/*,,;
788 # next, check if we have an action
789 my $action = $path_info;
790 $action =~ s,/.*$,,;
791 if (exists $actions{$action}) {
792 $path_info =~ s,^$action/*,,;
793 $input_params{'action'} = $action;
796 # list of actions that want hash_base instead of hash, but can have no
797 # pathname (f) parameter
798 my @wants_base = (
799 'tree',
800 'history',
803 # we want to catch, among others
804 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
805 my ($parentrefname, $parentpathname, $refname, $pathname) =
806 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
808 # first, analyze the 'current' part
809 if (defined $pathname) {
810 # we got "branch:filename" or "branch:dir/"
811 # we could use git_get_type(branch:pathname), but:
812 # - it needs $git_dir
813 # - it does a git() call
814 # - the convention of terminating directories with a slash
815 # makes it superfluous
816 # - embedding the action in the PATH_INFO would make it even
817 # more superfluous
818 $pathname =~ s,^/+,,;
819 if (!$pathname || substr($pathname, -1) eq "/") {
820 $input_params{'action'} ||= "tree";
821 $pathname =~ s,/$,,;
822 } else {
823 # the default action depends on whether we had parent info
824 # or not
825 if ($parentrefname) {
826 $input_params{'action'} ||= "blobdiff_plain";
827 } else {
828 $input_params{'action'} ||= "blob_plain";
831 $input_params{'hash_base'} ||= $refname;
832 $input_params{'file_name'} ||= $pathname;
833 } elsif (defined $refname) {
834 # we got "branch". In this case we have to choose if we have to
835 # set hash or hash_base.
837 # Most of the actions without a pathname only want hash to be
838 # set, except for the ones specified in @wants_base that want
839 # hash_base instead. It should also be noted that hand-crafted
840 # links having 'history' as an action and no pathname or hash
841 # set will fail, but that happens regardless of PATH_INFO.
842 if (defined $parentrefname) {
843 # if there is parent let the default be 'shortlog' action
844 # (for http://git.example.com/repo.git/A..B links); if there
845 # is no parent, dispatch will detect type of object and set
846 # action appropriately if required (if action is not set)
847 $input_params{'action'} ||= "shortlog";
849 if ($input_params{'action'} &&
850 grep { $_ eq $input_params{'action'} } @wants_base) {
851 $input_params{'hash_base'} ||= $refname;
852 } else {
853 $input_params{'hash'} ||= $refname;
857 # next, handle the 'parent' part, if present
858 if (defined $parentrefname) {
859 # a missing pathspec defaults to the 'current' filename, allowing e.g.
860 # someproject/blobdiff/oldrev..newrev:/filename
861 if ($parentpathname) {
862 $parentpathname =~ s,^/+,,;
863 $parentpathname =~ s,/$,,;
864 $input_params{'file_parent'} ||= $parentpathname;
865 } else {
866 $input_params{'file_parent'} ||= $input_params{'file_name'};
868 # we assume that hash_parent_base is wanted if a path was specified,
869 # or if the action wants hash_base instead of hash
870 if (defined $input_params{'file_parent'} ||
871 grep { $_ eq $input_params{'action'} } @wants_base) {
872 $input_params{'hash_parent_base'} ||= $parentrefname;
873 } else {
874 $input_params{'hash_parent'} ||= $parentrefname;
878 # for the snapshot action, we allow URLs in the form
879 # $project/snapshot/$hash.ext
880 # where .ext determines the snapshot and gets removed from the
881 # passed $refname to provide the $hash.
883 # To be able to tell that $refname includes the format extension, we
884 # require the following two conditions to be satisfied:
885 # - the hash input parameter MUST have been set from the $refname part
886 # of the URL (i.e. they must be equal)
887 # - the snapshot format MUST NOT have been defined already (e.g. from
888 # CGI parameter sf)
889 # It's also useless to try any matching unless $refname has a dot,
890 # so we check for that too
891 if (defined $input_params{'action'} &&
892 $input_params{'action'} eq 'snapshot' &&
893 defined $refname && index($refname, '.') != -1 &&
894 $refname eq $input_params{'hash'} &&
895 !defined $input_params{'snapshot_format'}) {
896 # We loop over the known snapshot formats, checking for
897 # extensions. Allowed extensions are both the defined suffix
898 # (which includes the initial dot already) and the snapshot
899 # format key itself, with a prepended dot
900 while (my ($fmt, $opt) = each %known_snapshot_formats) {
901 my $hash = $refname;
902 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
903 next;
905 my $sfx = $1;
906 # a valid suffix was found, so set the snapshot format
907 # and reset the hash parameter
908 $input_params{'snapshot_format'} = $fmt;
909 $input_params{'hash'} = $hash;
910 # we also set the format suffix to the one requested
911 # in the URL: this way a request for e.g. .tgz returns
912 # a .tgz instead of a .tar.gz
913 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
914 last;
919 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
920 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
921 $searchtext, $search_regexp);
922 sub evaluate_and_validate_params {
923 our $action = $input_params{'action'};
924 if (defined $action) {
925 if (!validate_action($action)) {
926 die_error(400, "Invalid action parameter");
930 # parameters which are pathnames
931 our $project = $input_params{'project'};
932 if (defined $project) {
933 if (!validate_project($project)) {
934 undef $project;
935 die_error(404, "No such project");
939 our $file_name = $input_params{'file_name'};
940 if (defined $file_name) {
941 if (!validate_pathname($file_name)) {
942 die_error(400, "Invalid file parameter");
946 our $file_parent = $input_params{'file_parent'};
947 if (defined $file_parent) {
948 if (!validate_pathname($file_parent)) {
949 die_error(400, "Invalid file parent parameter");
953 # parameters which are refnames
954 our $hash = $input_params{'hash'};
955 if (defined $hash) {
956 if (!validate_refname($hash)) {
957 die_error(400, "Invalid hash parameter");
961 our $hash_parent = $input_params{'hash_parent'};
962 if (defined $hash_parent) {
963 if (!validate_refname($hash_parent)) {
964 die_error(400, "Invalid hash parent parameter");
968 our $hash_base = $input_params{'hash_base'};
969 if (defined $hash_base) {
970 if (!validate_refname($hash_base)) {
971 die_error(400, "Invalid hash base parameter");
975 our @extra_options = @{$input_params{'extra_options'}};
976 # @extra_options is always defined, since it can only be (currently) set from
977 # CGI, and $cgi->param() returns the empty array in array context if the param
978 # is not set
979 foreach my $opt (@extra_options) {
980 if (not exists $allowed_options{$opt}) {
981 die_error(400, "Invalid option parameter");
983 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
984 die_error(400, "Invalid option parameter for this action");
988 our $hash_parent_base = $input_params{'hash_parent_base'};
989 if (defined $hash_parent_base) {
990 if (!validate_refname($hash_parent_base)) {
991 die_error(400, "Invalid hash parent base parameter");
995 # other parameters
996 our $page = $input_params{'page'};
997 if (defined $page) {
998 if ($page =~ m/[^0-9]/) {
999 die_error(400, "Invalid page parameter");
1003 our $searchtype = $input_params{'searchtype'};
1004 if (defined $searchtype) {
1005 if ($searchtype =~ m/[^a-z]/) {
1006 die_error(400, "Invalid searchtype parameter");
1010 our $search_use_regexp = $input_params{'search_use_regexp'};
1012 our $searchtext = $input_params{'searchtext'};
1013 our $search_regexp;
1014 if (defined $searchtext) {
1015 if (length($searchtext) < 2) {
1016 die_error(403, "At least two characters are required for search parameter");
1018 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1022 # path to the current git repository
1023 our $git_dir;
1024 sub evaluate_git_dir {
1025 our $git_dir = "$projectroot/$project" if $project;
1028 our (@snapshot_fmts, $git_avatar);
1029 sub configure_gitweb_features {
1030 # list of supported snapshot formats
1031 our @snapshot_fmts = gitweb_get_feature('snapshot');
1032 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1034 # check that the avatar feature is set to a known provider name,
1035 # and for each provider check if the dependencies are satisfied.
1036 # if the provider name is invalid or the dependencies are not met,
1037 # reset $git_avatar to the empty string.
1038 our ($git_avatar) = gitweb_get_feature('avatar');
1039 if ($git_avatar eq 'gravatar') {
1040 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1041 } elsif ($git_avatar eq 'picon') {
1042 # no dependencies
1043 } else {
1044 $git_avatar = '';
1048 # custom error handler: 'die <message>' is Internal Server Error
1049 sub handle_errors_html {
1050 my $msg = shift; # it is already HTML escaped
1052 # to avoid infinite loop where error occurs in die_error,
1053 # change handler to default handler, disabling handle_errors_html
1054 set_message("Error occured when inside die_error:\n$msg");
1056 # you cannot jump out of die_error when called as error handler;
1057 # the subroutine set via CGI::Carp::set_message is called _after_
1058 # HTTP headers are already written, so it cannot write them itself
1059 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1061 set_message(\&handle_errors_html);
1063 # dispatch
1064 sub dispatch {
1065 if (!defined $action) {
1066 if (defined $hash) {
1067 $action = git_get_type($hash);
1068 } elsif (defined $hash_base && defined $file_name) {
1069 $action = git_get_type("$hash_base:$file_name");
1070 } elsif (defined $project) {
1071 $action = 'summary';
1072 } else {
1073 $action = 'project_list';
1076 if (!defined($actions{$action})) {
1077 die_error(400, "Unknown action");
1079 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1080 !$project) {
1081 die_error(400, "Project needed");
1083 $actions{$action}->();
1086 sub reset_timer {
1087 our $t0 = [ gettimeofday() ]
1088 if defined $t0;
1089 our $number_of_git_cmds = 0;
1092 our $first_request = 1;
1093 sub run_request {
1094 reset_timer();
1096 evaluate_uri();
1097 if ($first_request) {
1098 evaluate_gitweb_config();
1099 evaluate_git_version();
1101 if ($per_request_config) {
1102 if (ref($per_request_config) eq 'CODE') {
1103 $per_request_config->();
1104 } elsif (!$first_request) {
1105 evaluate_gitweb_config();
1108 check_loadavg();
1110 # $projectroot and $projects_list might be set in gitweb config file
1111 $projects_list ||= $projectroot;
1113 evaluate_query_params();
1114 evaluate_path_info();
1115 evaluate_and_validate_params();
1116 evaluate_git_dir();
1118 configure_gitweb_features();
1120 dispatch();
1123 our $is_last_request = sub { 1 };
1124 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1125 our $CGI = 'CGI';
1126 our $cgi;
1127 sub configure_as_fcgi {
1128 require CGI::Fast;
1129 our $CGI = 'CGI::Fast';
1131 my $request_number = 0;
1132 # let each child service 100 requests
1133 our $is_last_request = sub { ++$request_number > 100 };
1135 sub evaluate_argv {
1136 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1137 configure_as_fcgi()
1138 if $script_name =~ /\.fcgi$/;
1140 return unless (@ARGV);
1142 require Getopt::Long;
1143 Getopt::Long::GetOptions(
1144 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1145 'nproc|n=i' => sub {
1146 my ($arg, $val) = @_;
1147 return unless eval { require FCGI::ProcManager; 1; };
1148 my $proc_manager = FCGI::ProcManager->new({
1149 n_processes => $val,
1151 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1152 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1153 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1158 sub run {
1159 evaluate_argv();
1161 $first_request = 1;
1162 $pre_listen_hook->()
1163 if $pre_listen_hook;
1165 REQUEST:
1166 while ($cgi = $CGI->new()) {
1167 $pre_dispatch_hook->()
1168 if $pre_dispatch_hook;
1170 run_request();
1172 $post_dispatch_hook->()
1173 if $post_dispatch_hook;
1174 $first_request = 0;
1176 last REQUEST if ($is_last_request->());
1179 DONE_GITWEB:
1183 run();
1185 if (defined caller) {
1186 # wrapped in a subroutine processing requests,
1187 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1188 return;
1189 } else {
1190 # pure CGI script, serving single request
1191 exit;
1194 ## ======================================================================
1195 ## action links
1197 # possible values of extra options
1198 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1199 # -replay => 1 - start from a current view (replay with modifications)
1200 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1201 sub href {
1202 my %params = @_;
1203 # default is to use -absolute url() i.e. $my_uri
1204 my $href = $params{-full} ? $my_url : $my_uri;
1206 $params{'project'} = $project unless exists $params{'project'};
1208 if ($params{-replay}) {
1209 while (my ($name, $symbol) = each %cgi_param_mapping) {
1210 if (!exists $params{$name}) {
1211 $params{$name} = $input_params{$name};
1216 my $use_pathinfo = gitweb_check_feature('pathinfo');
1217 if (defined $params{'project'} &&
1218 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1219 # try to put as many parameters as possible in PATH_INFO:
1220 # - project name
1221 # - action
1222 # - hash_parent or hash_parent_base:/file_parent
1223 # - hash or hash_base:/filename
1224 # - the snapshot_format as an appropriate suffix
1226 # When the script is the root DirectoryIndex for the domain,
1227 # $href here would be something like http://gitweb.example.com/
1228 # Thus, we strip any trailing / from $href, to spare us double
1229 # slashes in the final URL
1230 $href =~ s,/$,,;
1232 # Then add the project name, if present
1233 $href .= "/".esc_path_info($params{'project'});
1234 delete $params{'project'};
1236 # since we destructively absorb parameters, we keep this
1237 # boolean that remembers if we're handling a snapshot
1238 my $is_snapshot = $params{'action'} eq 'snapshot';
1240 # Summary just uses the project path URL, any other action is
1241 # added to the URL
1242 if (defined $params{'action'}) {
1243 $href .= "/".esc_path_info($params{'action'})
1244 unless $params{'action'} eq 'summary';
1245 delete $params{'action'};
1248 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1249 # stripping nonexistent or useless pieces
1250 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1251 || $params{'hash_parent'} || $params{'hash'});
1252 if (defined $params{'hash_base'}) {
1253 if (defined $params{'hash_parent_base'}) {
1254 $href .= esc_path_info($params{'hash_parent_base'});
1255 # skip the file_parent if it's the same as the file_name
1256 if (defined $params{'file_parent'}) {
1257 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1258 delete $params{'file_parent'};
1259 } elsif ($params{'file_parent'} !~ /\.\./) {
1260 $href .= ":/".esc_path_info($params{'file_parent'});
1261 delete $params{'file_parent'};
1264 $href .= "..";
1265 delete $params{'hash_parent'};
1266 delete $params{'hash_parent_base'};
1267 } elsif (defined $params{'hash_parent'}) {
1268 $href .= esc_path_info($params{'hash_parent'}). "..";
1269 delete $params{'hash_parent'};
1272 $href .= esc_path_info($params{'hash_base'});
1273 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1274 $href .= ":/".esc_path_info($params{'file_name'});
1275 delete $params{'file_name'};
1277 delete $params{'hash'};
1278 delete $params{'hash_base'};
1279 } elsif (defined $params{'hash'}) {
1280 $href .= esc_path_info($params{'hash'});
1281 delete $params{'hash'};
1284 # If the action was a snapshot, we can absorb the
1285 # snapshot_format parameter too
1286 if ($is_snapshot) {
1287 my $fmt = $params{'snapshot_format'};
1288 # snapshot_format should always be defined when href()
1289 # is called, but just in case some code forgets, we
1290 # fall back to the default
1291 $fmt ||= $snapshot_fmts[0];
1292 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1293 delete $params{'snapshot_format'};
1297 # now encode the parameters explicitly
1298 my @result = ();
1299 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1300 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1301 if (defined $params{$name}) {
1302 if (ref($params{$name}) eq "ARRAY") {
1303 foreach my $par (@{$params{$name}}) {
1304 push @result, $symbol . "=" . esc_param($par);
1306 } else {
1307 push @result, $symbol . "=" . esc_param($params{$name});
1311 $href .= "?" . join(';', @result) if scalar @result;
1313 # final transformation: trailing spaces must be escaped (URI-encoded)
1314 $href =~ s/(\s+)$/CGI::escape($1)/e;
1316 return $href;
1320 ## ======================================================================
1321 ## validation, quoting/unquoting and escaping
1323 sub validate_action {
1324 my $input = shift || return undef;
1325 return undef unless exists $actions{$input};
1326 return $input;
1329 sub validate_project {
1330 my $input = shift || return undef;
1331 if (!validate_pathname($input) ||
1332 !(-d "$projectroot/$input") ||
1333 !check_export_ok("$projectroot/$input") ||
1334 ($strict_export && !project_in_list($input))) {
1335 return undef;
1336 } else {
1337 return $input;
1341 sub validate_pathname {
1342 my $input = shift || return undef;
1344 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1345 # at the beginning, at the end, and between slashes.
1346 # also this catches doubled slashes
1347 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1348 return undef;
1350 # no null characters
1351 if ($input =~ m!\0!) {
1352 return undef;
1354 return $input;
1357 sub validate_refname {
1358 my $input = shift || return undef;
1360 # textual hashes are O.K.
1361 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1362 return $input;
1364 # it must be correct pathname
1365 $input = validate_pathname($input)
1366 or return undef;
1367 # restrictions on ref name according to git-check-ref-format
1368 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1369 return undef;
1371 return $input;
1374 # decode sequences of octets in utf8 into Perl's internal form,
1375 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1376 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1377 sub to_utf8 {
1378 my $str = shift;
1379 return undef unless defined $str;
1380 if (utf8::valid($str)) {
1381 utf8::decode($str);
1382 return $str;
1383 } else {
1384 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1388 # quote unsafe chars, but keep the slash, even when it's not
1389 # correct, but quoted slashes look too horrible in bookmarks
1390 sub esc_param {
1391 my $str = shift;
1392 return undef unless defined $str;
1393 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1394 $str =~ s/ /\+/g;
1395 return $str;
1398 # the quoting rules for path_info fragment are slightly different
1399 sub esc_path_info {
1400 my $str = shift;
1401 return undef unless defined $str;
1403 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1404 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1406 return $str;
1409 # quote unsafe chars in whole URL, so some characters cannot be quoted
1410 sub esc_url {
1411 my $str = shift;
1412 return undef unless defined $str;
1413 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1414 $str =~ s/ /\+/g;
1415 return $str;
1418 # replace invalid utf8 character with SUBSTITUTION sequence
1419 sub esc_html {
1420 my $str = shift;
1421 my %opts = @_;
1423 return undef unless defined $str;
1425 $str = to_utf8($str);
1426 $str = $cgi->escapeHTML($str);
1427 if ($opts{'-nbsp'}) {
1428 $str =~ s/ /&nbsp;/g;
1430 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1431 return $str;
1434 # quote control characters and escape filename to HTML
1435 sub esc_path {
1436 my $str = shift;
1437 my %opts = @_;
1439 return undef unless defined $str;
1441 $str = to_utf8($str);
1442 $str = $cgi->escapeHTML($str);
1443 if ($opts{'-nbsp'}) {
1444 $str =~ s/ /&nbsp;/g;
1446 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1447 return $str;
1450 # Make control characters "printable", using character escape codes (CEC)
1451 sub quot_cec {
1452 my $cntrl = shift;
1453 my %opts = @_;
1454 my %es = ( # character escape codes, aka escape sequences
1455 "\t" => '\t', # tab (HT)
1456 "\n" => '\n', # line feed (LF)
1457 "\r" => '\r', # carrige return (CR)
1458 "\f" => '\f', # form feed (FF)
1459 "\b" => '\b', # backspace (BS)
1460 "\a" => '\a', # alarm (bell) (BEL)
1461 "\e" => '\e', # escape (ESC)
1462 "\013" => '\v', # vertical tab (VT)
1463 "\000" => '\0', # nul character (NUL)
1465 my $chr = ( (exists $es{$cntrl})
1466 ? $es{$cntrl}
1467 : sprintf('\%2x', ord($cntrl)) );
1468 if ($opts{-nohtml}) {
1469 return $chr;
1470 } else {
1471 return "<span class=\"cntrl\">$chr</span>";
1475 # Alternatively use unicode control pictures codepoints,
1476 # Unicode "printable representation" (PR)
1477 sub quot_upr {
1478 my $cntrl = shift;
1479 my %opts = @_;
1481 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1482 if ($opts{-nohtml}) {
1483 return $chr;
1484 } else {
1485 return "<span class=\"cntrl\">$chr</span>";
1489 # git may return quoted and escaped filenames
1490 sub unquote {
1491 my $str = shift;
1493 sub unq {
1494 my $seq = shift;
1495 my %es = ( # character escape codes, aka escape sequences
1496 't' => "\t", # tab (HT, TAB)
1497 'n' => "\n", # newline (NL)
1498 'r' => "\r", # return (CR)
1499 'f' => "\f", # form feed (FF)
1500 'b' => "\b", # backspace (BS)
1501 'a' => "\a", # alarm (bell) (BEL)
1502 'e' => "\e", # escape (ESC)
1503 'v' => "\013", # vertical tab (VT)
1506 if ($seq =~ m/^[0-7]{1,3}$/) {
1507 # octal char sequence
1508 return chr(oct($seq));
1509 } elsif (exists $es{$seq}) {
1510 # C escape sequence, aka character escape code
1511 return $es{$seq};
1513 # quoted ordinary character
1514 return $seq;
1517 if ($str =~ m/^"(.*)"$/) {
1518 # needs unquoting
1519 $str = $1;
1520 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1522 return $str;
1525 # escape tabs (convert tabs to spaces)
1526 sub untabify {
1527 my $line = shift;
1529 while ((my $pos = index($line, "\t")) != -1) {
1530 if (my $count = (8 - ($pos % 8))) {
1531 my $spaces = ' ' x $count;
1532 $line =~ s/\t/$spaces/;
1536 return $line;
1539 sub project_in_list {
1540 my $project = shift;
1541 my @list = git_get_projects_list();
1542 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1545 ## ----------------------------------------------------------------------
1546 ## HTML aware string manipulation
1548 # Try to chop given string on a word boundary between position
1549 # $len and $len+$add_len. If there is no word boundary there,
1550 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1551 # (marking chopped part) would be longer than given string.
1552 sub chop_str {
1553 my $str = shift;
1554 my $len = shift;
1555 my $add_len = shift || 10;
1556 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1558 # Make sure perl knows it is utf8 encoded so we don't
1559 # cut in the middle of a utf8 multibyte char.
1560 $str = to_utf8($str);
1562 # allow only $len chars, but don't cut a word if it would fit in $add_len
1563 # if it doesn't fit, cut it if it's still longer than the dots we would add
1564 # remove chopped character entities entirely
1566 # when chopping in the middle, distribute $len into left and right part
1567 # return early if chopping wouldn't make string shorter
1568 if ($where eq 'center') {
1569 return $str if ($len + 5 >= length($str)); # filler is length 5
1570 $len = int($len/2);
1571 } else {
1572 return $str if ($len + 4 >= length($str)); # filler is length 4
1575 # regexps: ending and beginning with word part up to $add_len
1576 my $endre = qr/.{$len}\w{0,$add_len}/;
1577 my $begre = qr/\w{0,$add_len}.{$len}/;
1579 if ($where eq 'left') {
1580 $str =~ m/^(.*?)($begre)$/;
1581 my ($lead, $body) = ($1, $2);
1582 if (length($lead) > 4) {
1583 $lead = " ...";
1585 return "$lead$body";
1587 } elsif ($where eq 'center') {
1588 $str =~ m/^($endre)(.*)$/;
1589 my ($left, $str) = ($1, $2);
1590 $str =~ m/^(.*?)($begre)$/;
1591 my ($mid, $right) = ($1, $2);
1592 if (length($mid) > 5) {
1593 $mid = " ... ";
1595 return "$left$mid$right";
1597 } else {
1598 $str =~ m/^($endre)(.*)$/;
1599 my $body = $1;
1600 my $tail = $2;
1601 if (length($tail) > 4) {
1602 $tail = "... ";
1604 return "$body$tail";
1608 # takes the same arguments as chop_str, but also wraps a <span> around the
1609 # result with a title attribute if it does get chopped. Additionally, the
1610 # string is HTML-escaped.
1611 sub chop_and_escape_str {
1612 my ($str) = @_;
1614 my $chopped = chop_str(@_);
1615 if ($chopped eq $str) {
1616 return esc_html($chopped);
1617 } else {
1618 $str =~ s/[[:cntrl:]]/?/g;
1619 return $cgi->span({-title=>$str}, esc_html($chopped));
1623 ## ----------------------------------------------------------------------
1624 ## functions returning short strings
1626 # CSS class for given age value (in seconds)
1627 sub age_class {
1628 my $age = shift;
1630 if (!defined $age) {
1631 return "noage";
1632 } elsif ($age < 60*60*2) {
1633 return "age0";
1634 } elsif ($age < 60*60*24*2) {
1635 return "age1";
1636 } else {
1637 return "age2";
1641 # convert age in seconds to "nn units ago" string
1642 sub age_string {
1643 my $age = shift;
1644 my $age_str;
1646 if ($age > 60*60*24*365*2) {
1647 $age_str = (int $age/60/60/24/365);
1648 $age_str .= " years ago";
1649 } elsif ($age > 60*60*24*(365/12)*2) {
1650 $age_str = int $age/60/60/24/(365/12);
1651 $age_str .= " months ago";
1652 } elsif ($age > 60*60*24*7*2) {
1653 $age_str = int $age/60/60/24/7;
1654 $age_str .= " weeks ago";
1655 } elsif ($age > 60*60*24*2) {
1656 $age_str = int $age/60/60/24;
1657 $age_str .= " days ago";
1658 } elsif ($age > 60*60*2) {
1659 $age_str = int $age/60/60;
1660 $age_str .= " hours ago";
1661 } elsif ($age > 60*2) {
1662 $age_str = int $age/60;
1663 $age_str .= " min ago";
1664 } elsif ($age > 2) {
1665 $age_str = int $age;
1666 $age_str .= " sec ago";
1667 } else {
1668 $age_str .= " right now";
1670 return $age_str;
1673 use constant {
1674 S_IFINVALID => 0030000,
1675 S_IFGITLINK => 0160000,
1678 # submodule/subproject, a commit object reference
1679 sub S_ISGITLINK {
1680 my $mode = shift;
1682 return (($mode & S_IFMT) == S_IFGITLINK)
1685 # convert file mode in octal to symbolic file mode string
1686 sub mode_str {
1687 my $mode = oct shift;
1689 if (S_ISGITLINK($mode)) {
1690 return 'm---------';
1691 } elsif (S_ISDIR($mode & S_IFMT)) {
1692 return 'drwxr-xr-x';
1693 } elsif (S_ISLNK($mode)) {
1694 return 'lrwxrwxrwx';
1695 } elsif (S_ISREG($mode)) {
1696 # git cares only about the executable bit
1697 if ($mode & S_IXUSR) {
1698 return '-rwxr-xr-x';
1699 } else {
1700 return '-rw-r--r--';
1702 } else {
1703 return '----------';
1707 # convert file mode in octal to file type string
1708 sub file_type {
1709 my $mode = shift;
1711 if ($mode !~ m/^[0-7]+$/) {
1712 return $mode;
1713 } else {
1714 $mode = oct $mode;
1717 if (S_ISGITLINK($mode)) {
1718 return "submodule";
1719 } elsif (S_ISDIR($mode & S_IFMT)) {
1720 return "directory";
1721 } elsif (S_ISLNK($mode)) {
1722 return "symlink";
1723 } elsif (S_ISREG($mode)) {
1724 return "file";
1725 } else {
1726 return "unknown";
1730 # convert file mode in octal to file type description string
1731 sub file_type_long {
1732 my $mode = shift;
1734 if ($mode !~ m/^[0-7]+$/) {
1735 return $mode;
1736 } else {
1737 $mode = oct $mode;
1740 if (S_ISGITLINK($mode)) {
1741 return "submodule";
1742 } elsif (S_ISDIR($mode & S_IFMT)) {
1743 return "directory";
1744 } elsif (S_ISLNK($mode)) {
1745 return "symlink";
1746 } elsif (S_ISREG($mode)) {
1747 if ($mode & S_IXUSR) {
1748 return "executable";
1749 } else {
1750 return "file";
1752 } else {
1753 return "unknown";
1758 ## ----------------------------------------------------------------------
1759 ## functions returning short HTML fragments, or transforming HTML fragments
1760 ## which don't belong to other sections
1762 # format line of commit message.
1763 sub format_log_line_html {
1764 my $line = shift;
1766 $line = esc_html($line, -nbsp=>1);
1767 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1768 $cgi->a({-href => href(action=>"object", hash=>$1),
1769 -class => "text"}, $1);
1770 }eg;
1772 return $line;
1775 # format marker of refs pointing to given object
1777 # the destination action is chosen based on object type and current context:
1778 # - for annotated tags, we choose the tag view unless it's the current view
1779 # already, in which case we go to shortlog view
1780 # - for other refs, we keep the current view if we're in history, shortlog or
1781 # log view, and select shortlog otherwise
1782 sub format_ref_marker {
1783 my ($refs, $id) = @_;
1784 my $markers = '';
1786 if (defined $refs->{$id}) {
1787 foreach my $ref (@{$refs->{$id}}) {
1788 # this code exploits the fact that non-lightweight tags are the
1789 # only indirect objects, and that they are the only objects for which
1790 # we want to use tag instead of shortlog as action
1791 my ($type, $name) = qw();
1792 my $indirect = ($ref =~ s/\^\{\}$//);
1793 # e.g. tags/v2.6.11 or heads/next
1794 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1795 $type = $1;
1796 $name = $2;
1797 } else {
1798 $type = "ref";
1799 $name = $ref;
1802 my $class = $type;
1803 $class .= " indirect" if $indirect;
1805 my $dest_action = "shortlog";
1807 if ($indirect) {
1808 $dest_action = "tag" unless $action eq "tag";
1809 } elsif ($action =~ /^(history|(short)?log)$/) {
1810 $dest_action = $action;
1813 my $dest = "";
1814 $dest .= "refs/" unless $ref =~ m!^refs/!;
1815 $dest .= $ref;
1817 my $link = $cgi->a({
1818 -href => href(
1819 action=>$dest_action,
1820 hash=>$dest
1821 )}, $name);
1823 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1824 $link . "</span>";
1828 if ($markers) {
1829 return ' <span class="refs">'. $markers . '</span>';
1830 } else {
1831 return "";
1835 # format, perhaps shortened and with markers, title line
1836 sub format_subject_html {
1837 my ($long, $short, $href, $extra) = @_;
1838 $extra = '' unless defined($extra);
1840 if (length($short) < length($long)) {
1841 $long =~ s/[[:cntrl:]]/?/g;
1842 return $cgi->a({-href => $href, -class => "list subject",
1843 -title => to_utf8($long)},
1844 esc_html($short)) . $extra;
1845 } else {
1846 return $cgi->a({-href => $href, -class => "list subject"},
1847 esc_html($long)) . $extra;
1851 # Rather than recomputing the url for an email multiple times, we cache it
1852 # after the first hit. This gives a visible benefit in views where the avatar
1853 # for the same email is used repeatedly (e.g. shortlog).
1854 # The cache is shared by all avatar engines (currently gravatar only), which
1855 # are free to use it as preferred. Since only one avatar engine is used for any
1856 # given page, there's no risk for cache conflicts.
1857 our %avatar_cache = ();
1859 # Compute the picon url for a given email, by using the picon search service over at
1860 # http://www.cs.indiana.edu/picons/search.html
1861 sub picon_url {
1862 my $email = lc shift;
1863 if (!$avatar_cache{$email}) {
1864 my ($user, $domain) = split('@', $email);
1865 $avatar_cache{$email} =
1866 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1867 "$domain/$user/" .
1868 "users+domains+unknown/up/single";
1870 return $avatar_cache{$email};
1873 # Compute the gravatar url for a given email, if it's not in the cache already.
1874 # Gravatar stores only the part of the URL before the size, since that's the
1875 # one computationally more expensive. This also allows reuse of the cache for
1876 # different sizes (for this particular engine).
1877 sub gravatar_url {
1878 my $email = lc shift;
1879 my $size = shift;
1880 $avatar_cache{$email} ||=
1881 "http://www.gravatar.com/avatar/" .
1882 Digest::MD5::md5_hex($email) . "?s=";
1883 return $avatar_cache{$email} . $size;
1886 # Insert an avatar for the given $email at the given $size if the feature
1887 # is enabled.
1888 sub git_get_avatar {
1889 my ($email, %opts) = @_;
1890 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1891 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1892 $opts{-size} ||= 'default';
1893 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1894 my $url = "";
1895 if ($git_avatar eq 'gravatar') {
1896 $url = gravatar_url($email, $size);
1897 } elsif ($git_avatar eq 'picon') {
1898 $url = picon_url($email);
1900 # Other providers can be added by extending the if chain, defining $url
1901 # as needed. If no variant puts something in $url, we assume avatars
1902 # are completely disabled/unavailable.
1903 if ($url) {
1904 return $pre_white .
1905 "<img width=\"$size\" " .
1906 "class=\"avatar\" " .
1907 "src=\"$url\" " .
1908 "alt=\"\" " .
1909 "/>" . $post_white;
1910 } else {
1911 return "";
1915 sub format_search_author {
1916 my ($author, $searchtype, $displaytext) = @_;
1917 my $have_search = gitweb_check_feature('search');
1919 if ($have_search) {
1920 my $performed = "";
1921 if ($searchtype eq 'author') {
1922 $performed = "authored";
1923 } elsif ($searchtype eq 'committer') {
1924 $performed = "committed";
1927 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1928 searchtext=>$author,
1929 searchtype=>$searchtype), class=>"list",
1930 title=>"Search for commits $performed by $author"},
1931 $displaytext);
1933 } else {
1934 return $displaytext;
1938 # format the author name of the given commit with the given tag
1939 # the author name is chopped and escaped according to the other
1940 # optional parameters (see chop_str).
1941 sub format_author_html {
1942 my $tag = shift;
1943 my $co = shift;
1944 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1945 return "<$tag class=\"author\">" .
1946 format_search_author($co->{'author_name'}, "author",
1947 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1948 $author) .
1949 "</$tag>";
1952 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1953 sub format_git_diff_header_line {
1954 my $line = shift;
1955 my $diffinfo = shift;
1956 my ($from, $to) = @_;
1958 if ($diffinfo->{'nparents'}) {
1959 # combined diff
1960 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1961 if ($to->{'href'}) {
1962 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1963 esc_path($to->{'file'}));
1964 } else { # file was deleted (no href)
1965 $line .= esc_path($to->{'file'});
1967 } else {
1968 # "ordinary" diff
1969 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1970 if ($from->{'href'}) {
1971 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1972 'a/' . esc_path($from->{'file'}));
1973 } else { # file was added (no href)
1974 $line .= 'a/' . esc_path($from->{'file'});
1976 $line .= ' ';
1977 if ($to->{'href'}) {
1978 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1979 'b/' . esc_path($to->{'file'}));
1980 } else { # file was deleted
1981 $line .= 'b/' . esc_path($to->{'file'});
1985 return "<div class=\"diff header\">$line</div>\n";
1988 # format extended diff header line, before patch itself
1989 sub format_extended_diff_header_line {
1990 my $line = shift;
1991 my $diffinfo = shift;
1992 my ($from, $to) = @_;
1994 # match <path>
1995 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1996 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1997 esc_path($from->{'file'}));
1999 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2000 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2001 esc_path($to->{'file'}));
2003 # match single <mode>
2004 if ($line =~ m/\s(\d{6})$/) {
2005 $line .= '<span class="info"> (' .
2006 file_type_long($1) .
2007 ')</span>';
2009 # match <hash>
2010 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2011 # can match only for combined diff
2012 $line = 'index ';
2013 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2014 if ($from->{'href'}[$i]) {
2015 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2016 -class=>"hash"},
2017 substr($diffinfo->{'from_id'}[$i],0,7));
2018 } else {
2019 $line .= '0' x 7;
2021 # separator
2022 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2024 $line .= '..';
2025 if ($to->{'href'}) {
2026 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2027 substr($diffinfo->{'to_id'},0,7));
2028 } else {
2029 $line .= '0' x 7;
2032 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2033 # can match only for ordinary diff
2034 my ($from_link, $to_link);
2035 if ($from->{'href'}) {
2036 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2037 substr($diffinfo->{'from_id'},0,7));
2038 } else {
2039 $from_link = '0' x 7;
2041 if ($to->{'href'}) {
2042 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2043 substr($diffinfo->{'to_id'},0,7));
2044 } else {
2045 $to_link = '0' x 7;
2047 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2048 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2051 return $line . "<br/>\n";
2054 # format from-file/to-file diff header
2055 sub format_diff_from_to_header {
2056 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2057 my $line;
2058 my $result = '';
2060 $line = $from_line;
2061 #assert($line =~ m/^---/) if DEBUG;
2062 # no extra formatting for "^--- /dev/null"
2063 if (! $diffinfo->{'nparents'}) {
2064 # ordinary (single parent) diff
2065 if ($line =~ m!^--- "?a/!) {
2066 if ($from->{'href'}) {
2067 $line = '--- a/' .
2068 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2069 esc_path($from->{'file'}));
2070 } else {
2071 $line = '--- a/' .
2072 esc_path($from->{'file'});
2075 $result .= qq!<div class="diff from_file">$line</div>\n!;
2077 } else {
2078 # combined diff (merge commit)
2079 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2080 if ($from->{'href'}[$i]) {
2081 $line = '--- ' .
2082 $cgi->a({-href=>href(action=>"blobdiff",
2083 hash_parent=>$diffinfo->{'from_id'}[$i],
2084 hash_parent_base=>$parents[$i],
2085 file_parent=>$from->{'file'}[$i],
2086 hash=>$diffinfo->{'to_id'},
2087 hash_base=>$hash,
2088 file_name=>$to->{'file'}),
2089 -class=>"path",
2090 -title=>"diff" . ($i+1)},
2091 $i+1) .
2092 '/' .
2093 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2094 esc_path($from->{'file'}[$i]));
2095 } else {
2096 $line = '--- /dev/null';
2098 $result .= qq!<div class="diff from_file">$line</div>\n!;
2102 $line = $to_line;
2103 #assert($line =~ m/^\+\+\+/) if DEBUG;
2104 # no extra formatting for "^+++ /dev/null"
2105 if ($line =~ m!^\+\+\+ "?b/!) {
2106 if ($to->{'href'}) {
2107 $line = '+++ b/' .
2108 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2109 esc_path($to->{'file'}));
2110 } else {
2111 $line = '+++ b/' .
2112 esc_path($to->{'file'});
2115 $result .= qq!<div class="diff to_file">$line</div>\n!;
2117 return $result;
2120 # create note for patch simplified by combined diff
2121 sub format_diff_cc_simplified {
2122 my ($diffinfo, @parents) = @_;
2123 my $result = '';
2125 $result .= "<div class=\"diff header\">" .
2126 "diff --cc ";
2127 if (!is_deleted($diffinfo)) {
2128 $result .= $cgi->a({-href => href(action=>"blob",
2129 hash_base=>$hash,
2130 hash=>$diffinfo->{'to_id'},
2131 file_name=>$diffinfo->{'to_file'}),
2132 -class => "path"},
2133 esc_path($diffinfo->{'to_file'}));
2134 } else {
2135 $result .= esc_path($diffinfo->{'to_file'});
2137 $result .= "</div>\n" . # class="diff header"
2138 "<div class=\"diff nodifferences\">" .
2139 "Simple merge" .
2140 "</div>\n"; # class="diff nodifferences"
2142 return $result;
2145 # format patch (diff) line (not to be used for diff headers)
2146 sub format_diff_line {
2147 my $line = shift;
2148 my ($from, $to) = @_;
2149 my $diff_class = "";
2151 chomp $line;
2153 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2154 # combined diff
2155 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2156 if ($line =~ m/^\@{3}/) {
2157 $diff_class = " chunk_header";
2158 } elsif ($line =~ m/^\\/) {
2159 $diff_class = " incomplete";
2160 } elsif ($prefix =~ tr/+/+/) {
2161 $diff_class = " add";
2162 } elsif ($prefix =~ tr/-/-/) {
2163 $diff_class = " rem";
2165 } else {
2166 # assume ordinary diff
2167 my $char = substr($line, 0, 1);
2168 if ($char eq '+') {
2169 $diff_class = " add";
2170 } elsif ($char eq '-') {
2171 $diff_class = " rem";
2172 } elsif ($char eq '@') {
2173 $diff_class = " chunk_header";
2174 } elsif ($char eq "\\") {
2175 $diff_class = " incomplete";
2178 $line = untabify($line);
2179 if ($from && $to && $line =~ m/^\@{2} /) {
2180 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2181 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2183 $from_lines = 0 unless defined $from_lines;
2184 $to_lines = 0 unless defined $to_lines;
2186 if ($from->{'href'}) {
2187 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2188 -class=>"list"}, $from_text);
2190 if ($to->{'href'}) {
2191 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2192 -class=>"list"}, $to_text);
2194 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2195 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2196 return "<div class=\"diff$diff_class\">$line</div>\n";
2197 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2198 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2199 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2201 @from_text = split(' ', $ranges);
2202 for (my $i = 0; $i < @from_text; ++$i) {
2203 ($from_start[$i], $from_nlines[$i]) =
2204 (split(',', substr($from_text[$i], 1)), 0);
2207 $to_text = pop @from_text;
2208 $to_start = pop @from_start;
2209 $to_nlines = pop @from_nlines;
2211 $line = "<span class=\"chunk_info\">$prefix ";
2212 for (my $i = 0; $i < @from_text; ++$i) {
2213 if ($from->{'href'}[$i]) {
2214 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2215 -class=>"list"}, $from_text[$i]);
2216 } else {
2217 $line .= $from_text[$i];
2219 $line .= " ";
2221 if ($to->{'href'}) {
2222 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2223 -class=>"list"}, $to_text);
2224 } else {
2225 $line .= $to_text;
2227 $line .= " $prefix</span>" .
2228 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2229 return "<div class=\"diff$diff_class\">$line</div>\n";
2231 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2234 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2235 # linked. Pass the hash of the tree/commit to snapshot.
2236 sub format_snapshot_links {
2237 my ($hash) = @_;
2238 my $num_fmts = @snapshot_fmts;
2239 if ($num_fmts > 1) {
2240 # A parenthesized list of links bearing format names.
2241 # e.g. "snapshot (_tar.gz_ _zip_)"
2242 return "snapshot (" . join(' ', map
2243 $cgi->a({
2244 -href => href(
2245 action=>"snapshot",
2246 hash=>$hash,
2247 snapshot_format=>$_
2249 }, $known_snapshot_formats{$_}{'display'})
2250 , @snapshot_fmts) . ")";
2251 } elsif ($num_fmts == 1) {
2252 # A single "snapshot" link whose tooltip bears the format name.
2253 # i.e. "_snapshot_"
2254 my ($fmt) = @snapshot_fmts;
2255 return
2256 $cgi->a({
2257 -href => href(
2258 action=>"snapshot",
2259 hash=>$hash,
2260 snapshot_format=>$fmt
2262 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2263 }, "snapshot");
2264 } else { # $num_fmts == 0
2265 return undef;
2269 ## ......................................................................
2270 ## functions returning values to be passed, perhaps after some
2271 ## transformation, to other functions; e.g. returning arguments to href()
2273 # returns hash to be passed to href to generate gitweb URL
2274 # in -title key it returns description of link
2275 sub get_feed_info {
2276 my $format = shift || 'Atom';
2277 my %res = (action => lc($format));
2279 # feed links are possible only for project views
2280 return unless (defined $project);
2281 # some views should link to OPML, or to generic project feed,
2282 # or don't have specific feed yet (so they should use generic)
2283 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2285 my $branch;
2286 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2287 # from tag links; this also makes possible to detect branch links
2288 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2289 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2290 $branch = $1;
2292 # find log type for feed description (title)
2293 my $type = 'log';
2294 if (defined $file_name) {
2295 $type = "history of $file_name";
2296 $type .= "/" if ($action eq 'tree');
2297 $type .= " on '$branch'" if (defined $branch);
2298 } else {
2299 $type = "log of $branch" if (defined $branch);
2302 $res{-title} = $type;
2303 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2304 $res{'file_name'} = $file_name;
2306 return %res;
2309 ## ----------------------------------------------------------------------
2310 ## git utility subroutines, invoking git commands
2312 # returns path to the core git executable and the --git-dir parameter as list
2313 sub git_cmd {
2314 $number_of_git_cmds++;
2315 return $GIT, '--git-dir='.$git_dir;
2318 # quote the given arguments for passing them to the shell
2319 # quote_command("command", "arg 1", "arg with ' and ! characters")
2320 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2321 # Try to avoid using this function wherever possible.
2322 sub quote_command {
2323 return join(' ',
2324 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2327 # get HEAD ref of given project as hash
2328 sub git_get_head_hash {
2329 return git_get_full_hash(shift, 'HEAD');
2332 sub git_get_full_hash {
2333 return git_get_hash(@_);
2336 sub git_get_short_hash {
2337 return git_get_hash(@_, '--short=7');
2340 sub git_get_hash {
2341 my ($project, $hash, @options) = @_;
2342 my $o_git_dir = $git_dir;
2343 my $retval = undef;
2344 $git_dir = "$projectroot/$project";
2345 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2346 '--verify', '-q', @options, $hash) {
2347 $retval = <$fd>;
2348 chomp $retval if defined $retval;
2349 close $fd;
2351 if (defined $o_git_dir) {
2352 $git_dir = $o_git_dir;
2354 return $retval;
2357 # get type of given object
2358 sub git_get_type {
2359 my $hash = shift;
2361 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2362 my $type = <$fd>;
2363 close $fd or return;
2364 chomp $type;
2365 return $type;
2368 # repository configuration
2369 our $config_file = '';
2370 our %config;
2372 # store multiple values for single key as anonymous array reference
2373 # single values stored directly in the hash, not as [ <value> ]
2374 sub hash_set_multi {
2375 my ($hash, $key, $value) = @_;
2377 if (!exists $hash->{$key}) {
2378 $hash->{$key} = $value;
2379 } elsif (!ref $hash->{$key}) {
2380 $hash->{$key} = [ $hash->{$key}, $value ];
2381 } else {
2382 push @{$hash->{$key}}, $value;
2386 # return hash of git project configuration
2387 # optionally limited to some section, e.g. 'gitweb'
2388 sub git_parse_project_config {
2389 my $section_regexp = shift;
2390 my %config;
2392 local $/ = "\0";
2394 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2395 or return;
2397 while (my $keyval = <$fh>) {
2398 chomp $keyval;
2399 my ($key, $value) = split(/\n/, $keyval, 2);
2401 hash_set_multi(\%config, $key, $value)
2402 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2404 close $fh;
2406 return %config;
2409 # convert config value to boolean: 'true' or 'false'
2410 # no value, number > 0, 'true' and 'yes' values are true
2411 # rest of values are treated as false (never as error)
2412 sub config_to_bool {
2413 my $val = shift;
2415 return 1 if !defined $val; # section.key
2417 # strip leading and trailing whitespace
2418 $val =~ s/^\s+//;
2419 $val =~ s/\s+$//;
2421 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2422 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2425 # convert config value to simple decimal number
2426 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2427 # to be multiplied by 1024, 1048576, or 1073741824
2428 sub config_to_int {
2429 my $val = shift;
2431 # strip leading and trailing whitespace
2432 $val =~ s/^\s+//;
2433 $val =~ s/\s+$//;
2435 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2436 $unit = lc($unit);
2437 # unknown unit is treated as 1
2438 return $num * ($unit eq 'g' ? 1073741824 :
2439 $unit eq 'm' ? 1048576 :
2440 $unit eq 'k' ? 1024 : 1);
2442 return $val;
2445 # convert config value to array reference, if needed
2446 sub config_to_multi {
2447 my $val = shift;
2449 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2452 sub git_get_project_config {
2453 my ($key, $type) = @_;
2455 return unless defined $git_dir;
2457 # key sanity check
2458 return unless ($key);
2459 $key =~ s/^gitweb\.//;
2460 return if ($key =~ m/\W/);
2462 # type sanity check
2463 if (defined $type) {
2464 $type =~ s/^--//;
2465 $type = undef
2466 unless ($type eq 'bool' || $type eq 'int');
2469 # get config
2470 if (!defined $config_file ||
2471 $config_file ne "$git_dir/config") {
2472 %config = git_parse_project_config('gitweb');
2473 $config_file = "$git_dir/config";
2476 # check if config variable (key) exists
2477 return unless exists $config{"gitweb.$key"};
2479 # ensure given type
2480 if (!defined $type) {
2481 return $config{"gitweb.$key"};
2482 } elsif ($type eq 'bool') {
2483 # backward compatibility: 'git config --bool' returns true/false
2484 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2485 } elsif ($type eq 'int') {
2486 return config_to_int($config{"gitweb.$key"});
2488 return $config{"gitweb.$key"};
2491 # get hash of given path at given ref
2492 sub git_get_hash_by_path {
2493 my $base = shift;
2494 my $path = shift || return undef;
2495 my $type = shift;
2497 $path =~ s,/+$,,;
2499 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2500 or die_error(500, "Open git-ls-tree failed");
2501 my $line = <$fd>;
2502 close $fd or return undef;
2504 if (!defined $line) {
2505 # there is no tree or hash given by $path at $base
2506 return undef;
2509 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2510 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2511 if (defined $type && $type ne $2) {
2512 # type doesn't match
2513 return undef;
2515 return $3;
2518 # get path of entry with given hash at given tree-ish (ref)
2519 # used to get 'from' filename for combined diff (merge commit) for renames
2520 sub git_get_path_by_hash {
2521 my $base = shift || return;
2522 my $hash = shift || return;
2524 local $/ = "\0";
2526 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2527 or return undef;
2528 while (my $line = <$fd>) {
2529 chomp $line;
2531 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2532 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2533 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2534 close $fd;
2535 return $1;
2538 close $fd;
2539 return undef;
2542 ## ......................................................................
2543 ## git utility functions, directly accessing git repository
2545 sub git_get_project_description {
2546 my $path = shift;
2548 $git_dir = "$projectroot/$path";
2549 open my $fd, '<', "$git_dir/description"
2550 or return git_get_project_config('description');
2551 my $descr = <$fd>;
2552 close $fd;
2553 if (defined $descr) {
2554 chomp $descr;
2556 return $descr;
2559 sub git_get_project_ctags {
2560 my $path = shift;
2561 my $ctags = {};
2563 $git_dir = "$projectroot/$path";
2564 opendir my $dh, "$git_dir/ctags"
2565 or return $ctags;
2566 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2567 open my $ct, '<', $_ or next;
2568 my $val = <$ct>;
2569 chomp $val;
2570 close $ct;
2571 my $ctag = $_; $ctag =~ s#.*/##;
2572 $ctags->{$ctag} = $val;
2574 closedir $dh;
2575 $ctags;
2578 sub git_populate_project_tagcloud {
2579 my $ctags = shift;
2581 # First, merge different-cased tags; tags vote on casing
2582 my %ctags_lc;
2583 foreach (keys %$ctags) {
2584 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2585 if (not $ctags_lc{lc $_}->{topcount}
2586 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2587 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2588 $ctags_lc{lc $_}->{topname} = $_;
2592 my $cloud;
2593 if (eval { require HTML::TagCloud; 1; }) {
2594 $cloud = HTML::TagCloud->new;
2595 foreach (sort keys %ctags_lc) {
2596 # Pad the title with spaces so that the cloud looks
2597 # less crammed.
2598 my $title = $ctags_lc{$_}->{topname};
2599 $title =~ s/ /&nbsp;/g;
2600 $title =~ s/^/&nbsp;/g;
2601 $title =~ s/$/&nbsp;/g;
2602 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2604 } else {
2605 $cloud = \%ctags_lc;
2607 $cloud;
2610 sub git_show_project_tagcloud {
2611 my ($cloud, $count) = @_;
2612 print STDERR ref($cloud)."..\n";
2613 if (ref $cloud eq 'HTML::TagCloud') {
2614 return $cloud->html_and_css($count);
2615 } else {
2616 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2617 return '<p align="center">' . join (', ', map {
2618 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2619 } splice(@tags, 0, $count)) . '</p>';
2623 sub git_get_project_url_list {
2624 my $path = shift;
2626 $git_dir = "$projectroot/$path";
2627 open my $fd, '<', "$git_dir/cloneurl"
2628 or return wantarray ?
2629 @{ config_to_multi(git_get_project_config('url')) } :
2630 config_to_multi(git_get_project_config('url'));
2631 my @git_project_url_list = map { chomp; $_ } <$fd>;
2632 close $fd;
2634 return wantarray ? @git_project_url_list : \@git_project_url_list;
2637 sub git_get_projects_list {
2638 my ($filter) = @_;
2639 my @list;
2641 $filter ||= '';
2642 $filter =~ s/\.git$//;
2644 my $check_forks = gitweb_check_feature('forks');
2646 if (-d $projects_list) {
2647 # search in directory
2648 my $dir = $projects_list . ($filter ? "/$filter" : '');
2649 # remove the trailing "/"
2650 $dir =~ s!/+$!!;
2651 my $pfxlen = length("$dir");
2652 my $pfxdepth = ($dir =~ tr!/!!);
2654 File::Find::find({
2655 follow_fast => 1, # follow symbolic links
2656 follow_skip => 2, # ignore duplicates
2657 dangling_symlinks => 0, # ignore dangling symlinks, silently
2658 wanted => sub {
2659 # global variables
2660 our $project_maxdepth;
2661 our $projectroot;
2662 # skip project-list toplevel, if we get it.
2663 return if (m!^[/.]$!);
2664 # only directories can be git repositories
2665 return unless (-d $_);
2666 # don't traverse too deep (Find is super slow on os x)
2667 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2668 $File::Find::prune = 1;
2669 return;
2672 my $subdir = substr($File::Find::name, $pfxlen + 1);
2673 # we check related file in $projectroot
2674 my $path = ($filter ? "$filter/" : '') . $subdir;
2675 if (check_export_ok("$projectroot/$path")) {
2676 push @list, { path => $path };
2677 $File::Find::prune = 1;
2680 }, "$dir");
2682 } elsif (-f $projects_list) {
2683 # read from file(url-encoded):
2684 # 'git%2Fgit.git Linus+Torvalds'
2685 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2686 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2687 my %paths;
2688 open my $fd, '<', $projects_list or return;
2689 PROJECT:
2690 while (my $line = <$fd>) {
2691 chomp $line;
2692 my ($path, $owner) = split ' ', $line;
2693 $path = unescape($path);
2694 $owner = unescape($owner);
2695 if (!defined $path) {
2696 next;
2698 if ($filter ne '') {
2699 # looking for forks;
2700 my $pfx = substr($path, 0, length($filter));
2701 if ($pfx ne $filter) {
2702 next PROJECT;
2704 my $sfx = substr($path, length($filter));
2705 if ($sfx !~ /^\/.*\.git$/) {
2706 next PROJECT;
2708 } elsif ($check_forks) {
2709 PATH:
2710 foreach my $filter (keys %paths) {
2711 # looking for forks;
2712 my $pfx = substr($path, 0, length($filter));
2713 if ($pfx ne $filter) {
2714 next PATH;
2716 my $sfx = substr($path, length($filter));
2717 if ($sfx !~ /^\/.*\.git$/) {
2718 next PATH;
2720 # is a fork, don't include it in
2721 # the list
2722 next PROJECT;
2725 if (check_export_ok("$projectroot/$path")) {
2726 my $pr = {
2727 path => $path,
2728 owner => to_utf8($owner),
2730 push @list, $pr;
2731 (my $forks_path = $path) =~ s/\.git$//;
2732 $paths{$forks_path}++;
2735 close $fd;
2737 return @list;
2740 our $gitweb_project_owner = undef;
2741 sub git_get_project_list_from_file {
2743 return if (defined $gitweb_project_owner);
2745 $gitweb_project_owner = {};
2746 # read from file (url-encoded):
2747 # 'git%2Fgit.git Linus+Torvalds'
2748 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2749 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2750 if (-f $projects_list) {
2751 open(my $fd, '<', $projects_list);
2752 while (my $line = <$fd>) {
2753 chomp $line;
2754 my ($pr, $ow) = split ' ', $line;
2755 $pr = unescape($pr);
2756 $ow = unescape($ow);
2757 $gitweb_project_owner->{$pr} = to_utf8($ow);
2759 close $fd;
2763 sub git_get_project_owner {
2764 my $project = shift;
2765 my $owner;
2767 return undef unless $project;
2768 $git_dir = "$projectroot/$project";
2770 if (!defined $gitweb_project_owner) {
2771 git_get_project_list_from_file();
2774 if (exists $gitweb_project_owner->{$project}) {
2775 $owner = $gitweb_project_owner->{$project};
2777 if (!defined $owner){
2778 $owner = git_get_project_config('owner');
2780 if (!defined $owner) {
2781 $owner = get_file_owner("$git_dir");
2784 return $owner;
2787 sub git_get_last_activity {
2788 my ($path) = @_;
2789 my $fd;
2791 $git_dir = "$projectroot/$path";
2792 open($fd, "-|", git_cmd(), 'for-each-ref',
2793 '--format=%(committer)',
2794 '--sort=-committerdate',
2795 '--count=1',
2796 'refs/heads') or return;
2797 my $most_recent = <$fd>;
2798 close $fd or return;
2799 if (defined $most_recent &&
2800 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2801 my $timestamp = $1;
2802 my $age = time - $timestamp;
2803 return ($age, age_string($age));
2805 return (undef, undef);
2808 # Implementation note: when a single remote is wanted, we cannot use 'git
2809 # remote show -n' because that command always work (assuming it's a remote URL
2810 # if it's not defined), and we cannot use 'git remote show' because that would
2811 # try to make a network roundtrip. So the only way to find if that particular
2812 # remote is defined is to walk the list provided by 'git remote -v' and stop if
2813 # and when we find what we want.
2814 sub git_get_remotes_list {
2815 my $wanted = shift;
2816 my %remotes = ();
2818 open my $fd, '-|' , git_cmd(), 'remote', '-v';
2819 return unless $fd;
2820 while (my $remote = <$fd>) {
2821 chomp $remote;
2822 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
2823 next if $wanted and not $remote eq $wanted;
2824 my ($url, $key) = ($1, $2);
2826 $remotes{$remote} ||= { 'heads' => () };
2827 $remotes{$remote}{$key} = $url;
2829 close $fd or return;
2830 return wantarray ? %remotes : \%remotes;
2833 # Takes a hash of remotes as first parameter and fills it by adding the
2834 # available remote heads for each of the indicated remotes.
2835 sub fill_remote_heads {
2836 my $remotes = shift;
2837 my @heads = map { "remotes/$_" } keys %$remotes;
2838 my @remoteheads = git_get_heads_list(undef, @heads);
2839 foreach my $remote (keys %$remotes) {
2840 $remotes->{$remote}{'heads'} = [ grep {
2841 $_->{'name'} =~ s!^$remote/!!
2842 } @remoteheads ];
2846 sub git_get_references {
2847 my $type = shift || "";
2848 my %refs;
2849 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2850 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2851 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2852 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2853 or return;
2855 while (my $line = <$fd>) {
2856 chomp $line;
2857 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2858 if (defined $refs{$1}) {
2859 push @{$refs{$1}}, $2;
2860 } else {
2861 $refs{$1} = [ $2 ];
2865 close $fd or return;
2866 return \%refs;
2869 sub git_get_rev_name_tags {
2870 my $hash = shift || return undef;
2872 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2873 or return;
2874 my $name_rev = <$fd>;
2875 close $fd;
2877 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2878 return $1;
2879 } else {
2880 # catches also '$hash undefined' output
2881 return undef;
2885 ## ----------------------------------------------------------------------
2886 ## parse to hash functions
2888 sub parse_date {
2889 my $epoch = shift;
2890 my $tz = shift || "-0000";
2892 my %date;
2893 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2894 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2895 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2896 $date{'hour'} = $hour;
2897 $date{'minute'} = $min;
2898 $date{'mday'} = $mday;
2899 $date{'day'} = $days[$wday];
2900 $date{'month'} = $months[$mon];
2901 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2902 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2903 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2904 $mday, $months[$mon], $hour ,$min;
2905 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2906 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2908 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2909 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2910 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2911 $date{'hour_local'} = $hour;
2912 $date{'minute_local'} = $min;
2913 $date{'tz_local'} = $tz;
2914 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2915 1900+$year, $mon+1, $mday,
2916 $hour, $min, $sec, $tz);
2917 return %date;
2920 sub parse_tag {
2921 my $tag_id = shift;
2922 my %tag;
2923 my @comment;
2925 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2926 $tag{'id'} = $tag_id;
2927 while (my $line = <$fd>) {
2928 chomp $line;
2929 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2930 $tag{'object'} = $1;
2931 } elsif ($line =~ m/^type (.+)$/) {
2932 $tag{'type'} = $1;
2933 } elsif ($line =~ m/^tag (.+)$/) {
2934 $tag{'name'} = $1;
2935 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2936 $tag{'author'} = $1;
2937 $tag{'author_epoch'} = $2;
2938 $tag{'author_tz'} = $3;
2939 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2940 $tag{'author_name'} = $1;
2941 $tag{'author_email'} = $2;
2942 } else {
2943 $tag{'author_name'} = $tag{'author'};
2945 } elsif ($line =~ m/--BEGIN/) {
2946 push @comment, $line;
2947 last;
2948 } elsif ($line eq "") {
2949 last;
2952 push @comment, <$fd>;
2953 $tag{'comment'} = \@comment;
2954 close $fd or return;
2955 if (!defined $tag{'name'}) {
2956 return
2958 return %tag
2961 sub parse_commit_text {
2962 my ($commit_text, $withparents) = @_;
2963 my @commit_lines = split '\n', $commit_text;
2964 my %co;
2966 pop @commit_lines; # Remove '\0'
2968 if (! @commit_lines) {
2969 return;
2972 my $header = shift @commit_lines;
2973 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2974 return;
2976 ($co{'id'}, my @parents) = split ' ', $header;
2977 while (my $line = shift @commit_lines) {
2978 last if $line eq "\n";
2979 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2980 $co{'tree'} = $1;
2981 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2982 push @parents, $1;
2983 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2984 $co{'author'} = to_utf8($1);
2985 $co{'author_epoch'} = $2;
2986 $co{'author_tz'} = $3;
2987 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2988 $co{'author_name'} = $1;
2989 $co{'author_email'} = $2;
2990 } else {
2991 $co{'author_name'} = $co{'author'};
2993 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2994 $co{'committer'} = to_utf8($1);
2995 $co{'committer_epoch'} = $2;
2996 $co{'committer_tz'} = $3;
2997 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2998 $co{'committer_name'} = $1;
2999 $co{'committer_email'} = $2;
3000 } else {
3001 $co{'committer_name'} = $co{'committer'};
3005 if (!defined $co{'tree'}) {
3006 return;
3008 $co{'parents'} = \@parents;
3009 $co{'parent'} = $parents[0];
3011 foreach my $title (@commit_lines) {
3012 $title =~ s/^ //;
3013 if ($title ne "") {
3014 $co{'title'} = chop_str($title, 80, 5);
3015 # remove leading stuff of merges to make the interesting part visible
3016 if (length($title) > 50) {
3017 $title =~ s/^Automatic //;
3018 $title =~ s/^merge (of|with) /Merge ... /i;
3019 if (length($title) > 50) {
3020 $title =~ s/(http|rsync):\/\///;
3022 if (length($title) > 50) {
3023 $title =~ s/(master|www|rsync)\.//;
3025 if (length($title) > 50) {
3026 $title =~ s/kernel.org:?//;
3028 if (length($title) > 50) {
3029 $title =~ s/\/pub\/scm//;
3032 $co{'title_short'} = chop_str($title, 50, 5);
3033 last;
3036 if (! defined $co{'title'} || $co{'title'} eq "") {
3037 $co{'title'} = $co{'title_short'} = '(no commit message)';
3039 # remove added spaces
3040 foreach my $line (@commit_lines) {
3041 $line =~ s/^ //;
3043 $co{'comment'} = \@commit_lines;
3045 my $age = time - $co{'committer_epoch'};
3046 $co{'age'} = $age;
3047 $co{'age_string'} = age_string($age);
3048 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3049 if ($age > 60*60*24*7*2) {
3050 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3051 $co{'age_string_age'} = $co{'age_string'};
3052 } else {
3053 $co{'age_string_date'} = $co{'age_string'};
3054 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3056 return %co;
3059 sub parse_commit {
3060 my ($commit_id) = @_;
3061 my %co;
3063 local $/ = "\0";
3065 open my $fd, "-|", git_cmd(), "rev-list",
3066 "--parents",
3067 "--header",
3068 "--max-count=1",
3069 $commit_id,
3070 "--",
3071 or die_error(500, "Open git-rev-list failed");
3072 %co = parse_commit_text(<$fd>, 1);
3073 close $fd;
3075 return %co;
3078 sub parse_commits {
3079 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3080 my @cos;
3082 $maxcount ||= 1;
3083 $skip ||= 0;
3085 local $/ = "\0";
3087 open my $fd, "-|", git_cmd(), "rev-list",
3088 "--header",
3089 @args,
3090 ("--max-count=" . $maxcount),
3091 ("--skip=" . $skip),
3092 @extra_options,
3093 $commit_id,
3094 "--",
3095 ($filename ? ($filename) : ())
3096 or die_error(500, "Open git-rev-list failed");
3097 while (my $line = <$fd>) {
3098 my %co = parse_commit_text($line);
3099 push @cos, \%co;
3101 close $fd;
3103 return wantarray ? @cos : \@cos;
3106 # parse line of git-diff-tree "raw" output
3107 sub parse_difftree_raw_line {
3108 my $line = shift;
3109 my %res;
3111 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3112 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3113 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3114 $res{'from_mode'} = $1;
3115 $res{'to_mode'} = $2;
3116 $res{'from_id'} = $3;
3117 $res{'to_id'} = $4;
3118 $res{'status'} = $5;
3119 $res{'similarity'} = $6;
3120 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3121 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3122 } else {
3123 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3126 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3127 # combined diff (for merge commit)
3128 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3129 $res{'nparents'} = length($1);
3130 $res{'from_mode'} = [ split(' ', $2) ];
3131 $res{'to_mode'} = pop @{$res{'from_mode'}};
3132 $res{'from_id'} = [ split(' ', $3) ];
3133 $res{'to_id'} = pop @{$res{'from_id'}};
3134 $res{'status'} = [ split('', $4) ];
3135 $res{'to_file'} = unquote($5);
3137 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3138 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3139 $res{'commit'} = $1;
3142 return wantarray ? %res : \%res;
3145 # wrapper: return parsed line of git-diff-tree "raw" output
3146 # (the argument might be raw line, or parsed info)
3147 sub parsed_difftree_line {
3148 my $line_or_ref = shift;
3150 if (ref($line_or_ref) eq "HASH") {
3151 # pre-parsed (or generated by hand)
3152 return $line_or_ref;
3153 } else {
3154 return parse_difftree_raw_line($line_or_ref);
3158 # parse line of git-ls-tree output
3159 sub parse_ls_tree_line {
3160 my $line = shift;
3161 my %opts = @_;
3162 my %res;
3164 if ($opts{'-l'}) {
3165 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3166 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3168 $res{'mode'} = $1;
3169 $res{'type'} = $2;
3170 $res{'hash'} = $3;
3171 $res{'size'} = $4;
3172 if ($opts{'-z'}) {
3173 $res{'name'} = $5;
3174 } else {
3175 $res{'name'} = unquote($5);
3177 } else {
3178 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3179 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3181 $res{'mode'} = $1;
3182 $res{'type'} = $2;
3183 $res{'hash'} = $3;
3184 if ($opts{'-z'}) {
3185 $res{'name'} = $4;
3186 } else {
3187 $res{'name'} = unquote($4);
3191 return wantarray ? %res : \%res;
3194 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3195 sub parse_from_to_diffinfo {
3196 my ($diffinfo, $from, $to, @parents) = @_;
3198 if ($diffinfo->{'nparents'}) {
3199 # combined diff
3200 $from->{'file'} = [];
3201 $from->{'href'} = [];
3202 fill_from_file_info($diffinfo, @parents)
3203 unless exists $diffinfo->{'from_file'};
3204 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3205 $from->{'file'}[$i] =
3206 defined $diffinfo->{'from_file'}[$i] ?
3207 $diffinfo->{'from_file'}[$i] :
3208 $diffinfo->{'to_file'};
3209 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3210 $from->{'href'}[$i] = href(action=>"blob",
3211 hash_base=>$parents[$i],
3212 hash=>$diffinfo->{'from_id'}[$i],
3213 file_name=>$from->{'file'}[$i]);
3214 } else {
3215 $from->{'href'}[$i] = undef;
3218 } else {
3219 # ordinary (not combined) diff
3220 $from->{'file'} = $diffinfo->{'from_file'};
3221 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3222 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3223 hash=>$diffinfo->{'from_id'},
3224 file_name=>$from->{'file'});
3225 } else {
3226 delete $from->{'href'};
3230 $to->{'file'} = $diffinfo->{'to_file'};
3231 if (!is_deleted($diffinfo)) { # file exists in result
3232 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3233 hash=>$diffinfo->{'to_id'},
3234 file_name=>$to->{'file'});
3235 } else {
3236 delete $to->{'href'};
3240 ## ......................................................................
3241 ## parse to array of hashes functions
3243 sub git_get_heads_list {
3244 my ($limit, @classes) = @_;
3245 @classes = ('heads') unless @classes;
3246 my @patterns = map { "refs/$_" } @classes;
3247 my @headslist;
3249 open my $fd, '-|', git_cmd(), 'for-each-ref',
3250 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3251 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3252 @patterns
3253 or return;
3254 while (my $line = <$fd>) {
3255 my %ref_item;
3257 chomp $line;
3258 my ($refinfo, $committerinfo) = split(/\0/, $line);
3259 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3260 my ($committer, $epoch, $tz) =
3261 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3262 $ref_item{'fullname'} = $name;
3263 $name =~ s!^refs/(?:head|remote)s/!!;
3265 $ref_item{'name'} = $name;
3266 $ref_item{'id'} = $hash;
3267 $ref_item{'title'} = $title || '(no commit message)';
3268 $ref_item{'epoch'} = $epoch;
3269 if ($epoch) {
3270 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3271 } else {
3272 $ref_item{'age'} = "unknown";
3275 push @headslist, \%ref_item;
3277 close $fd;
3279 return wantarray ? @headslist : \@headslist;
3282 sub git_get_tags_list {
3283 my $limit = shift;
3284 my @tagslist;
3286 open my $fd, '-|', git_cmd(), 'for-each-ref',
3287 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3288 '--format=%(objectname) %(objecttype) %(refname) '.
3289 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3290 'refs/tags'
3291 or return;
3292 while (my $line = <$fd>) {
3293 my %ref_item;
3295 chomp $line;
3296 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3297 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3298 my ($creator, $epoch, $tz) =
3299 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3300 $ref_item{'fullname'} = $name;
3301 $name =~ s!^refs/tags/!!;
3303 $ref_item{'type'} = $type;
3304 $ref_item{'id'} = $id;
3305 $ref_item{'name'} = $name;
3306 if ($type eq "tag") {
3307 $ref_item{'subject'} = $title;
3308 $ref_item{'reftype'} = $reftype;
3309 $ref_item{'refid'} = $refid;
3310 } else {
3311 $ref_item{'reftype'} = $type;
3312 $ref_item{'refid'} = $id;
3315 if ($type eq "tag" || $type eq "commit") {
3316 $ref_item{'epoch'} = $epoch;
3317 if ($epoch) {
3318 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3319 } else {
3320 $ref_item{'age'} = "unknown";
3324 push @tagslist, \%ref_item;
3326 close $fd;
3328 return wantarray ? @tagslist : \@tagslist;
3331 ## ----------------------------------------------------------------------
3332 ## filesystem-related functions
3334 sub get_file_owner {
3335 my $path = shift;
3337 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3338 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3339 if (!defined $gcos) {
3340 return undef;
3342 my $owner = $gcos;
3343 $owner =~ s/[,;].*$//;
3344 return to_utf8($owner);
3347 # assume that file exists
3348 sub insert_file {
3349 my $filename = shift;
3351 open my $fd, '<', $filename;
3352 print map { to_utf8($_) } <$fd>;
3353 close $fd;
3356 ## ......................................................................
3357 ## mimetype related functions
3359 sub mimetype_guess_file {
3360 my $filename = shift;
3361 my $mimemap = shift;
3362 -r $mimemap or return undef;
3364 my %mimemap;
3365 open(my $mh, '<', $mimemap) or return undef;
3366 while (<$mh>) {
3367 next if m/^#/; # skip comments
3368 my ($mimetype, $exts) = split(/\t+/);
3369 if (defined $exts) {
3370 my @exts = split(/\s+/, $exts);
3371 foreach my $ext (@exts) {
3372 $mimemap{$ext} = $mimetype;
3376 close($mh);
3378 $filename =~ /\.([^.]*)$/;
3379 return $mimemap{$1};
3382 sub mimetype_guess {
3383 my $filename = shift;
3384 my $mime;
3385 $filename =~ /\./ or return undef;
3387 if ($mimetypes_file) {
3388 my $file = $mimetypes_file;
3389 if ($file !~ m!^/!) { # if it is relative path
3390 # it is relative to project
3391 $file = "$projectroot/$project/$file";
3393 $mime = mimetype_guess_file($filename, $file);
3395 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3396 return $mime;
3399 sub blob_mimetype {
3400 my $fd = shift;
3401 my $filename = shift;
3403 if ($filename) {
3404 my $mime = mimetype_guess($filename);
3405 $mime and return $mime;
3408 # just in case
3409 return $default_blob_plain_mimetype unless $fd;
3411 if (-T $fd) {
3412 return 'text/plain';
3413 } elsif (! $filename) {
3414 return 'application/octet-stream';
3415 } elsif ($filename =~ m/\.png$/i) {
3416 return 'image/png';
3417 } elsif ($filename =~ m/\.gif$/i) {
3418 return 'image/gif';
3419 } elsif ($filename =~ m/\.jpe?g$/i) {
3420 return 'image/jpeg';
3421 } else {
3422 return 'application/octet-stream';
3426 sub blob_contenttype {
3427 my ($fd, $file_name, $type) = @_;
3429 $type ||= blob_mimetype($fd, $file_name);
3430 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3431 $type .= "; charset=$default_text_plain_charset";
3434 return $type;
3437 # guess file syntax for syntax highlighting; return undef if no highlighting
3438 # the name of syntax can (in the future) depend on syntax highlighter used
3439 sub guess_file_syntax {
3440 my ($highlight, $mimetype, $file_name) = @_;
3441 return undef unless ($highlight && defined $file_name);
3442 my $basename = basename($file_name, '.in');
3443 return $highlight_basename{$basename}
3444 if exists $highlight_basename{$basename};
3446 $basename =~ /\.([^.]*)$/;
3447 my $ext = $1 or return undef;
3448 return $highlight_ext{$ext}
3449 if exists $highlight_ext{$ext};
3451 return undef;
3454 # run highlighter and return FD of its output,
3455 # or return original FD if no highlighting
3456 sub run_highlighter {
3457 my ($fd, $highlight, $syntax) = @_;
3458 return $fd unless ($highlight && defined $syntax);
3460 close $fd
3461 or die_error(404, "Reading blob failed");
3462 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3463 quote_command($highlight_bin).
3464 " --xhtml --fragment --syntax $syntax |"
3465 or die_error(500, "Couldn't open file or run syntax highlighter");
3466 return $fd;
3469 ## ======================================================================
3470 ## functions printing HTML: header, footer, error page
3472 sub get_page_title {
3473 my $title = to_utf8($site_name);
3475 return $title unless (defined $project);
3476 $title .= " - " . to_utf8($project);
3478 return $title unless (defined $action);
3479 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3481 return $title unless (defined $file_name);
3482 $title .= " - " . esc_path($file_name);
3483 if ($action eq "tree" && $file_name !~ m|/$|) {
3484 $title .= "/";
3487 return $title;
3490 sub git_header_html {
3491 my $status = shift || "200 OK";
3492 my $expires = shift;
3493 my %opts = @_;
3495 my $title = get_page_title();
3496 my $content_type;
3497 # require explicit support from the UA if we are to send the page as
3498 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3499 # we have to do this because MSIE sometimes globs '*/*', pretending to
3500 # support xhtml+xml but choking when it gets what it asked for.
3501 if (defined $cgi->http('HTTP_ACCEPT') &&
3502 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3503 $cgi->Accept('application/xhtml+xml') != 0) {
3504 $content_type = 'application/xhtml+xml';
3505 } else {
3506 $content_type = 'text/html';
3508 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3509 -status=> $status, -expires => $expires)
3510 unless ($opts{'-no_http_header'});
3511 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3512 print <<EOF;
3513 <?xml version="1.0" encoding="utf-8"?>
3514 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3515 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3516 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3517 <!-- git core binaries version $git_version -->
3518 <head>
3519 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3520 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3521 <meta name="robots" content="index, nofollow"/>
3522 <title>$title</title>
3524 # the stylesheet, favicon etc urls won't work correctly with path_info
3525 # unless we set the appropriate base URL
3526 if ($ENV{'PATH_INFO'}) {
3527 print "<base href=\"".esc_url($base_url)."\" />\n";
3529 # print out each stylesheet that exist, providing backwards capability
3530 # for those people who defined $stylesheet in a config file
3531 if (defined $stylesheet) {
3532 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3533 } else {
3534 foreach my $stylesheet (@stylesheets) {
3535 next unless $stylesheet;
3536 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3539 if (defined $project) {
3540 my %href_params = get_feed_info();
3541 if (!exists $href_params{'-title'}) {
3542 $href_params{'-title'} = 'log';
3545 foreach my $format qw(RSS Atom) {
3546 my $type = lc($format);
3547 my %link_attr = (
3548 '-rel' => 'alternate',
3549 '-title' => "$project - $href_params{'-title'} - $format feed",
3550 '-type' => "application/$type+xml"
3553 $href_params{'action'} = $type;
3554 $link_attr{'-href'} = href(%href_params);
3555 print "<link ".
3556 "rel=\"$link_attr{'-rel'}\" ".
3557 "title=\"$link_attr{'-title'}\" ".
3558 "href=\"$link_attr{'-href'}\" ".
3559 "type=\"$link_attr{'-type'}\" ".
3560 "/>\n";
3562 $href_params{'extra_options'} = '--no-merges';
3563 $link_attr{'-href'} = href(%href_params);
3564 $link_attr{'-title'} .= ' (no merges)';
3565 print "<link ".
3566 "rel=\"$link_attr{'-rel'}\" ".
3567 "title=\"$link_attr{'-title'}\" ".
3568 "href=\"$link_attr{'-href'}\" ".
3569 "type=\"$link_attr{'-type'}\" ".
3570 "/>\n";
3573 } else {
3574 printf('<link rel="alternate" title="%s projects list" '.
3575 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3576 $site_name, href(project=>undef, action=>"project_index"));
3577 printf('<link rel="alternate" title="%s projects feeds" '.
3578 'href="%s" type="text/x-opml" />'."\n",
3579 $site_name, href(project=>undef, action=>"opml"));
3581 if (defined $favicon) {
3582 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3585 print "</head>\n" .
3586 "<body>\n";
3588 if (defined $site_header && -f $site_header) {
3589 insert_file($site_header);
3592 print "<div class=\"page_header\">\n" .
3593 $cgi->a({-href => esc_url($logo_url),
3594 -title => $logo_label},
3595 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3596 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3597 if (defined $project) {
3598 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3599 if (defined $action) {
3600 my $action_print = $action ;
3601 if (defined $opts{-action_extra}) {
3602 $action_print = $cgi->a({-href => href(action=>$action)},
3603 $action);
3605 print " / $action_print";
3607 if (defined $opts{-action_extra}) {
3608 print " / $opts{-action_extra}";
3610 print "\n";
3612 print "</div>\n";
3614 my $have_search = gitweb_check_feature('search');
3615 if (defined $project && $have_search) {
3616 if (!defined $searchtext) {
3617 $searchtext = "";
3619 my $search_hash;
3620 if (defined $hash_base) {
3621 $search_hash = $hash_base;
3622 } elsif (defined $hash) {
3623 $search_hash = $hash;
3624 } else {
3625 $search_hash = "HEAD";
3627 my $action = $my_uri;
3628 my $use_pathinfo = gitweb_check_feature('pathinfo');
3629 if ($use_pathinfo) {
3630 $action .= "/".esc_url($project);
3632 print $cgi->startform(-method => "get", -action => $action) .
3633 "<div class=\"search\">\n" .
3634 (!$use_pathinfo &&
3635 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3636 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3637 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3638 $cgi->popup_menu(-name => 'st', -default => 'commit',
3639 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3640 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3641 " search:\n",
3642 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3643 "<span title=\"Extended regular expression\">" .
3644 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3645 -checked => $search_use_regexp) .
3646 "</span>" .
3647 "</div>" .
3648 $cgi->end_form() . "\n";
3652 sub git_footer_html {
3653 my $feed_class = 'rss_logo';
3655 print "<div class=\"page_footer\">\n";
3656 if (defined $project) {
3657 my $descr = git_get_project_description($project);
3658 if (defined $descr) {
3659 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3662 my %href_params = get_feed_info();
3663 if (!%href_params) {
3664 $feed_class .= ' generic';
3666 $href_params{'-title'} ||= 'log';
3668 foreach my $format qw(RSS Atom) {
3669 $href_params{'action'} = lc($format);
3670 print $cgi->a({-href => href(%href_params),
3671 -title => "$href_params{'-title'} $format feed",
3672 -class => $feed_class}, $format)."\n";
3675 } else {
3676 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3677 -class => $feed_class}, "OPML") . " ";
3678 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3679 -class => $feed_class}, "TXT") . "\n";
3681 print "</div>\n"; # class="page_footer"
3683 if (defined $t0 && gitweb_check_feature('timed')) {
3684 print "<div id=\"generating_info\">\n";
3685 print 'This page took '.
3686 '<span id="generating_time" class="time_span">'.
3687 tv_interval($t0, [ gettimeofday() ]).
3688 ' seconds </span>'.
3689 ' and '.
3690 '<span id="generating_cmd">'.
3691 $number_of_git_cmds.
3692 '</span> git commands '.
3693 " to generate.\n";
3694 print "</div>\n"; # class="page_footer"
3697 if (defined $site_footer && -f $site_footer) {
3698 insert_file($site_footer);
3701 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3702 if (defined $action &&
3703 $action eq 'blame_incremental') {
3704 print qq!<script type="text/javascript">\n!.
3705 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3706 qq! "!. href() .qq!");\n!.
3707 qq!</script>\n!;
3708 } elsif (gitweb_check_feature('javascript-actions')) {
3709 print qq!<script type="text/javascript">\n!.
3710 qq!window.onload = fixLinks;\n!.
3711 qq!</script>\n!;
3714 print "</body>\n" .
3715 "</html>";
3718 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3719 # Example: die_error(404, 'Hash not found')
3720 # By convention, use the following status codes (as defined in RFC 2616):
3721 # 400: Invalid or missing CGI parameters, or
3722 # requested object exists but has wrong type.
3723 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3724 # this server or project.
3725 # 404: Requested object/revision/project doesn't exist.
3726 # 500: The server isn't configured properly, or
3727 # an internal error occurred (e.g. failed assertions caused by bugs), or
3728 # an unknown error occurred (e.g. the git binary died unexpectedly).
3729 # 503: The server is currently unavailable (because it is overloaded,
3730 # or down for maintenance). Generally, this is a temporary state.
3731 sub die_error {
3732 my $status = shift || 500;
3733 my $error = esc_html(shift) || "Internal Server Error";
3734 my $extra = shift;
3735 my %opts = @_;
3737 my %http_responses = (
3738 400 => '400 Bad Request',
3739 403 => '403 Forbidden',
3740 404 => '404 Not Found',
3741 500 => '500 Internal Server Error',
3742 503 => '503 Service Unavailable',
3744 git_header_html($http_responses{$status}, undef, %opts);
3745 print <<EOF;
3746 <div class="page_body">
3747 <br /><br />
3748 $status - $error
3749 <br />
3751 if (defined $extra) {
3752 print "<hr />\n" .
3753 "$extra\n";
3755 print "</div>\n";
3757 git_footer_html();
3758 goto DONE_GITWEB
3759 unless ($opts{'-error_handler'});
3762 ## ----------------------------------------------------------------------
3763 ## functions printing or outputting HTML: navigation
3765 sub git_print_page_nav {
3766 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3767 $extra = '' if !defined $extra; # pager or formats
3769 my @navs = qw(summary shortlog log commit commitdiff tree);
3770 if ($suppress) {
3771 @navs = grep { $_ ne $suppress } @navs;
3774 my %arg = map { $_ => {action=>$_} } @navs;
3775 if (defined $head) {
3776 for (qw(commit commitdiff)) {
3777 $arg{$_}{'hash'} = $head;
3779 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3780 for (qw(shortlog log)) {
3781 $arg{$_}{'hash'} = $head;
3786 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3787 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3789 my @actions = gitweb_get_feature('actions');
3790 my %repl = (
3791 '%' => '%',
3792 'n' => $project, # project name
3793 'f' => $git_dir, # project path within filesystem
3794 'h' => $treehead || '', # current hash ('h' parameter)
3795 'b' => $treebase || '', # hash base ('hb' parameter)
3797 while (@actions) {
3798 my ($label, $link, $pos) = splice(@actions,0,3);
3799 # insert
3800 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3801 # munch munch
3802 $link =~ s/%([%nfhb])/$repl{$1}/g;
3803 $arg{$label}{'_href'} = $link;
3806 print "<div class=\"page_nav\">\n" .
3807 (join " | ",
3808 map { $_ eq $current ?
3809 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3810 } @navs);
3811 print "<br/>\n$extra<br/>\n" .
3812 "</div>\n";
3815 # returns a submenu for the nagivation of the refs views (tags, heads,
3816 # remotes) with the current view disabled and the remotes view only
3817 # available if the feature is enabled
3818 sub format_ref_views {
3819 my ($current) = @_;
3820 my @ref_views = qw{tags heads};
3821 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
3822 return join " | ", map {
3823 $_ eq $current ? $_ :
3824 $cgi->a({-href => href(action=>$_)}, $_)
3825 } @ref_views
3828 sub format_paging_nav {
3829 my ($action, $page, $has_next_link) = @_;
3830 my $paging_nav;
3833 if ($page > 0) {
3834 $paging_nav .=
3835 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3836 " &sdot; " .
3837 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3838 -accesskey => "p", -title => "Alt-p"}, "prev");
3839 } else {
3840 $paging_nav .= "first &sdot; prev";
3843 if ($has_next_link) {
3844 $paging_nav .= " &sdot; " .
3845 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3846 -accesskey => "n", -title => "Alt-n"}, "next");
3847 } else {
3848 $paging_nav .= " &sdot; next";
3851 return $paging_nav;
3854 ## ......................................................................
3855 ## functions printing or outputting HTML: div
3857 sub git_print_header_div {
3858 my ($action, $title, $hash, $hash_base) = @_;
3859 my %args = ();
3861 $args{'action'} = $action;
3862 $args{'hash'} = $hash if $hash;
3863 $args{'hash_base'} = $hash_base if $hash_base;
3865 print "<div class=\"header\">\n" .
3866 $cgi->a({-href => href(%args), -class => "title"},
3867 $title ? $title : $action) .
3868 "\n</div>\n";
3871 sub format_repo_url {
3872 my ($name, $url) = @_;
3873 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
3876 # Group output by placing it in a DIV element and adding a header.
3877 # Options for start_div() can be provided by passing a hash reference as the
3878 # first parameter to the function.
3879 # Options to git_print_header_div() can be provided by passing an array
3880 # reference. This must follow the options to start_div if they are present.
3881 # The content can be a scalar, which is output as-is, a scalar reference, which
3882 # is output after html escaping, an IO handle passed either as *handle or
3883 # *handle{IO}, or a function reference. In the latter case all following
3884 # parameters will be taken as argument to the content function call.
3885 sub git_print_section {
3886 my ($div_args, $header_args, $content);
3887 my $arg = shift;
3888 if (ref($arg) eq 'HASH') {
3889 $div_args = $arg;
3890 $arg = shift;
3892 if (ref($arg) eq 'ARRAY') {
3893 $header_args = $arg;
3894 $arg = shift;
3896 $content = $arg;
3898 print $cgi->start_div($div_args);
3899 git_print_header_div(@$header_args);
3901 if (ref($content) eq 'CODE') {
3902 $content->(@_);
3903 } elsif (ref($content) eq 'SCALAR') {
3904 print esc_html($$content);
3905 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
3906 print <$content>;
3907 } elsif (!ref($content) && defined($content)) {
3908 print $content;
3911 print $cgi->end_div;
3914 sub print_local_time {
3915 print format_local_time(@_);
3918 sub format_local_time {
3919 my $localtime = '';
3920 my %date = @_;
3921 if ($date{'hour_local'} < 6) {
3922 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3923 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3924 } else {
3925 $localtime .= sprintf(" (%02d:%02d %s)",
3926 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3929 return $localtime;
3932 # Outputs the author name and date in long form
3933 sub git_print_authorship {
3934 my $co = shift;
3935 my %opts = @_;
3936 my $tag = $opts{-tag} || 'div';
3937 my $author = $co->{'author_name'};
3939 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3940 print "<$tag class=\"author_date\">" .
3941 format_search_author($author, "author", esc_html($author)) .
3942 " [$ad{'rfc2822'}";
3943 print_local_time(%ad) if ($opts{-localtime});
3944 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3945 . "</$tag>\n";
3948 # Outputs table rows containing the full author or committer information,
3949 # in the format expected for 'commit' view (& similar).
3950 # Parameters are a commit hash reference, followed by the list of people
3951 # to output information for. If the list is empty it defaults to both
3952 # author and committer.
3953 sub git_print_authorship_rows {
3954 my $co = shift;
3955 # too bad we can't use @people = @_ || ('author', 'committer')
3956 my @people = @_;
3957 @people = ('author', 'committer') unless @people;
3958 foreach my $who (@people) {
3959 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3960 print "<tr><td>$who</td><td>" .
3961 format_search_author($co->{"${who}_name"}, $who,
3962 esc_html($co->{"${who}_name"})) . " " .
3963 format_search_author($co->{"${who}_email"}, $who,
3964 esc_html("<" . $co->{"${who}_email"} . ">")) .
3965 "</td><td rowspan=\"2\">" .
3966 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3967 "</td></tr>\n" .
3968 "<tr>" .
3969 "<td></td><td> $wd{'rfc2822'}";
3970 print_local_time(%wd);
3971 print "</td>" .
3972 "</tr>\n";
3976 sub git_print_page_path {
3977 my $name = shift;
3978 my $type = shift;
3979 my $hb = shift;
3982 print "<div class=\"page_path\">";
3983 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3984 -title => 'tree root'}, to_utf8("[$project]"));
3985 print " / ";
3986 if (defined $name) {
3987 my @dirname = split '/', $name;
3988 my $basename = pop @dirname;
3989 my $fullname = '';
3991 foreach my $dir (@dirname) {
3992 $fullname .= ($fullname ? '/' : '') . $dir;
3993 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3994 hash_base=>$hb),
3995 -title => $fullname}, esc_path($dir));
3996 print " / ";
3998 if (defined $type && $type eq 'blob') {
3999 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4000 hash_base=>$hb),
4001 -title => $name}, esc_path($basename));
4002 } elsif (defined $type && $type eq 'tree') {
4003 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4004 hash_base=>$hb),
4005 -title => $name}, esc_path($basename));
4006 print " / ";
4007 } else {
4008 print esc_path($basename);
4011 print "<br/></div>\n";
4014 sub git_print_log {
4015 my $log = shift;
4016 my %opts = @_;
4018 if ($opts{'-remove_title'}) {
4019 # remove title, i.e. first line of log
4020 shift @$log;
4022 # remove leading empty lines
4023 while (defined $log->[0] && $log->[0] eq "") {
4024 shift @$log;
4027 # print log
4028 my $signoff = 0;
4029 my $empty = 0;
4030 foreach my $line (@$log) {
4031 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4032 $signoff = 1;
4033 $empty = 0;
4034 if (! $opts{'-remove_signoff'}) {
4035 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4036 next;
4037 } else {
4038 # remove signoff lines
4039 next;
4041 } else {
4042 $signoff = 0;
4045 # print only one empty line
4046 # do not print empty line after signoff
4047 if ($line eq "") {
4048 next if ($empty || $signoff);
4049 $empty = 1;
4050 } else {
4051 $empty = 0;
4054 print format_log_line_html($line) . "<br/>\n";
4057 if ($opts{'-final_empty_line'}) {
4058 # end with single empty line
4059 print "<br/>\n" unless $empty;
4063 # return link target (what link points to)
4064 sub git_get_link_target {
4065 my $hash = shift;
4066 my $link_target;
4068 # read link
4069 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4070 or return;
4072 local $/ = undef;
4073 $link_target = <$fd>;
4075 close $fd
4076 or return;
4078 return $link_target;
4081 # given link target, and the directory (basedir) the link is in,
4082 # return target of link relative to top directory (top tree);
4083 # return undef if it is not possible (including absolute links).
4084 sub normalize_link_target {
4085 my ($link_target, $basedir) = @_;
4087 # absolute symlinks (beginning with '/') cannot be normalized
4088 return if (substr($link_target, 0, 1) eq '/');
4090 # normalize link target to path from top (root) tree (dir)
4091 my $path;
4092 if ($basedir) {
4093 $path = $basedir . '/' . $link_target;
4094 } else {
4095 # we are in top (root) tree (dir)
4096 $path = $link_target;
4099 # remove //, /./, and /../
4100 my @path_parts;
4101 foreach my $part (split('/', $path)) {
4102 # discard '.' and ''
4103 next if (!$part || $part eq '.');
4104 # handle '..'
4105 if ($part eq '..') {
4106 if (@path_parts) {
4107 pop @path_parts;
4108 } else {
4109 # link leads outside repository (outside top dir)
4110 return;
4112 } else {
4113 push @path_parts, $part;
4116 $path = join('/', @path_parts);
4118 return $path;
4121 # print tree entry (row of git_tree), but without encompassing <tr> element
4122 sub git_print_tree_entry {
4123 my ($t, $basedir, $hash_base, $have_blame) = @_;
4125 my %base_key = ();
4126 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4128 # The format of a table row is: mode list link. Where mode is
4129 # the mode of the entry, list is the name of the entry, an href,
4130 # and link is the action links of the entry.
4132 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4133 if (exists $t->{'size'}) {
4134 print "<td class=\"size\">$t->{'size'}</td>\n";
4136 if ($t->{'type'} eq "blob") {
4137 print "<td class=\"list\">" .
4138 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4139 file_name=>"$basedir$t->{'name'}", %base_key),
4140 -class => "list"}, esc_path($t->{'name'}));
4141 if (S_ISLNK(oct $t->{'mode'})) {
4142 my $link_target = git_get_link_target($t->{'hash'});
4143 if ($link_target) {
4144 my $norm_target = normalize_link_target($link_target, $basedir);
4145 if (defined $norm_target) {
4146 print " -> " .
4147 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4148 file_name=>$norm_target),
4149 -title => $norm_target}, esc_path($link_target));
4150 } else {
4151 print " -> " . esc_path($link_target);
4155 print "</td>\n";
4156 print "<td class=\"link\">";
4157 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4158 file_name=>"$basedir$t->{'name'}", %base_key)},
4159 "blob");
4160 if ($have_blame) {
4161 print " | " .
4162 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4163 file_name=>"$basedir$t->{'name'}", %base_key)},
4164 "blame");
4166 if (defined $hash_base) {
4167 print " | " .
4168 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4169 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4170 "history");
4172 print " | " .
4173 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4174 file_name=>"$basedir$t->{'name'}")},
4175 "raw");
4176 print "</td>\n";
4178 } elsif ($t->{'type'} eq "tree") {
4179 print "<td class=\"list\">";
4180 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4181 file_name=>"$basedir$t->{'name'}",
4182 %base_key)},
4183 esc_path($t->{'name'}));
4184 print "</td>\n";
4185 print "<td class=\"link\">";
4186 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4187 file_name=>"$basedir$t->{'name'}",
4188 %base_key)},
4189 "tree");
4190 if (defined $hash_base) {
4191 print " | " .
4192 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4193 file_name=>"$basedir$t->{'name'}")},
4194 "history");
4196 print "</td>\n";
4197 } else {
4198 # unknown object: we can only present history for it
4199 # (this includes 'commit' object, i.e. submodule support)
4200 print "<td class=\"list\">" .
4201 esc_path($t->{'name'}) .
4202 "</td>\n";
4203 print "<td class=\"link\">";
4204 if (defined $hash_base) {
4205 print $cgi->a({-href => href(action=>"history",
4206 hash_base=>$hash_base,
4207 file_name=>"$basedir$t->{'name'}")},
4208 "history");
4210 print "</td>\n";
4214 ## ......................................................................
4215 ## functions printing large fragments of HTML
4217 # get pre-image filenames for merge (combined) diff
4218 sub fill_from_file_info {
4219 my ($diff, @parents) = @_;
4221 $diff->{'from_file'} = [ ];
4222 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4223 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4224 if ($diff->{'status'}[$i] eq 'R' ||
4225 $diff->{'status'}[$i] eq 'C') {
4226 $diff->{'from_file'}[$i] =
4227 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4231 return $diff;
4234 # is current raw difftree line of file deletion
4235 sub is_deleted {
4236 my $diffinfo = shift;
4238 return $diffinfo->{'to_id'} eq ('0' x 40);
4241 # does patch correspond to [previous] difftree raw line
4242 # $diffinfo - hashref of parsed raw diff format
4243 # $patchinfo - hashref of parsed patch diff format
4244 # (the same keys as in $diffinfo)
4245 sub is_patch_split {
4246 my ($diffinfo, $patchinfo) = @_;
4248 return defined $diffinfo && defined $patchinfo
4249 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4253 sub git_difftree_body {
4254 my ($difftree, $hash, @parents) = @_;
4255 my ($parent) = $parents[0];
4256 my $have_blame = gitweb_check_feature('blame');
4257 print "<div class=\"list_head\">\n";
4258 if ($#{$difftree} > 10) {
4259 print(($#{$difftree} + 1) . " files changed:\n");
4261 print "</div>\n";
4263 print "<table class=\"" .
4264 (@parents > 1 ? "combined " : "") .
4265 "diff_tree\">\n";
4267 # header only for combined diff in 'commitdiff' view
4268 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4269 if ($has_header) {
4270 # table header
4271 print "<thead><tr>\n" .
4272 "<th></th><th></th>\n"; # filename, patchN link
4273 for (my $i = 0; $i < @parents; $i++) {
4274 my $par = $parents[$i];
4275 print "<th>" .
4276 $cgi->a({-href => href(action=>"commitdiff",
4277 hash=>$hash, hash_parent=>$par),
4278 -title => 'commitdiff to parent number ' .
4279 ($i+1) . ': ' . substr($par,0,7)},
4280 $i+1) .
4281 "&nbsp;</th>\n";
4283 print "</tr></thead>\n<tbody>\n";
4286 my $alternate = 1;
4287 my $patchno = 0;
4288 foreach my $line (@{$difftree}) {
4289 my $diff = parsed_difftree_line($line);
4291 if ($alternate) {
4292 print "<tr class=\"dark\">\n";
4293 } else {
4294 print "<tr class=\"light\">\n";
4296 $alternate ^= 1;
4298 if (exists $diff->{'nparents'}) { # combined diff
4300 fill_from_file_info($diff, @parents)
4301 unless exists $diff->{'from_file'};
4303 if (!is_deleted($diff)) {
4304 # file exists in the result (child) commit
4305 print "<td>" .
4306 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4307 file_name=>$diff->{'to_file'},
4308 hash_base=>$hash),
4309 -class => "list"}, esc_path($diff->{'to_file'})) .
4310 "</td>\n";
4311 } else {
4312 print "<td>" .
4313 esc_path($diff->{'to_file'}) .
4314 "</td>\n";
4317 if ($action eq 'commitdiff') {
4318 # link to patch
4319 $patchno++;
4320 print "<td class=\"link\">" .
4321 $cgi->a({-href => "#patch$patchno"}, "patch") .
4322 " | " .
4323 "</td>\n";
4326 my $has_history = 0;
4327 my $not_deleted = 0;
4328 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4329 my $hash_parent = $parents[$i];
4330 my $from_hash = $diff->{'from_id'}[$i];
4331 my $from_path = $diff->{'from_file'}[$i];
4332 my $status = $diff->{'status'}[$i];
4334 $has_history ||= ($status ne 'A');
4335 $not_deleted ||= ($status ne 'D');
4337 if ($status eq 'A') {
4338 print "<td class=\"link\" align=\"right\"> | </td>\n";
4339 } elsif ($status eq 'D') {
4340 print "<td class=\"link\">" .
4341 $cgi->a({-href => href(action=>"blob",
4342 hash_base=>$hash,
4343 hash=>$from_hash,
4344 file_name=>$from_path)},
4345 "blob" . ($i+1)) .
4346 " | </td>\n";
4347 } else {
4348 if ($diff->{'to_id'} eq $from_hash) {
4349 print "<td class=\"link nochange\">";
4350 } else {
4351 print "<td class=\"link\">";
4353 print $cgi->a({-href => href(action=>"blobdiff",
4354 hash=>$diff->{'to_id'},
4355 hash_parent=>$from_hash,
4356 hash_base=>$hash,
4357 hash_parent_base=>$hash_parent,
4358 file_name=>$diff->{'to_file'},
4359 file_parent=>$from_path)},
4360 "diff" . ($i+1)) .
4361 " | </td>\n";
4365 print "<td class=\"link\">";
4366 if ($not_deleted) {
4367 print $cgi->a({-href => href(action=>"blob",
4368 hash=>$diff->{'to_id'},
4369 file_name=>$diff->{'to_file'},
4370 hash_base=>$hash)},
4371 "blob");
4372 print " | " if ($has_history);
4374 if ($has_history) {
4375 print $cgi->a({-href => href(action=>"history",
4376 file_name=>$diff->{'to_file'},
4377 hash_base=>$hash)},
4378 "history");
4380 print "</td>\n";
4382 print "</tr>\n";
4383 next; # instead of 'else' clause, to avoid extra indent
4385 # else ordinary diff
4387 my ($to_mode_oct, $to_mode_str, $to_file_type);
4388 my ($from_mode_oct, $from_mode_str, $from_file_type);
4389 if ($diff->{'to_mode'} ne ('0' x 6)) {
4390 $to_mode_oct = oct $diff->{'to_mode'};
4391 if (S_ISREG($to_mode_oct)) { # only for regular file
4392 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4394 $to_file_type = file_type($diff->{'to_mode'});
4396 if ($diff->{'from_mode'} ne ('0' x 6)) {
4397 $from_mode_oct = oct $diff->{'from_mode'};
4398 if (S_ISREG($to_mode_oct)) { # only for regular file
4399 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4401 $from_file_type = file_type($diff->{'from_mode'});
4404 if ($diff->{'status'} eq "A") { # created
4405 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4406 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4407 $mode_chng .= "]</span>";
4408 print "<td>";
4409 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4410 hash_base=>$hash, file_name=>$diff->{'file'}),
4411 -class => "list"}, esc_path($diff->{'file'}));
4412 print "</td>\n";
4413 print "<td>$mode_chng</td>\n";
4414 print "<td class=\"link\">";
4415 if ($action eq 'commitdiff') {
4416 # link to patch
4417 $patchno++;
4418 print $cgi->a({-href => "#patch$patchno"}, "patch");
4419 print " | ";
4421 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4422 hash_base=>$hash, file_name=>$diff->{'file'})},
4423 "blob");
4424 print "</td>\n";
4426 } elsif ($diff->{'status'} eq "D") { # deleted
4427 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4428 print "<td>";
4429 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4430 hash_base=>$parent, file_name=>$diff->{'file'}),
4431 -class => "list"}, esc_path($diff->{'file'}));
4432 print "</td>\n";
4433 print "<td>$mode_chng</td>\n";
4434 print "<td class=\"link\">";
4435 if ($action eq 'commitdiff') {
4436 # link to patch
4437 $patchno++;
4438 print $cgi->a({-href => "#patch$patchno"}, "patch");
4439 print " | ";
4441 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4442 hash_base=>$parent, file_name=>$diff->{'file'})},
4443 "blob") . " | ";
4444 if ($have_blame) {
4445 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4446 file_name=>$diff->{'file'})},
4447 "blame") . " | ";
4449 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4450 file_name=>$diff->{'file'})},
4451 "history");
4452 print "</td>\n";
4454 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4455 my $mode_chnge = "";
4456 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4457 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4458 if ($from_file_type ne $to_file_type) {
4459 $mode_chnge .= " from $from_file_type to $to_file_type";
4461 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4462 if ($from_mode_str && $to_mode_str) {
4463 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4464 } elsif ($to_mode_str) {
4465 $mode_chnge .= " mode: $to_mode_str";
4468 $mode_chnge .= "]</span>\n";
4470 print "<td>";
4471 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4472 hash_base=>$hash, file_name=>$diff->{'file'}),
4473 -class => "list"}, esc_path($diff->{'file'}));
4474 print "</td>\n";
4475 print "<td>$mode_chnge</td>\n";
4476 print "<td class=\"link\">";
4477 if ($action eq 'commitdiff') {
4478 # link to patch
4479 $patchno++;
4480 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4481 " | ";
4482 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4483 # "commit" view and modified file (not onlu mode changed)
4484 print $cgi->a({-href => href(action=>"blobdiff",
4485 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4486 hash_base=>$hash, hash_parent_base=>$parent,
4487 file_name=>$diff->{'file'})},
4488 "diff") .
4489 " | ";
4491 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4492 hash_base=>$hash, file_name=>$diff->{'file'})},
4493 "blob") . " | ";
4494 if ($have_blame) {
4495 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4496 file_name=>$diff->{'file'})},
4497 "blame") . " | ";
4499 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4500 file_name=>$diff->{'file'})},
4501 "history");
4502 print "</td>\n";
4504 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4505 my %status_name = ('R' => 'moved', 'C' => 'copied');
4506 my $nstatus = $status_name{$diff->{'status'}};
4507 my $mode_chng = "";
4508 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4509 # mode also for directories, so we cannot use $to_mode_str
4510 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4512 print "<td>" .
4513 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4514 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4515 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4516 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4517 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4518 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4519 -class => "list"}, esc_path($diff->{'from_file'})) .
4520 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4521 "<td class=\"link\">";
4522 if ($action eq 'commitdiff') {
4523 # link to patch
4524 $patchno++;
4525 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4526 " | ";
4527 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4528 # "commit" view and modified file (not only pure rename or copy)
4529 print $cgi->a({-href => href(action=>"blobdiff",
4530 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4531 hash_base=>$hash, hash_parent_base=>$parent,
4532 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4533 "diff") .
4534 " | ";
4536 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4537 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4538 "blob") . " | ";
4539 if ($have_blame) {
4540 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4541 file_name=>$diff->{'to_file'})},
4542 "blame") . " | ";
4544 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4545 file_name=>$diff->{'to_file'})},
4546 "history");
4547 print "</td>\n";
4549 } # we should not encounter Unmerged (U) or Unknown (X) status
4550 print "</tr>\n";
4552 print "</tbody>" if $has_header;
4553 print "</table>\n";
4556 sub git_patchset_body {
4557 my ($fd, $difftree, $hash, @hash_parents) = @_;
4558 my ($hash_parent) = $hash_parents[0];
4560 my $is_combined = (@hash_parents > 1);
4561 my $patch_idx = 0;
4562 my $patch_number = 0;
4563 my $patch_line;
4564 my $diffinfo;
4565 my $to_name;
4566 my (%from, %to);
4568 print "<div class=\"patchset\">\n";
4570 # skip to first patch
4571 while ($patch_line = <$fd>) {
4572 chomp $patch_line;
4574 last if ($patch_line =~ m/^diff /);
4577 PATCH:
4578 while ($patch_line) {
4580 # parse "git diff" header line
4581 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4582 # $1 is from_name, which we do not use
4583 $to_name = unquote($2);
4584 $to_name =~ s!^b/!!;
4585 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4586 # $1 is 'cc' or 'combined', which we do not use
4587 $to_name = unquote($2);
4588 } else {
4589 $to_name = undef;
4592 # check if current patch belong to current raw line
4593 # and parse raw git-diff line if needed
4594 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4595 # this is continuation of a split patch
4596 print "<div class=\"patch cont\">\n";
4597 } else {
4598 # advance raw git-diff output if needed
4599 $patch_idx++ if defined $diffinfo;
4601 # read and prepare patch information
4602 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4604 # compact combined diff output can have some patches skipped
4605 # find which patch (using pathname of result) we are at now;
4606 if ($is_combined) {
4607 while ($to_name ne $diffinfo->{'to_file'}) {
4608 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4609 format_diff_cc_simplified($diffinfo, @hash_parents) .
4610 "</div>\n"; # class="patch"
4612 $patch_idx++;
4613 $patch_number++;
4615 last if $patch_idx > $#$difftree;
4616 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4620 # modifies %from, %to hashes
4621 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4623 # this is first patch for raw difftree line with $patch_idx index
4624 # we index @$difftree array from 0, but number patches from 1
4625 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4628 # git diff header
4629 #assert($patch_line =~ m/^diff /) if DEBUG;
4630 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4631 $patch_number++;
4632 # print "git diff" header
4633 print format_git_diff_header_line($patch_line, $diffinfo,
4634 \%from, \%to);
4636 # print extended diff header
4637 print "<div class=\"diff extended_header\">\n";
4638 EXTENDED_HEADER:
4639 while ($patch_line = <$fd>) {
4640 chomp $patch_line;
4642 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4644 print format_extended_diff_header_line($patch_line, $diffinfo,
4645 \%from, \%to);
4647 print "</div>\n"; # class="diff extended_header"
4649 # from-file/to-file diff header
4650 if (! $patch_line) {
4651 print "</div>\n"; # class="patch"
4652 last PATCH;
4654 next PATCH if ($patch_line =~ m/^diff /);
4655 #assert($patch_line =~ m/^---/) if DEBUG;
4657 my $last_patch_line = $patch_line;
4658 $patch_line = <$fd>;
4659 chomp $patch_line;
4660 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4662 print format_diff_from_to_header($last_patch_line, $patch_line,
4663 $diffinfo, \%from, \%to,
4664 @hash_parents);
4666 # the patch itself
4667 LINE:
4668 while ($patch_line = <$fd>) {
4669 chomp $patch_line;
4671 next PATCH if ($patch_line =~ m/^diff /);
4673 print format_diff_line($patch_line, \%from, \%to);
4676 } continue {
4677 print "</div>\n"; # class="patch"
4680 # for compact combined (--cc) format, with chunk and patch simplification
4681 # the patchset might be empty, but there might be unprocessed raw lines
4682 for (++$patch_idx if $patch_number > 0;
4683 $patch_idx < @$difftree;
4684 ++$patch_idx) {
4685 # read and prepare patch information
4686 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4688 # generate anchor for "patch" links in difftree / whatchanged part
4689 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4690 format_diff_cc_simplified($diffinfo, @hash_parents) .
4691 "</div>\n"; # class="patch"
4693 $patch_number++;
4696 if ($patch_number == 0) {
4697 if (@hash_parents > 1) {
4698 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4699 } else {
4700 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4704 print "</div>\n"; # class="patchset"
4707 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4709 # fills project list info (age, description, owner, forks) for each
4710 # project in the list, removing invalid projects from returned list
4711 # NOTE: modifies $projlist, but does not remove entries from it
4712 sub fill_project_list_info {
4713 my ($projlist, $check_forks) = @_;
4714 my @projects;
4716 my $show_ctags = gitweb_check_feature('ctags');
4717 PROJECT:
4718 foreach my $pr (@$projlist) {
4719 my (@activity) = git_get_last_activity($pr->{'path'});
4720 unless (@activity) {
4721 next PROJECT;
4723 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4724 if (!defined $pr->{'descr'}) {
4725 my $descr = git_get_project_description($pr->{'path'}) || "";
4726 $descr = to_utf8($descr);
4727 $pr->{'descr_long'} = $descr;
4728 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4730 if (!defined $pr->{'owner'}) {
4731 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4733 if ($check_forks) {
4734 my $pname = $pr->{'path'};
4735 if (($pname =~ s/\.git$//) &&
4736 ($pname !~ /\/$/) &&
4737 (-d "$projectroot/$pname")) {
4738 $pr->{'forks'} = "-d $projectroot/$pname";
4739 } else {
4740 $pr->{'forks'} = 0;
4743 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4744 push @projects, $pr;
4747 return @projects;
4750 # print 'sort by' <th> element, generating 'sort by $name' replay link
4751 # if that order is not selected
4752 sub print_sort_th {
4753 print format_sort_th(@_);
4756 sub format_sort_th {
4757 my ($name, $order, $header) = @_;
4758 my $sort_th = "";
4759 $header ||= ucfirst($name);
4761 if ($order eq $name) {
4762 $sort_th .= "<th>$header</th>\n";
4763 } else {
4764 $sort_th .= "<th>" .
4765 $cgi->a({-href => href(-replay=>1, order=>$name),
4766 -class => "header"}, $header) .
4767 "</th>\n";
4770 return $sort_th;
4773 sub git_project_list_body {
4774 # actually uses global variable $project
4775 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4777 my $check_forks = gitweb_check_feature('forks');
4778 my @projects = fill_project_list_info($projlist, $check_forks);
4780 $order ||= $default_projects_order;
4781 $from = 0 unless defined $from;
4782 $to = $#projects if (!defined $to || $#projects < $to);
4784 my %order_info = (
4785 project => { key => 'path', type => 'str' },
4786 descr => { key => 'descr_long', type => 'str' },
4787 owner => { key => 'owner', type => 'str' },
4788 age => { key => 'age', type => 'num' }
4790 my $oi = $order_info{$order};
4791 if ($oi->{'type'} eq 'str') {
4792 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4793 } else {
4794 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4797 my $show_ctags = gitweb_check_feature('ctags');
4798 if ($show_ctags) {
4799 my %ctags;
4800 foreach my $p (@projects) {
4801 foreach my $ct (keys %{$p->{'ctags'}}) {
4802 $ctags{$ct} += $p->{'ctags'}->{$ct};
4805 my $cloud = git_populate_project_tagcloud(\%ctags);
4806 print git_show_project_tagcloud($cloud, 64);
4809 print "<table class=\"project_list\">\n";
4810 unless ($no_header) {
4811 print "<tr>\n";
4812 if ($check_forks) {
4813 print "<th></th>\n";
4815 print_sort_th('project', $order, 'Project');
4816 print_sort_th('descr', $order, 'Description');
4817 print_sort_th('owner', $order, 'Owner');
4818 print_sort_th('age', $order, 'Last Change');
4819 print "<th></th>\n" . # for links
4820 "</tr>\n";
4822 my $alternate = 1;
4823 my $tagfilter = $cgi->param('by_tag');
4824 for (my $i = $from; $i <= $to; $i++) {
4825 my $pr = $projects[$i];
4827 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4828 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4829 and not $pr->{'descr_long'} =~ /$searchtext/;
4830 # Weed out forks or non-matching entries of search
4831 if ($check_forks) {
4832 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4833 $forkbase="^$forkbase" if $forkbase;
4834 next if not $searchtext and not $tagfilter and $show_ctags
4835 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4838 if ($alternate) {
4839 print "<tr class=\"dark\">\n";
4840 } else {
4841 print "<tr class=\"light\">\n";
4843 $alternate ^= 1;
4844 if ($check_forks) {
4845 print "<td>";
4846 if ($pr->{'forks'}) {
4847 print "<!-- $pr->{'forks'} -->\n";
4848 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4850 print "</td>\n";
4852 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4853 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4854 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4855 -class => "list", -title => $pr->{'descr_long'}},
4856 esc_html($pr->{'descr'})) . "</td>\n" .
4857 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4858 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4859 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4860 "<td class=\"link\">" .
4861 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4862 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4863 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4864 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4865 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4866 "</td>\n" .
4867 "</tr>\n";
4869 if (defined $extra) {
4870 print "<tr>\n";
4871 if ($check_forks) {
4872 print "<td></td>\n";
4874 print "<td colspan=\"5\">$extra</td>\n" .
4875 "</tr>\n";
4877 print "</table>\n";
4880 sub git_log_body {
4881 # uses global variable $project
4882 my ($commitlist, $from, $to, $refs, $extra) = @_;
4884 $from = 0 unless defined $from;
4885 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4887 for (my $i = 0; $i <= $to; $i++) {
4888 my %co = %{$commitlist->[$i]};
4889 next if !%co;
4890 my $commit = $co{'id'};
4891 my $ref = format_ref_marker($refs, $commit);
4892 my %ad = parse_date($co{'author_epoch'});
4893 git_print_header_div('commit',
4894 "<span class=\"age\">$co{'age_string'}</span>" .
4895 esc_html($co{'title'}) . $ref,
4896 $commit);
4897 print "<div class=\"title_text\">\n" .
4898 "<div class=\"log_link\">\n" .
4899 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4900 " | " .
4901 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4902 " | " .
4903 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4904 "<br/>\n" .
4905 "</div>\n";
4906 git_print_authorship(\%co, -tag => 'span');
4907 print "<br/>\n</div>\n";
4909 print "<div class=\"log_body\">\n";
4910 git_print_log($co{'comment'}, -final_empty_line=> 1);
4911 print "</div>\n";
4913 if ($extra) {
4914 print "<div class=\"page_nav\">\n";
4915 print "$extra\n";
4916 print "</div>\n";
4920 sub git_shortlog_body {
4921 # uses global variable $project
4922 my ($commitlist, $from, $to, $refs, $extra) = @_;
4924 $from = 0 unless defined $from;
4925 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4927 print "<table class=\"shortlog\">\n";
4928 my $alternate = 1;
4929 for (my $i = $from; $i <= $to; $i++) {
4930 my %co = %{$commitlist->[$i]};
4931 my $commit = $co{'id'};
4932 my $ref = format_ref_marker($refs, $commit);
4933 if ($alternate) {
4934 print "<tr class=\"dark\">\n";
4935 } else {
4936 print "<tr class=\"light\">\n";
4938 $alternate ^= 1;
4939 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4940 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4941 format_author_html('td', \%co, 10) . "<td>";
4942 print format_subject_html($co{'title'}, $co{'title_short'},
4943 href(action=>"commit", hash=>$commit), $ref);
4944 print "</td>\n" .
4945 "<td class=\"link\">" .
4946 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4947 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4948 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4949 my $snapshot_links = format_snapshot_links($commit);
4950 if (defined $snapshot_links) {
4951 print " | " . $snapshot_links;
4953 print "</td>\n" .
4954 "</tr>\n";
4956 if (defined $extra) {
4957 print "<tr>\n" .
4958 "<td colspan=\"4\">$extra</td>\n" .
4959 "</tr>\n";
4961 print "</table>\n";
4964 sub git_history_body {
4965 # Warning: assumes constant type (blob or tree) during history
4966 my ($commitlist, $from, $to, $refs, $extra,
4967 $file_name, $file_hash, $ftype) = @_;
4969 $from = 0 unless defined $from;
4970 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4972 print "<table class=\"history\">\n";
4973 my $alternate = 1;
4974 for (my $i = $from; $i <= $to; $i++) {
4975 my %co = %{$commitlist->[$i]};
4976 if (!%co) {
4977 next;
4979 my $commit = $co{'id'};
4981 my $ref = format_ref_marker($refs, $commit);
4983 if ($alternate) {
4984 print "<tr class=\"dark\">\n";
4985 } else {
4986 print "<tr class=\"light\">\n";
4988 $alternate ^= 1;
4989 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4990 # shortlog: format_author_html('td', \%co, 10)
4991 format_author_html('td', \%co, 15, 3) . "<td>";
4992 # originally git_history used chop_str($co{'title'}, 50)
4993 print format_subject_html($co{'title'}, $co{'title_short'},
4994 href(action=>"commit", hash=>$commit), $ref);
4995 print "</td>\n" .
4996 "<td class=\"link\">" .
4997 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4998 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5000 if ($ftype eq 'blob') {
5001 my $blob_current = $file_hash;
5002 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5003 if (defined $blob_current && defined $blob_parent &&
5004 $blob_current ne $blob_parent) {
5005 print " | " .
5006 $cgi->a({-href => href(action=>"blobdiff",
5007 hash=>$blob_current, hash_parent=>$blob_parent,
5008 hash_base=>$hash_base, hash_parent_base=>$commit,
5009 file_name=>$file_name)},
5010 "diff to current");
5013 print "</td>\n" .
5014 "</tr>\n";
5016 if (defined $extra) {
5017 print "<tr>\n" .
5018 "<td colspan=\"4\">$extra</td>\n" .
5019 "</tr>\n";
5021 print "</table>\n";
5024 sub git_tags_body {
5025 # uses global variable $project
5026 my ($taglist, $from, $to, $extra) = @_;
5027 $from = 0 unless defined $from;
5028 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5030 print "<table class=\"tags\">\n";
5031 my $alternate = 1;
5032 for (my $i = $from; $i <= $to; $i++) {
5033 my $entry = $taglist->[$i];
5034 my %tag = %$entry;
5035 my $comment = $tag{'subject'};
5036 my $comment_short;
5037 if (defined $comment) {
5038 $comment_short = chop_str($comment, 30, 5);
5040 if ($alternate) {
5041 print "<tr class=\"dark\">\n";
5042 } else {
5043 print "<tr class=\"light\">\n";
5045 $alternate ^= 1;
5046 if (defined $tag{'age'}) {
5047 print "<td><i>$tag{'age'}</i></td>\n";
5048 } else {
5049 print "<td></td>\n";
5051 print "<td>" .
5052 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5053 -class => "list name"}, esc_html($tag{'name'})) .
5054 "</td>\n" .
5055 "<td>";
5056 if (defined $comment) {
5057 print format_subject_html($comment, $comment_short,
5058 href(action=>"tag", hash=>$tag{'id'}));
5060 print "</td>\n" .
5061 "<td class=\"selflink\">";
5062 if ($tag{'type'} eq "tag") {
5063 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5064 } else {
5065 print "&nbsp;";
5067 print "</td>\n" .
5068 "<td class=\"link\">" . " | " .
5069 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5070 if ($tag{'reftype'} eq "commit") {
5071 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5072 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5073 } elsif ($tag{'reftype'} eq "blob") {
5074 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5076 print "</td>\n" .
5077 "</tr>";
5079 if (defined $extra) {
5080 print "<tr>\n" .
5081 "<td colspan=\"5\">$extra</td>\n" .
5082 "</tr>\n";
5084 print "</table>\n";
5087 sub git_heads_body {
5088 # uses global variable $project
5089 my ($headlist, $head, $from, $to, $extra) = @_;
5090 $from = 0 unless defined $from;
5091 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5093 print "<table class=\"heads\">\n";
5094 my $alternate = 1;
5095 for (my $i = $from; $i <= $to; $i++) {
5096 my $entry = $headlist->[$i];
5097 my %ref = %$entry;
5098 my $curr = $ref{'id'} eq $head;
5099 if ($alternate) {
5100 print "<tr class=\"dark\">\n";
5101 } else {
5102 print "<tr class=\"light\">\n";
5104 $alternate ^= 1;
5105 print "<td><i>$ref{'age'}</i></td>\n" .
5106 ($curr ? "<td class=\"current_head\">" : "<td>") .
5107 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5108 -class => "list name"},esc_html($ref{'name'})) .
5109 "</td>\n" .
5110 "<td class=\"link\">" .
5111 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5112 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5113 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
5114 "</td>\n" .
5115 "</tr>";
5117 if (defined $extra) {
5118 print "<tr>\n" .
5119 "<td colspan=\"3\">$extra</td>\n" .
5120 "</tr>\n";
5122 print "</table>\n";
5125 # Display a single remote block
5126 sub git_remote_block {
5127 my ($remote, $rdata, $limit, $head) = @_;
5129 my $heads = $rdata->{'heads'};
5130 my $fetch = $rdata->{'fetch'};
5131 my $push = $rdata->{'push'};
5133 my $urls_table = "<table class=\"projects_list\">\n" ;
5135 if (defined $fetch) {
5136 if ($fetch eq $push) {
5137 $urls_table .= format_repo_url("URL", $fetch);
5138 } else {
5139 $urls_table .= format_repo_url("Fetch URL", $fetch);
5140 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
5142 } elsif (defined $push) {
5143 $urls_table .= format_repo_url("Push URL", $push);
5144 } else {
5145 $urls_table .= format_repo_url("", "No remote URL");
5148 $urls_table .= "</table>\n";
5150 my $dots;
5151 if (defined $limit && $limit < @$heads) {
5152 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
5155 print $urls_table;
5156 git_heads_body($heads, $head, 0, $limit, $dots);
5159 # Display a list of remote names with the respective fetch and push URLs
5160 sub git_remotes_list {
5161 my ($remotedata, $limit) = @_;
5162 print "<table class=\"heads\">\n";
5163 my $alternate = 1;
5164 my @remotes = sort keys %$remotedata;
5166 my $limited = $limit && $limit < @remotes;
5168 $#remotes = $limit - 1 if $limited;
5170 while (my $remote = shift @remotes) {
5171 my $rdata = $remotedata->{$remote};
5172 my $fetch = $rdata->{'fetch'};
5173 my $push = $rdata->{'push'};
5174 if ($alternate) {
5175 print "<tr class=\"dark\">\n";
5176 } else {
5177 print "<tr class=\"light\">\n";
5179 $alternate ^= 1;
5180 print "<td>" .
5181 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
5182 -class=> "list name"},esc_html($remote)) .
5183 "</td>";
5184 print "<td class=\"link\">" .
5185 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
5186 " | " .
5187 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
5188 "</td>";
5190 print "</tr>\n";
5193 if ($limited) {
5194 print "<tr>\n" .
5195 "<td colspan=\"3\">" .
5196 $cgi->a({-href => href(action=>"remotes")}, "...") .
5197 "</td>\n" . "</tr>\n";
5200 print "</table>";
5203 # Display remote heads grouped by remote, unless there are too many
5204 # remotes, in which case we only display the remote names
5205 sub git_remotes_body {
5206 my ($remotedata, $limit, $head) = @_;
5207 if ($limit and $limit < keys %$remotedata) {
5208 git_remotes_list($remotedata, $limit);
5209 } else {
5210 fill_remote_heads($remotedata);
5211 while (my ($remote, $rdata) = each %$remotedata) {
5212 git_print_section({-class=>"remote", -id=>$remote},
5213 ["remotes", $remote, $remote], sub {
5214 git_remote_block($remote, $rdata, $limit, $head);
5220 sub git_search_grep_body {
5221 my ($commitlist, $from, $to, $extra) = @_;
5222 $from = 0 unless defined $from;
5223 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5225 print "<table class=\"commit_search\">\n";
5226 my $alternate = 1;
5227 for (my $i = $from; $i <= $to; $i++) {
5228 my %co = %{$commitlist->[$i]};
5229 if (!%co) {
5230 next;
5232 my $commit = $co{'id'};
5233 if ($alternate) {
5234 print "<tr class=\"dark\">\n";
5235 } else {
5236 print "<tr class=\"light\">\n";
5238 $alternate ^= 1;
5239 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5240 format_author_html('td', \%co, 15, 5) .
5241 "<td>" .
5242 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5243 -class => "list subject"},
5244 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5245 my $comment = $co{'comment'};
5246 foreach my $line (@$comment) {
5247 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5248 my ($lead, $match, $trail) = ($1, $2, $3);
5249 $match = chop_str($match, 70, 5, 'center');
5250 my $contextlen = int((80 - length($match))/2);
5251 $contextlen = 30 if ($contextlen > 30);
5252 $lead = chop_str($lead, $contextlen, 10, 'left');
5253 $trail = chop_str($trail, $contextlen, 10, 'right');
5255 $lead = esc_html($lead);
5256 $match = esc_html($match);
5257 $trail = esc_html($trail);
5259 print "$lead<span class=\"match\">$match</span>$trail<br />";
5262 print "</td>\n" .
5263 "<td class=\"link\">" .
5264 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5265 " | " .
5266 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5267 " | " .
5268 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5269 print "</td>\n" .
5270 "</tr>\n";
5272 if (defined $extra) {
5273 print "<tr>\n" .
5274 "<td colspan=\"3\">$extra</td>\n" .
5275 "</tr>\n";
5277 print "</table>\n";
5280 ## ======================================================================
5281 ## ======================================================================
5282 ## actions
5284 sub git_project_list {
5285 my $order = $input_params{'order'};
5286 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5287 die_error(400, "Unknown order parameter");
5290 my @list = git_get_projects_list();
5291 if (!@list) {
5292 die_error(404, "No projects found");
5295 git_header_html();
5296 if (defined $home_text && -f $home_text) {
5297 print "<div class=\"index_include\">\n";
5298 insert_file($home_text);
5299 print "</div>\n";
5301 print $cgi->startform(-method => "get") .
5302 "<p class=\"projsearch\">Search:\n" .
5303 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5304 "</p>" .
5305 $cgi->end_form() . "\n";
5306 git_project_list_body(\@list, $order);
5307 git_footer_html();
5310 sub git_forks {
5311 my $order = $input_params{'order'};
5312 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5313 die_error(400, "Unknown order parameter");
5316 my @list = git_get_projects_list($project);
5317 if (!@list) {
5318 die_error(404, "No forks found");
5321 git_header_html();
5322 git_print_page_nav('','');
5323 git_print_header_div('summary', "$project forks");
5324 git_project_list_body(\@list, $order);
5325 git_footer_html();
5328 sub git_project_index {
5329 my @projects = git_get_projects_list($project);
5331 print $cgi->header(
5332 -type => 'text/plain',
5333 -charset => 'utf-8',
5334 -content_disposition => 'inline; filename="index.aux"');
5336 foreach my $pr (@projects) {
5337 if (!exists $pr->{'owner'}) {
5338 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5341 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5342 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5343 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5344 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5345 $path =~ s/ /\+/g;
5346 $owner =~ s/ /\+/g;
5348 print "$path $owner\n";
5352 sub git_summary {
5353 my $descr = git_get_project_description($project) || "none";
5354 my %co = parse_commit("HEAD");
5355 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5356 my $head = $co{'id'};
5357 my $remote_heads = gitweb_check_feature('remote_heads');
5359 my $owner = git_get_project_owner($project);
5361 my $refs = git_get_references();
5362 # These get_*_list functions return one more to allow us to see if
5363 # there are more ...
5364 my @taglist = git_get_tags_list(16);
5365 my @headlist = git_get_heads_list(16);
5366 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
5367 my @forklist;
5368 my $check_forks = gitweb_check_feature('forks');
5370 if ($check_forks) {
5371 @forklist = git_get_projects_list($project);
5374 git_header_html();
5375 git_print_page_nav('summary','', $head);
5377 print "<div class=\"title\">&nbsp;</div>\n";
5378 print "<table class=\"projects_list\">\n" .
5379 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5380 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5381 if (defined $cd{'rfc2822'}) {
5382 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5385 # use per project git URL list in $projectroot/$project/cloneurl
5386 # or make project git URL from git base URL and project name
5387 my $url_tag = "URL";
5388 my @url_list = git_get_project_url_list($project);
5389 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5390 foreach my $git_url (@url_list) {
5391 next unless $git_url;
5392 print format_repo_url($url_tag, $git_url);
5393 $url_tag = "";
5396 # Tag cloud
5397 my $show_ctags = gitweb_check_feature('ctags');
5398 if ($show_ctags) {
5399 my $ctags = git_get_project_ctags($project);
5400 my $cloud = git_populate_project_tagcloud($ctags);
5401 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5402 print "</td>\n<td>" unless %$ctags;
5403 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5404 print "</td>\n<td>" if %$ctags;
5405 print git_show_project_tagcloud($cloud, 48);
5406 print "</td></tr>";
5409 print "</table>\n";
5411 # If XSS prevention is on, we don't include README.html.
5412 # TODO: Allow a readme in some safe format.
5413 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5414 print "<div class=\"title\">readme</div>\n" .
5415 "<div class=\"readme\">\n";
5416 insert_file("$projectroot/$project/README.html");
5417 print "\n</div>\n"; # class="readme"
5420 # we need to request one more than 16 (0..15) to check if
5421 # those 16 are all
5422 my @commitlist = $head ? parse_commits($head, 17) : ();
5423 if (@commitlist) {
5424 git_print_header_div('shortlog');
5425 git_shortlog_body(\@commitlist, 0, 15, $refs,
5426 $#commitlist <= 15 ? undef :
5427 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5430 if (@taglist) {
5431 git_print_header_div('tags');
5432 git_tags_body(\@taglist, 0, 15,
5433 $#taglist <= 15 ? undef :
5434 $cgi->a({-href => href(action=>"tags")}, "..."));
5437 if (@headlist) {
5438 git_print_header_div('heads');
5439 git_heads_body(\@headlist, $head, 0, 15,
5440 $#headlist <= 15 ? undef :
5441 $cgi->a({-href => href(action=>"heads")}, "..."));
5444 if (%remotedata) {
5445 git_print_header_div('remotes');
5446 git_remotes_body(\%remotedata, 15, $head);
5449 if (@forklist) {
5450 git_print_header_div('forks');
5451 git_project_list_body(\@forklist, 'age', 0, 15,
5452 $#forklist <= 15 ? undef :
5453 $cgi->a({-href => href(action=>"forks")}, "..."),
5454 'no_header');
5457 git_footer_html();
5460 sub git_tag {
5461 my %tag = parse_tag($hash);
5463 if (! %tag) {
5464 die_error(404, "Unknown tag object");
5467 my $head = git_get_head_hash($project);
5468 git_header_html();
5469 git_print_page_nav('','', $head,undef,$head);
5470 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5471 print "<div class=\"title_text\">\n" .
5472 "<table class=\"object_header\">\n" .
5473 "<tr>\n" .
5474 "<td>object</td>\n" .
5475 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5476 $tag{'object'}) . "</td>\n" .
5477 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5478 $tag{'type'}) . "</td>\n" .
5479 "</tr>\n";
5480 if (defined($tag{'author'})) {
5481 git_print_authorship_rows(\%tag, 'author');
5483 print "</table>\n\n" .
5484 "</div>\n";
5485 print "<div class=\"page_body\">";
5486 my $comment = $tag{'comment'};
5487 foreach my $line (@$comment) {
5488 chomp $line;
5489 print esc_html($line, -nbsp=>1) . "<br/>\n";
5491 print "</div>\n";
5492 git_footer_html();
5495 sub git_blame_common {
5496 my $format = shift || 'porcelain';
5497 if ($format eq 'porcelain' && $cgi->param('js')) {
5498 $format = 'incremental';
5499 $action = 'blame_incremental'; # for page title etc
5502 # permissions
5503 gitweb_check_feature('blame')
5504 or die_error(403, "Blame view not allowed");
5506 # error checking
5507 die_error(400, "No file name given") unless $file_name;
5508 $hash_base ||= git_get_head_hash($project);
5509 die_error(404, "Couldn't find base commit") unless $hash_base;
5510 my %co = parse_commit($hash_base)
5511 or die_error(404, "Commit not found");
5512 my $ftype = "blob";
5513 if (!defined $hash) {
5514 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5515 or die_error(404, "Error looking up file");
5516 } else {
5517 $ftype = git_get_type($hash);
5518 if ($ftype !~ "blob") {
5519 die_error(400, "Object is not a blob");
5523 my $fd;
5524 if ($format eq 'incremental') {
5525 # get file contents (as base)
5526 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5527 or die_error(500, "Open git-cat-file failed");
5528 } elsif ($format eq 'data') {
5529 # run git-blame --incremental
5530 open $fd, "-|", git_cmd(), "blame", "--incremental",
5531 $hash_base, "--", $file_name
5532 or die_error(500, "Open git-blame --incremental failed");
5533 } else {
5534 # run git-blame --porcelain
5535 open $fd, "-|", git_cmd(), "blame", '-p',
5536 $hash_base, '--', $file_name
5537 or die_error(500, "Open git-blame --porcelain failed");
5540 # incremental blame data returns early
5541 if ($format eq 'data') {
5542 print $cgi->header(
5543 -type=>"text/plain", -charset => "utf-8",
5544 -status=> "200 OK");
5545 local $| = 1; # output autoflush
5546 print while <$fd>;
5547 close $fd
5548 or print "ERROR $!\n";
5550 print 'END';
5551 if (defined $t0 && gitweb_check_feature('timed')) {
5552 print ' '.
5553 tv_interval($t0, [ gettimeofday() ]).
5554 ' '.$number_of_git_cmds;
5556 print "\n";
5558 return;
5561 # page header
5562 git_header_html();
5563 my $formats_nav =
5564 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5565 "blob") .
5566 " | ";
5567 if ($format eq 'incremental') {
5568 $formats_nav .=
5569 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5570 "blame") . " (non-incremental)";
5571 } else {
5572 $formats_nav .=
5573 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5574 "blame") . " (incremental)";
5576 $formats_nav .=
5577 " | " .
5578 $cgi->a({-href => href(action=>"history", -replay=>1)},
5579 "history") .
5580 " | " .
5581 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5582 "HEAD");
5583 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5584 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5585 git_print_page_path($file_name, $ftype, $hash_base);
5587 # page body
5588 if ($format eq 'incremental') {
5589 print "<noscript>\n<div class=\"error\"><center><b>\n".
5590 "This page requires JavaScript to run.\n Use ".
5591 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5592 'this page').
5593 " instead.\n".
5594 "</b></center></div>\n</noscript>\n";
5596 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5599 print qq!<div class="page_body">\n!;
5600 print qq!<div id="progress_info">... / ...</div>\n!
5601 if ($format eq 'incremental');
5602 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5603 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5604 qq!<thead>\n!.
5605 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5606 qq!</thead>\n!.
5607 qq!<tbody>\n!;
5609 my @rev_color = qw(light dark);
5610 my $num_colors = scalar(@rev_color);
5611 my $current_color = 0;
5613 if ($format eq 'incremental') {
5614 my $color_class = $rev_color[$current_color];
5616 #contents of a file
5617 my $linenr = 0;
5618 LINE:
5619 while (my $line = <$fd>) {
5620 chomp $line;
5621 $linenr++;
5623 print qq!<tr id="l$linenr" class="$color_class">!.
5624 qq!<td class="sha1"><a href=""> </a></td>!.
5625 qq!<td class="linenr">!.
5626 qq!<a class="linenr" href="">$linenr</a></td>!;
5627 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5628 print qq!</tr>\n!;
5631 } else { # porcelain, i.e. ordinary blame
5632 my %metainfo = (); # saves information about commits
5634 # blame data
5635 LINE:
5636 while (my $line = <$fd>) {
5637 chomp $line;
5638 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5639 # no <lines in group> for subsequent lines in group of lines
5640 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5641 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5642 if (!exists $metainfo{$full_rev}) {
5643 $metainfo{$full_rev} = { 'nprevious' => 0 };
5645 my $meta = $metainfo{$full_rev};
5646 my $data;
5647 while ($data = <$fd>) {
5648 chomp $data;
5649 last if ($data =~ s/^\t//); # contents of line
5650 if ($data =~ /^(\S+)(?: (.*))?$/) {
5651 $meta->{$1} = $2 unless exists $meta->{$1};
5653 if ($data =~ /^previous /) {
5654 $meta->{'nprevious'}++;
5657 my $short_rev = substr($full_rev, 0, 8);
5658 my $author = $meta->{'author'};
5659 my %date =
5660 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5661 my $date = $date{'iso-tz'};
5662 if ($group_size) {
5663 $current_color = ($current_color + 1) % $num_colors;
5665 my $tr_class = $rev_color[$current_color];
5666 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5667 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5668 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5669 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5670 if ($group_size) {
5671 print "<td class=\"sha1\"";
5672 print " title=\"". esc_html($author) . ", $date\"";
5673 print " rowspan=\"$group_size\"" if ($group_size > 1);
5674 print ">";
5675 print $cgi->a({-href => href(action=>"commit",
5676 hash=>$full_rev,
5677 file_name=>$file_name)},
5678 esc_html($short_rev));
5679 if ($group_size >= 2) {
5680 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5681 if (@author_initials) {
5682 print "<br />" .
5683 esc_html(join('', @author_initials));
5684 # or join('.', ...)
5687 print "</td>\n";
5689 # 'previous' <sha1 of parent commit> <filename at commit>
5690 if (exists $meta->{'previous'} &&
5691 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5692 $meta->{'parent'} = $1;
5693 $meta->{'file_parent'} = unquote($2);
5695 my $linenr_commit =
5696 exists($meta->{'parent'}) ?
5697 $meta->{'parent'} : $full_rev;
5698 my $linenr_filename =
5699 exists($meta->{'file_parent'}) ?
5700 $meta->{'file_parent'} : unquote($meta->{'filename'});
5701 my $blamed = href(action => 'blame',
5702 file_name => $linenr_filename,
5703 hash_base => $linenr_commit);
5704 print "<td class=\"linenr\">";
5705 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5706 -class => "linenr" },
5707 esc_html($lineno));
5708 print "</td>";
5709 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5710 print "</tr>\n";
5711 } # end while
5715 # footer
5716 print "</tbody>\n".
5717 "</table>\n"; # class="blame"
5718 print "</div>\n"; # class="blame_body"
5719 close $fd
5720 or print "Reading blob failed\n";
5722 git_footer_html();
5725 sub git_blame {
5726 git_blame_common();
5729 sub git_blame_incremental {
5730 git_blame_common('incremental');
5733 sub git_blame_data {
5734 git_blame_common('data');
5737 sub git_tags {
5738 my $head = git_get_head_hash($project);
5739 git_header_html();
5740 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
5741 git_print_header_div('summary', $project);
5743 my @tagslist = git_get_tags_list();
5744 if (@tagslist) {
5745 git_tags_body(\@tagslist);
5747 git_footer_html();
5750 sub git_heads {
5751 my $head = git_get_head_hash($project);
5752 git_header_html();
5753 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
5754 git_print_header_div('summary', $project);
5756 my @headslist = git_get_heads_list();
5757 if (@headslist) {
5758 git_heads_body(\@headslist, $head);
5760 git_footer_html();
5763 # used both for single remote view and for list of all the remotes
5764 sub git_remotes {
5765 gitweb_check_feature('remote_heads')
5766 or die_error(403, "Remote heads view is disabled");
5768 my $head = git_get_head_hash($project);
5769 my $remote = $input_params{'hash'};
5771 my $remotedata = git_get_remotes_list($remote);
5772 die_error(500, "Unable to get remote information") unless defined $remotedata;
5774 unless (%$remotedata) {
5775 die_error(404, defined $remote ?
5776 "Remote $remote not found" :
5777 "No remotes found");
5780 git_header_html(undef, undef, -action_extra => $remote);
5781 git_print_page_nav('', '', $head, undef, $head,
5782 format_ref_views($remote ? '' : 'remotes'));
5784 fill_remote_heads($remotedata);
5785 if (defined $remote) {
5786 git_print_header_div('remotes', "$remote remote for $project");
5787 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
5788 } else {
5789 git_print_header_div('summary', "$project remotes");
5790 git_remotes_body($remotedata, undef, $head);
5793 git_footer_html();
5796 sub git_blob_plain {
5797 my $type = shift;
5798 my $expires;
5800 if (!defined $hash) {
5801 if (defined $file_name) {
5802 my $base = $hash_base || git_get_head_hash($project);
5803 $hash = git_get_hash_by_path($base, $file_name, "blob")
5804 or die_error(404, "Cannot find file");
5805 } else {
5806 die_error(400, "No file name defined");
5808 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5809 # blobs defined by non-textual hash id's can be cached
5810 $expires = "+1d";
5813 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5814 or die_error(500, "Open git-cat-file blob '$hash' failed");
5816 # content-type (can include charset)
5817 $type = blob_contenttype($fd, $file_name, $type);
5819 # "save as" filename, even when no $file_name is given
5820 my $save_as = "$hash";
5821 if (defined $file_name) {
5822 $save_as = $file_name;
5823 } elsif ($type =~ m/^text\//) {
5824 $save_as .= '.txt';
5827 # With XSS prevention on, blobs of all types except a few known safe
5828 # ones are served with "Content-Disposition: attachment" to make sure
5829 # they don't run in our security domain. For certain image types,
5830 # blob view writes an <img> tag referring to blob_plain view, and we
5831 # want to be sure not to break that by serving the image as an
5832 # attachment (though Firefox 3 doesn't seem to care).
5833 my $sandbox = $prevent_xss &&
5834 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5836 print $cgi->header(
5837 -type => $type,
5838 -expires => $expires,
5839 -content_disposition =>
5840 ($sandbox ? 'attachment' : 'inline')
5841 . '; filename="' . $save_as . '"');
5842 local $/ = undef;
5843 binmode STDOUT, ':raw';
5844 print <$fd>;
5845 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5846 close $fd;
5849 sub git_blob {
5850 my $expires;
5852 if (!defined $hash) {
5853 if (defined $file_name) {
5854 my $base = $hash_base || git_get_head_hash($project);
5855 $hash = git_get_hash_by_path($base, $file_name, "blob")
5856 or die_error(404, "Cannot find file");
5857 } else {
5858 die_error(400, "No file name defined");
5860 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5861 # blobs defined by non-textual hash id's can be cached
5862 $expires = "+1d";
5865 my $have_blame = gitweb_check_feature('blame');
5866 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5867 or die_error(500, "Couldn't cat $file_name, $hash");
5868 my $mimetype = blob_mimetype($fd, $file_name);
5869 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5870 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5871 close $fd;
5872 return git_blob_plain($mimetype);
5874 # we can have blame only for text/* mimetype
5875 $have_blame &&= ($mimetype =~ m!^text/!);
5877 my $highlight = gitweb_check_feature('highlight');
5878 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5879 $fd = run_highlighter($fd, $highlight, $syntax)
5880 if $syntax;
5882 git_header_html(undef, $expires);
5883 my $formats_nav = '';
5884 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5885 if (defined $file_name) {
5886 if ($have_blame) {
5887 $formats_nav .=
5888 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5889 "blame") .
5890 " | ";
5892 $formats_nav .=
5893 $cgi->a({-href => href(action=>"history", -replay=>1)},
5894 "history") .
5895 " | " .
5896 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5897 "raw") .
5898 " | " .
5899 $cgi->a({-href => href(action=>"blob",
5900 hash_base=>"HEAD", file_name=>$file_name)},
5901 "HEAD");
5902 } else {
5903 $formats_nav .=
5904 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5905 "raw");
5907 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5908 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5909 } else {
5910 print "<div class=\"page_nav\">\n" .
5911 "<br/><br/></div>\n" .
5912 "<div class=\"title\">$hash</div>\n";
5914 git_print_page_path($file_name, "blob", $hash_base);
5915 print "<div class=\"page_body\">\n";
5916 if ($mimetype =~ m!^image/!) {
5917 print qq!<img type="$mimetype"!;
5918 if ($file_name) {
5919 print qq! alt="$file_name" title="$file_name"!;
5921 print qq! src="! .
5922 href(action=>"blob_plain", hash=>$hash,
5923 hash_base=>$hash_base, file_name=>$file_name) .
5924 qq!" />\n!;
5925 } else {
5926 my $nr;
5927 while (my $line = <$fd>) {
5928 chomp $line;
5929 $nr++;
5930 $line = untabify($line);
5931 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5932 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5935 close $fd
5936 or print "Reading blob failed.\n";
5937 print "</div>";
5938 git_footer_html();
5941 sub git_tree {
5942 if (!defined $hash_base) {
5943 $hash_base = "HEAD";
5945 if (!defined $hash) {
5946 if (defined $file_name) {
5947 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5948 } else {
5949 $hash = $hash_base;
5952 die_error(404, "No such tree") unless defined($hash);
5954 my $show_sizes = gitweb_check_feature('show-sizes');
5955 my $have_blame = gitweb_check_feature('blame');
5957 my @entries = ();
5959 local $/ = "\0";
5960 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5961 ($show_sizes ? '-l' : ()), @extra_options, $hash
5962 or die_error(500, "Open git-ls-tree failed");
5963 @entries = map { chomp; $_ } <$fd>;
5964 close $fd
5965 or die_error(404, "Reading tree failed");
5968 my $refs = git_get_references();
5969 my $ref = format_ref_marker($refs, $hash_base);
5970 git_header_html();
5971 my $basedir = '';
5972 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5973 my @views_nav = ();
5974 if (defined $file_name) {
5975 push @views_nav,
5976 $cgi->a({-href => href(action=>"history", -replay=>1)},
5977 "history"),
5978 $cgi->a({-href => href(action=>"tree",
5979 hash_base=>"HEAD", file_name=>$file_name)},
5980 "HEAD"),
5982 my $snapshot_links = format_snapshot_links($hash);
5983 if (defined $snapshot_links) {
5984 # FIXME: Should be available when we have no hash base as well.
5985 push @views_nav, $snapshot_links;
5987 git_print_page_nav('tree','', $hash_base, undef, undef,
5988 join(' | ', @views_nav));
5989 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5990 } else {
5991 undef $hash_base;
5992 print "<div class=\"page_nav\">\n";
5993 print "<br/><br/></div>\n";
5994 print "<div class=\"title\">$hash</div>\n";
5996 if (defined $file_name) {
5997 $basedir = $file_name;
5998 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5999 $basedir .= '/';
6001 git_print_page_path($file_name, 'tree', $hash_base);
6003 print "<div class=\"page_body\">\n";
6004 print "<table class=\"tree\">\n";
6005 my $alternate = 1;
6006 # '..' (top directory) link if possible
6007 if (defined $hash_base &&
6008 defined $file_name && $file_name =~ m![^/]+$!) {
6009 if ($alternate) {
6010 print "<tr class=\"dark\">\n";
6011 } else {
6012 print "<tr class=\"light\">\n";
6014 $alternate ^= 1;
6016 my $up = $file_name;
6017 $up =~ s!/?[^/]+$!!;
6018 undef $up unless $up;
6019 # based on git_print_tree_entry
6020 print '<td class="mode">' . mode_str('040000') . "</td>\n";
6021 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
6022 print '<td class="list">';
6023 print $cgi->a({-href => href(action=>"tree",
6024 hash_base=>$hash_base,
6025 file_name=>$up)},
6026 "..");
6027 print "</td>\n";
6028 print "<td class=\"link\"></td>\n";
6030 print "</tr>\n";
6032 foreach my $line (@entries) {
6033 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
6035 if ($alternate) {
6036 print "<tr class=\"dark\">\n";
6037 } else {
6038 print "<tr class=\"light\">\n";
6040 $alternate ^= 1;
6042 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
6044 print "</tr>\n";
6046 print "</table>\n" .
6047 "</div>";
6048 git_footer_html();
6051 sub snapshot_name {
6052 my ($project, $hash) = @_;
6054 # path/to/project.git -> project
6055 # path/to/project/.git -> project
6056 my $name = to_utf8($project);
6057 $name =~ s,([^/])/*\.git$,$1,;
6058 $name = basename($name);
6059 # sanitize name
6060 $name =~ s/[[:cntrl:]]/?/g;
6062 my $ver = $hash;
6063 if ($hash =~ /^[0-9a-fA-F]+$/) {
6064 # shorten SHA-1 hash
6065 my $full_hash = git_get_full_hash($project, $hash);
6066 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
6067 $ver = git_get_short_hash($project, $hash);
6069 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
6070 # tags don't need shortened SHA-1 hash
6071 $ver = $1;
6072 } else {
6073 # branches and other need shortened SHA-1 hash
6074 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
6075 $ver = $1;
6077 $ver .= '-' . git_get_short_hash($project, $hash);
6079 # in case of hierarchical branch names
6080 $ver =~ s!/!.!g;
6082 # name = project-version_string
6083 $name = "$name-$ver";
6085 return wantarray ? ($name, $name) : $name;
6088 sub git_snapshot {
6089 my $format = $input_params{'snapshot_format'};
6090 if (!@snapshot_fmts) {
6091 die_error(403, "Snapshots not allowed");
6093 # default to first supported snapshot format
6094 $format ||= $snapshot_fmts[0];
6095 if ($format !~ m/^[a-z0-9]+$/) {
6096 die_error(400, "Invalid snapshot format parameter");
6097 } elsif (!exists($known_snapshot_formats{$format})) {
6098 die_error(400, "Unknown snapshot format");
6099 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
6100 die_error(403, "Snapshot format not allowed");
6101 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
6102 die_error(403, "Unsupported snapshot format");
6105 my $type = git_get_type("$hash^{}");
6106 if (!$type) {
6107 die_error(404, 'Object does not exist');
6108 } elsif ($type eq 'blob') {
6109 die_error(400, 'Object is not a tree-ish');
6112 my ($name, $prefix) = snapshot_name($project, $hash);
6113 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6114 my $cmd = quote_command(
6115 git_cmd(), 'archive',
6116 "--format=$known_snapshot_formats{$format}{'format'}",
6117 "--prefix=$prefix/", $hash);
6118 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6119 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6122 $filename =~ s/(["\\])/\\$1/g;
6123 print $cgi->header(
6124 -type => $known_snapshot_formats{$format}{'type'},
6125 -content_disposition => 'inline; filename="' . $filename . '"',
6126 -status => '200 OK');
6128 open my $fd, "-|", $cmd
6129 or die_error(500, "Execute git-archive failed");
6130 binmode STDOUT, ':raw';
6131 print <$fd>;
6132 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6133 close $fd;
6136 sub git_log_generic {
6137 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6139 my $head = git_get_head_hash($project);
6140 if (!defined $base) {
6141 $base = $head;
6143 if (!defined $page) {
6144 $page = 0;
6146 my $refs = git_get_references();
6148 my $commit_hash = $base;
6149 if (defined $parent) {
6150 $commit_hash = "$parent..$base";
6152 my @commitlist =
6153 parse_commits($commit_hash, 101, (100 * $page),
6154 defined $file_name ? ($file_name, "--full-history") : ());
6156 my $ftype;
6157 if (!defined $file_hash && defined $file_name) {
6158 # some commits could have deleted file in question,
6159 # and not have it in tree, but one of them has to have it
6160 for (my $i = 0; $i < @commitlist; $i++) {
6161 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6162 last if defined $file_hash;
6165 if (defined $file_hash) {
6166 $ftype = git_get_type($file_hash);
6168 if (defined $file_name && !defined $ftype) {
6169 die_error(500, "Unknown type of object");
6171 my %co;
6172 if (defined $file_name) {
6173 %co = parse_commit($base)
6174 or die_error(404, "Unknown commit object");
6178 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6179 my $next_link = '';
6180 if ($#commitlist >= 100) {
6181 $next_link =
6182 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6183 -accesskey => "n", -title => "Alt-n"}, "next");
6185 my $patch_max = gitweb_get_feature('patches');
6186 if ($patch_max && !defined $file_name) {
6187 if ($patch_max < 0 || @commitlist <= $patch_max) {
6188 $paging_nav .= " &sdot; " .
6189 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6190 "patches");
6194 git_header_html();
6195 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6196 if (defined $file_name) {
6197 git_print_header_div('commit', esc_html($co{'title'}), $base);
6198 } else {
6199 git_print_header_div('summary', $project)
6201 git_print_page_path($file_name, $ftype, $hash_base)
6202 if (defined $file_name);
6204 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6205 $file_name, $file_hash, $ftype);
6207 git_footer_html();
6210 sub git_log {
6211 git_log_generic('log', \&git_log_body,
6212 $hash, $hash_parent);
6215 sub git_commit {
6216 $hash ||= $hash_base || "HEAD";
6217 my %co = parse_commit($hash)
6218 or die_error(404, "Unknown commit object");
6220 my $parent = $co{'parent'};
6221 my $parents = $co{'parents'}; # listref
6223 # we need to prepare $formats_nav before any parameter munging
6224 my $formats_nav;
6225 if (!defined $parent) {
6226 # --root commitdiff
6227 $formats_nav .= '(initial)';
6228 } elsif (@$parents == 1) {
6229 # single parent commit
6230 $formats_nav .=
6231 '(parent: ' .
6232 $cgi->a({-href => href(action=>"commit",
6233 hash=>$parent)},
6234 esc_html(substr($parent, 0, 7))) .
6235 ')';
6236 } else {
6237 # merge commit
6238 $formats_nav .=
6239 '(merge: ' .
6240 join(' ', map {
6241 $cgi->a({-href => href(action=>"commit",
6242 hash=>$_)},
6243 esc_html(substr($_, 0, 7)));
6244 } @$parents ) .
6245 ')';
6247 if (gitweb_check_feature('patches') && @$parents <= 1) {
6248 $formats_nav .= " | " .
6249 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6250 "patch");
6253 if (!defined $parent) {
6254 $parent = "--root";
6256 my @difftree;
6257 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6258 @diff_opts,
6259 (@$parents <= 1 ? $parent : '-c'),
6260 $hash, "--"
6261 or die_error(500, "Open git-diff-tree failed");
6262 @difftree = map { chomp; $_ } <$fd>;
6263 close $fd or die_error(404, "Reading git-diff-tree failed");
6265 # non-textual hash id's can be cached
6266 my $expires;
6267 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6268 $expires = "+1d";
6270 my $refs = git_get_references();
6271 my $ref = format_ref_marker($refs, $co{'id'});
6273 git_header_html(undef, $expires);
6274 git_print_page_nav('commit', '',
6275 $hash, $co{'tree'}, $hash,
6276 $formats_nav);
6278 if (defined $co{'parent'}) {
6279 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6280 } else {
6281 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6283 print "<div class=\"title_text\">\n" .
6284 "<table class=\"object_header\">\n";
6285 git_print_authorship_rows(\%co);
6286 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6287 print "<tr>" .
6288 "<td>tree</td>" .
6289 "<td class=\"sha1\">" .
6290 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6291 class => "list"}, $co{'tree'}) .
6292 "</td>" .
6293 "<td class=\"link\">" .
6294 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6295 "tree");
6296 my $snapshot_links = format_snapshot_links($hash);
6297 if (defined $snapshot_links) {
6298 print " | " . $snapshot_links;
6300 print "</td>" .
6301 "</tr>\n";
6303 foreach my $par (@$parents) {
6304 print "<tr>" .
6305 "<td>parent</td>" .
6306 "<td class=\"sha1\">" .
6307 $cgi->a({-href => href(action=>"commit", hash=>$par),
6308 class => "list"}, $par) .
6309 "</td>" .
6310 "<td class=\"link\">" .
6311 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6312 " | " .
6313 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6314 "</td>" .
6315 "</tr>\n";
6317 print "</table>".
6318 "</div>\n";
6320 print "<div class=\"page_body\">\n";
6321 git_print_log($co{'comment'});
6322 print "</div>\n";
6324 git_difftree_body(\@difftree, $hash, @$parents);
6326 git_footer_html();
6329 sub git_object {
6330 # object is defined by:
6331 # - hash or hash_base alone
6332 # - hash_base and file_name
6333 my $type;
6335 # - hash or hash_base alone
6336 if ($hash || ($hash_base && !defined $file_name)) {
6337 my $object_id = $hash || $hash_base;
6339 open my $fd, "-|", quote_command(
6340 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6341 or die_error(404, "Object does not exist");
6342 $type = <$fd>;
6343 chomp $type;
6344 close $fd
6345 or die_error(404, "Object does not exist");
6347 # - hash_base and file_name
6348 } elsif ($hash_base && defined $file_name) {
6349 $file_name =~ s,/+$,,;
6351 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6352 or die_error(404, "Base object does not exist");
6354 # here errors should not hapen
6355 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6356 or die_error(500, "Open git-ls-tree failed");
6357 my $line = <$fd>;
6358 close $fd;
6360 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6361 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6362 die_error(404, "File or directory for given base does not exist");
6364 $type = $2;
6365 $hash = $3;
6366 } else {
6367 die_error(400, "Not enough information to find object");
6370 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6371 hash=>$hash, hash_base=>$hash_base,
6372 file_name=>$file_name),
6373 -status => '302 Found');
6376 sub git_blobdiff {
6377 my $format = shift || 'html';
6379 my $fd;
6380 my @difftree;
6381 my %diffinfo;
6382 my $expires;
6384 # preparing $fd and %diffinfo for git_patchset_body
6385 # new style URI
6386 if (defined $hash_base && defined $hash_parent_base) {
6387 if (defined $file_name) {
6388 # read raw output
6389 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6390 $hash_parent_base, $hash_base,
6391 "--", (defined $file_parent ? $file_parent : ()), $file_name
6392 or die_error(500, "Open git-diff-tree failed");
6393 @difftree = map { chomp; $_ } <$fd>;
6394 close $fd
6395 or die_error(404, "Reading git-diff-tree failed");
6396 @difftree
6397 or die_error(404, "Blob diff not found");
6399 } elsif (defined $hash &&
6400 $hash =~ /[0-9a-fA-F]{40}/) {
6401 # try to find filename from $hash
6403 # read filtered raw output
6404 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6405 $hash_parent_base, $hash_base, "--"
6406 or die_error(500, "Open git-diff-tree failed");
6407 @difftree =
6408 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6409 # $hash == to_id
6410 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6411 map { chomp; $_ } <$fd>;
6412 close $fd
6413 or die_error(404, "Reading git-diff-tree failed");
6414 @difftree
6415 or die_error(404, "Blob diff not found");
6417 } else {
6418 die_error(400, "Missing one of the blob diff parameters");
6421 if (@difftree > 1) {
6422 die_error(400, "Ambiguous blob diff specification");
6425 %diffinfo = parse_difftree_raw_line($difftree[0]);
6426 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6427 $file_name ||= $diffinfo{'to_file'};
6429 $hash_parent ||= $diffinfo{'from_id'};
6430 $hash ||= $diffinfo{'to_id'};
6432 # non-textual hash id's can be cached
6433 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6434 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6435 $expires = '+1d';
6438 # open patch output
6439 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6440 '-p', ($format eq 'html' ? "--full-index" : ()),
6441 $hash_parent_base, $hash_base,
6442 "--", (defined $file_parent ? $file_parent : ()), $file_name
6443 or die_error(500, "Open git-diff-tree failed");
6446 # old/legacy style URI -- not generated anymore since 1.4.3.
6447 if (!%diffinfo) {
6448 die_error('404 Not Found', "Missing one of the blob diff parameters")
6451 # header
6452 if ($format eq 'html') {
6453 my $formats_nav =
6454 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6455 "raw");
6456 git_header_html(undef, $expires);
6457 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6458 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6459 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6460 } else {
6461 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6462 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6464 if (defined $file_name) {
6465 git_print_page_path($file_name, "blob", $hash_base);
6466 } else {
6467 print "<div class=\"page_path\"></div>\n";
6470 } elsif ($format eq 'plain') {
6471 print $cgi->header(
6472 -type => 'text/plain',
6473 -charset => 'utf-8',
6474 -expires => $expires,
6475 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6477 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6479 } else {
6480 die_error(400, "Unknown blobdiff format");
6483 # patch
6484 if ($format eq 'html') {
6485 print "<div class=\"page_body\">\n";
6487 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6488 close $fd;
6490 print "</div>\n"; # class="page_body"
6491 git_footer_html();
6493 } else {
6494 while (my $line = <$fd>) {
6495 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6496 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6498 print $line;
6500 last if $line =~ m!^\+\+\+!;
6502 local $/ = undef;
6503 print <$fd>;
6504 close $fd;
6508 sub git_blobdiff_plain {
6509 git_blobdiff('plain');
6512 sub git_commitdiff {
6513 my %params = @_;
6514 my $format = $params{-format} || 'html';
6516 my ($patch_max) = gitweb_get_feature('patches');
6517 if ($format eq 'patch') {
6518 die_error(403, "Patch view not allowed") unless $patch_max;
6521 $hash ||= $hash_base || "HEAD";
6522 my %co = parse_commit($hash)
6523 or die_error(404, "Unknown commit object");
6525 # choose format for commitdiff for merge
6526 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6527 $hash_parent = '--cc';
6529 # we need to prepare $formats_nav before almost any parameter munging
6530 my $formats_nav;
6531 if ($format eq 'html') {
6532 $formats_nav =
6533 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6534 "raw");
6535 if ($patch_max && @{$co{'parents'}} <= 1) {
6536 $formats_nav .= " | " .
6537 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6538 "patch");
6541 if (defined $hash_parent &&
6542 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6543 # commitdiff with two commits given
6544 my $hash_parent_short = $hash_parent;
6545 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6546 $hash_parent_short = substr($hash_parent, 0, 7);
6548 $formats_nav .=
6549 ' (from';
6550 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6551 if ($co{'parents'}[$i] eq $hash_parent) {
6552 $formats_nav .= ' parent ' . ($i+1);
6553 last;
6556 $formats_nav .= ': ' .
6557 $cgi->a({-href => href(action=>"commitdiff",
6558 hash=>$hash_parent)},
6559 esc_html($hash_parent_short)) .
6560 ')';
6561 } elsif (!$co{'parent'}) {
6562 # --root commitdiff
6563 $formats_nav .= ' (initial)';
6564 } elsif (scalar @{$co{'parents'}} == 1) {
6565 # single parent commit
6566 $formats_nav .=
6567 ' (parent: ' .
6568 $cgi->a({-href => href(action=>"commitdiff",
6569 hash=>$co{'parent'})},
6570 esc_html(substr($co{'parent'}, 0, 7))) .
6571 ')';
6572 } else {
6573 # merge commit
6574 if ($hash_parent eq '--cc') {
6575 $formats_nav .= ' | ' .
6576 $cgi->a({-href => href(action=>"commitdiff",
6577 hash=>$hash, hash_parent=>'-c')},
6578 'combined');
6579 } else { # $hash_parent eq '-c'
6580 $formats_nav .= ' | ' .
6581 $cgi->a({-href => href(action=>"commitdiff",
6582 hash=>$hash, hash_parent=>'--cc')},
6583 'compact');
6585 $formats_nav .=
6586 ' (merge: ' .
6587 join(' ', map {
6588 $cgi->a({-href => href(action=>"commitdiff",
6589 hash=>$_)},
6590 esc_html(substr($_, 0, 7)));
6591 } @{$co{'parents'}} ) .
6592 ')';
6596 my $hash_parent_param = $hash_parent;
6597 if (!defined $hash_parent_param) {
6598 # --cc for multiple parents, --root for parentless
6599 $hash_parent_param =
6600 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6603 # read commitdiff
6604 my $fd;
6605 my @difftree;
6606 if ($format eq 'html') {
6607 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6608 "--no-commit-id", "--patch-with-raw", "--full-index",
6609 $hash_parent_param, $hash, "--"
6610 or die_error(500, "Open git-diff-tree failed");
6612 while (my $line = <$fd>) {
6613 chomp $line;
6614 # empty line ends raw part of diff-tree output
6615 last unless $line;
6616 push @difftree, scalar parse_difftree_raw_line($line);
6619 } elsif ($format eq 'plain') {
6620 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6621 '-p', $hash_parent_param, $hash, "--"
6622 or die_error(500, "Open git-diff-tree failed");
6623 } elsif ($format eq 'patch') {
6624 # For commit ranges, we limit the output to the number of
6625 # patches specified in the 'patches' feature.
6626 # For single commits, we limit the output to a single patch,
6627 # diverging from the git-format-patch default.
6628 my @commit_spec = ();
6629 if ($hash_parent) {
6630 if ($patch_max > 0) {
6631 push @commit_spec, "-$patch_max";
6633 push @commit_spec, '-n', "$hash_parent..$hash";
6634 } else {
6635 if ($params{-single}) {
6636 push @commit_spec, '-1';
6637 } else {
6638 if ($patch_max > 0) {
6639 push @commit_spec, "-$patch_max";
6641 push @commit_spec, "-n";
6643 push @commit_spec, '--root', $hash;
6645 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6646 '--encoding=utf8', '--stdout', @commit_spec
6647 or die_error(500, "Open git-format-patch failed");
6648 } else {
6649 die_error(400, "Unknown commitdiff format");
6652 # non-textual hash id's can be cached
6653 my $expires;
6654 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6655 $expires = "+1d";
6658 # write commit message
6659 if ($format eq 'html') {
6660 my $refs = git_get_references();
6661 my $ref = format_ref_marker($refs, $co{'id'});
6663 git_header_html(undef, $expires);
6664 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6665 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6666 print "<div class=\"title_text\">\n" .
6667 "<table class=\"object_header\">\n";
6668 git_print_authorship_rows(\%co);
6669 print "</table>".
6670 "</div>\n";
6671 print "<div class=\"page_body\">\n";
6672 if (@{$co{'comment'}} > 1) {
6673 print "<div class=\"log\">\n";
6674 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6675 print "</div>\n"; # class="log"
6678 } elsif ($format eq 'plain') {
6679 my $refs = git_get_references("tags");
6680 my $tagname = git_get_rev_name_tags($hash);
6681 my $filename = basename($project) . "-$hash.patch";
6683 print $cgi->header(
6684 -type => 'text/plain',
6685 -charset => 'utf-8',
6686 -expires => $expires,
6687 -content_disposition => 'inline; filename="' . "$filename" . '"');
6688 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6689 print "From: " . to_utf8($co{'author'}) . "\n";
6690 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6691 print "Subject: " . to_utf8($co{'title'}) . "\n";
6693 print "X-Git-Tag: $tagname\n" if $tagname;
6694 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6696 foreach my $line (@{$co{'comment'}}) {
6697 print to_utf8($line) . "\n";
6699 print "---\n\n";
6700 } elsif ($format eq 'patch') {
6701 my $filename = basename($project) . "-$hash.patch";
6703 print $cgi->header(
6704 -type => 'text/plain',
6705 -charset => 'utf-8',
6706 -expires => $expires,
6707 -content_disposition => 'inline; filename="' . "$filename" . '"');
6710 # write patch
6711 if ($format eq 'html') {
6712 my $use_parents = !defined $hash_parent ||
6713 $hash_parent eq '-c' || $hash_parent eq '--cc';
6714 git_difftree_body(\@difftree, $hash,
6715 $use_parents ? @{$co{'parents'}} : $hash_parent);
6716 print "<br/>\n";
6718 git_patchset_body($fd, \@difftree, $hash,
6719 $use_parents ? @{$co{'parents'}} : $hash_parent);
6720 close $fd;
6721 print "</div>\n"; # class="page_body"
6722 git_footer_html();
6724 } elsif ($format eq 'plain') {
6725 local $/ = undef;
6726 print <$fd>;
6727 close $fd
6728 or print "Reading git-diff-tree failed\n";
6729 } elsif ($format eq 'patch') {
6730 local $/ = undef;
6731 print <$fd>;
6732 close $fd
6733 or print "Reading git-format-patch failed\n";
6737 sub git_commitdiff_plain {
6738 git_commitdiff(-format => 'plain');
6741 # format-patch-style patches
6742 sub git_patch {
6743 git_commitdiff(-format => 'patch', -single => 1);
6746 sub git_patches {
6747 git_commitdiff(-format => 'patch');
6750 sub git_history {
6751 git_log_generic('history', \&git_history_body,
6752 $hash_base, $hash_parent_base,
6753 $file_name, $hash);
6756 sub git_search {
6757 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6758 if (!defined $searchtext) {
6759 die_error(400, "Text field is empty");
6761 if (!defined $hash) {
6762 $hash = git_get_head_hash($project);
6764 my %co = parse_commit($hash);
6765 if (!%co) {
6766 die_error(404, "Unknown commit object");
6768 if (!defined $page) {
6769 $page = 0;
6772 $searchtype ||= 'commit';
6773 if ($searchtype eq 'pickaxe') {
6774 # pickaxe may take all resources of your box and run for several minutes
6775 # with every query - so decide by yourself how public you make this feature
6776 gitweb_check_feature('pickaxe')
6777 or die_error(403, "Pickaxe is disabled");
6779 if ($searchtype eq 'grep') {
6780 gitweb_check_feature('grep')
6781 or die_error(403, "Grep is disabled");
6784 git_header_html();
6786 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6787 my $greptype;
6788 if ($searchtype eq 'commit') {
6789 $greptype = "--grep=";
6790 } elsif ($searchtype eq 'author') {
6791 $greptype = "--author=";
6792 } elsif ($searchtype eq 'committer') {
6793 $greptype = "--committer=";
6795 $greptype .= $searchtext;
6796 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6797 $greptype, '--regexp-ignore-case',
6798 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6800 my $paging_nav = '';
6801 if ($page > 0) {
6802 $paging_nav .=
6803 $cgi->a({-href => href(action=>"search", hash=>$hash,
6804 searchtext=>$searchtext,
6805 searchtype=>$searchtype)},
6806 "first");
6807 $paging_nav .= " &sdot; " .
6808 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6809 -accesskey => "p", -title => "Alt-p"}, "prev");
6810 } else {
6811 $paging_nav .= "first";
6812 $paging_nav .= " &sdot; prev";
6814 my $next_link = '';
6815 if ($#commitlist >= 100) {
6816 $next_link =
6817 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6818 -accesskey => "n", -title => "Alt-n"}, "next");
6819 $paging_nav .= " &sdot; $next_link";
6820 } else {
6821 $paging_nav .= " &sdot; next";
6824 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6825 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6826 if ($page == 0 && !@commitlist) {
6827 print "<p>No match.</p>\n";
6828 } else {
6829 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6833 if ($searchtype eq 'pickaxe') {
6834 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6835 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6837 print "<table class=\"pickaxe search\">\n";
6838 my $alternate = 1;
6839 local $/ = "\n";
6840 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6841 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6842 ($search_use_regexp ? '--pickaxe-regex' : ());
6843 undef %co;
6844 my @files;
6845 while (my $line = <$fd>) {
6846 chomp $line;
6847 next unless $line;
6849 my %set = parse_difftree_raw_line($line);
6850 if (defined $set{'commit'}) {
6851 # finish previous commit
6852 if (%co) {
6853 print "</td>\n" .
6854 "<td class=\"link\">" .
6855 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6856 " | " .
6857 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6858 print "</td>\n" .
6859 "</tr>\n";
6862 if ($alternate) {
6863 print "<tr class=\"dark\">\n";
6864 } else {
6865 print "<tr class=\"light\">\n";
6867 $alternate ^= 1;
6868 %co = parse_commit($set{'commit'});
6869 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6870 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6871 "<td><i>$author</i></td>\n" .
6872 "<td>" .
6873 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6874 -class => "list subject"},
6875 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6876 } elsif (defined $set{'to_id'}) {
6877 next if ($set{'to_id'} =~ m/^0{40}$/);
6879 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6880 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6881 -class => "list"},
6882 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6883 "<br/>\n";
6886 close $fd;
6888 # finish last commit (warning: repetition!)
6889 if (%co) {
6890 print "</td>\n" .
6891 "<td class=\"link\">" .
6892 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6893 " | " .
6894 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6895 print "</td>\n" .
6896 "</tr>\n";
6899 print "</table>\n";
6902 if ($searchtype eq 'grep') {
6903 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6904 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6906 print "<table class=\"grep_search\">\n";
6907 my $alternate = 1;
6908 my $matches = 0;
6909 local $/ = "\n";
6910 open my $fd, "-|", git_cmd(), 'grep', '-n',
6911 $search_use_regexp ? ('-E', '-i') : '-F',
6912 $searchtext, $co{'tree'};
6913 my $lastfile = '';
6914 while (my $line = <$fd>) {
6915 chomp $line;
6916 my ($file, $lno, $ltext, $binary);
6917 last if ($matches++ > 1000);
6918 if ($line =~ /^Binary file (.+) matches$/) {
6919 $file = $1;
6920 $binary = 1;
6921 } else {
6922 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6924 if ($file ne $lastfile) {
6925 $lastfile and print "</td></tr>\n";
6926 if ($alternate++) {
6927 print "<tr class=\"dark\">\n";
6928 } else {
6929 print "<tr class=\"light\">\n";
6931 print "<td class=\"list\">".
6932 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6933 file_name=>"$file"),
6934 -class => "list"}, esc_path($file));
6935 print "</td><td>\n";
6936 $lastfile = $file;
6938 if ($binary) {
6939 print "<div class=\"binary\">Binary file</div>\n";
6940 } else {
6941 $ltext = untabify($ltext);
6942 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6943 $ltext = esc_html($1, -nbsp=>1);
6944 $ltext .= '<span class="match">';
6945 $ltext .= esc_html($2, -nbsp=>1);
6946 $ltext .= '</span>';
6947 $ltext .= esc_html($3, -nbsp=>1);
6948 } else {
6949 $ltext = esc_html($ltext, -nbsp=>1);
6951 print "<div class=\"pre\">" .
6952 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6953 file_name=>"$file").'#l'.$lno,
6954 -class => "linenr"}, sprintf('%4i', $lno))
6955 . ' ' . $ltext . "</div>\n";
6958 if ($lastfile) {
6959 print "</td></tr>\n";
6960 if ($matches > 1000) {
6961 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6963 } else {
6964 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6966 close $fd;
6968 print "</table>\n";
6970 git_footer_html();
6973 sub git_search_help {
6974 git_header_html();
6975 git_print_page_nav('','', $hash,$hash,$hash);
6976 print <<EOT;
6977 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6978 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6979 the pattern entered is recognized as the POSIX extended
6980 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6981 insensitive).</p>
6982 <dl>
6983 <dt><b>commit</b></dt>
6984 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6986 my $have_grep = gitweb_check_feature('grep');
6987 if ($have_grep) {
6988 print <<EOT;
6989 <dt><b>grep</b></dt>
6990 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6991 a different one) are searched for the given pattern. On large trees, this search can take
6992 a while and put some strain on the server, so please use it with some consideration. Note that
6993 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6994 case-sensitive.</dd>
6997 print <<EOT;
6998 <dt><b>author</b></dt>
6999 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7000 <dt><b>committer</b></dt>
7001 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7003 my $have_pickaxe = gitweb_check_feature('pickaxe');
7004 if ($have_pickaxe) {
7005 print <<EOT;
7006 <dt><b>pickaxe</b></dt>
7007 <dd>All commits that caused the string to appear or disappear from any file (changes that
7008 added, removed or "modified" the string) will be listed. This search can take a while and
7009 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7010 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7013 print "</dl>\n";
7014 git_footer_html();
7017 sub git_shortlog {
7018 git_log_generic('shortlog', \&git_shortlog_body,
7019 $hash, $hash_parent);
7022 ## ......................................................................
7023 ## feeds (RSS, Atom; OPML)
7025 sub git_feed {
7026 my $format = shift || 'atom';
7027 my $have_blame = gitweb_check_feature('blame');
7029 # Atom: http://www.atomenabled.org/developers/syndication/
7030 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
7031 if ($format ne 'rss' && $format ne 'atom') {
7032 die_error(400, "Unknown web feed format");
7035 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
7036 my $head = $hash || 'HEAD';
7037 my @commitlist = parse_commits($head, 150, 0, $file_name);
7039 my %latest_commit;
7040 my %latest_date;
7041 my $content_type = "application/$format+xml";
7042 if (defined $cgi->http('HTTP_ACCEPT') &&
7043 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
7044 # browser (feed reader) prefers text/xml
7045 $content_type = 'text/xml';
7047 if (defined($commitlist[0])) {
7048 %latest_commit = %{$commitlist[0]};
7049 my $latest_epoch = $latest_commit{'committer_epoch'};
7050 %latest_date = parse_date($latest_epoch);
7051 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7052 if (defined $if_modified) {
7053 my $since;
7054 if (eval { require HTTP::Date; 1; }) {
7055 $since = HTTP::Date::str2time($if_modified);
7056 } elsif (eval { require Time::ParseDate; 1; }) {
7057 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7059 if (defined $since && $latest_epoch <= $since) {
7060 print $cgi->header(
7061 -type => $content_type,
7062 -charset => 'utf-8',
7063 -last_modified => $latest_date{'rfc2822'},
7064 -status => '304 Not Modified');
7065 return;
7068 print $cgi->header(
7069 -type => $content_type,
7070 -charset => 'utf-8',
7071 -last_modified => $latest_date{'rfc2822'});
7072 } else {
7073 print $cgi->header(
7074 -type => $content_type,
7075 -charset => 'utf-8');
7078 # Optimization: skip generating the body if client asks only
7079 # for Last-Modified date.
7080 return if ($cgi->request_method() eq 'HEAD');
7082 # header variables
7083 my $title = "$site_name - $project/$action";
7084 my $feed_type = 'log';
7085 if (defined $hash) {
7086 $title .= " - '$hash'";
7087 $feed_type = 'branch log';
7088 if (defined $file_name) {
7089 $title .= " :: $file_name";
7090 $feed_type = 'history';
7092 } elsif (defined $file_name) {
7093 $title .= " - $file_name";
7094 $feed_type = 'history';
7096 $title .= " $feed_type";
7097 my $descr = git_get_project_description($project);
7098 if (defined $descr) {
7099 $descr = esc_html($descr);
7100 } else {
7101 $descr = "$project " .
7102 ($format eq 'rss' ? 'RSS' : 'Atom') .
7103 " feed";
7105 my $owner = git_get_project_owner($project);
7106 $owner = esc_html($owner);
7108 #header
7109 my $alt_url;
7110 if (defined $file_name) {
7111 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7112 } elsif (defined $hash) {
7113 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7114 } else {
7115 $alt_url = href(-full=>1, action=>"summary");
7117 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7118 if ($format eq 'rss') {
7119 print <<XML;
7120 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7121 <channel>
7123 print "<title>$title</title>\n" .
7124 "<link>$alt_url</link>\n" .
7125 "<description>$descr</description>\n" .
7126 "<language>en</language>\n" .
7127 # project owner is responsible for 'editorial' content
7128 "<managingEditor>$owner</managingEditor>\n";
7129 if (defined $logo || defined $favicon) {
7130 # prefer the logo to the favicon, since RSS
7131 # doesn't allow both
7132 my $img = esc_url($logo || $favicon);
7133 print "<image>\n" .
7134 "<url>$img</url>\n" .
7135 "<title>$title</title>\n" .
7136 "<link>$alt_url</link>\n" .
7137 "</image>\n";
7139 if (%latest_date) {
7140 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7141 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7143 print "<generator>gitweb v.$version/$git_version</generator>\n";
7144 } elsif ($format eq 'atom') {
7145 print <<XML;
7146 <feed xmlns="http://www.w3.org/2005/Atom">
7148 print "<title>$title</title>\n" .
7149 "<subtitle>$descr</subtitle>\n" .
7150 '<link rel="alternate" type="text/html" href="' .
7151 $alt_url . '" />' . "\n" .
7152 '<link rel="self" type="' . $content_type . '" href="' .
7153 $cgi->self_url() . '" />' . "\n" .
7154 "<id>" . href(-full=>1) . "</id>\n" .
7155 # use project owner for feed author
7156 "<author><name>$owner</name></author>\n";
7157 if (defined $favicon) {
7158 print "<icon>" . esc_url($favicon) . "</icon>\n";
7160 if (defined $logo_url) {
7161 # not twice as wide as tall: 72 x 27 pixels
7162 print "<logo>" . esc_url($logo) . "</logo>\n";
7164 if (! %latest_date) {
7165 # dummy date to keep the feed valid until commits trickle in:
7166 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7167 } else {
7168 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7170 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7173 # contents
7174 for (my $i = 0; $i <= $#commitlist; $i++) {
7175 my %co = %{$commitlist[$i]};
7176 my $commit = $co{'id'};
7177 # we read 150, we always show 30 and the ones more recent than 48 hours
7178 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7179 last;
7181 my %cd = parse_date($co{'author_epoch'});
7183 # get list of changed files
7184 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7185 $co{'parent'} || "--root",
7186 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7187 or next;
7188 my @difftree = map { chomp; $_ } <$fd>;
7189 close $fd
7190 or next;
7192 # print element (entry, item)
7193 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7194 if ($format eq 'rss') {
7195 print "<item>\n" .
7196 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7197 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7198 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7199 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7200 "<link>$co_url</link>\n" .
7201 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7202 "<content:encoded>" .
7203 "<![CDATA[\n";
7204 } elsif ($format eq 'atom') {
7205 print "<entry>\n" .
7206 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7207 "<updated>$cd{'iso-8601'}</updated>\n" .
7208 "<author>\n" .
7209 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7210 if ($co{'author_email'}) {
7211 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7213 print "</author>\n" .
7214 # use committer for contributor
7215 "<contributor>\n" .
7216 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7217 if ($co{'committer_email'}) {
7218 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7220 print "</contributor>\n" .
7221 "<published>$cd{'iso-8601'}</published>\n" .
7222 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7223 "<id>$co_url</id>\n" .
7224 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7225 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7227 my $comment = $co{'comment'};
7228 print "<pre>\n";
7229 foreach my $line (@$comment) {
7230 $line = esc_html($line);
7231 print "$line\n";
7233 print "</pre><ul>\n";
7234 foreach my $difftree_line (@difftree) {
7235 my %difftree = parse_difftree_raw_line($difftree_line);
7236 next if !$difftree{'from_id'};
7238 my $file = $difftree{'file'} || $difftree{'to_file'};
7240 print "<li>" .
7241 "[" .
7242 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7243 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7244 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7245 file_name=>$file, file_parent=>$difftree{'from_file'}),
7246 -title => "diff"}, 'D');
7247 if ($have_blame) {
7248 print $cgi->a({-href => href(-full=>1, action=>"blame",
7249 file_name=>$file, hash_base=>$commit),
7250 -title => "blame"}, 'B');
7252 # if this is not a feed of a file history
7253 if (!defined $file_name || $file_name ne $file) {
7254 print $cgi->a({-href => href(-full=>1, action=>"history",
7255 file_name=>$file, hash=>$commit),
7256 -title => "history"}, 'H');
7258 $file = esc_path($file);
7259 print "] ".
7260 "$file</li>\n";
7262 if ($format eq 'rss') {
7263 print "</ul>]]>\n" .
7264 "</content:encoded>\n" .
7265 "</item>\n";
7266 } elsif ($format eq 'atom') {
7267 print "</ul>\n</div>\n" .
7268 "</content>\n" .
7269 "</entry>\n";
7273 # end of feed
7274 if ($format eq 'rss') {
7275 print "</channel>\n</rss>\n";
7276 } elsif ($format eq 'atom') {
7277 print "</feed>\n";
7281 sub git_rss {
7282 git_feed('rss');
7285 sub git_atom {
7286 git_feed('atom');
7289 sub git_opml {
7290 my @list = git_get_projects_list();
7292 print $cgi->header(
7293 -type => 'text/xml',
7294 -charset => 'utf-8',
7295 -content_disposition => 'inline; filename="opml.xml"');
7297 print <<XML;
7298 <?xml version="1.0" encoding="utf-8"?>
7299 <opml version="1.0">
7300 <head>
7301 <title>$site_name OPML Export</title>
7302 </head>
7303 <body>
7304 <outline text="git RSS feeds">
7307 foreach my $pr (@list) {
7308 my %proj = %$pr;
7309 my $head = git_get_head_hash($proj{'path'});
7310 if (!defined $head) {
7311 next;
7313 $git_dir = "$projectroot/$proj{'path'}";
7314 my %co = parse_commit($head);
7315 if (!%co) {
7316 next;
7319 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7320 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7321 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7322 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7324 print <<XML;
7325 </outline>
7326 </body>
7327 </opml>