gitweb: Create Gitweb::Util module
[git/jnareb-git/bp-gitweb.git] / gitweb / gitweb.perl
blobe8d858990e8663dd93b0b4a2524456e965e5bd81
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use 5.008;
11 use strict;
12 use warnings;
14 use File::Spec;
16 # __DIR__ is excerpt from Dir::Self
17 sub __DIR__ () {
18 File::Spec->rel2abs(join '', (File::Spec->splitpath(__FILE__))[0, 1]);
20 use lib __DIR__ . '/lib';
21 use lib "++GITWEBLIBDIR++";
23 use CGI qw(:standard :escapeHTML -nosticky);
24 use CGI::Util qw(unescape);
25 use CGI::Carp qw(fatalsToBrowser set_message);
26 use Fcntl ':mode';
27 use File::Find qw();
28 use File::Basename qw(basename);
29 use Time::HiRes qw(gettimeofday tv_interval);
31 use Gitweb::Util;
33 binmode STDOUT, ':utf8';
35 our $t0 = [ gettimeofday() ];
36 our $number_of_git_cmds = 0;
38 BEGIN {
39 CGI->compile() if $ENV{'MOD_PERL'};
42 our $version = "++GIT_VERSION++";
44 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
45 sub evaluate_uri {
46 our $cgi;
48 our $my_url = $cgi->url();
49 our $my_uri = $cgi->url(-absolute => 1);
51 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
52 # needed and used only for URLs with nonempty PATH_INFO
53 our $base_url = $my_url;
55 # When the script is used as DirectoryIndex, the URL does not contain the name
56 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
57 # have to do it ourselves. We make $path_info global because it's also used
58 # later on.
60 # Another issue with the script being the DirectoryIndex is that the resulting
61 # $my_url data is not the full script URL: this is good, because we want
62 # generated links to keep implying the script name if it wasn't explicitly
63 # indicated in the URL we're handling, but it means that $my_url cannot be used
64 # as base URL.
65 # Therefore, if we needed to strip PATH_INFO, then we know that we have
66 # to build the base URL ourselves:
67 our $path_info = $ENV{"PATH_INFO"};
68 if ($path_info) {
69 if ($my_url =~ s,\Q$path_info\E$,, &&
70 $my_uri =~ s,\Q$path_info\E$,, &&
71 defined $ENV{'SCRIPT_NAME'}) {
72 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
76 # target of the home link on top of all pages
77 our $home_link = $my_uri || "/";
80 # core git executable to use
81 # this can just be "git" if your webserver has a sensible PATH
82 our $GIT = "++GIT_BINDIR++/git";
84 # absolute fs-path which will be prepended to the project path
85 #our $projectroot = "/pub/scm";
86 our $projectroot = "++GITWEB_PROJECTROOT++";
88 # fs traversing limit for getting project list
89 # the number is relative to the projectroot
90 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
92 # string of the home link on top of all pages
93 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
95 # name of your site or organization to appear in page titles
96 # replace this with something more descriptive for clearer bookmarks
97 our $site_name = "++GITWEB_SITENAME++"
98 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
100 # filename of html text to include at top of each page
101 our $site_header = "++GITWEB_SITE_HEADER++";
102 # html text to include at home page
103 our $home_text = "++GITWEB_HOMETEXT++";
104 # filename of html text to include at bottom of each page
105 our $site_footer = "++GITWEB_SITE_FOOTER++";
107 # URI of stylesheets
108 our @stylesheets = ("++GITWEB_CSS++");
109 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
110 our $stylesheet = undef;
111 # URI of GIT logo (72x27 size)
112 our $logo = "++GITWEB_LOGO++";
113 # URI of GIT favicon, assumed to be image/png type
114 our $favicon = "++GITWEB_FAVICON++";
115 # URI of gitweb.js (JavaScript code for gitweb)
116 our $javascript = "++GITWEB_JS++";
118 # URI and label (title) of GIT logo link
119 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
120 #our $logo_label = "git documentation";
121 our $logo_url = "http://git-scm.com/";
122 our $logo_label = "git homepage";
124 # source of projects list
125 our $projects_list = "++GITWEB_LIST++";
127 # the width (in characters) of the projects list "Description" column
128 our $projects_list_description_width = 25;
130 # default order of projects list
131 # valid values are none, project, descr, owner, and age
132 our $default_projects_order = "project";
134 # show repository only if this file exists
135 # (only effective if this variable evaluates to true)
136 our $export_ok = "++GITWEB_EXPORT_OK++";
138 # show repository only if this subroutine returns true
139 # when given the path to the project, for example:
140 # sub { return -e "$_[0]/git-daemon-export-ok"; }
141 our $export_auth_hook = undef;
143 # only allow viewing of repositories also shown on the overview page
144 our $strict_export = "++GITWEB_STRICT_EXPORT++";
146 # list of git base URLs used for URL to where fetch project from,
147 # i.e. full URL is "$git_base_url/$project"
148 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
150 # default blob_plain mimetype and default charset for text/plain blob
151 our $default_blob_plain_mimetype = 'text/plain';
152 our $default_text_plain_charset = undef;
154 # file to use for guessing MIME types before trying /etc/mime.types
155 # (relative to the current git repository)
156 our $mimetypes_file = undef;
158 # assume this charset if line contains non-UTF-8 characters;
159 # it should be valid encoding (see Encoding::Supported(3pm) for list),
160 # for which encoding all byte sequences are valid, for example
161 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
162 # could be even 'utf-8' for the old behavior)
163 our $fallback_encoding = 'latin1';
165 # rename detection options for git-diff and git-diff-tree
166 # - default is '-M', with the cost proportional to
167 # (number of removed files) * (number of new files).
168 # - more costly is '-C' (which implies '-M'), with the cost proportional to
169 # (number of changed files + number of removed files) * (number of new files)
170 # - even more costly is '-C', '--find-copies-harder' with cost
171 # (number of files in the original tree) * (number of new files)
172 # - one might want to include '-B' option, e.g. '-B', '-M'
173 our @diff_opts = ('-M'); # taken from git_commit
175 # Disables features that would allow repository owners to inject script into
176 # the gitweb domain.
177 our $prevent_xss = 0;
179 # Path to the highlight executable to use (must be the one from
180 # http://www.andre-simon.de due to assumptions about parameters and output).
181 # Useful if highlight is not installed on your webserver's PATH.
182 # [Default: highlight]
183 our $highlight_bin = "++HIGHLIGHT_BIN++";
185 # information about snapshot formats that gitweb is capable of serving
186 our %known_snapshot_formats = (
187 # name => {
188 # 'display' => display name,
189 # 'type' => mime type,
190 # 'suffix' => filename suffix,
191 # 'format' => --format for git-archive,
192 # 'compressor' => [compressor command and arguments]
193 # (array reference, optional)
194 # 'disabled' => boolean (optional)}
196 'tgz' => {
197 'display' => 'tar.gz',
198 'type' => 'application/x-gzip',
199 'suffix' => '.tar.gz',
200 'format' => 'tar',
201 'compressor' => ['gzip']},
203 'tbz2' => {
204 'display' => 'tar.bz2',
205 'type' => 'application/x-bzip2',
206 'suffix' => '.tar.bz2',
207 'format' => 'tar',
208 'compressor' => ['bzip2']},
210 'txz' => {
211 'display' => 'tar.xz',
212 'type' => 'application/x-xz',
213 'suffix' => '.tar.xz',
214 'format' => 'tar',
215 'compressor' => ['xz'],
216 'disabled' => 1},
218 'zip' => {
219 'display' => 'zip',
220 'type' => 'application/x-zip',
221 'suffix' => '.zip',
222 'format' => 'zip'},
225 # Aliases so we understand old gitweb.snapshot values in repository
226 # configuration.
227 our %known_snapshot_format_aliases = (
228 'gzip' => 'tgz',
229 'bzip2' => 'tbz2',
230 'xz' => 'txz',
232 # backward compatibility: legacy gitweb config support
233 'x-gzip' => undef, 'gz' => undef,
234 'x-bzip2' => undef, 'bz2' => undef,
235 'x-zip' => undef, '' => undef,
238 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
239 # are changed, it may be appropriate to change these values too via
240 # $GITWEB_CONFIG.
241 our %avatar_size = (
242 'default' => 16,
243 'double' => 32
246 # Used to set the maximum load that we will still respond to gitweb queries.
247 # If server load exceed this value then return "503 server busy" error.
248 # If gitweb cannot determined server load, it is taken to be 0.
249 # Leave it undefined (or set to 'undef') to turn off load checking.
250 our $maxload = 300;
252 # configuration for 'highlight' (http://www.andre-simon.de/)
253 # match by basename
254 our %highlight_basename = (
255 #'Program' => 'py',
256 #'Library' => 'py',
257 'SConstruct' => 'py', # SCons equivalent of Makefile
258 'Makefile' => 'make',
260 # match by extension
261 our %highlight_ext = (
262 # main extensions, defining name of syntax;
263 # see files in /usr/share/highlight/langDefs/ directory
264 map { $_ => $_ }
265 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make),
266 # alternate extensions, see /etc/highlight/filetypes.conf
267 'h' => 'c',
268 map { $_ => 'sh' } qw(bash zsh ksh),
269 map { $_ => 'cpp' } qw(cxx c++ cc),
270 map { $_ => 'php' } qw(php3 php4 php5 phps),
271 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
272 map { $_ => 'make'} qw(mak mk),
273 map { $_ => 'xml' } qw(xhtml html htm),
276 # You define site-wide feature defaults here; override them with
277 # $GITWEB_CONFIG as necessary.
278 our %feature = (
279 # feature => {
280 # 'sub' => feature-sub (subroutine),
281 # 'override' => allow-override (boolean),
282 # 'default' => [ default options...] (array reference)}
284 # if feature is overridable (it means that allow-override has true value),
285 # then feature-sub will be called with default options as parameters;
286 # return value of feature-sub indicates if to enable specified feature
288 # if there is no 'sub' key (no feature-sub), then feature cannot be
289 # overridden
291 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
292 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
293 # is enabled
295 # Enable the 'blame' blob view, showing the last commit that modified
296 # each line in the file. This can be very CPU-intensive.
298 # To enable system wide have in $GITWEB_CONFIG
299 # $feature{'blame'}{'default'} = [1];
300 # To have project specific config enable override in $GITWEB_CONFIG
301 # $feature{'blame'}{'override'} = 1;
302 # and in project config gitweb.blame = 0|1;
303 'blame' => {
304 'sub' => sub { feature_bool('blame', @_) },
305 'override' => 0,
306 'default' => [0]},
308 # Enable the 'snapshot' link, providing a compressed archive of any
309 # tree. This can potentially generate high traffic if you have large
310 # project.
312 # Value is a list of formats defined in %known_snapshot_formats that
313 # you wish to offer.
314 # To disable system wide have in $GITWEB_CONFIG
315 # $feature{'snapshot'}{'default'} = [];
316 # To have project specific config enable override in $GITWEB_CONFIG
317 # $feature{'snapshot'}{'override'} = 1;
318 # and in project config, a comma-separated list of formats or "none"
319 # to disable. Example: gitweb.snapshot = tbz2,zip;
320 'snapshot' => {
321 'sub' => \&feature_snapshot,
322 'override' => 0,
323 'default' => ['tgz']},
325 # Enable text search, which will list the commits which match author,
326 # committer or commit text to a given string. Enabled by default.
327 # Project specific override is not supported.
328 'search' => {
329 'override' => 0,
330 'default' => [1]},
332 # Enable grep search, which will list the files in currently selected
333 # tree containing the given string. Enabled by default. This can be
334 # potentially CPU-intensive, of course.
336 # To enable system wide have in $GITWEB_CONFIG
337 # $feature{'grep'}{'default'} = [1];
338 # To have project specific config enable override in $GITWEB_CONFIG
339 # $feature{'grep'}{'override'} = 1;
340 # and in project config gitweb.grep = 0|1;
341 'grep' => {
342 'sub' => sub { feature_bool('grep', @_) },
343 'override' => 0,
344 'default' => [1]},
346 # Enable the pickaxe search, which will list the commits that modified
347 # a given string in a file. This can be practical and quite faster
348 # alternative to 'blame', but still potentially CPU-intensive.
350 # To enable system wide have in $GITWEB_CONFIG
351 # $feature{'pickaxe'}{'default'} = [1];
352 # To have project specific config enable override in $GITWEB_CONFIG
353 # $feature{'pickaxe'}{'override'} = 1;
354 # and in project config gitweb.pickaxe = 0|1;
355 'pickaxe' => {
356 'sub' => sub { feature_bool('pickaxe', @_) },
357 'override' => 0,
358 'default' => [1]},
360 # Enable showing size of blobs in a 'tree' view, in a separate
361 # column, similar to what 'ls -l' does. This cost a bit of IO.
363 # To disable system wide have in $GITWEB_CONFIG
364 # $feature{'show-sizes'}{'default'} = [0];
365 # To have project specific config enable override in $GITWEB_CONFIG
366 # $feature{'show-sizes'}{'override'} = 1;
367 # and in project config gitweb.showsizes = 0|1;
368 'show-sizes' => {
369 'sub' => sub { feature_bool('showsizes', @_) },
370 'override' => 0,
371 'default' => [1]},
373 # Make gitweb use an alternative format of the URLs which can be
374 # more readable and natural-looking: project name is embedded
375 # directly in the path and the query string contains other
376 # auxiliary information. All gitweb installations recognize
377 # URL in either format; this configures in which formats gitweb
378 # generates links.
380 # To enable system wide have in $GITWEB_CONFIG
381 # $feature{'pathinfo'}{'default'} = [1];
382 # Project specific override is not supported.
384 # Note that you will need to change the default location of CSS,
385 # favicon, logo and possibly other files to an absolute URL. Also,
386 # if gitweb.cgi serves as your indexfile, you will need to force
387 # $my_uri to contain the script name in your $GITWEB_CONFIG.
388 'pathinfo' => {
389 'override' => 0,
390 'default' => [0]},
392 # Make gitweb consider projects in project root subdirectories
393 # to be forks of existing projects. Given project $projname.git,
394 # projects matching $projname/*.git will not be shown in the main
395 # projects list, instead a '+' mark will be added to $projname
396 # there and a 'forks' view will be enabled for the project, listing
397 # all the forks. If project list is taken from a file, forks have
398 # to be listed after the main project.
400 # To enable system wide have in $GITWEB_CONFIG
401 # $feature{'forks'}{'default'} = [1];
402 # Project specific override is not supported.
403 'forks' => {
404 'override' => 0,
405 'default' => [0]},
407 # Insert custom links to the action bar of all project pages.
408 # This enables you mainly to link to third-party scripts integrating
409 # into gitweb; e.g. git-browser for graphical history representation
410 # or custom web-based repository administration interface.
412 # The 'default' value consists of a list of triplets in the form
413 # (label, link, position) where position is the label after which
414 # to insert the link and link is a format string where %n expands
415 # to the project name, %f to the project path within the filesystem,
416 # %h to the current hash (h gitweb parameter) and %b to the current
417 # hash base (hb gitweb parameter); %% expands to %.
419 # To enable system wide have in $GITWEB_CONFIG e.g.
420 # $feature{'actions'}{'default'} = [('graphiclog',
421 # '/git-browser/by-commit.html?r=%n', 'summary')];
422 # Project specific override is not supported.
423 'actions' => {
424 'override' => 0,
425 'default' => []},
427 # Allow gitweb scan project content tags described in ctags/
428 # of project repository, and display the popular Web 2.0-ish
429 # "tag cloud" near the project list. Note that this is something
430 # COMPLETELY different from the normal Git tags.
432 # gitweb by itself can show existing tags, but it does not handle
433 # tagging itself; you need an external application for that.
434 # For an example script, check Girocco's cgi/tagproj.cgi.
435 # You may want to install the HTML::TagCloud Perl module to get
436 # a pretty tag cloud instead of just a list of tags.
438 # To enable system wide have in $GITWEB_CONFIG
439 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
440 # Project specific override is not supported.
441 'ctags' => {
442 'override' => 0,
443 'default' => [0]},
445 # The maximum number of patches in a patchset generated in patch
446 # view. Set this to 0 or undef to disable patch view, or to a
447 # negative number to remove any limit.
449 # To disable system wide have in $GITWEB_CONFIG
450 # $feature{'patches'}{'default'} = [0];
451 # To have project specific config enable override in $GITWEB_CONFIG
452 # $feature{'patches'}{'override'} = 1;
453 # and in project config gitweb.patches = 0|n;
454 # where n is the maximum number of patches allowed in a patchset.
455 'patches' => {
456 'sub' => \&feature_patches,
457 'override' => 0,
458 'default' => [16]},
460 # Avatar support. When this feature is enabled, views such as
461 # shortlog or commit will display an avatar associated with
462 # the email of the committer(s) and/or author(s).
464 # Currently available providers are gravatar and picon.
465 # If an unknown provider is specified, the feature is disabled.
467 # Gravatar depends on Digest::MD5.
468 # Picon currently relies on the indiana.edu database.
470 # To enable system wide have in $GITWEB_CONFIG
471 # $feature{'avatar'}{'default'} = ['<provider>'];
472 # where <provider> is either gravatar or picon.
473 # To have project specific config enable override in $GITWEB_CONFIG
474 # $feature{'avatar'}{'override'} = 1;
475 # and in project config gitweb.avatar = <provider>;
476 'avatar' => {
477 'sub' => \&feature_avatar,
478 'override' => 0,
479 'default' => ['']},
481 # Enable displaying how much time and how many git commands
482 # it took to generate and display page. Disabled by default.
483 # Project specific override is not supported.
484 'timed' => {
485 'override' => 0,
486 'default' => [0]},
488 # Enable turning some links into links to actions which require
489 # JavaScript to run (like 'blame_incremental'). Not enabled by
490 # default. Project specific override is currently not supported.
491 'javascript-actions' => {
492 'override' => 0,
493 'default' => [0]},
495 # Syntax highlighting support. This is based on Daniel Svensson's
496 # and Sham Chukoury's work in gitweb-xmms2.git.
497 # It requires the 'highlight' program present in $PATH,
498 # and therefore is disabled by default.
500 # To enable system wide have in $GITWEB_CONFIG
501 # $feature{'highlight'}{'default'} = [1];
503 'highlight' => {
504 'sub' => sub { feature_bool('highlight', @_) },
505 'override' => 0,
506 'default' => [0]},
508 # Enable displaying of remote heads in the heads list
510 # To enable system wide have in $GITWEB_CONFIG
511 # $feature{'remote_heads'}{'default'} = [1];
512 # To have project specific config enable override in $GITWEB_CONFIG
513 # $feature{'remote_heads'}{'override'} = 1;
514 # and in project config gitweb.remote_heads = 0|1;
515 'remote_heads' => {
516 'sub' => sub { feature_bool('remote_heads', @_) },
517 'override' => 0,
518 'default' => [0]},
521 sub gitweb_get_feature {
522 my ($name) = @_;
523 return unless exists $feature{$name};
524 my ($sub, $override, @defaults) = (
525 $feature{$name}{'sub'},
526 $feature{$name}{'override'},
527 @{$feature{$name}{'default'}});
528 # project specific override is possible only if we have project
529 our $git_dir; # global variable, declared later
530 if (!$override || !defined $git_dir) {
531 return @defaults;
533 if (!defined $sub) {
534 warn "feature $name is not overridable";
535 return @defaults;
537 return $sub->(@defaults);
540 # A wrapper to check if a given feature is enabled.
541 # With this, you can say
543 # my $bool_feat = gitweb_check_feature('bool_feat');
544 # gitweb_check_feature('bool_feat') or somecode;
546 # instead of
548 # my ($bool_feat) = gitweb_get_feature('bool_feat');
549 # (gitweb_get_feature('bool_feat'))[0] or somecode;
551 sub gitweb_check_feature {
552 return (gitweb_get_feature(@_))[0];
556 sub feature_bool {
557 my $key = shift;
558 my ($val) = git_get_project_config($key, '--bool');
560 if (!defined $val) {
561 return ($_[0]);
562 } elsif ($val eq 'true') {
563 return (1);
564 } elsif ($val eq 'false') {
565 return (0);
569 sub feature_snapshot {
570 my (@fmts) = @_;
572 my ($val) = git_get_project_config('snapshot');
574 if ($val) {
575 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
578 return @fmts;
581 sub feature_patches {
582 my @val = (git_get_project_config('patches', '--int'));
584 if (@val) {
585 return @val;
588 return ($_[0]);
591 sub feature_avatar {
592 my @val = (git_get_project_config('avatar'));
594 return @val ? @val : @_;
597 # checking HEAD file with -e is fragile if the repository was
598 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
599 # and then pruned.
600 sub check_head_link {
601 my ($dir) = @_;
602 my $headfile = "$dir/HEAD";
603 return ((-e $headfile) ||
604 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
607 sub check_export_ok {
608 my ($dir) = @_;
609 return (check_head_link($dir) &&
610 (!$export_ok || -e "$dir/$export_ok") &&
611 (!$export_auth_hook || $export_auth_hook->($dir)));
614 # process alternate names for backward compatibility
615 # filter out unsupported (unknown) snapshot formats
616 sub filter_snapshot_fmts {
617 my @fmts = @_;
619 @fmts = map {
620 exists $known_snapshot_format_aliases{$_} ?
621 $known_snapshot_format_aliases{$_} : $_} @fmts;
622 @fmts = grep {
623 exists $known_snapshot_formats{$_} &&
624 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
627 # If it is set to code reference, it is code that it is to be run once per
628 # request, allowing updating configurations that change with each request,
629 # while running other code in config file only once.
631 # Otherwise, if it is false then gitweb would process config file only once;
632 # if it is true then gitweb config would be run for each request.
633 our $per_request_config = 1;
635 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
636 sub evaluate_gitweb_config {
637 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
638 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
639 # die if there are errors parsing config file
640 if (-e $GITWEB_CONFIG) {
641 do $GITWEB_CONFIG;
642 die $@ if $@;
643 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
644 do $GITWEB_CONFIG_SYSTEM;
645 die $@ if $@;
649 # Get loadavg of system, to compare against $maxload.
650 # Currently it requires '/proc/loadavg' present to get loadavg;
651 # if it is not present it returns 0, which means no load checking.
652 sub get_loadavg {
653 if( -e '/proc/loadavg' ){
654 open my $fd, '<', '/proc/loadavg'
655 or return 0;
656 my @load = split(/\s+/, scalar <$fd>);
657 close $fd;
659 # The first three columns measure CPU and IO utilization of the last one,
660 # five, and 10 minute periods. The fourth column shows the number of
661 # currently running processes and the total number of processes in the m/n
662 # format. The last column displays the last process ID used.
663 return $load[0] || 0;
665 # additional checks for load average should go here for things that don't export
666 # /proc/loadavg
668 return 0;
671 # version of the core git binary
672 our $git_version;
673 sub evaluate_git_version {
674 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
675 $number_of_git_cmds++;
678 sub check_loadavg {
679 if (defined $maxload && get_loadavg() > $maxload) {
680 die_error(503, "The load average on the server is too high");
684 # ======================================================================
685 # input validation and dispatch
687 # input parameters can be collected from a variety of sources (presently, CGI
688 # and PATH_INFO), so we define an %input_params hash that collects them all
689 # together during validation: this allows subsequent uses (e.g. href()) to be
690 # agnostic of the parameter origin
692 our %input_params = ();
694 # input parameters are stored with the long parameter name as key. This will
695 # also be used in the href subroutine to convert parameters to their CGI
696 # equivalent, and since the href() usage is the most frequent one, we store
697 # the name -> CGI key mapping here, instead of the reverse.
699 # XXX: Warning: If you touch this, check the search form for updating,
700 # too.
702 our @cgi_param_mapping = (
703 project => "p",
704 action => "a",
705 file_name => "f",
706 file_parent => "fp",
707 hash => "h",
708 hash_parent => "hp",
709 hash_base => "hb",
710 hash_parent_base => "hpb",
711 page => "pg",
712 order => "o",
713 searchtext => "s",
714 searchtype => "st",
715 snapshot_format => "sf",
716 extra_options => "opt",
717 search_use_regexp => "sr",
718 # this must be last entry (for manipulation from JavaScript)
719 javascript => "js"
721 our %cgi_param_mapping = @cgi_param_mapping;
723 # we will also need to know the possible actions, for validation
724 our %actions = (
725 "blame" => \&git_blame,
726 "blame_incremental" => \&git_blame_incremental,
727 "blame_data" => \&git_blame_data,
728 "blobdiff" => \&git_blobdiff,
729 "blobdiff_plain" => \&git_blobdiff_plain,
730 "blob" => \&git_blob,
731 "blob_plain" => \&git_blob_plain,
732 "commitdiff" => \&git_commitdiff,
733 "commitdiff_plain" => \&git_commitdiff_plain,
734 "commit" => \&git_commit,
735 "forks" => \&git_forks,
736 "heads" => \&git_heads,
737 "history" => \&git_history,
738 "log" => \&git_log,
739 "patch" => \&git_patch,
740 "patches" => \&git_patches,
741 "remotes" => \&git_remotes,
742 "rss" => \&git_rss,
743 "atom" => \&git_atom,
744 "search" => \&git_search,
745 "search_help" => \&git_search_help,
746 "shortlog" => \&git_shortlog,
747 "summary" => \&git_summary,
748 "tag" => \&git_tag,
749 "tags" => \&git_tags,
750 "tree" => \&git_tree,
751 "snapshot" => \&git_snapshot,
752 "object" => \&git_object,
753 # those below don't need $project
754 "opml" => \&git_opml,
755 "project_list" => \&git_project_list,
756 "project_index" => \&git_project_index,
759 # finally, we have the hash of allowed extra_options for the commands that
760 # allow them
761 our %allowed_options = (
762 "--no-merges" => [ qw(rss atom log shortlog history) ],
765 # fill %input_params with the CGI parameters. All values except for 'opt'
766 # should be single values, but opt can be an array. We should probably
767 # build an array of parameters that can be multi-valued, but since for the time
768 # being it's only this one, we just single it out
769 sub evaluate_query_params {
770 our $cgi;
772 while (my ($name, $symbol) = each %cgi_param_mapping) {
773 if ($symbol eq 'opt') {
774 $input_params{$name} = [ $cgi->param($symbol) ];
775 } else {
776 $input_params{$name} = $cgi->param($symbol);
781 # now read PATH_INFO and update the parameter list for missing parameters
782 sub evaluate_path_info {
783 return if defined $input_params{'project'};
784 return if !$path_info;
785 $path_info =~ s,^/+,,;
786 return if !$path_info;
788 # find which part of PATH_INFO is project
789 my $project = $path_info;
790 $project =~ s,/+$,,;
791 while ($project && !check_head_link("$projectroot/$project")) {
792 $project =~ s,/*[^/]*$,,;
794 return unless $project;
795 $input_params{'project'} = $project;
797 # do not change any parameters if an action is given using the query string
798 return if $input_params{'action'};
799 $path_info =~ s,^\Q$project\E/*,,;
801 # next, check if we have an action
802 my $action = $path_info;
803 $action =~ s,/.*$,,;
804 if (exists $actions{$action}) {
805 $path_info =~ s,^$action/*,,;
806 $input_params{'action'} = $action;
809 # list of actions that want hash_base instead of hash, but can have no
810 # pathname (f) parameter
811 my @wants_base = (
812 'tree',
813 'history',
816 # we want to catch, among others
817 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
818 my ($parentrefname, $parentpathname, $refname, $pathname) =
819 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
821 # first, analyze the 'current' part
822 if (defined $pathname) {
823 # we got "branch:filename" or "branch:dir/"
824 # we could use git_get_type(branch:pathname), but:
825 # - it needs $git_dir
826 # - it does a git() call
827 # - the convention of terminating directories with a slash
828 # makes it superfluous
829 # - embedding the action in the PATH_INFO would make it even
830 # more superfluous
831 $pathname =~ s,^/+,,;
832 if (!$pathname || substr($pathname, -1) eq "/") {
833 $input_params{'action'} ||= "tree";
834 $pathname =~ s,/$,,;
835 } else {
836 # the default action depends on whether we had parent info
837 # or not
838 if ($parentrefname) {
839 $input_params{'action'} ||= "blobdiff_plain";
840 } else {
841 $input_params{'action'} ||= "blob_plain";
844 $input_params{'hash_base'} ||= $refname;
845 $input_params{'file_name'} ||= $pathname;
846 } elsif (defined $refname) {
847 # we got "branch". In this case we have to choose if we have to
848 # set hash or hash_base.
850 # Most of the actions without a pathname only want hash to be
851 # set, except for the ones specified in @wants_base that want
852 # hash_base instead. It should also be noted that hand-crafted
853 # links having 'history' as an action and no pathname or hash
854 # set will fail, but that happens regardless of PATH_INFO.
855 if (defined $parentrefname) {
856 # if there is parent let the default be 'shortlog' action
857 # (for http://git.example.com/repo.git/A..B links); if there
858 # is no parent, dispatch will detect type of object and set
859 # action appropriately if required (if action is not set)
860 $input_params{'action'} ||= "shortlog";
862 if ($input_params{'action'} &&
863 grep { $_ eq $input_params{'action'} } @wants_base) {
864 $input_params{'hash_base'} ||= $refname;
865 } else {
866 $input_params{'hash'} ||= $refname;
870 # next, handle the 'parent' part, if present
871 if (defined $parentrefname) {
872 # a missing pathspec defaults to the 'current' filename, allowing e.g.
873 # someproject/blobdiff/oldrev..newrev:/filename
874 if ($parentpathname) {
875 $parentpathname =~ s,^/+,,;
876 $parentpathname =~ s,/$,,;
877 $input_params{'file_parent'} ||= $parentpathname;
878 } else {
879 $input_params{'file_parent'} ||= $input_params{'file_name'};
881 # we assume that hash_parent_base is wanted if a path was specified,
882 # or if the action wants hash_base instead of hash
883 if (defined $input_params{'file_parent'} ||
884 grep { $_ eq $input_params{'action'} } @wants_base) {
885 $input_params{'hash_parent_base'} ||= $parentrefname;
886 } else {
887 $input_params{'hash_parent'} ||= $parentrefname;
891 # for the snapshot action, we allow URLs in the form
892 # $project/snapshot/$hash.ext
893 # where .ext determines the snapshot and gets removed from the
894 # passed $refname to provide the $hash.
896 # To be able to tell that $refname includes the format extension, we
897 # require the following two conditions to be satisfied:
898 # - the hash input parameter MUST have been set from the $refname part
899 # of the URL (i.e. they must be equal)
900 # - the snapshot format MUST NOT have been defined already (e.g. from
901 # CGI parameter sf)
902 # It's also useless to try any matching unless $refname has a dot,
903 # so we check for that too
904 if (defined $input_params{'action'} &&
905 $input_params{'action'} eq 'snapshot' &&
906 defined $refname && index($refname, '.') != -1 &&
907 $refname eq $input_params{'hash'} &&
908 !defined $input_params{'snapshot_format'}) {
909 # We loop over the known snapshot formats, checking for
910 # extensions. Allowed extensions are both the defined suffix
911 # (which includes the initial dot already) and the snapshot
912 # format key itself, with a prepended dot
913 while (my ($fmt, $opt) = each %known_snapshot_formats) {
914 my $hash = $refname;
915 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
916 next;
918 my $sfx = $1;
919 # a valid suffix was found, so set the snapshot format
920 # and reset the hash parameter
921 $input_params{'snapshot_format'} = $fmt;
922 $input_params{'hash'} = $hash;
923 # we also set the format suffix to the one requested
924 # in the URL: this way a request for e.g. .tgz returns
925 # a .tgz instead of a .tar.gz
926 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
927 last;
932 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
933 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
934 $searchtext, $search_regexp);
935 sub evaluate_and_validate_params {
936 our $action = $input_params{'action'};
937 if (defined $action) {
938 if (!validate_action($action)) {
939 die_error(400, "Invalid action parameter");
943 # parameters which are pathnames
944 our $project = $input_params{'project'};
945 if (defined $project) {
946 if (!validate_project($project)) {
947 undef $project;
948 die_error(404, "No such project");
952 our $file_name = $input_params{'file_name'};
953 if (defined $file_name) {
954 if (!validate_pathname($file_name)) {
955 die_error(400, "Invalid file parameter");
959 our $file_parent = $input_params{'file_parent'};
960 if (defined $file_parent) {
961 if (!validate_pathname($file_parent)) {
962 die_error(400, "Invalid file parent parameter");
966 # parameters which are refnames
967 our $hash = $input_params{'hash'};
968 if (defined $hash) {
969 if (!validate_refname($hash)) {
970 die_error(400, "Invalid hash parameter");
974 our $hash_parent = $input_params{'hash_parent'};
975 if (defined $hash_parent) {
976 if (!validate_refname($hash_parent)) {
977 die_error(400, "Invalid hash parent parameter");
981 our $hash_base = $input_params{'hash_base'};
982 if (defined $hash_base) {
983 if (!validate_refname($hash_base)) {
984 die_error(400, "Invalid hash base parameter");
988 our @extra_options = @{$input_params{'extra_options'}};
989 # @extra_options is always defined, since it can only be (currently) set from
990 # CGI, and $cgi->param() returns the empty array in array context if the param
991 # is not set
992 foreach my $opt (@extra_options) {
993 if (not exists $allowed_options{$opt}) {
994 die_error(400, "Invalid option parameter");
996 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
997 die_error(400, "Invalid option parameter for this action");
1001 our $hash_parent_base = $input_params{'hash_parent_base'};
1002 if (defined $hash_parent_base) {
1003 if (!validate_refname($hash_parent_base)) {
1004 die_error(400, "Invalid hash parent base parameter");
1008 # other parameters
1009 our $page = $input_params{'page'};
1010 if (defined $page) {
1011 if ($page =~ m/[^0-9]/) {
1012 die_error(400, "Invalid page parameter");
1016 our $searchtype = $input_params{'searchtype'};
1017 if (defined $searchtype) {
1018 if ($searchtype =~ m/[^a-z]/) {
1019 die_error(400, "Invalid searchtype parameter");
1023 our $search_use_regexp = $input_params{'search_use_regexp'};
1025 our $searchtext = $input_params{'searchtext'};
1026 our $search_regexp;
1027 if (defined $searchtext) {
1028 if (length($searchtext) < 2) {
1029 die_error(403, "At least two characters are required for search parameter");
1031 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1035 # path to the current git repository
1036 our $git_dir;
1037 sub evaluate_git_dir {
1038 our $git_dir = "$projectroot/$project" if $project;
1041 our (@snapshot_fmts, $git_avatar);
1042 sub configure_gitweb_features {
1043 # list of supported snapshot formats
1044 our @snapshot_fmts = gitweb_get_feature('snapshot');
1045 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1047 # check that the avatar feature is set to a known provider name,
1048 # and for each provider check if the dependencies are satisfied.
1049 # if the provider name is invalid or the dependencies are not met,
1050 # reset $git_avatar to the empty string.
1051 our ($git_avatar) = gitweb_get_feature('avatar');
1052 if ($git_avatar eq 'gravatar') {
1053 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1054 } elsif ($git_avatar eq 'picon') {
1055 # no dependencies
1056 } else {
1057 $git_avatar = '';
1061 # custom error handler: 'die <message>' is Internal Server Error
1062 sub handle_errors_html {
1063 my $msg = shift; # it is already HTML escaped
1065 # to avoid infinite loop where error occurs in die_error,
1066 # change handler to default handler, disabling handle_errors_html
1067 set_message("Error occured when inside die_error:\n$msg");
1069 # you cannot jump out of die_error when called as error handler;
1070 # the subroutine set via CGI::Carp::set_message is called _after_
1071 # HTTP headers are already written, so it cannot write them itself
1072 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1074 set_message(\&handle_errors_html);
1076 # dispatch
1077 sub dispatch {
1078 if (!defined $action) {
1079 if (defined $hash) {
1080 $action = git_get_type($hash);
1081 } elsif (defined $hash_base && defined $file_name) {
1082 $action = git_get_type("$hash_base:$file_name");
1083 } elsif (defined $project) {
1084 $action = 'summary';
1085 } else {
1086 $action = 'project_list';
1089 if (!defined($actions{$action})) {
1090 die_error(400, "Unknown action");
1092 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1093 !$project) {
1094 die_error(400, "Project needed");
1096 $actions{$action}->();
1099 sub reset_timer {
1100 our $t0 = [ gettimeofday() ]
1101 if defined $t0;
1102 our $number_of_git_cmds = 0;
1105 our $first_request = 1;
1106 sub run_request {
1107 reset_timer();
1109 evaluate_uri();
1110 if ($first_request) {
1111 evaluate_gitweb_config();
1112 evaluate_git_version();
1114 if ($per_request_config) {
1115 if (ref($per_request_config) eq 'CODE') {
1116 $per_request_config->();
1117 } elsif (!$first_request) {
1118 evaluate_gitweb_config();
1121 check_loadavg();
1123 # $projectroot and $projects_list might be set in gitweb config file
1124 $projects_list ||= $projectroot;
1126 evaluate_query_params();
1127 evaluate_path_info();
1128 evaluate_and_validate_params();
1129 evaluate_git_dir();
1131 configure_gitweb_features();
1133 dispatch();
1136 our $is_last_request = sub { 1 };
1137 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1138 our $CGI = 'CGI';
1139 our $cgi;
1140 sub configure_as_fcgi {
1141 require CGI::Fast;
1142 our $CGI = 'CGI::Fast';
1144 my $request_number = 0;
1145 # let each child service 100 requests
1146 our $is_last_request = sub { ++$request_number > 100 };
1148 sub evaluate_argv {
1149 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1150 configure_as_fcgi()
1151 if $script_name =~ /\.fcgi$/;
1153 return unless (@ARGV);
1155 require Getopt::Long;
1156 Getopt::Long::GetOptions(
1157 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1158 'nproc|n=i' => sub {
1159 my ($arg, $val) = @_;
1160 return unless eval { require FCGI::ProcManager; 1; };
1161 my $proc_manager = FCGI::ProcManager->new({
1162 n_processes => $val,
1164 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1165 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1166 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1171 sub run {
1172 evaluate_argv();
1174 $first_request = 1;
1175 $pre_listen_hook->()
1176 if $pre_listen_hook;
1178 REQUEST:
1179 while ($cgi = $CGI->new()) {
1180 $pre_dispatch_hook->()
1181 if $pre_dispatch_hook;
1183 run_request();
1185 $post_dispatch_hook->()
1186 if $post_dispatch_hook;
1187 $first_request = 0;
1189 last REQUEST if ($is_last_request->());
1192 DONE_GITWEB:
1196 run();
1198 if (defined caller) {
1199 # wrapped in a subroutine processing requests,
1200 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1201 return;
1202 } else {
1203 # pure CGI script, serving single request
1204 exit;
1207 ## ======================================================================
1208 ## action links
1210 # possible values of extra options
1211 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1212 # -replay => 1 - start from a current view (replay with modifications)
1213 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1214 sub href {
1215 my %params = @_;
1216 # default is to use -absolute url() i.e. $my_uri
1217 my $href = $params{-full} ? $my_url : $my_uri;
1219 $params{'project'} = $project unless exists $params{'project'};
1221 if ($params{-replay}) {
1222 while (my ($name, $symbol) = each %cgi_param_mapping) {
1223 if (!exists $params{$name}) {
1224 $params{$name} = $input_params{$name};
1229 my $use_pathinfo = gitweb_check_feature('pathinfo');
1230 if (defined $params{'project'} &&
1231 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1232 # try to put as many parameters as possible in PATH_INFO:
1233 # - project name
1234 # - action
1235 # - hash_parent or hash_parent_base:/file_parent
1236 # - hash or hash_base:/filename
1237 # - the snapshot_format as an appropriate suffix
1239 # When the script is the root DirectoryIndex for the domain,
1240 # $href here would be something like http://gitweb.example.com/
1241 # Thus, we strip any trailing / from $href, to spare us double
1242 # slashes in the final URL
1243 $href =~ s,/$,,;
1245 # Then add the project name, if present
1246 $href .= "/".esc_path_info($params{'project'});
1247 delete $params{'project'};
1249 # since we destructively absorb parameters, we keep this
1250 # boolean that remembers if we're handling a snapshot
1251 my $is_snapshot = $params{'action'} eq 'snapshot';
1253 # Summary just uses the project path URL, any other action is
1254 # added to the URL
1255 if (defined $params{'action'}) {
1256 $href .= "/".esc_path_info($params{'action'})
1257 unless $params{'action'} eq 'summary';
1258 delete $params{'action'};
1261 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1262 # stripping nonexistent or useless pieces
1263 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1264 || $params{'hash_parent'} || $params{'hash'});
1265 if (defined $params{'hash_base'}) {
1266 if (defined $params{'hash_parent_base'}) {
1267 $href .= esc_path_info($params{'hash_parent_base'});
1268 # skip the file_parent if it's the same as the file_name
1269 if (defined $params{'file_parent'}) {
1270 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1271 delete $params{'file_parent'};
1272 } elsif ($params{'file_parent'} !~ /\.\./) {
1273 $href .= ":/".esc_path_info($params{'file_parent'});
1274 delete $params{'file_parent'};
1277 $href .= "..";
1278 delete $params{'hash_parent'};
1279 delete $params{'hash_parent_base'};
1280 } elsif (defined $params{'hash_parent'}) {
1281 $href .= esc_path_info($params{'hash_parent'}). "..";
1282 delete $params{'hash_parent'};
1285 $href .= esc_path_info($params{'hash_base'});
1286 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1287 $href .= ":/".esc_path_info($params{'file_name'});
1288 delete $params{'file_name'};
1290 delete $params{'hash'};
1291 delete $params{'hash_base'};
1292 } elsif (defined $params{'hash'}) {
1293 $href .= esc_path_info($params{'hash'});
1294 delete $params{'hash'};
1297 # If the action was a snapshot, we can absorb the
1298 # snapshot_format parameter too
1299 if ($is_snapshot) {
1300 my $fmt = $params{'snapshot_format'};
1301 # snapshot_format should always be defined when href()
1302 # is called, but just in case some code forgets, we
1303 # fall back to the default
1304 $fmt ||= $snapshot_fmts[0];
1305 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1306 delete $params{'snapshot_format'};
1310 # now encode the parameters explicitly
1311 my @result = ();
1312 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1313 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1314 if (defined $params{$name}) {
1315 if (ref($params{$name}) eq "ARRAY") {
1316 foreach my $par (@{$params{$name}}) {
1317 push @result, $symbol . "=" . esc_param($par);
1319 } else {
1320 push @result, $symbol . "=" . esc_param($params{$name});
1324 $href .= "?" . join(';', @result) if scalar @result;
1326 # final transformation: trailing spaces must be escaped (URI-encoded)
1327 $href =~ s/(\s+)$/CGI::escape($1)/e;
1329 return $href;
1333 ## ======================================================================
1334 ## validation, quoting/unquoting and escaping
1336 sub validate_action {
1337 my $input = shift || return undef;
1338 return undef unless exists $actions{$input};
1339 return $input;
1342 sub validate_project {
1343 my $input = shift || return undef;
1344 if (!validate_pathname($input) ||
1345 !(-d "$projectroot/$input") ||
1346 !check_export_ok("$projectroot/$input") ||
1347 ($strict_export && !project_in_list($input))) {
1348 return undef;
1349 } else {
1350 return $input;
1354 sub validate_pathname {
1355 my $input = shift || return undef;
1357 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1358 # at the beginning, at the end, and between slashes.
1359 # also this catches doubled slashes
1360 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1361 return undef;
1363 # no null characters
1364 if ($input =~ m!\0!) {
1365 return undef;
1367 return $input;
1370 sub validate_refname {
1371 my $input = shift || return undef;
1373 # textual hashes are O.K.
1374 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1375 return $input;
1377 # it must be correct pathname
1378 $input = validate_pathname($input)
1379 or return undef;
1380 # restrictions on ref name according to git-check-ref-format
1381 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1382 return undef;
1384 return $input;
1387 # git may return quoted and escaped filenames
1388 sub unquote {
1389 my $str = shift;
1391 sub unq {
1392 my $seq = shift;
1393 my %es = ( # character escape codes, aka escape sequences
1394 't' => "\t", # tab (HT, TAB)
1395 'n' => "\n", # newline (NL)
1396 'r' => "\r", # return (CR)
1397 'f' => "\f", # form feed (FF)
1398 'b' => "\b", # backspace (BS)
1399 'a' => "\a", # alarm (bell) (BEL)
1400 'e' => "\e", # escape (ESC)
1401 'v' => "\013", # vertical tab (VT)
1404 if ($seq =~ m/^[0-7]{1,3}$/) {
1405 # octal char sequence
1406 return chr(oct($seq));
1407 } elsif (exists $es{$seq}) {
1408 # C escape sequence, aka character escape code
1409 return $es{$seq};
1411 # quoted ordinary character
1412 return $seq;
1415 if ($str =~ m/^"(.*)"$/) {
1416 # needs unquoting
1417 $str = $1;
1418 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1420 return $str;
1423 sub project_in_list {
1424 my $project = shift;
1425 my @list = git_get_projects_list();
1426 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1429 ## ----------------------------------------------------------------------
1430 ## HTML aware string manipulation
1432 # Try to chop given string on a word boundary between position
1433 # $len and $len+$add_len. If there is no word boundary there,
1434 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1435 # (marking chopped part) would be longer than given string.
1436 sub chop_str {
1437 my $str = shift;
1438 my $len = shift;
1439 my $add_len = shift || 10;
1440 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1442 # Make sure perl knows it is utf8 encoded so we don't
1443 # cut in the middle of a utf8 multibyte char.
1444 $str = to_utf8($str);
1446 # allow only $len chars, but don't cut a word if it would fit in $add_len
1447 # if it doesn't fit, cut it if it's still longer than the dots we would add
1448 # remove chopped character entities entirely
1450 # when chopping in the middle, distribute $len into left and right part
1451 # return early if chopping wouldn't make string shorter
1452 if ($where eq 'center') {
1453 return $str if ($len + 5 >= length($str)); # filler is length 5
1454 $len = int($len/2);
1455 } else {
1456 return $str if ($len + 4 >= length($str)); # filler is length 4
1459 # regexps: ending and beginning with word part up to $add_len
1460 my $endre = qr/.{$len}\w{0,$add_len}/;
1461 my $begre = qr/\w{0,$add_len}.{$len}/;
1463 if ($where eq 'left') {
1464 $str =~ m/^(.*?)($begre)$/;
1465 my ($lead, $body) = ($1, $2);
1466 if (length($lead) > 4) {
1467 $lead = " ...";
1469 return "$lead$body";
1471 } elsif ($where eq 'center') {
1472 $str =~ m/^($endre)(.*)$/;
1473 my ($left, $str) = ($1, $2);
1474 $str =~ m/^(.*?)($begre)$/;
1475 my ($mid, $right) = ($1, $2);
1476 if (length($mid) > 5) {
1477 $mid = " ... ";
1479 return "$left$mid$right";
1481 } else {
1482 $str =~ m/^($endre)(.*)$/;
1483 my $body = $1;
1484 my $tail = $2;
1485 if (length($tail) > 4) {
1486 $tail = "... ";
1488 return "$body$tail";
1492 # takes the same arguments as chop_str, but also wraps a <span> around the
1493 # result with a title attribute if it does get chopped. Additionally, the
1494 # string is HTML-escaped.
1495 sub chop_and_escape_str {
1496 my ($str) = @_;
1498 my $chopped = chop_str(@_);
1499 if ($chopped eq $str) {
1500 return esc_html($chopped);
1501 } else {
1502 $str =~ s/[[:cntrl:]]/?/g;
1503 return $cgi->span({-title=>$str}, esc_html($chopped));
1507 ## ----------------------------------------------------------------------
1508 ## functions returning short strings
1510 # CSS class for given age value (in seconds)
1511 sub age_class {
1512 my $age = shift;
1514 if (!defined $age) {
1515 return "noage";
1516 } elsif ($age < 60*60*2) {
1517 return "age0";
1518 } elsif ($age < 60*60*24*2) {
1519 return "age1";
1520 } else {
1521 return "age2";
1525 # convert age in seconds to "nn units ago" string
1526 sub age_string {
1527 my $age = shift;
1528 my $age_str;
1530 if ($age > 60*60*24*365*2) {
1531 $age_str = (int $age/60/60/24/365);
1532 $age_str .= " years ago";
1533 } elsif ($age > 60*60*24*(365/12)*2) {
1534 $age_str = int $age/60/60/24/(365/12);
1535 $age_str .= " months ago";
1536 } elsif ($age > 60*60*24*7*2) {
1537 $age_str = int $age/60/60/24/7;
1538 $age_str .= " weeks ago";
1539 } elsif ($age > 60*60*24*2) {
1540 $age_str = int $age/60/60/24;
1541 $age_str .= " days ago";
1542 } elsif ($age > 60*60*2) {
1543 $age_str = int $age/60/60;
1544 $age_str .= " hours ago";
1545 } elsif ($age > 60*2) {
1546 $age_str = int $age/60;
1547 $age_str .= " min ago";
1548 } elsif ($age > 2) {
1549 $age_str = int $age;
1550 $age_str .= " sec ago";
1551 } else {
1552 $age_str .= " right now";
1554 return $age_str;
1557 use constant {
1558 S_IFINVALID => 0030000,
1559 S_IFGITLINK => 0160000,
1562 # submodule/subproject, a commit object reference
1563 sub S_ISGITLINK {
1564 my $mode = shift;
1566 return (($mode & S_IFMT) == S_IFGITLINK)
1569 # convert file mode in octal to symbolic file mode string
1570 sub mode_str {
1571 my $mode = oct shift;
1573 if (S_ISGITLINK($mode)) {
1574 return 'm---------';
1575 } elsif (S_ISDIR($mode & S_IFMT)) {
1576 return 'drwxr-xr-x';
1577 } elsif (S_ISLNK($mode)) {
1578 return 'lrwxrwxrwx';
1579 } elsif (S_ISREG($mode)) {
1580 # git cares only about the executable bit
1581 if ($mode & S_IXUSR) {
1582 return '-rwxr-xr-x';
1583 } else {
1584 return '-rw-r--r--';
1586 } else {
1587 return '----------';
1591 # convert file mode in octal to file type string
1592 sub file_type {
1593 my $mode = shift;
1595 if ($mode !~ m/^[0-7]+$/) {
1596 return $mode;
1597 } else {
1598 $mode = oct $mode;
1601 if (S_ISGITLINK($mode)) {
1602 return "submodule";
1603 } elsif (S_ISDIR($mode & S_IFMT)) {
1604 return "directory";
1605 } elsif (S_ISLNK($mode)) {
1606 return "symlink";
1607 } elsif (S_ISREG($mode)) {
1608 return "file";
1609 } else {
1610 return "unknown";
1614 # convert file mode in octal to file type description string
1615 sub file_type_long {
1616 my $mode = shift;
1618 if ($mode !~ m/^[0-7]+$/) {
1619 return $mode;
1620 } else {
1621 $mode = oct $mode;
1624 if (S_ISGITLINK($mode)) {
1625 return "submodule";
1626 } elsif (S_ISDIR($mode & S_IFMT)) {
1627 return "directory";
1628 } elsif (S_ISLNK($mode)) {
1629 return "symlink";
1630 } elsif (S_ISREG($mode)) {
1631 if ($mode & S_IXUSR) {
1632 return "executable";
1633 } else {
1634 return "file";
1636 } else {
1637 return "unknown";
1642 ## ----------------------------------------------------------------------
1643 ## functions returning short HTML fragments, or transforming HTML fragments
1644 ## which don't belong to other sections
1646 # format line of commit message.
1647 sub format_log_line_html {
1648 my $line = shift;
1650 $line = esc_html($line, -nbsp=>1);
1651 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1652 $cgi->a({-href => href(action=>"object", hash=>$1),
1653 -class => "text"}, $1);
1654 }eg;
1656 return $line;
1659 # format marker of refs pointing to given object
1661 # the destination action is chosen based on object type and current context:
1662 # - for annotated tags, we choose the tag view unless it's the current view
1663 # already, in which case we go to shortlog view
1664 # - for other refs, we keep the current view if we're in history, shortlog or
1665 # log view, and select shortlog otherwise
1666 sub format_ref_marker {
1667 my ($refs, $id) = @_;
1668 my $markers = '';
1670 if (defined $refs->{$id}) {
1671 foreach my $ref (@{$refs->{$id}}) {
1672 # this code exploits the fact that non-lightweight tags are the
1673 # only indirect objects, and that they are the only objects for which
1674 # we want to use tag instead of shortlog as action
1675 my ($type, $name) = qw();
1676 my $indirect = ($ref =~ s/\^\{\}$//);
1677 # e.g. tags/v2.6.11 or heads/next
1678 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1679 $type = $1;
1680 $name = $2;
1681 } else {
1682 $type = "ref";
1683 $name = $ref;
1686 my $class = $type;
1687 $class .= " indirect" if $indirect;
1689 my $dest_action = "shortlog";
1691 if ($indirect) {
1692 $dest_action = "tag" unless $action eq "tag";
1693 } elsif ($action =~ /^(history|(short)?log)$/) {
1694 $dest_action = $action;
1697 my $dest = "";
1698 $dest .= "refs/" unless $ref =~ m!^refs/!;
1699 $dest .= $ref;
1701 my $link = $cgi->a({
1702 -href => href(
1703 action=>$dest_action,
1704 hash=>$dest
1705 )}, $name);
1707 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
1708 $link . "</span>";
1712 if ($markers) {
1713 return ' <span class="refs">'. $markers . '</span>';
1714 } else {
1715 return "";
1719 # format, perhaps shortened and with markers, title line
1720 sub format_subject_html {
1721 my ($long, $short, $href, $extra) = @_;
1722 $extra = '' unless defined($extra);
1724 if (length($short) < length($long)) {
1725 $long =~ s/[[:cntrl:]]/?/g;
1726 return $cgi->a({-href => $href, -class => "list subject",
1727 -title => to_utf8($long)},
1728 esc_html($short)) . $extra;
1729 } else {
1730 return $cgi->a({-href => $href, -class => "list subject"},
1731 esc_html($long)) . $extra;
1735 # Rather than recomputing the url for an email multiple times, we cache it
1736 # after the first hit. This gives a visible benefit in views where the avatar
1737 # for the same email is used repeatedly (e.g. shortlog).
1738 # The cache is shared by all avatar engines (currently gravatar only), which
1739 # are free to use it as preferred. Since only one avatar engine is used for any
1740 # given page, there's no risk for cache conflicts.
1741 our %avatar_cache = ();
1743 # Compute the picon url for a given email, by using the picon search service over at
1744 # http://www.cs.indiana.edu/picons/search.html
1745 sub picon_url {
1746 my $email = lc shift;
1747 if (!$avatar_cache{$email}) {
1748 my ($user, $domain) = split('@', $email);
1749 $avatar_cache{$email} =
1750 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1751 "$domain/$user/" .
1752 "users+domains+unknown/up/single";
1754 return $avatar_cache{$email};
1757 # Compute the gravatar url for a given email, if it's not in the cache already.
1758 # Gravatar stores only the part of the URL before the size, since that's the
1759 # one computationally more expensive. This also allows reuse of the cache for
1760 # different sizes (for this particular engine).
1761 sub gravatar_url {
1762 my $email = lc shift;
1763 my $size = shift;
1764 $avatar_cache{$email} ||=
1765 "http://www.gravatar.com/avatar/" .
1766 Digest::MD5::md5_hex($email) . "?s=";
1767 return $avatar_cache{$email} . $size;
1770 # Insert an avatar for the given $email at the given $size if the feature
1771 # is enabled.
1772 sub git_get_avatar {
1773 my ($email, %opts) = @_;
1774 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1775 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1776 $opts{-size} ||= 'default';
1777 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1778 my $url = "";
1779 if ($git_avatar eq 'gravatar') {
1780 $url = gravatar_url($email, $size);
1781 } elsif ($git_avatar eq 'picon') {
1782 $url = picon_url($email);
1784 # Other providers can be added by extending the if chain, defining $url
1785 # as needed. If no variant puts something in $url, we assume avatars
1786 # are completely disabled/unavailable.
1787 if ($url) {
1788 return $pre_white .
1789 "<img width=\"$size\" " .
1790 "class=\"avatar\" " .
1791 "src=\"".esc_url($url)."\" " .
1792 "alt=\"\" " .
1793 "/>" . $post_white;
1794 } else {
1795 return "";
1799 sub format_search_author {
1800 my ($author, $searchtype, $displaytext) = @_;
1801 my $have_search = gitweb_check_feature('search');
1803 if ($have_search) {
1804 my $performed = "";
1805 if ($searchtype eq 'author') {
1806 $performed = "authored";
1807 } elsif ($searchtype eq 'committer') {
1808 $performed = "committed";
1811 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1812 searchtext=>$author,
1813 searchtype=>$searchtype), class=>"list",
1814 title=>"Search for commits $performed by $author"},
1815 $displaytext);
1817 } else {
1818 return $displaytext;
1822 # format the author name of the given commit with the given tag
1823 # the author name is chopped and escaped according to the other
1824 # optional parameters (see chop_str).
1825 sub format_author_html {
1826 my $tag = shift;
1827 my $co = shift;
1828 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1829 return "<$tag class=\"author\">" .
1830 format_search_author($co->{'author_name'}, "author",
1831 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1832 $author) .
1833 "</$tag>";
1836 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1837 sub format_git_diff_header_line {
1838 my $line = shift;
1839 my $diffinfo = shift;
1840 my ($from, $to) = @_;
1842 if ($diffinfo->{'nparents'}) {
1843 # combined diff
1844 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1845 if ($to->{'href'}) {
1846 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1847 esc_path($to->{'file'}));
1848 } else { # file was deleted (no href)
1849 $line .= esc_path($to->{'file'});
1851 } else {
1852 # "ordinary" diff
1853 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1854 if ($from->{'href'}) {
1855 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1856 'a/' . esc_path($from->{'file'}));
1857 } else { # file was added (no href)
1858 $line .= 'a/' . esc_path($from->{'file'});
1860 $line .= ' ';
1861 if ($to->{'href'}) {
1862 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1863 'b/' . esc_path($to->{'file'}));
1864 } else { # file was deleted
1865 $line .= 'b/' . esc_path($to->{'file'});
1869 return "<div class=\"diff header\">$line</div>\n";
1872 # format extended diff header line, before patch itself
1873 sub format_extended_diff_header_line {
1874 my $line = shift;
1875 my $diffinfo = shift;
1876 my ($from, $to) = @_;
1878 # match <path>
1879 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1880 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1881 esc_path($from->{'file'}));
1883 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1884 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1885 esc_path($to->{'file'}));
1887 # match single <mode>
1888 if ($line =~ m/\s(\d{6})$/) {
1889 $line .= '<span class="info"> (' .
1890 file_type_long($1) .
1891 ')</span>';
1893 # match <hash>
1894 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1895 # can match only for combined diff
1896 $line = 'index ';
1897 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1898 if ($from->{'href'}[$i]) {
1899 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1900 -class=>"hash"},
1901 substr($diffinfo->{'from_id'}[$i],0,7));
1902 } else {
1903 $line .= '0' x 7;
1905 # separator
1906 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1908 $line .= '..';
1909 if ($to->{'href'}) {
1910 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1911 substr($diffinfo->{'to_id'},0,7));
1912 } else {
1913 $line .= '0' x 7;
1916 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1917 # can match only for ordinary diff
1918 my ($from_link, $to_link);
1919 if ($from->{'href'}) {
1920 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1921 substr($diffinfo->{'from_id'},0,7));
1922 } else {
1923 $from_link = '0' x 7;
1925 if ($to->{'href'}) {
1926 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1927 substr($diffinfo->{'to_id'},0,7));
1928 } else {
1929 $to_link = '0' x 7;
1931 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1932 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1935 return $line . "<br/>\n";
1938 # format from-file/to-file diff header
1939 sub format_diff_from_to_header {
1940 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1941 my $line;
1942 my $result = '';
1944 $line = $from_line;
1945 #assert($line =~ m/^---/) if DEBUG;
1946 # no extra formatting for "^--- /dev/null"
1947 if (! $diffinfo->{'nparents'}) {
1948 # ordinary (single parent) diff
1949 if ($line =~ m!^--- "?a/!) {
1950 if ($from->{'href'}) {
1951 $line = '--- a/' .
1952 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1953 esc_path($from->{'file'}));
1954 } else {
1955 $line = '--- a/' .
1956 esc_path($from->{'file'});
1959 $result .= qq!<div class="diff from_file">$line</div>\n!;
1961 } else {
1962 # combined diff (merge commit)
1963 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1964 if ($from->{'href'}[$i]) {
1965 $line = '--- ' .
1966 $cgi->a({-href=>href(action=>"blobdiff",
1967 hash_parent=>$diffinfo->{'from_id'}[$i],
1968 hash_parent_base=>$parents[$i],
1969 file_parent=>$from->{'file'}[$i],
1970 hash=>$diffinfo->{'to_id'},
1971 hash_base=>$hash,
1972 file_name=>$to->{'file'}),
1973 -class=>"path",
1974 -title=>"diff" . ($i+1)},
1975 $i+1) .
1976 '/' .
1977 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1978 esc_path($from->{'file'}[$i]));
1979 } else {
1980 $line = '--- /dev/null';
1982 $result .= qq!<div class="diff from_file">$line</div>\n!;
1986 $line = $to_line;
1987 #assert($line =~ m/^\+\+\+/) if DEBUG;
1988 # no extra formatting for "^+++ /dev/null"
1989 if ($line =~ m!^\+\+\+ "?b/!) {
1990 if ($to->{'href'}) {
1991 $line = '+++ b/' .
1992 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1993 esc_path($to->{'file'}));
1994 } else {
1995 $line = '+++ b/' .
1996 esc_path($to->{'file'});
1999 $result .= qq!<div class="diff to_file">$line</div>\n!;
2001 return $result;
2004 # create note for patch simplified by combined diff
2005 sub format_diff_cc_simplified {
2006 my ($diffinfo, @parents) = @_;
2007 my $result = '';
2009 $result .= "<div class=\"diff header\">" .
2010 "diff --cc ";
2011 if (!is_deleted($diffinfo)) {
2012 $result .= $cgi->a({-href => href(action=>"blob",
2013 hash_base=>$hash,
2014 hash=>$diffinfo->{'to_id'},
2015 file_name=>$diffinfo->{'to_file'}),
2016 -class => "path"},
2017 esc_path($diffinfo->{'to_file'}));
2018 } else {
2019 $result .= esc_path($diffinfo->{'to_file'});
2021 $result .= "</div>\n" . # class="diff header"
2022 "<div class=\"diff nodifferences\">" .
2023 "Simple merge" .
2024 "</div>\n"; # class="diff nodifferences"
2026 return $result;
2029 # format patch (diff) line (not to be used for diff headers)
2030 sub format_diff_line {
2031 my $line = shift;
2032 my ($from, $to) = @_;
2033 my $diff_class = "";
2035 chomp $line;
2037 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2038 # combined diff
2039 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2040 if ($line =~ m/^\@{3}/) {
2041 $diff_class = " chunk_header";
2042 } elsif ($line =~ m/^\\/) {
2043 $diff_class = " incomplete";
2044 } elsif ($prefix =~ tr/+/+/) {
2045 $diff_class = " add";
2046 } elsif ($prefix =~ tr/-/-/) {
2047 $diff_class = " rem";
2049 } else {
2050 # assume ordinary diff
2051 my $char = substr($line, 0, 1);
2052 if ($char eq '+') {
2053 $diff_class = " add";
2054 } elsif ($char eq '-') {
2055 $diff_class = " rem";
2056 } elsif ($char eq '@') {
2057 $diff_class = " chunk_header";
2058 } elsif ($char eq "\\") {
2059 $diff_class = " incomplete";
2062 $line = untabify($line);
2063 if ($from && $to && $line =~ m/^\@{2} /) {
2064 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2065 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2067 $from_lines = 0 unless defined $from_lines;
2068 $to_lines = 0 unless defined $to_lines;
2070 if ($from->{'href'}) {
2071 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2072 -class=>"list"}, $from_text);
2074 if ($to->{'href'}) {
2075 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2076 -class=>"list"}, $to_text);
2078 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2079 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2080 return "<div class=\"diff$diff_class\">$line</div>\n";
2081 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2082 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2083 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2085 @from_text = split(' ', $ranges);
2086 for (my $i = 0; $i < @from_text; ++$i) {
2087 ($from_start[$i], $from_nlines[$i]) =
2088 (split(',', substr($from_text[$i], 1)), 0);
2091 $to_text = pop @from_text;
2092 $to_start = pop @from_start;
2093 $to_nlines = pop @from_nlines;
2095 $line = "<span class=\"chunk_info\">$prefix ";
2096 for (my $i = 0; $i < @from_text; ++$i) {
2097 if ($from->{'href'}[$i]) {
2098 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2099 -class=>"list"}, $from_text[$i]);
2100 } else {
2101 $line .= $from_text[$i];
2103 $line .= " ";
2105 if ($to->{'href'}) {
2106 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2107 -class=>"list"}, $to_text);
2108 } else {
2109 $line .= $to_text;
2111 $line .= " $prefix</span>" .
2112 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2113 return "<div class=\"diff$diff_class\">$line</div>\n";
2115 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2118 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2119 # linked. Pass the hash of the tree/commit to snapshot.
2120 sub format_snapshot_links {
2121 my ($hash) = @_;
2122 my $num_fmts = @snapshot_fmts;
2123 if ($num_fmts > 1) {
2124 # A parenthesized list of links bearing format names.
2125 # e.g. "snapshot (_tar.gz_ _zip_)"
2126 return "snapshot (" . join(' ', map
2127 $cgi->a({
2128 -href => href(
2129 action=>"snapshot",
2130 hash=>$hash,
2131 snapshot_format=>$_
2133 }, $known_snapshot_formats{$_}{'display'})
2134 , @snapshot_fmts) . ")";
2135 } elsif ($num_fmts == 1) {
2136 # A single "snapshot" link whose tooltip bears the format name.
2137 # i.e. "_snapshot_"
2138 my ($fmt) = @snapshot_fmts;
2139 return
2140 $cgi->a({
2141 -href => href(
2142 action=>"snapshot",
2143 hash=>$hash,
2144 snapshot_format=>$fmt
2146 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2147 }, "snapshot");
2148 } else { # $num_fmts == 0
2149 return undef;
2153 ## ......................................................................
2154 ## functions returning values to be passed, perhaps after some
2155 ## transformation, to other functions; e.g. returning arguments to href()
2157 # returns hash to be passed to href to generate gitweb URL
2158 # in -title key it returns description of link
2159 sub get_feed_info {
2160 my $format = shift || 'Atom';
2161 my %res = (action => lc($format));
2163 # feed links are possible only for project views
2164 return unless (defined $project);
2165 # some views should link to OPML, or to generic project feed,
2166 # or don't have specific feed yet (so they should use generic)
2167 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2169 my $branch;
2170 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2171 # from tag links; this also makes possible to detect branch links
2172 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2173 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2174 $branch = $1;
2176 # find log type for feed description (title)
2177 my $type = 'log';
2178 if (defined $file_name) {
2179 $type = "history of $file_name";
2180 $type .= "/" if ($action eq 'tree');
2181 $type .= " on '$branch'" if (defined $branch);
2182 } else {
2183 $type = "log of $branch" if (defined $branch);
2186 $res{-title} = $type;
2187 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2188 $res{'file_name'} = $file_name;
2190 return %res;
2193 ## ----------------------------------------------------------------------
2194 ## git utility subroutines, invoking git commands
2196 # returns path to the core git executable and the --git-dir parameter as list
2197 sub git_cmd {
2198 $number_of_git_cmds++;
2199 return $GIT, '--git-dir='.$git_dir;
2202 # quote the given arguments for passing them to the shell
2203 # quote_command("command", "arg 1", "arg with ' and ! characters")
2204 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2205 # Try to avoid using this function wherever possible.
2206 sub quote_command {
2207 return join(' ',
2208 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2211 # get HEAD ref of given project as hash
2212 sub git_get_head_hash {
2213 return git_get_full_hash(shift, 'HEAD');
2216 sub git_get_full_hash {
2217 return git_get_hash(@_);
2220 sub git_get_short_hash {
2221 return git_get_hash(@_, '--short=7');
2224 sub git_get_hash {
2225 my ($project, $hash, @options) = @_;
2226 my $o_git_dir = $git_dir;
2227 my $retval = undef;
2228 $git_dir = "$projectroot/$project";
2229 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2230 '--verify', '-q', @options, $hash) {
2231 $retval = <$fd>;
2232 chomp $retval if defined $retval;
2233 close $fd;
2235 if (defined $o_git_dir) {
2236 $git_dir = $o_git_dir;
2238 return $retval;
2241 # get type of given object
2242 sub git_get_type {
2243 my $hash = shift;
2245 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2246 my $type = <$fd>;
2247 close $fd or return;
2248 chomp $type;
2249 return $type;
2252 # repository configuration
2253 our $config_file = '';
2254 our %config;
2256 # store multiple values for single key as anonymous array reference
2257 # single values stored directly in the hash, not as [ <value> ]
2258 sub hash_set_multi {
2259 my ($hash, $key, $value) = @_;
2261 if (!exists $hash->{$key}) {
2262 $hash->{$key} = $value;
2263 } elsif (!ref $hash->{$key}) {
2264 $hash->{$key} = [ $hash->{$key}, $value ];
2265 } else {
2266 push @{$hash->{$key}}, $value;
2270 # return hash of git project configuration
2271 # optionally limited to some section, e.g. 'gitweb'
2272 sub git_parse_project_config {
2273 my $section_regexp = shift;
2274 my %config;
2276 local $/ = "\0";
2278 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2279 or return;
2281 while (my $keyval = <$fh>) {
2282 chomp $keyval;
2283 my ($key, $value) = split(/\n/, $keyval, 2);
2285 hash_set_multi(\%config, $key, $value)
2286 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2288 close $fh;
2290 return %config;
2293 # convert config value to boolean: 'true' or 'false'
2294 # no value, number > 0, 'true' and 'yes' values are true
2295 # rest of values are treated as false (never as error)
2296 sub config_to_bool {
2297 my $val = shift;
2299 return 1 if !defined $val; # section.key
2301 # strip leading and trailing whitespace
2302 $val =~ s/^\s+//;
2303 $val =~ s/\s+$//;
2305 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2306 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2309 # convert config value to simple decimal number
2310 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2311 # to be multiplied by 1024, 1048576, or 1073741824
2312 sub config_to_int {
2313 my $val = shift;
2315 # strip leading and trailing whitespace
2316 $val =~ s/^\s+//;
2317 $val =~ s/\s+$//;
2319 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2320 $unit = lc($unit);
2321 # unknown unit is treated as 1
2322 return $num * ($unit eq 'g' ? 1073741824 :
2323 $unit eq 'm' ? 1048576 :
2324 $unit eq 'k' ? 1024 : 1);
2326 return $val;
2329 # convert config value to array reference, if needed
2330 sub config_to_multi {
2331 my $val = shift;
2333 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2336 sub git_get_project_config {
2337 my ($key, $type) = @_;
2339 return unless defined $git_dir;
2341 # key sanity check
2342 return unless ($key);
2343 $key =~ s/^gitweb\.//;
2344 return if ($key =~ m/\W/);
2346 # type sanity check
2347 if (defined $type) {
2348 $type =~ s/^--//;
2349 $type = undef
2350 unless ($type eq 'bool' || $type eq 'int');
2353 # get config
2354 if (!defined $config_file ||
2355 $config_file ne "$git_dir/config") {
2356 %config = git_parse_project_config('gitweb');
2357 $config_file = "$git_dir/config";
2360 # check if config variable (key) exists
2361 return unless exists $config{"gitweb.$key"};
2363 # ensure given type
2364 if (!defined $type) {
2365 return $config{"gitweb.$key"};
2366 } elsif ($type eq 'bool') {
2367 # backward compatibility: 'git config --bool' returns true/false
2368 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2369 } elsif ($type eq 'int') {
2370 return config_to_int($config{"gitweb.$key"});
2372 return $config{"gitweb.$key"};
2375 # get hash of given path at given ref
2376 sub git_get_hash_by_path {
2377 my $base = shift;
2378 my $path = shift || return undef;
2379 my $type = shift;
2381 $path =~ s,/+$,,;
2383 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2384 or die_error(500, "Open git-ls-tree failed");
2385 my $line = <$fd>;
2386 close $fd or return undef;
2388 if (!defined $line) {
2389 # there is no tree or hash given by $path at $base
2390 return undef;
2393 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2394 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2395 if (defined $type && $type ne $2) {
2396 # type doesn't match
2397 return undef;
2399 return $3;
2402 # get path of entry with given hash at given tree-ish (ref)
2403 # used to get 'from' filename for combined diff (merge commit) for renames
2404 sub git_get_path_by_hash {
2405 my $base = shift || return;
2406 my $hash = shift || return;
2408 local $/ = "\0";
2410 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2411 or return undef;
2412 while (my $line = <$fd>) {
2413 chomp $line;
2415 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2416 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2417 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2418 close $fd;
2419 return $1;
2422 close $fd;
2423 return undef;
2426 ## ......................................................................
2427 ## git utility functions, directly accessing git repository
2429 sub git_get_project_description {
2430 my $path = shift;
2432 $git_dir = "$projectroot/$path";
2433 open my $fd, '<', "$git_dir/description"
2434 or return git_get_project_config('description');
2435 my $descr = <$fd>;
2436 close $fd;
2437 if (defined $descr) {
2438 chomp $descr;
2440 return $descr;
2443 sub git_get_project_ctags {
2444 my $path = shift;
2445 my $ctags = {};
2447 $git_dir = "$projectroot/$path";
2448 opendir my $dh, "$git_dir/ctags"
2449 or return $ctags;
2450 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2451 open my $ct, '<', $_ or next;
2452 my $val = <$ct>;
2453 chomp $val;
2454 close $ct;
2455 my $ctag = $_; $ctag =~ s#.*/##;
2456 $ctags->{$ctag} = $val;
2458 closedir $dh;
2459 $ctags;
2462 sub git_populate_project_tagcloud {
2463 my $ctags = shift;
2465 # First, merge different-cased tags; tags vote on casing
2466 my %ctags_lc;
2467 foreach (keys %$ctags) {
2468 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2469 if (not $ctags_lc{lc $_}->{topcount}
2470 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2471 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2472 $ctags_lc{lc $_}->{topname} = $_;
2476 my $cloud;
2477 if (eval { require HTML::TagCloud; 1; }) {
2478 $cloud = HTML::TagCloud->new;
2479 foreach (sort keys %ctags_lc) {
2480 # Pad the title with spaces so that the cloud looks
2481 # less crammed.
2482 my $title = $ctags_lc{$_}->{topname};
2483 $title =~ s/ /&nbsp;/g;
2484 $title =~ s/^/&nbsp;/g;
2485 $title =~ s/$/&nbsp;/g;
2486 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2488 } else {
2489 $cloud = \%ctags_lc;
2491 $cloud;
2494 sub git_show_project_tagcloud {
2495 my ($cloud, $count) = @_;
2496 print STDERR ref($cloud)."..\n";
2497 if (ref $cloud eq 'HTML::TagCloud') {
2498 return $cloud->html_and_css($count);
2499 } else {
2500 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2501 return '<p align="center">' . join (', ', map {
2502 $cgi->a({-href=>"$home_link?by_tag=$_"}, $cloud->{$_}->{topname})
2503 } splice(@tags, 0, $count)) . '</p>';
2507 sub git_get_project_url_list {
2508 my $path = shift;
2510 $git_dir = "$projectroot/$path";
2511 open my $fd, '<', "$git_dir/cloneurl"
2512 or return wantarray ?
2513 @{ config_to_multi(git_get_project_config('url')) } :
2514 config_to_multi(git_get_project_config('url'));
2515 my @git_project_url_list = map { chomp; $_ } <$fd>;
2516 close $fd;
2518 return wantarray ? @git_project_url_list : \@git_project_url_list;
2521 sub git_get_projects_list {
2522 my ($filter) = @_;
2523 my @list;
2525 $filter ||= '';
2526 $filter =~ s/\.git$//;
2528 my $check_forks = gitweb_check_feature('forks');
2530 if (-d $projects_list) {
2531 # search in directory
2532 my $dir = $projects_list . ($filter ? "/$filter" : '');
2533 # remove the trailing "/"
2534 $dir =~ s!/+$!!;
2535 my $pfxlen = length("$dir");
2536 my $pfxdepth = ($dir =~ tr!/!!);
2538 File::Find::find({
2539 follow_fast => 1, # follow symbolic links
2540 follow_skip => 2, # ignore duplicates
2541 dangling_symlinks => 0, # ignore dangling symlinks, silently
2542 wanted => sub {
2543 # global variables
2544 our $project_maxdepth;
2545 our $projectroot;
2546 # skip project-list toplevel, if we get it.
2547 return if (m!^[/.]$!);
2548 # only directories can be git repositories
2549 return unless (-d $_);
2550 # don't traverse too deep (Find is super slow on os x)
2551 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2552 $File::Find::prune = 1;
2553 return;
2556 my $subdir = substr($File::Find::name, $pfxlen + 1);
2557 # we check related file in $projectroot
2558 my $path = ($filter ? "$filter/" : '') . $subdir;
2559 if (check_export_ok("$projectroot/$path")) {
2560 push @list, { path => $path };
2561 $File::Find::prune = 1;
2564 }, "$dir");
2566 } elsif (-f $projects_list) {
2567 # read from file(url-encoded):
2568 # 'git%2Fgit.git Linus+Torvalds'
2569 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2570 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2571 my %paths;
2572 open my $fd, '<', $projects_list or return;
2573 PROJECT:
2574 while (my $line = <$fd>) {
2575 chomp $line;
2576 my ($path, $owner) = split ' ', $line;
2577 $path = unescape($path);
2578 $owner = unescape($owner);
2579 if (!defined $path) {
2580 next;
2582 if ($filter ne '') {
2583 # looking for forks;
2584 my $pfx = substr($path, 0, length($filter));
2585 if ($pfx ne $filter) {
2586 next PROJECT;
2588 my $sfx = substr($path, length($filter));
2589 if ($sfx !~ /^\/.*\.git$/) {
2590 next PROJECT;
2592 } elsif ($check_forks) {
2593 PATH:
2594 foreach my $filter (keys %paths) {
2595 # looking for forks;
2596 my $pfx = substr($path, 0, length($filter));
2597 if ($pfx ne $filter) {
2598 next PATH;
2600 my $sfx = substr($path, length($filter));
2601 if ($sfx !~ /^\/.*\.git$/) {
2602 next PATH;
2604 # is a fork, don't include it in
2605 # the list
2606 next PROJECT;
2609 if (check_export_ok("$projectroot/$path")) {
2610 my $pr = {
2611 path => $path,
2612 owner => to_utf8($owner),
2614 push @list, $pr;
2615 (my $forks_path = $path) =~ s/\.git$//;
2616 $paths{$forks_path}++;
2619 close $fd;
2621 return @list;
2624 our $gitweb_project_owner = undef;
2625 sub git_get_project_list_from_file {
2627 return if (defined $gitweb_project_owner);
2629 $gitweb_project_owner = {};
2630 # read from file (url-encoded):
2631 # 'git%2Fgit.git Linus+Torvalds'
2632 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2633 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2634 if (-f $projects_list) {
2635 open(my $fd, '<', $projects_list);
2636 while (my $line = <$fd>) {
2637 chomp $line;
2638 my ($pr, $ow) = split ' ', $line;
2639 $pr = unescape($pr);
2640 $ow = unescape($ow);
2641 $gitweb_project_owner->{$pr} = to_utf8($ow);
2643 close $fd;
2647 sub git_get_project_owner {
2648 my $project = shift;
2649 my $owner;
2651 return undef unless $project;
2652 $git_dir = "$projectroot/$project";
2654 if (!defined $gitweb_project_owner) {
2655 git_get_project_list_from_file();
2658 if (exists $gitweb_project_owner->{$project}) {
2659 $owner = $gitweb_project_owner->{$project};
2661 if (!defined $owner){
2662 $owner = git_get_project_config('owner');
2664 if (!defined $owner) {
2665 $owner = get_file_owner("$git_dir");
2668 return $owner;
2671 sub git_get_last_activity {
2672 my ($path) = @_;
2673 my $fd;
2675 $git_dir = "$projectroot/$path";
2676 open($fd, "-|", git_cmd(), 'for-each-ref',
2677 '--format=%(committer)',
2678 '--sort=-committerdate',
2679 '--count=1',
2680 'refs/heads') or return;
2681 my $most_recent = <$fd>;
2682 close $fd or return;
2683 if (defined $most_recent &&
2684 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2685 my $timestamp = $1;
2686 my $age = time - $timestamp;
2687 return ($age, age_string($age));
2689 return (undef, undef);
2692 # Implementation note: when a single remote is wanted, we cannot use 'git
2693 # remote show -n' because that command always work (assuming it's a remote URL
2694 # if it's not defined), and we cannot use 'git remote show' because that would
2695 # try to make a network roundtrip. So the only way to find if that particular
2696 # remote is defined is to walk the list provided by 'git remote -v' and stop if
2697 # and when we find what we want.
2698 sub git_get_remotes_list {
2699 my $wanted = shift;
2700 my %remotes = ();
2702 open my $fd, '-|' , git_cmd(), 'remote', '-v';
2703 return unless $fd;
2704 while (my $remote = <$fd>) {
2705 chomp $remote;
2706 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
2707 next if $wanted and not $remote eq $wanted;
2708 my ($url, $key) = ($1, $2);
2710 $remotes{$remote} ||= { 'heads' => () };
2711 $remotes{$remote}{$key} = $url;
2713 close $fd or return;
2714 return wantarray ? %remotes : \%remotes;
2717 # Takes a hash of remotes as first parameter and fills it by adding the
2718 # available remote heads for each of the indicated remotes.
2719 sub fill_remote_heads {
2720 my $remotes = shift;
2721 my @heads = map { "remotes/$_" } keys %$remotes;
2722 my @remoteheads = git_get_heads_list(undef, @heads);
2723 foreach my $remote (keys %$remotes) {
2724 $remotes->{$remote}{'heads'} = [ grep {
2725 $_->{'name'} =~ s!^$remote/!!
2726 } @remoteheads ];
2730 sub git_get_references {
2731 my $type = shift || "";
2732 my %refs;
2733 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2734 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2735 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2736 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2737 or return;
2739 while (my $line = <$fd>) {
2740 chomp $line;
2741 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2742 if (defined $refs{$1}) {
2743 push @{$refs{$1}}, $2;
2744 } else {
2745 $refs{$1} = [ $2 ];
2749 close $fd or return;
2750 return \%refs;
2753 sub git_get_rev_name_tags {
2754 my $hash = shift || return undef;
2756 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2757 or return;
2758 my $name_rev = <$fd>;
2759 close $fd;
2761 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2762 return $1;
2763 } else {
2764 # catches also '$hash undefined' output
2765 return undef;
2769 ## ----------------------------------------------------------------------
2770 ## parse to hash functions
2772 sub parse_date {
2773 my $epoch = shift;
2774 my $tz = shift || "-0000";
2776 my %date;
2777 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2778 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2779 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2780 $date{'hour'} = $hour;
2781 $date{'minute'} = $min;
2782 $date{'mday'} = $mday;
2783 $date{'day'} = $days[$wday];
2784 $date{'month'} = $months[$mon];
2785 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2786 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2787 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2788 $mday, $months[$mon], $hour ,$min;
2789 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2790 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2792 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2793 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2794 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2795 $date{'hour_local'} = $hour;
2796 $date{'minute_local'} = $min;
2797 $date{'tz_local'} = $tz;
2798 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2799 1900+$year, $mon+1, $mday,
2800 $hour, $min, $sec, $tz);
2801 return %date;
2804 sub parse_tag {
2805 my $tag_id = shift;
2806 my %tag;
2807 my @comment;
2809 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2810 $tag{'id'} = $tag_id;
2811 while (my $line = <$fd>) {
2812 chomp $line;
2813 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2814 $tag{'object'} = $1;
2815 } elsif ($line =~ m/^type (.+)$/) {
2816 $tag{'type'} = $1;
2817 } elsif ($line =~ m/^tag (.+)$/) {
2818 $tag{'name'} = $1;
2819 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2820 $tag{'author'} = $1;
2821 $tag{'author_epoch'} = $2;
2822 $tag{'author_tz'} = $3;
2823 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2824 $tag{'author_name'} = $1;
2825 $tag{'author_email'} = $2;
2826 } else {
2827 $tag{'author_name'} = $tag{'author'};
2829 } elsif ($line =~ m/--BEGIN/) {
2830 push @comment, $line;
2831 last;
2832 } elsif ($line eq "") {
2833 last;
2836 push @comment, <$fd>;
2837 $tag{'comment'} = \@comment;
2838 close $fd or return;
2839 if (!defined $tag{'name'}) {
2840 return
2842 return %tag
2845 sub parse_commit_text {
2846 my ($commit_text, $withparents) = @_;
2847 my @commit_lines = split '\n', $commit_text;
2848 my %co;
2850 pop @commit_lines; # Remove '\0'
2852 if (! @commit_lines) {
2853 return;
2856 my $header = shift @commit_lines;
2857 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2858 return;
2860 ($co{'id'}, my @parents) = split ' ', $header;
2861 while (my $line = shift @commit_lines) {
2862 last if $line eq "\n";
2863 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2864 $co{'tree'} = $1;
2865 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2866 push @parents, $1;
2867 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2868 $co{'author'} = to_utf8($1);
2869 $co{'author_epoch'} = $2;
2870 $co{'author_tz'} = $3;
2871 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2872 $co{'author_name'} = $1;
2873 $co{'author_email'} = $2;
2874 } else {
2875 $co{'author_name'} = $co{'author'};
2877 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2878 $co{'committer'} = to_utf8($1);
2879 $co{'committer_epoch'} = $2;
2880 $co{'committer_tz'} = $3;
2881 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2882 $co{'committer_name'} = $1;
2883 $co{'committer_email'} = $2;
2884 } else {
2885 $co{'committer_name'} = $co{'committer'};
2889 if (!defined $co{'tree'}) {
2890 return;
2892 $co{'parents'} = \@parents;
2893 $co{'parent'} = $parents[0];
2895 foreach my $title (@commit_lines) {
2896 $title =~ s/^ //;
2897 if ($title ne "") {
2898 $co{'title'} = chop_str($title, 80, 5);
2899 # remove leading stuff of merges to make the interesting part visible
2900 if (length($title) > 50) {
2901 $title =~ s/^Automatic //;
2902 $title =~ s/^merge (of|with) /Merge ... /i;
2903 if (length($title) > 50) {
2904 $title =~ s/(http|rsync):\/\///;
2906 if (length($title) > 50) {
2907 $title =~ s/(master|www|rsync)\.//;
2909 if (length($title) > 50) {
2910 $title =~ s/kernel.org:?//;
2912 if (length($title) > 50) {
2913 $title =~ s/\/pub\/scm//;
2916 $co{'title_short'} = chop_str($title, 50, 5);
2917 last;
2920 if (! defined $co{'title'} || $co{'title'} eq "") {
2921 $co{'title'} = $co{'title_short'} = '(no commit message)';
2923 # remove added spaces
2924 foreach my $line (@commit_lines) {
2925 $line =~ s/^ //;
2927 $co{'comment'} = \@commit_lines;
2929 my $age = time - $co{'committer_epoch'};
2930 $co{'age'} = $age;
2931 $co{'age_string'} = age_string($age);
2932 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2933 if ($age > 60*60*24*7*2) {
2934 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2935 $co{'age_string_age'} = $co{'age_string'};
2936 } else {
2937 $co{'age_string_date'} = $co{'age_string'};
2938 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2940 return %co;
2943 sub parse_commit {
2944 my ($commit_id) = @_;
2945 my %co;
2947 local $/ = "\0";
2949 open my $fd, "-|", git_cmd(), "rev-list",
2950 "--parents",
2951 "--header",
2952 "--max-count=1",
2953 $commit_id,
2954 "--",
2955 or die_error(500, "Open git-rev-list failed");
2956 %co = parse_commit_text(<$fd>, 1);
2957 close $fd;
2959 return %co;
2962 sub parse_commits {
2963 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2964 my @cos;
2966 $maxcount ||= 1;
2967 $skip ||= 0;
2969 local $/ = "\0";
2971 open my $fd, "-|", git_cmd(), "rev-list",
2972 "--header",
2973 @args,
2974 ("--max-count=" . $maxcount),
2975 ("--skip=" . $skip),
2976 @extra_options,
2977 $commit_id,
2978 "--",
2979 ($filename ? ($filename) : ())
2980 or die_error(500, "Open git-rev-list failed");
2981 while (my $line = <$fd>) {
2982 my %co = parse_commit_text($line);
2983 push @cos, \%co;
2985 close $fd;
2987 return wantarray ? @cos : \@cos;
2990 # parse line of git-diff-tree "raw" output
2991 sub parse_difftree_raw_line {
2992 my $line = shift;
2993 my %res;
2995 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2996 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2997 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2998 $res{'from_mode'} = $1;
2999 $res{'to_mode'} = $2;
3000 $res{'from_id'} = $3;
3001 $res{'to_id'} = $4;
3002 $res{'status'} = $5;
3003 $res{'similarity'} = $6;
3004 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3005 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3006 } else {
3007 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3010 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3011 # combined diff (for merge commit)
3012 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3013 $res{'nparents'} = length($1);
3014 $res{'from_mode'} = [ split(' ', $2) ];
3015 $res{'to_mode'} = pop @{$res{'from_mode'}};
3016 $res{'from_id'} = [ split(' ', $3) ];
3017 $res{'to_id'} = pop @{$res{'from_id'}};
3018 $res{'status'} = [ split('', $4) ];
3019 $res{'to_file'} = unquote($5);
3021 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3022 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3023 $res{'commit'} = $1;
3026 return wantarray ? %res : \%res;
3029 # wrapper: return parsed line of git-diff-tree "raw" output
3030 # (the argument might be raw line, or parsed info)
3031 sub parsed_difftree_line {
3032 my $line_or_ref = shift;
3034 if (ref($line_or_ref) eq "HASH") {
3035 # pre-parsed (or generated by hand)
3036 return $line_or_ref;
3037 } else {
3038 return parse_difftree_raw_line($line_or_ref);
3042 # parse line of git-ls-tree output
3043 sub parse_ls_tree_line {
3044 my $line = shift;
3045 my %opts = @_;
3046 my %res;
3048 if ($opts{'-l'}) {
3049 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3050 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3052 $res{'mode'} = $1;
3053 $res{'type'} = $2;
3054 $res{'hash'} = $3;
3055 $res{'size'} = $4;
3056 if ($opts{'-z'}) {
3057 $res{'name'} = $5;
3058 } else {
3059 $res{'name'} = unquote($5);
3061 } else {
3062 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3063 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3065 $res{'mode'} = $1;
3066 $res{'type'} = $2;
3067 $res{'hash'} = $3;
3068 if ($opts{'-z'}) {
3069 $res{'name'} = $4;
3070 } else {
3071 $res{'name'} = unquote($4);
3075 return wantarray ? %res : \%res;
3078 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3079 sub parse_from_to_diffinfo {
3080 my ($diffinfo, $from, $to, @parents) = @_;
3082 if ($diffinfo->{'nparents'}) {
3083 # combined diff
3084 $from->{'file'} = [];
3085 $from->{'href'} = [];
3086 fill_from_file_info($diffinfo, @parents)
3087 unless exists $diffinfo->{'from_file'};
3088 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3089 $from->{'file'}[$i] =
3090 defined $diffinfo->{'from_file'}[$i] ?
3091 $diffinfo->{'from_file'}[$i] :
3092 $diffinfo->{'to_file'};
3093 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3094 $from->{'href'}[$i] = href(action=>"blob",
3095 hash_base=>$parents[$i],
3096 hash=>$diffinfo->{'from_id'}[$i],
3097 file_name=>$from->{'file'}[$i]);
3098 } else {
3099 $from->{'href'}[$i] = undef;
3102 } else {
3103 # ordinary (not combined) diff
3104 $from->{'file'} = $diffinfo->{'from_file'};
3105 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3106 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3107 hash=>$diffinfo->{'from_id'},
3108 file_name=>$from->{'file'});
3109 } else {
3110 delete $from->{'href'};
3114 $to->{'file'} = $diffinfo->{'to_file'};
3115 if (!is_deleted($diffinfo)) { # file exists in result
3116 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3117 hash=>$diffinfo->{'to_id'},
3118 file_name=>$to->{'file'});
3119 } else {
3120 delete $to->{'href'};
3124 ## ......................................................................
3125 ## parse to array of hashes functions
3127 sub git_get_heads_list {
3128 my ($limit, @classes) = @_;
3129 @classes = ('heads') unless @classes;
3130 my @patterns = map { "refs/$_" } @classes;
3131 my @headslist;
3133 open my $fd, '-|', git_cmd(), 'for-each-ref',
3134 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3135 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3136 @patterns
3137 or return;
3138 while (my $line = <$fd>) {
3139 my %ref_item;
3141 chomp $line;
3142 my ($refinfo, $committerinfo) = split(/\0/, $line);
3143 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3144 my ($committer, $epoch, $tz) =
3145 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3146 $ref_item{'fullname'} = $name;
3147 $name =~ s!^refs/(?:head|remote)s/!!;
3149 $ref_item{'name'} = $name;
3150 $ref_item{'id'} = $hash;
3151 $ref_item{'title'} = $title || '(no commit message)';
3152 $ref_item{'epoch'} = $epoch;
3153 if ($epoch) {
3154 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3155 } else {
3156 $ref_item{'age'} = "unknown";
3159 push @headslist, \%ref_item;
3161 close $fd;
3163 return wantarray ? @headslist : \@headslist;
3166 sub git_get_tags_list {
3167 my $limit = shift;
3168 my @tagslist;
3170 open my $fd, '-|', git_cmd(), 'for-each-ref',
3171 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3172 '--format=%(objectname) %(objecttype) %(refname) '.
3173 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3174 'refs/tags'
3175 or return;
3176 while (my $line = <$fd>) {
3177 my %ref_item;
3179 chomp $line;
3180 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3181 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3182 my ($creator, $epoch, $tz) =
3183 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3184 $ref_item{'fullname'} = $name;
3185 $name =~ s!^refs/tags/!!;
3187 $ref_item{'type'} = $type;
3188 $ref_item{'id'} = $id;
3189 $ref_item{'name'} = $name;
3190 if ($type eq "tag") {
3191 $ref_item{'subject'} = $title;
3192 $ref_item{'reftype'} = $reftype;
3193 $ref_item{'refid'} = $refid;
3194 } else {
3195 $ref_item{'reftype'} = $type;
3196 $ref_item{'refid'} = $id;
3199 if ($type eq "tag" || $type eq "commit") {
3200 $ref_item{'epoch'} = $epoch;
3201 if ($epoch) {
3202 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3203 } else {
3204 $ref_item{'age'} = "unknown";
3208 push @tagslist, \%ref_item;
3210 close $fd;
3212 return wantarray ? @tagslist : \@tagslist;
3215 ## ----------------------------------------------------------------------
3216 ## filesystem-related functions
3218 sub get_file_owner {
3219 my $path = shift;
3221 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3222 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3223 if (!defined $gcos) {
3224 return undef;
3226 my $owner = $gcos;
3227 $owner =~ s/[,;].*$//;
3228 return to_utf8($owner);
3231 # assume that file exists
3232 sub insert_file {
3233 my $filename = shift;
3235 open my $fd, '<', $filename;
3236 print map { to_utf8($_) } <$fd>;
3237 close $fd;
3240 ## ......................................................................
3241 ## mimetype related functions
3243 sub mimetype_guess_file {
3244 my $filename = shift;
3245 my $mimemap = shift;
3246 -r $mimemap or return undef;
3248 my %mimemap;
3249 open(my $mh, '<', $mimemap) or return undef;
3250 while (<$mh>) {
3251 next if m/^#/; # skip comments
3252 my ($mimetype, $exts) = split(/\t+/);
3253 if (defined $exts) {
3254 my @exts = split(/\s+/, $exts);
3255 foreach my $ext (@exts) {
3256 $mimemap{$ext} = $mimetype;
3260 close($mh);
3262 $filename =~ /\.([^.]*)$/;
3263 return $mimemap{$1};
3266 sub mimetype_guess {
3267 my $filename = shift;
3268 my $mime;
3269 $filename =~ /\./ or return undef;
3271 if ($mimetypes_file) {
3272 my $file = $mimetypes_file;
3273 if ($file !~ m!^/!) { # if it is relative path
3274 # it is relative to project
3275 $file = "$projectroot/$project/$file";
3277 $mime = mimetype_guess_file($filename, $file);
3279 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3280 return $mime;
3283 sub blob_mimetype {
3284 my $fd = shift;
3285 my $filename = shift;
3287 if ($filename) {
3288 my $mime = mimetype_guess($filename);
3289 $mime and return $mime;
3292 # just in case
3293 return $default_blob_plain_mimetype unless $fd;
3295 if (-T $fd) {
3296 return 'text/plain';
3297 } elsif (! $filename) {
3298 return 'application/octet-stream';
3299 } elsif ($filename =~ m/\.png$/i) {
3300 return 'image/png';
3301 } elsif ($filename =~ m/\.gif$/i) {
3302 return 'image/gif';
3303 } elsif ($filename =~ m/\.jpe?g$/i) {
3304 return 'image/jpeg';
3305 } else {
3306 return 'application/octet-stream';
3310 sub blob_contenttype {
3311 my ($fd, $file_name, $type) = @_;
3313 $type ||= blob_mimetype($fd, $file_name);
3314 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3315 $type .= "; charset=$default_text_plain_charset";
3318 return $type;
3321 # guess file syntax for syntax highlighting; return undef if no highlighting
3322 # the name of syntax can (in the future) depend on syntax highlighter used
3323 sub guess_file_syntax {
3324 my ($highlight, $mimetype, $file_name) = @_;
3325 return undef unless ($highlight && defined $file_name);
3326 my $basename = basename($file_name, '.in');
3327 return $highlight_basename{$basename}
3328 if exists $highlight_basename{$basename};
3330 $basename =~ /\.([^.]*)$/;
3331 my $ext = $1 or return undef;
3332 return $highlight_ext{$ext}
3333 if exists $highlight_ext{$ext};
3335 return undef;
3338 # run highlighter and return FD of its output,
3339 # or return original FD if no highlighting
3340 sub run_highlighter {
3341 my ($fd, $highlight, $syntax) = @_;
3342 return $fd unless ($highlight && defined $syntax);
3344 close $fd;
3345 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3346 quote_command($highlight_bin).
3347 " --xhtml --fragment --syntax $syntax |"
3348 or die_error(500, "Couldn't open file or run syntax highlighter");
3349 return $fd;
3352 ## ======================================================================
3353 ## functions printing HTML: header, footer, error page
3355 sub get_page_title {
3356 my $title = to_utf8($site_name);
3358 return $title unless (defined $project);
3359 $title .= " - " . to_utf8($project);
3361 return $title unless (defined $action);
3362 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3364 return $title unless (defined $file_name);
3365 $title .= " - " . esc_path($file_name);
3366 if ($action eq "tree" && $file_name !~ m|/$|) {
3367 $title .= "/";
3370 return $title;
3373 sub print_feed_meta {
3374 if (defined $project) {
3375 my %href_params = get_feed_info();
3376 if (!exists $href_params{'-title'}) {
3377 $href_params{'-title'} = 'log';
3380 foreach my $format qw(RSS Atom) {
3381 my $type = lc($format);
3382 my %link_attr = (
3383 '-rel' => 'alternate',
3384 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
3385 '-type' => "application/$type+xml"
3388 $href_params{'action'} = $type;
3389 $link_attr{'-href'} = href(%href_params);
3390 print "<link ".
3391 "rel=\"$link_attr{'-rel'}\" ".
3392 "title=\"$link_attr{'-title'}\" ".
3393 "href=\"$link_attr{'-href'}\" ".
3394 "type=\"$link_attr{'-type'}\" ".
3395 "/>\n";
3397 $href_params{'extra_options'} = '--no-merges';
3398 $link_attr{'-href'} = href(%href_params);
3399 $link_attr{'-title'} .= ' (no merges)';
3400 print "<link ".
3401 "rel=\"$link_attr{'-rel'}\" ".
3402 "title=\"$link_attr{'-title'}\" ".
3403 "href=\"$link_attr{'-href'}\" ".
3404 "type=\"$link_attr{'-type'}\" ".
3405 "/>\n";
3408 } else {
3409 printf('<link rel="alternate" title="%s projects list" '.
3410 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3411 esc_attr($site_name), href(project=>undef, action=>"project_index"));
3412 printf('<link rel="alternate" title="%s projects feeds" '.
3413 'href="%s" type="text/x-opml" />'."\n",
3414 esc_attr($site_name), href(project=>undef, action=>"opml"));
3418 sub git_header_html {
3419 my $status = shift || "200 OK";
3420 my $expires = shift;
3421 my %opts = @_;
3423 my $title = get_page_title();
3424 my $content_type;
3425 # require explicit support from the UA if we are to send the page as
3426 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3427 # we have to do this because MSIE sometimes globs '*/*', pretending to
3428 # support xhtml+xml but choking when it gets what it asked for.
3429 if (defined $cgi->http('HTTP_ACCEPT') &&
3430 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3431 $cgi->Accept('application/xhtml+xml') != 0) {
3432 $content_type = 'application/xhtml+xml';
3433 } else {
3434 $content_type = 'text/html';
3436 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3437 -status=> $status, -expires => $expires)
3438 unless ($opts{'-no_http_header'});
3439 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3440 print <<EOF;
3441 <?xml version="1.0" encoding="utf-8"?>
3442 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3443 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3444 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3445 <!-- git core binaries version $git_version -->
3446 <head>
3447 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3448 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3449 <meta name="robots" content="index, nofollow"/>
3450 <title>$title</title>
3452 # the stylesheet, favicon etc urls won't work correctly with path_info
3453 # unless we set the appropriate base URL
3454 if ($ENV{'PATH_INFO'}) {
3455 print "<base href=\"".esc_url($base_url)."\" />\n";
3457 # print out each stylesheet that exist, providing backwards capability
3458 # for those people who defined $stylesheet in a config file
3459 if (defined $stylesheet) {
3460 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3461 } else {
3462 foreach my $stylesheet (@stylesheets) {
3463 next unless $stylesheet;
3464 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3467 print_feed_meta()
3468 if ($status eq '200 OK');
3469 if (defined $favicon) {
3470 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
3473 print "</head>\n" .
3474 "<body>\n";
3476 if (defined $site_header && -f $site_header) {
3477 insert_file($site_header);
3480 print "<div class=\"page_header\">\n";
3481 if (defined $logo) {
3482 print $cgi->a({-href => esc_url($logo_url),
3483 -title => $logo_label},
3484 $cgi->img({-src => esc_url($logo),
3485 -width => 72, -height => 27,
3486 -alt => "git",
3487 -class => "logo"}));
3489 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3490 if (defined $project) {
3491 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3492 if (defined $action) {
3493 my $action_print = $action ;
3494 if (defined $opts{-action_extra}) {
3495 $action_print = $cgi->a({-href => href(action=>$action)},
3496 $action);
3498 print " / $action_print";
3500 if (defined $opts{-action_extra}) {
3501 print " / $opts{-action_extra}";
3503 print "\n";
3505 print "</div>\n";
3507 my $have_search = gitweb_check_feature('search');
3508 if (defined $project && $have_search) {
3509 if (!defined $searchtext) {
3510 $searchtext = "";
3512 my $search_hash;
3513 if (defined $hash_base) {
3514 $search_hash = $hash_base;
3515 } elsif (defined $hash) {
3516 $search_hash = $hash;
3517 } else {
3518 $search_hash = "HEAD";
3520 my $action = $my_uri;
3521 my $use_pathinfo = gitweb_check_feature('pathinfo');
3522 if ($use_pathinfo) {
3523 $action .= "/".esc_url($project);
3525 print $cgi->startform(-method => "get", -action => $action) .
3526 "<div class=\"search\">\n" .
3527 (!$use_pathinfo &&
3528 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3529 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3530 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3531 $cgi->popup_menu(-name => 'st', -default => 'commit',
3532 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3533 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3534 " search:\n",
3535 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3536 "<span title=\"Extended regular expression\">" .
3537 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3538 -checked => $search_use_regexp) .
3539 "</span>" .
3540 "</div>" .
3541 $cgi->end_form() . "\n";
3545 sub git_footer_html {
3546 my $feed_class = 'rss_logo';
3548 print "<div class=\"page_footer\">\n";
3549 if (defined $project) {
3550 my $descr = git_get_project_description($project);
3551 if (defined $descr) {
3552 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3555 my %href_params = get_feed_info();
3556 if (!%href_params) {
3557 $feed_class .= ' generic';
3559 $href_params{'-title'} ||= 'log';
3561 foreach my $format qw(RSS Atom) {
3562 $href_params{'action'} = lc($format);
3563 print $cgi->a({-href => href(%href_params),
3564 -title => "$href_params{'-title'} $format feed",
3565 -class => $feed_class}, $format)."\n";
3568 } else {
3569 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3570 -class => $feed_class}, "OPML") . " ";
3571 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3572 -class => $feed_class}, "TXT") . "\n";
3574 print "</div>\n"; # class="page_footer"
3576 if (defined $t0 && gitweb_check_feature('timed')) {
3577 print "<div id=\"generating_info\">\n";
3578 print 'This page took '.
3579 '<span id="generating_time" class="time_span">'.
3580 tv_interval($t0, [ gettimeofday() ]).
3581 ' seconds </span>'.
3582 ' and '.
3583 '<span id="generating_cmd">'.
3584 $number_of_git_cmds.
3585 '</span> git commands '.
3586 " to generate.\n";
3587 print "</div>\n"; # class="page_footer"
3590 if (defined $site_footer && -f $site_footer) {
3591 insert_file($site_footer);
3594 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
3595 if (defined $action &&
3596 $action eq 'blame_incremental') {
3597 print qq!<script type="text/javascript">\n!.
3598 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3599 qq! "!. href() .qq!");\n!.
3600 qq!</script>\n!;
3601 } elsif (gitweb_check_feature('javascript-actions')) {
3602 print qq!<script type="text/javascript">\n!.
3603 qq!window.onload = fixLinks;\n!.
3604 qq!</script>\n!;
3607 print "</body>\n" .
3608 "</html>";
3611 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3612 # Example: die_error(404, 'Hash not found')
3613 # By convention, use the following status codes (as defined in RFC 2616):
3614 # 400: Invalid or missing CGI parameters, or
3615 # requested object exists but has wrong type.
3616 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3617 # this server or project.
3618 # 404: Requested object/revision/project doesn't exist.
3619 # 500: The server isn't configured properly, or
3620 # an internal error occurred (e.g. failed assertions caused by bugs), or
3621 # an unknown error occurred (e.g. the git binary died unexpectedly).
3622 # 503: The server is currently unavailable (because it is overloaded,
3623 # or down for maintenance). Generally, this is a temporary state.
3624 sub die_error {
3625 my $status = shift || 500;
3626 my $error = esc_html(shift) || "Internal Server Error";
3627 my $extra = shift;
3628 my %opts = @_;
3630 my %http_responses = (
3631 400 => '400 Bad Request',
3632 403 => '403 Forbidden',
3633 404 => '404 Not Found',
3634 500 => '500 Internal Server Error',
3635 503 => '503 Service Unavailable',
3637 git_header_html($http_responses{$status}, undef, %opts);
3638 print <<EOF;
3639 <div class="page_body">
3640 <br /><br />
3641 $status - $error
3642 <br />
3644 if (defined $extra) {
3645 print "<hr />\n" .
3646 "$extra\n";
3648 print "</div>\n";
3650 git_footer_html();
3651 goto DONE_GITWEB
3652 unless ($opts{'-error_handler'});
3655 ## ----------------------------------------------------------------------
3656 ## functions printing or outputting HTML: navigation
3658 sub git_print_page_nav {
3659 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3660 $extra = '' if !defined $extra; # pager or formats
3662 my @navs = qw(summary shortlog log commit commitdiff tree);
3663 if ($suppress) {
3664 @navs = grep { $_ ne $suppress } @navs;
3667 my %arg = map { $_ => {action=>$_} } @navs;
3668 if (defined $head) {
3669 for (qw(commit commitdiff)) {
3670 $arg{$_}{'hash'} = $head;
3672 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3673 for (qw(shortlog log)) {
3674 $arg{$_}{'hash'} = $head;
3679 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3680 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3682 my @actions = gitweb_get_feature('actions');
3683 my %repl = (
3684 '%' => '%',
3685 'n' => $project, # project name
3686 'f' => $git_dir, # project path within filesystem
3687 'h' => $treehead || '', # current hash ('h' parameter)
3688 'b' => $treebase || '', # hash base ('hb' parameter)
3690 while (@actions) {
3691 my ($label, $link, $pos) = splice(@actions,0,3);
3692 # insert
3693 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3694 # munch munch
3695 $link =~ s/%([%nfhb])/$repl{$1}/g;
3696 $arg{$label}{'_href'} = $link;
3699 print "<div class=\"page_nav\">\n" .
3700 (join " | ",
3701 map { $_ eq $current ?
3702 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3703 } @navs);
3704 print "<br/>\n$extra<br/>\n" .
3705 "</div>\n";
3708 # returns a submenu for the nagivation of the refs views (tags, heads,
3709 # remotes) with the current view disabled and the remotes view only
3710 # available if the feature is enabled
3711 sub format_ref_views {
3712 my ($current) = @_;
3713 my @ref_views = qw{tags heads};
3714 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
3715 return join " | ", map {
3716 $_ eq $current ? $_ :
3717 $cgi->a({-href => href(action=>$_)}, $_)
3718 } @ref_views
3721 sub format_paging_nav {
3722 my ($action, $page, $has_next_link) = @_;
3723 my $paging_nav;
3726 if ($page > 0) {
3727 $paging_nav .=
3728 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3729 " &sdot; " .
3730 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3731 -accesskey => "p", -title => "Alt-p"}, "prev");
3732 } else {
3733 $paging_nav .= "first &sdot; prev";
3736 if ($has_next_link) {
3737 $paging_nav .= " &sdot; " .
3738 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3739 -accesskey => "n", -title => "Alt-n"}, "next");
3740 } else {
3741 $paging_nav .= " &sdot; next";
3744 return $paging_nav;
3747 ## ......................................................................
3748 ## functions printing or outputting HTML: div
3750 sub git_print_header_div {
3751 my ($action, $title, $hash, $hash_base) = @_;
3752 my %args = ();
3754 $args{'action'} = $action;
3755 $args{'hash'} = $hash if $hash;
3756 $args{'hash_base'} = $hash_base if $hash_base;
3758 print "<div class=\"header\">\n" .
3759 $cgi->a({-href => href(%args), -class => "title"},
3760 $title ? $title : $action) .
3761 "\n</div>\n";
3764 sub format_repo_url {
3765 my ($name, $url) = @_;
3766 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
3769 # Group output by placing it in a DIV element and adding a header.
3770 # Options for start_div() can be provided by passing a hash reference as the
3771 # first parameter to the function.
3772 # Options to git_print_header_div() can be provided by passing an array
3773 # reference. This must follow the options to start_div if they are present.
3774 # The content can be a scalar, which is output as-is, a scalar reference, which
3775 # is output after html escaping, an IO handle passed either as *handle or
3776 # *handle{IO}, or a function reference. In the latter case all following
3777 # parameters will be taken as argument to the content function call.
3778 sub git_print_section {
3779 my ($div_args, $header_args, $content);
3780 my $arg = shift;
3781 if (ref($arg) eq 'HASH') {
3782 $div_args = $arg;
3783 $arg = shift;
3785 if (ref($arg) eq 'ARRAY') {
3786 $header_args = $arg;
3787 $arg = shift;
3789 $content = $arg;
3791 print $cgi->start_div($div_args);
3792 git_print_header_div(@$header_args);
3794 if (ref($content) eq 'CODE') {
3795 $content->(@_);
3796 } elsif (ref($content) eq 'SCALAR') {
3797 print esc_html($$content);
3798 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
3799 print <$content>;
3800 } elsif (!ref($content) && defined($content)) {
3801 print $content;
3804 print $cgi->end_div;
3807 sub print_local_time {
3808 print format_local_time(@_);
3811 sub format_local_time {
3812 my $localtime = '';
3813 my %date = @_;
3814 if ($date{'hour_local'} < 6) {
3815 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3816 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3817 } else {
3818 $localtime .= sprintf(" (%02d:%02d %s)",
3819 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3822 return $localtime;
3825 # Outputs the author name and date in long form
3826 sub git_print_authorship {
3827 my $co = shift;
3828 my %opts = @_;
3829 my $tag = $opts{-tag} || 'div';
3830 my $author = $co->{'author_name'};
3832 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3833 print "<$tag class=\"author_date\">" .
3834 format_search_author($author, "author", esc_html($author)) .
3835 " [$ad{'rfc2822'}";
3836 print_local_time(%ad) if ($opts{-localtime});
3837 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3838 . "</$tag>\n";
3841 # Outputs table rows containing the full author or committer information,
3842 # in the format expected for 'commit' view (& similar).
3843 # Parameters are a commit hash reference, followed by the list of people
3844 # to output information for. If the list is empty it defaults to both
3845 # author and committer.
3846 sub git_print_authorship_rows {
3847 my $co = shift;
3848 # too bad we can't use @people = @_ || ('author', 'committer')
3849 my @people = @_;
3850 @people = ('author', 'committer') unless @people;
3851 foreach my $who (@people) {
3852 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3853 print "<tr><td>$who</td><td>" .
3854 format_search_author($co->{"${who}_name"}, $who,
3855 esc_html($co->{"${who}_name"})) . " " .
3856 format_search_author($co->{"${who}_email"}, $who,
3857 esc_html("<" . $co->{"${who}_email"} . ">")) .
3858 "</td><td rowspan=\"2\">" .
3859 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3860 "</td></tr>\n" .
3861 "<tr>" .
3862 "<td></td><td> $wd{'rfc2822'}";
3863 print_local_time(%wd);
3864 print "</td>" .
3865 "</tr>\n";
3869 sub git_print_page_path {
3870 my $name = shift;
3871 my $type = shift;
3872 my $hb = shift;
3875 print "<div class=\"page_path\">";
3876 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3877 -title => 'tree root'}, to_utf8("[$project]"));
3878 print " / ";
3879 if (defined $name) {
3880 my @dirname = split '/', $name;
3881 my $basename = pop @dirname;
3882 my $fullname = '';
3884 foreach my $dir (@dirname) {
3885 $fullname .= ($fullname ? '/' : '') . $dir;
3886 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3887 hash_base=>$hb),
3888 -title => $fullname}, esc_path($dir));
3889 print " / ";
3891 if (defined $type && $type eq 'blob') {
3892 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3893 hash_base=>$hb),
3894 -title => $name}, esc_path($basename));
3895 } elsif (defined $type && $type eq 'tree') {
3896 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3897 hash_base=>$hb),
3898 -title => $name}, esc_path($basename));
3899 print " / ";
3900 } else {
3901 print esc_path($basename);
3904 print "<br/></div>\n";
3907 sub git_print_log {
3908 my $log = shift;
3909 my %opts = @_;
3911 if ($opts{'-remove_title'}) {
3912 # remove title, i.e. first line of log
3913 shift @$log;
3915 # remove leading empty lines
3916 while (defined $log->[0] && $log->[0] eq "") {
3917 shift @$log;
3920 # print log
3921 my $signoff = 0;
3922 my $empty = 0;
3923 foreach my $line (@$log) {
3924 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3925 $signoff = 1;
3926 $empty = 0;
3927 if (! $opts{'-remove_signoff'}) {
3928 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3929 next;
3930 } else {
3931 # remove signoff lines
3932 next;
3934 } else {
3935 $signoff = 0;
3938 # print only one empty line
3939 # do not print empty line after signoff
3940 if ($line eq "") {
3941 next if ($empty || $signoff);
3942 $empty = 1;
3943 } else {
3944 $empty = 0;
3947 print format_log_line_html($line) . "<br/>\n";
3950 if ($opts{'-final_empty_line'}) {
3951 # end with single empty line
3952 print "<br/>\n" unless $empty;
3956 # return link target (what link points to)
3957 sub git_get_link_target {
3958 my $hash = shift;
3959 my $link_target;
3961 # read link
3962 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3963 or return;
3965 local $/ = undef;
3966 $link_target = <$fd>;
3968 close $fd
3969 or return;
3971 return $link_target;
3974 # given link target, and the directory (basedir) the link is in,
3975 # return target of link relative to top directory (top tree);
3976 # return undef if it is not possible (including absolute links).
3977 sub normalize_link_target {
3978 my ($link_target, $basedir) = @_;
3980 # absolute symlinks (beginning with '/') cannot be normalized
3981 return if (substr($link_target, 0, 1) eq '/');
3983 # normalize link target to path from top (root) tree (dir)
3984 my $path;
3985 if ($basedir) {
3986 $path = $basedir . '/' . $link_target;
3987 } else {
3988 # we are in top (root) tree (dir)
3989 $path = $link_target;
3992 # remove //, /./, and /../
3993 my @path_parts;
3994 foreach my $part (split('/', $path)) {
3995 # discard '.' and ''
3996 next if (!$part || $part eq '.');
3997 # handle '..'
3998 if ($part eq '..') {
3999 if (@path_parts) {
4000 pop @path_parts;
4001 } else {
4002 # link leads outside repository (outside top dir)
4003 return;
4005 } else {
4006 push @path_parts, $part;
4009 $path = join('/', @path_parts);
4011 return $path;
4014 # print tree entry (row of git_tree), but without encompassing <tr> element
4015 sub git_print_tree_entry {
4016 my ($t, $basedir, $hash_base, $have_blame) = @_;
4018 my %base_key = ();
4019 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4021 # The format of a table row is: mode list link. Where mode is
4022 # the mode of the entry, list is the name of the entry, an href,
4023 # and link is the action links of the entry.
4025 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4026 if (exists $t->{'size'}) {
4027 print "<td class=\"size\">$t->{'size'}</td>\n";
4029 if ($t->{'type'} eq "blob") {
4030 print "<td class=\"list\">" .
4031 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4032 file_name=>"$basedir$t->{'name'}", %base_key),
4033 -class => "list"}, esc_path($t->{'name'}));
4034 if (S_ISLNK(oct $t->{'mode'})) {
4035 my $link_target = git_get_link_target($t->{'hash'});
4036 if ($link_target) {
4037 my $norm_target = normalize_link_target($link_target, $basedir);
4038 if (defined $norm_target) {
4039 print " -> " .
4040 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4041 file_name=>$norm_target),
4042 -title => $norm_target}, esc_path($link_target));
4043 } else {
4044 print " -> " . esc_path($link_target);
4048 print "</td>\n";
4049 print "<td class=\"link\">";
4050 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4051 file_name=>"$basedir$t->{'name'}", %base_key)},
4052 "blob");
4053 if ($have_blame) {
4054 print " | " .
4055 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4056 file_name=>"$basedir$t->{'name'}", %base_key)},
4057 "blame");
4059 if (defined $hash_base) {
4060 print " | " .
4061 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4062 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4063 "history");
4065 print " | " .
4066 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4067 file_name=>"$basedir$t->{'name'}")},
4068 "raw");
4069 print "</td>\n";
4071 } elsif ($t->{'type'} eq "tree") {
4072 print "<td class=\"list\">";
4073 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4074 file_name=>"$basedir$t->{'name'}",
4075 %base_key)},
4076 esc_path($t->{'name'}));
4077 print "</td>\n";
4078 print "<td class=\"link\">";
4079 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4080 file_name=>"$basedir$t->{'name'}",
4081 %base_key)},
4082 "tree");
4083 if (defined $hash_base) {
4084 print " | " .
4085 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4086 file_name=>"$basedir$t->{'name'}")},
4087 "history");
4089 print "</td>\n";
4090 } else {
4091 # unknown object: we can only present history for it
4092 # (this includes 'commit' object, i.e. submodule support)
4093 print "<td class=\"list\">" .
4094 esc_path($t->{'name'}) .
4095 "</td>\n";
4096 print "<td class=\"link\">";
4097 if (defined $hash_base) {
4098 print $cgi->a({-href => href(action=>"history",
4099 hash_base=>$hash_base,
4100 file_name=>"$basedir$t->{'name'}")},
4101 "history");
4103 print "</td>\n";
4107 ## ......................................................................
4108 ## functions printing large fragments of HTML
4110 # get pre-image filenames for merge (combined) diff
4111 sub fill_from_file_info {
4112 my ($diff, @parents) = @_;
4114 $diff->{'from_file'} = [ ];
4115 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4116 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4117 if ($diff->{'status'}[$i] eq 'R' ||
4118 $diff->{'status'}[$i] eq 'C') {
4119 $diff->{'from_file'}[$i] =
4120 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4124 return $diff;
4127 # is current raw difftree line of file deletion
4128 sub is_deleted {
4129 my $diffinfo = shift;
4131 return $diffinfo->{'to_id'} eq ('0' x 40);
4134 # does patch correspond to [previous] difftree raw line
4135 # $diffinfo - hashref of parsed raw diff format
4136 # $patchinfo - hashref of parsed patch diff format
4137 # (the same keys as in $diffinfo)
4138 sub is_patch_split {
4139 my ($diffinfo, $patchinfo) = @_;
4141 return defined $diffinfo && defined $patchinfo
4142 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4146 sub git_difftree_body {
4147 my ($difftree, $hash, @parents) = @_;
4148 my ($parent) = $parents[0];
4149 my $have_blame = gitweb_check_feature('blame');
4150 print "<div class=\"list_head\">\n";
4151 if ($#{$difftree} > 10) {
4152 print(($#{$difftree} + 1) . " files changed:\n");
4154 print "</div>\n";
4156 print "<table class=\"" .
4157 (@parents > 1 ? "combined " : "") .
4158 "diff_tree\">\n";
4160 # header only for combined diff in 'commitdiff' view
4161 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4162 if ($has_header) {
4163 # table header
4164 print "<thead><tr>\n" .
4165 "<th></th><th></th>\n"; # filename, patchN link
4166 for (my $i = 0; $i < @parents; $i++) {
4167 my $par = $parents[$i];
4168 print "<th>" .
4169 $cgi->a({-href => href(action=>"commitdiff",
4170 hash=>$hash, hash_parent=>$par),
4171 -title => 'commitdiff to parent number ' .
4172 ($i+1) . ': ' . substr($par,0,7)},
4173 $i+1) .
4174 "&nbsp;</th>\n";
4176 print "</tr></thead>\n<tbody>\n";
4179 my $alternate = 1;
4180 my $patchno = 0;
4181 foreach my $line (@{$difftree}) {
4182 my $diff = parsed_difftree_line($line);
4184 if ($alternate) {
4185 print "<tr class=\"dark\">\n";
4186 } else {
4187 print "<tr class=\"light\">\n";
4189 $alternate ^= 1;
4191 if (exists $diff->{'nparents'}) { # combined diff
4193 fill_from_file_info($diff, @parents)
4194 unless exists $diff->{'from_file'};
4196 if (!is_deleted($diff)) {
4197 # file exists in the result (child) commit
4198 print "<td>" .
4199 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4200 file_name=>$diff->{'to_file'},
4201 hash_base=>$hash),
4202 -class => "list"}, esc_path($diff->{'to_file'})) .
4203 "</td>\n";
4204 } else {
4205 print "<td>" .
4206 esc_path($diff->{'to_file'}) .
4207 "</td>\n";
4210 if ($action eq 'commitdiff') {
4211 # link to patch
4212 $patchno++;
4213 print "<td class=\"link\">" .
4214 $cgi->a({-href => "#patch$patchno"}, "patch") .
4215 " | " .
4216 "</td>\n";
4219 my $has_history = 0;
4220 my $not_deleted = 0;
4221 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4222 my $hash_parent = $parents[$i];
4223 my $from_hash = $diff->{'from_id'}[$i];
4224 my $from_path = $diff->{'from_file'}[$i];
4225 my $status = $diff->{'status'}[$i];
4227 $has_history ||= ($status ne 'A');
4228 $not_deleted ||= ($status ne 'D');
4230 if ($status eq 'A') {
4231 print "<td class=\"link\" align=\"right\"> | </td>\n";
4232 } elsif ($status eq 'D') {
4233 print "<td class=\"link\">" .
4234 $cgi->a({-href => href(action=>"blob",
4235 hash_base=>$hash,
4236 hash=>$from_hash,
4237 file_name=>$from_path)},
4238 "blob" . ($i+1)) .
4239 " | </td>\n";
4240 } else {
4241 if ($diff->{'to_id'} eq $from_hash) {
4242 print "<td class=\"link nochange\">";
4243 } else {
4244 print "<td class=\"link\">";
4246 print $cgi->a({-href => href(action=>"blobdiff",
4247 hash=>$diff->{'to_id'},
4248 hash_parent=>$from_hash,
4249 hash_base=>$hash,
4250 hash_parent_base=>$hash_parent,
4251 file_name=>$diff->{'to_file'},
4252 file_parent=>$from_path)},
4253 "diff" . ($i+1)) .
4254 " | </td>\n";
4258 print "<td class=\"link\">";
4259 if ($not_deleted) {
4260 print $cgi->a({-href => href(action=>"blob",
4261 hash=>$diff->{'to_id'},
4262 file_name=>$diff->{'to_file'},
4263 hash_base=>$hash)},
4264 "blob");
4265 print " | " if ($has_history);
4267 if ($has_history) {
4268 print $cgi->a({-href => href(action=>"history",
4269 file_name=>$diff->{'to_file'},
4270 hash_base=>$hash)},
4271 "history");
4273 print "</td>\n";
4275 print "</tr>\n";
4276 next; # instead of 'else' clause, to avoid extra indent
4278 # else ordinary diff
4280 my ($to_mode_oct, $to_mode_str, $to_file_type);
4281 my ($from_mode_oct, $from_mode_str, $from_file_type);
4282 if ($diff->{'to_mode'} ne ('0' x 6)) {
4283 $to_mode_oct = oct $diff->{'to_mode'};
4284 if (S_ISREG($to_mode_oct)) { # only for regular file
4285 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4287 $to_file_type = file_type($diff->{'to_mode'});
4289 if ($diff->{'from_mode'} ne ('0' x 6)) {
4290 $from_mode_oct = oct $diff->{'from_mode'};
4291 if (S_ISREG($to_mode_oct)) { # only for regular file
4292 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4294 $from_file_type = file_type($diff->{'from_mode'});
4297 if ($diff->{'status'} eq "A") { # created
4298 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4299 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4300 $mode_chng .= "]</span>";
4301 print "<td>";
4302 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4303 hash_base=>$hash, file_name=>$diff->{'file'}),
4304 -class => "list"}, esc_path($diff->{'file'}));
4305 print "</td>\n";
4306 print "<td>$mode_chng</td>\n";
4307 print "<td class=\"link\">";
4308 if ($action eq 'commitdiff') {
4309 # link to patch
4310 $patchno++;
4311 print $cgi->a({-href => "#patch$patchno"}, "patch");
4312 print " | ";
4314 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4315 hash_base=>$hash, file_name=>$diff->{'file'})},
4316 "blob");
4317 print "</td>\n";
4319 } elsif ($diff->{'status'} eq "D") { # deleted
4320 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4321 print "<td>";
4322 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4323 hash_base=>$parent, file_name=>$diff->{'file'}),
4324 -class => "list"}, esc_path($diff->{'file'}));
4325 print "</td>\n";
4326 print "<td>$mode_chng</td>\n";
4327 print "<td class=\"link\">";
4328 if ($action eq 'commitdiff') {
4329 # link to patch
4330 $patchno++;
4331 print $cgi->a({-href => "#patch$patchno"}, "patch");
4332 print " | ";
4334 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4335 hash_base=>$parent, file_name=>$diff->{'file'})},
4336 "blob") . " | ";
4337 if ($have_blame) {
4338 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4339 file_name=>$diff->{'file'})},
4340 "blame") . " | ";
4342 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4343 file_name=>$diff->{'file'})},
4344 "history");
4345 print "</td>\n";
4347 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4348 my $mode_chnge = "";
4349 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4350 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4351 if ($from_file_type ne $to_file_type) {
4352 $mode_chnge .= " from $from_file_type to $to_file_type";
4354 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4355 if ($from_mode_str && $to_mode_str) {
4356 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4357 } elsif ($to_mode_str) {
4358 $mode_chnge .= " mode: $to_mode_str";
4361 $mode_chnge .= "]</span>\n";
4363 print "<td>";
4364 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4365 hash_base=>$hash, file_name=>$diff->{'file'}),
4366 -class => "list"}, esc_path($diff->{'file'}));
4367 print "</td>\n";
4368 print "<td>$mode_chnge</td>\n";
4369 print "<td class=\"link\">";
4370 if ($action eq 'commitdiff') {
4371 # link to patch
4372 $patchno++;
4373 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4374 " | ";
4375 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4376 # "commit" view and modified file (not onlu mode changed)
4377 print $cgi->a({-href => href(action=>"blobdiff",
4378 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4379 hash_base=>$hash, hash_parent_base=>$parent,
4380 file_name=>$diff->{'file'})},
4381 "diff") .
4382 " | ";
4384 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4385 hash_base=>$hash, file_name=>$diff->{'file'})},
4386 "blob") . " | ";
4387 if ($have_blame) {
4388 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4389 file_name=>$diff->{'file'})},
4390 "blame") . " | ";
4392 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4393 file_name=>$diff->{'file'})},
4394 "history");
4395 print "</td>\n";
4397 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4398 my %status_name = ('R' => 'moved', 'C' => 'copied');
4399 my $nstatus = $status_name{$diff->{'status'}};
4400 my $mode_chng = "";
4401 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4402 # mode also for directories, so we cannot use $to_mode_str
4403 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4405 print "<td>" .
4406 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4407 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4408 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4409 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4410 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4411 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4412 -class => "list"}, esc_path($diff->{'from_file'})) .
4413 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4414 "<td class=\"link\">";
4415 if ($action eq 'commitdiff') {
4416 # link to patch
4417 $patchno++;
4418 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4419 " | ";
4420 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4421 # "commit" view and modified file (not only pure rename or copy)
4422 print $cgi->a({-href => href(action=>"blobdiff",
4423 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4424 hash_base=>$hash, hash_parent_base=>$parent,
4425 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4426 "diff") .
4427 " | ";
4429 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4430 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4431 "blob") . " | ";
4432 if ($have_blame) {
4433 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4434 file_name=>$diff->{'to_file'})},
4435 "blame") . " | ";
4437 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4438 file_name=>$diff->{'to_file'})},
4439 "history");
4440 print "</td>\n";
4442 } # we should not encounter Unmerged (U) or Unknown (X) status
4443 print "</tr>\n";
4445 print "</tbody>" if $has_header;
4446 print "</table>\n";
4449 sub git_patchset_body {
4450 my ($fd, $difftree, $hash, @hash_parents) = @_;
4451 my ($hash_parent) = $hash_parents[0];
4453 my $is_combined = (@hash_parents > 1);
4454 my $patch_idx = 0;
4455 my $patch_number = 0;
4456 my $patch_line;
4457 my $diffinfo;
4458 my $to_name;
4459 my (%from, %to);
4461 print "<div class=\"patchset\">\n";
4463 # skip to first patch
4464 while ($patch_line = <$fd>) {
4465 chomp $patch_line;
4467 last if ($patch_line =~ m/^diff /);
4470 PATCH:
4471 while ($patch_line) {
4473 # parse "git diff" header line
4474 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4475 # $1 is from_name, which we do not use
4476 $to_name = unquote($2);
4477 $to_name =~ s!^b/!!;
4478 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4479 # $1 is 'cc' or 'combined', which we do not use
4480 $to_name = unquote($2);
4481 } else {
4482 $to_name = undef;
4485 # check if current patch belong to current raw line
4486 # and parse raw git-diff line if needed
4487 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4488 # this is continuation of a split patch
4489 print "<div class=\"patch cont\">\n";
4490 } else {
4491 # advance raw git-diff output if needed
4492 $patch_idx++ if defined $diffinfo;
4494 # read and prepare patch information
4495 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4497 # compact combined diff output can have some patches skipped
4498 # find which patch (using pathname of result) we are at now;
4499 if ($is_combined) {
4500 while ($to_name ne $diffinfo->{'to_file'}) {
4501 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4502 format_diff_cc_simplified($diffinfo, @hash_parents) .
4503 "</div>\n"; # class="patch"
4505 $patch_idx++;
4506 $patch_number++;
4508 last if $patch_idx > $#$difftree;
4509 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4513 # modifies %from, %to hashes
4514 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4516 # this is first patch for raw difftree line with $patch_idx index
4517 # we index @$difftree array from 0, but number patches from 1
4518 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4521 # git diff header
4522 #assert($patch_line =~ m/^diff /) if DEBUG;
4523 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4524 $patch_number++;
4525 # print "git diff" header
4526 print format_git_diff_header_line($patch_line, $diffinfo,
4527 \%from, \%to);
4529 # print extended diff header
4530 print "<div class=\"diff extended_header\">\n";
4531 EXTENDED_HEADER:
4532 while ($patch_line = <$fd>) {
4533 chomp $patch_line;
4535 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4537 print format_extended_diff_header_line($patch_line, $diffinfo,
4538 \%from, \%to);
4540 print "</div>\n"; # class="diff extended_header"
4542 # from-file/to-file diff header
4543 if (! $patch_line) {
4544 print "</div>\n"; # class="patch"
4545 last PATCH;
4547 next PATCH if ($patch_line =~ m/^diff /);
4548 #assert($patch_line =~ m/^---/) if DEBUG;
4550 my $last_patch_line = $patch_line;
4551 $patch_line = <$fd>;
4552 chomp $patch_line;
4553 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4555 print format_diff_from_to_header($last_patch_line, $patch_line,
4556 $diffinfo, \%from, \%to,
4557 @hash_parents);
4559 # the patch itself
4560 LINE:
4561 while ($patch_line = <$fd>) {
4562 chomp $patch_line;
4564 next PATCH if ($patch_line =~ m/^diff /);
4566 print format_diff_line($patch_line, \%from, \%to);
4569 } continue {
4570 print "</div>\n"; # class="patch"
4573 # for compact combined (--cc) format, with chunk and patch simplification
4574 # the patchset might be empty, but there might be unprocessed raw lines
4575 for (++$patch_idx if $patch_number > 0;
4576 $patch_idx < @$difftree;
4577 ++$patch_idx) {
4578 # read and prepare patch information
4579 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4581 # generate anchor for "patch" links in difftree / whatchanged part
4582 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4583 format_diff_cc_simplified($diffinfo, @hash_parents) .
4584 "</div>\n"; # class="patch"
4586 $patch_number++;
4589 if ($patch_number == 0) {
4590 if (@hash_parents > 1) {
4591 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4592 } else {
4593 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4597 print "</div>\n"; # class="patchset"
4600 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4602 # fills project list info (age, description, owner, forks) for each
4603 # project in the list, removing invalid projects from returned list
4604 # NOTE: modifies $projlist, but does not remove entries from it
4605 sub fill_project_list_info {
4606 my ($projlist, $check_forks) = @_;
4607 my @projects;
4609 my $show_ctags = gitweb_check_feature('ctags');
4610 PROJECT:
4611 foreach my $pr (@$projlist) {
4612 my (@activity) = git_get_last_activity($pr->{'path'});
4613 unless (@activity) {
4614 next PROJECT;
4616 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4617 if (!defined $pr->{'descr'}) {
4618 my $descr = git_get_project_description($pr->{'path'}) || "";
4619 $descr = to_utf8($descr);
4620 $pr->{'descr_long'} = $descr;
4621 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4623 if (!defined $pr->{'owner'}) {
4624 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4626 if ($check_forks) {
4627 my $pname = $pr->{'path'};
4628 if (($pname =~ s/\.git$//) &&
4629 ($pname !~ /\/$/) &&
4630 (-d "$projectroot/$pname")) {
4631 $pr->{'forks'} = "-d $projectroot/$pname";
4632 } else {
4633 $pr->{'forks'} = 0;
4636 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4637 push @projects, $pr;
4640 return @projects;
4643 # print 'sort by' <th> element, generating 'sort by $name' replay link
4644 # if that order is not selected
4645 sub print_sort_th {
4646 print format_sort_th(@_);
4649 sub format_sort_th {
4650 my ($name, $order, $header) = @_;
4651 my $sort_th = "";
4652 $header ||= ucfirst($name);
4654 if ($order eq $name) {
4655 $sort_th .= "<th>$header</th>\n";
4656 } else {
4657 $sort_th .= "<th>" .
4658 $cgi->a({-href => href(-replay=>1, order=>$name),
4659 -class => "header"}, $header) .
4660 "</th>\n";
4663 return $sort_th;
4666 sub git_project_list_body {
4667 # actually uses global variable $project
4668 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4670 my $check_forks = gitweb_check_feature('forks');
4671 my @projects = fill_project_list_info($projlist, $check_forks);
4673 $order ||= $default_projects_order;
4674 $from = 0 unless defined $from;
4675 $to = $#projects if (!defined $to || $#projects < $to);
4677 my %order_info = (
4678 project => { key => 'path', type => 'str' },
4679 descr => { key => 'descr_long', type => 'str' },
4680 owner => { key => 'owner', type => 'str' },
4681 age => { key => 'age', type => 'num' }
4683 my $oi = $order_info{$order};
4684 if ($oi->{'type'} eq 'str') {
4685 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4686 } else {
4687 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4690 my $show_ctags = gitweb_check_feature('ctags');
4691 if ($show_ctags) {
4692 my %ctags;
4693 foreach my $p (@projects) {
4694 foreach my $ct (keys %{$p->{'ctags'}}) {
4695 $ctags{$ct} += $p->{'ctags'}->{$ct};
4698 my $cloud = git_populate_project_tagcloud(\%ctags);
4699 print git_show_project_tagcloud($cloud, 64);
4702 print "<table class=\"project_list\">\n";
4703 unless ($no_header) {
4704 print "<tr>\n";
4705 if ($check_forks) {
4706 print "<th></th>\n";
4708 print_sort_th('project', $order, 'Project');
4709 print_sort_th('descr', $order, 'Description');
4710 print_sort_th('owner', $order, 'Owner');
4711 print_sort_th('age', $order, 'Last Change');
4712 print "<th></th>\n" . # for links
4713 "</tr>\n";
4715 my $alternate = 1;
4716 my $tagfilter = $cgi->param('by_tag');
4717 for (my $i = $from; $i <= $to; $i++) {
4718 my $pr = $projects[$i];
4720 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4721 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4722 and not $pr->{'descr_long'} =~ /$searchtext/;
4723 # Weed out forks or non-matching entries of search
4724 if ($check_forks) {
4725 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4726 $forkbase="^$forkbase" if $forkbase;
4727 next if not $searchtext and not $tagfilter and $show_ctags
4728 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4731 if ($alternate) {
4732 print "<tr class=\"dark\">\n";
4733 } else {
4734 print "<tr class=\"light\">\n";
4736 $alternate ^= 1;
4737 if ($check_forks) {
4738 print "<td>";
4739 if ($pr->{'forks'}) {
4740 print "<!-- $pr->{'forks'} -->\n";
4741 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4743 print "</td>\n";
4745 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4746 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4747 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4748 -class => "list", -title => $pr->{'descr_long'}},
4749 esc_html($pr->{'descr'})) . "</td>\n" .
4750 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4751 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4752 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4753 "<td class=\"link\">" .
4754 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4755 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4756 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4757 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4758 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4759 "</td>\n" .
4760 "</tr>\n";
4762 if (defined $extra) {
4763 print "<tr>\n";
4764 if ($check_forks) {
4765 print "<td></td>\n";
4767 print "<td colspan=\"5\">$extra</td>\n" .
4768 "</tr>\n";
4770 print "</table>\n";
4773 sub git_log_body {
4774 # uses global variable $project
4775 my ($commitlist, $from, $to, $refs, $extra) = @_;
4777 $from = 0 unless defined $from;
4778 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4780 for (my $i = 0; $i <= $to; $i++) {
4781 my %co = %{$commitlist->[$i]};
4782 next if !%co;
4783 my $commit = $co{'id'};
4784 my $ref = format_ref_marker($refs, $commit);
4785 my %ad = parse_date($co{'author_epoch'});
4786 git_print_header_div('commit',
4787 "<span class=\"age\">$co{'age_string'}</span>" .
4788 esc_html($co{'title'}) . $ref,
4789 $commit);
4790 print "<div class=\"title_text\">\n" .
4791 "<div class=\"log_link\">\n" .
4792 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4793 " | " .
4794 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4795 " | " .
4796 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4797 "<br/>\n" .
4798 "</div>\n";
4799 git_print_authorship(\%co, -tag => 'span');
4800 print "<br/>\n</div>\n";
4802 print "<div class=\"log_body\">\n";
4803 git_print_log($co{'comment'}, -final_empty_line=> 1);
4804 print "</div>\n";
4806 if ($extra) {
4807 print "<div class=\"page_nav\">\n";
4808 print "$extra\n";
4809 print "</div>\n";
4813 sub git_shortlog_body {
4814 # uses global variable $project
4815 my ($commitlist, $from, $to, $refs, $extra) = @_;
4817 $from = 0 unless defined $from;
4818 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4820 print "<table class=\"shortlog\">\n";
4821 my $alternate = 1;
4822 for (my $i = $from; $i <= $to; $i++) {
4823 my %co = %{$commitlist->[$i]};
4824 my $commit = $co{'id'};
4825 my $ref = format_ref_marker($refs, $commit);
4826 if ($alternate) {
4827 print "<tr class=\"dark\">\n";
4828 } else {
4829 print "<tr class=\"light\">\n";
4831 $alternate ^= 1;
4832 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4833 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4834 format_author_html('td', \%co, 10) . "<td>";
4835 print format_subject_html($co{'title'}, $co{'title_short'},
4836 href(action=>"commit", hash=>$commit), $ref);
4837 print "</td>\n" .
4838 "<td class=\"link\">" .
4839 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4840 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4841 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4842 my $snapshot_links = format_snapshot_links($commit);
4843 if (defined $snapshot_links) {
4844 print " | " . $snapshot_links;
4846 print "</td>\n" .
4847 "</tr>\n";
4849 if (defined $extra) {
4850 print "<tr>\n" .
4851 "<td colspan=\"4\">$extra</td>\n" .
4852 "</tr>\n";
4854 print "</table>\n";
4857 sub git_history_body {
4858 # Warning: assumes constant type (blob or tree) during history
4859 my ($commitlist, $from, $to, $refs, $extra,
4860 $file_name, $file_hash, $ftype) = @_;
4862 $from = 0 unless defined $from;
4863 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4865 print "<table class=\"history\">\n";
4866 my $alternate = 1;
4867 for (my $i = $from; $i <= $to; $i++) {
4868 my %co = %{$commitlist->[$i]};
4869 if (!%co) {
4870 next;
4872 my $commit = $co{'id'};
4874 my $ref = format_ref_marker($refs, $commit);
4876 if ($alternate) {
4877 print "<tr class=\"dark\">\n";
4878 } else {
4879 print "<tr class=\"light\">\n";
4881 $alternate ^= 1;
4882 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4883 # shortlog: format_author_html('td', \%co, 10)
4884 format_author_html('td', \%co, 15, 3) . "<td>";
4885 # originally git_history used chop_str($co{'title'}, 50)
4886 print format_subject_html($co{'title'}, $co{'title_short'},
4887 href(action=>"commit", hash=>$commit), $ref);
4888 print "</td>\n" .
4889 "<td class=\"link\">" .
4890 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4891 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4893 if ($ftype eq 'blob') {
4894 my $blob_current = $file_hash;
4895 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4896 if (defined $blob_current && defined $blob_parent &&
4897 $blob_current ne $blob_parent) {
4898 print " | " .
4899 $cgi->a({-href => href(action=>"blobdiff",
4900 hash=>$blob_current, hash_parent=>$blob_parent,
4901 hash_base=>$hash_base, hash_parent_base=>$commit,
4902 file_name=>$file_name)},
4903 "diff to current");
4906 print "</td>\n" .
4907 "</tr>\n";
4909 if (defined $extra) {
4910 print "<tr>\n" .
4911 "<td colspan=\"4\">$extra</td>\n" .
4912 "</tr>\n";
4914 print "</table>\n";
4917 sub git_tags_body {
4918 # uses global variable $project
4919 my ($taglist, $from, $to, $extra) = @_;
4920 $from = 0 unless defined $from;
4921 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4923 print "<table class=\"tags\">\n";
4924 my $alternate = 1;
4925 for (my $i = $from; $i <= $to; $i++) {
4926 my $entry = $taglist->[$i];
4927 my %tag = %$entry;
4928 my $comment = $tag{'subject'};
4929 my $comment_short;
4930 if (defined $comment) {
4931 $comment_short = chop_str($comment, 30, 5);
4933 if ($alternate) {
4934 print "<tr class=\"dark\">\n";
4935 } else {
4936 print "<tr class=\"light\">\n";
4938 $alternate ^= 1;
4939 if (defined $tag{'age'}) {
4940 print "<td><i>$tag{'age'}</i></td>\n";
4941 } else {
4942 print "<td></td>\n";
4944 print "<td>" .
4945 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4946 -class => "list name"}, esc_html($tag{'name'})) .
4947 "</td>\n" .
4948 "<td>";
4949 if (defined $comment) {
4950 print format_subject_html($comment, $comment_short,
4951 href(action=>"tag", hash=>$tag{'id'}));
4953 print "</td>\n" .
4954 "<td class=\"selflink\">";
4955 if ($tag{'type'} eq "tag") {
4956 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4957 } else {
4958 print "&nbsp;";
4960 print "</td>\n" .
4961 "<td class=\"link\">" . " | " .
4962 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4963 if ($tag{'reftype'} eq "commit") {
4964 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4965 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4966 } elsif ($tag{'reftype'} eq "blob") {
4967 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4969 print "</td>\n" .
4970 "</tr>";
4972 if (defined $extra) {
4973 print "<tr>\n" .
4974 "<td colspan=\"5\">$extra</td>\n" .
4975 "</tr>\n";
4977 print "</table>\n";
4980 sub git_heads_body {
4981 # uses global variable $project
4982 my ($headlist, $head, $from, $to, $extra) = @_;
4983 $from = 0 unless defined $from;
4984 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4986 print "<table class=\"heads\">\n";
4987 my $alternate = 1;
4988 for (my $i = $from; $i <= $to; $i++) {
4989 my $entry = $headlist->[$i];
4990 my %ref = %$entry;
4991 my $curr = $ref{'id'} eq $head;
4992 if ($alternate) {
4993 print "<tr class=\"dark\">\n";
4994 } else {
4995 print "<tr class=\"light\">\n";
4997 $alternate ^= 1;
4998 print "<td><i>$ref{'age'}</i></td>\n" .
4999 ($curr ? "<td class=\"current_head\">" : "<td>") .
5000 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5001 -class => "list name"},esc_html($ref{'name'})) .
5002 "</td>\n" .
5003 "<td class=\"link\">" .
5004 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5005 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5006 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
5007 "</td>\n" .
5008 "</tr>";
5010 if (defined $extra) {
5011 print "<tr>\n" .
5012 "<td colspan=\"3\">$extra</td>\n" .
5013 "</tr>\n";
5015 print "</table>\n";
5018 # Display a single remote block
5019 sub git_remote_block {
5020 my ($remote, $rdata, $limit, $head) = @_;
5022 my $heads = $rdata->{'heads'};
5023 my $fetch = $rdata->{'fetch'};
5024 my $push = $rdata->{'push'};
5026 my $urls_table = "<table class=\"projects_list\">\n" ;
5028 if (defined $fetch) {
5029 if ($fetch eq $push) {
5030 $urls_table .= format_repo_url("URL", $fetch);
5031 } else {
5032 $urls_table .= format_repo_url("Fetch URL", $fetch);
5033 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
5035 } elsif (defined $push) {
5036 $urls_table .= format_repo_url("Push URL", $push);
5037 } else {
5038 $urls_table .= format_repo_url("", "No remote URL");
5041 $urls_table .= "</table>\n";
5043 my $dots;
5044 if (defined $limit && $limit < @$heads) {
5045 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
5048 print $urls_table;
5049 git_heads_body($heads, $head, 0, $limit, $dots);
5052 # Display a list of remote names with the respective fetch and push URLs
5053 sub git_remotes_list {
5054 my ($remotedata, $limit) = @_;
5055 print "<table class=\"heads\">\n";
5056 my $alternate = 1;
5057 my @remotes = sort keys %$remotedata;
5059 my $limited = $limit && $limit < @remotes;
5061 $#remotes = $limit - 1 if $limited;
5063 while (my $remote = shift @remotes) {
5064 my $rdata = $remotedata->{$remote};
5065 my $fetch = $rdata->{'fetch'};
5066 my $push = $rdata->{'push'};
5067 if ($alternate) {
5068 print "<tr class=\"dark\">\n";
5069 } else {
5070 print "<tr class=\"light\">\n";
5072 $alternate ^= 1;
5073 print "<td>" .
5074 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
5075 -class=> "list name"},esc_html($remote)) .
5076 "</td>";
5077 print "<td class=\"link\">" .
5078 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
5079 " | " .
5080 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
5081 "</td>";
5083 print "</tr>\n";
5086 if ($limited) {
5087 print "<tr>\n" .
5088 "<td colspan=\"3\">" .
5089 $cgi->a({-href => href(action=>"remotes")}, "...") .
5090 "</td>\n" . "</tr>\n";
5093 print "</table>";
5096 # Display remote heads grouped by remote, unless there are too many
5097 # remotes, in which case we only display the remote names
5098 sub git_remotes_body {
5099 my ($remotedata, $limit, $head) = @_;
5100 if ($limit and $limit < keys %$remotedata) {
5101 git_remotes_list($remotedata, $limit);
5102 } else {
5103 fill_remote_heads($remotedata);
5104 while (my ($remote, $rdata) = each %$remotedata) {
5105 git_print_section({-class=>"remote", -id=>$remote},
5106 ["remotes", $remote, $remote], sub {
5107 git_remote_block($remote, $rdata, $limit, $head);
5113 sub git_search_grep_body {
5114 my ($commitlist, $from, $to, $extra) = @_;
5115 $from = 0 unless defined $from;
5116 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5118 print "<table class=\"commit_search\">\n";
5119 my $alternate = 1;
5120 for (my $i = $from; $i <= $to; $i++) {
5121 my %co = %{$commitlist->[$i]};
5122 if (!%co) {
5123 next;
5125 my $commit = $co{'id'};
5126 if ($alternate) {
5127 print "<tr class=\"dark\">\n";
5128 } else {
5129 print "<tr class=\"light\">\n";
5131 $alternate ^= 1;
5132 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5133 format_author_html('td', \%co, 15, 5) .
5134 "<td>" .
5135 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5136 -class => "list subject"},
5137 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5138 my $comment = $co{'comment'};
5139 foreach my $line (@$comment) {
5140 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5141 my ($lead, $match, $trail) = ($1, $2, $3);
5142 $match = chop_str($match, 70, 5, 'center');
5143 my $contextlen = int((80 - length($match))/2);
5144 $contextlen = 30 if ($contextlen > 30);
5145 $lead = chop_str($lead, $contextlen, 10, 'left');
5146 $trail = chop_str($trail, $contextlen, 10, 'right');
5148 $lead = esc_html($lead);
5149 $match = esc_html($match);
5150 $trail = esc_html($trail);
5152 print "$lead<span class=\"match\">$match</span>$trail<br />";
5155 print "</td>\n" .
5156 "<td class=\"link\">" .
5157 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5158 " | " .
5159 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5160 " | " .
5161 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5162 print "</td>\n" .
5163 "</tr>\n";
5165 if (defined $extra) {
5166 print "<tr>\n" .
5167 "<td colspan=\"3\">$extra</td>\n" .
5168 "</tr>\n";
5170 print "</table>\n";
5173 ## ======================================================================
5174 ## ======================================================================
5175 ## actions
5177 sub git_project_list {
5178 my $order = $input_params{'order'};
5179 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5180 die_error(400, "Unknown order parameter");
5183 my @list = git_get_projects_list();
5184 if (!@list) {
5185 die_error(404, "No projects found");
5188 git_header_html();
5189 if (defined $home_text && -f $home_text) {
5190 print "<div class=\"index_include\">\n";
5191 insert_file($home_text);
5192 print "</div>\n";
5194 print $cgi->startform(-method => "get") .
5195 "<p class=\"projsearch\">Search:\n" .
5196 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5197 "</p>" .
5198 $cgi->end_form() . "\n";
5199 git_project_list_body(\@list, $order);
5200 git_footer_html();
5203 sub git_forks {
5204 my $order = $input_params{'order'};
5205 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5206 die_error(400, "Unknown order parameter");
5209 my @list = git_get_projects_list($project);
5210 if (!@list) {
5211 die_error(404, "No forks found");
5214 git_header_html();
5215 git_print_page_nav('','');
5216 git_print_header_div('summary', "$project forks");
5217 git_project_list_body(\@list, $order);
5218 git_footer_html();
5221 sub git_project_index {
5222 my @projects = git_get_projects_list($project);
5224 print $cgi->header(
5225 -type => 'text/plain',
5226 -charset => 'utf-8',
5227 -content_disposition => 'inline; filename="index.aux"');
5229 foreach my $pr (@projects) {
5230 if (!exists $pr->{'owner'}) {
5231 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5234 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5235 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5236 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5237 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5238 $path =~ s/ /\+/g;
5239 $owner =~ s/ /\+/g;
5241 print "$path $owner\n";
5245 sub git_summary {
5246 my $descr = git_get_project_description($project) || "none";
5247 my %co = parse_commit("HEAD");
5248 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5249 my $head = $co{'id'};
5250 my $remote_heads = gitweb_check_feature('remote_heads');
5252 my $owner = git_get_project_owner($project);
5254 my $refs = git_get_references();
5255 # These get_*_list functions return one more to allow us to see if
5256 # there are more ...
5257 my @taglist = git_get_tags_list(16);
5258 my @headlist = git_get_heads_list(16);
5259 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
5260 my @forklist;
5261 my $check_forks = gitweb_check_feature('forks');
5263 if ($check_forks) {
5264 @forklist = git_get_projects_list($project);
5267 git_header_html();
5268 git_print_page_nav('summary','', $head);
5270 print "<div class=\"title\">&nbsp;</div>\n";
5271 print "<table class=\"projects_list\">\n" .
5272 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5273 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5274 if (defined $cd{'rfc2822'}) {
5275 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5278 # use per project git URL list in $projectroot/$project/cloneurl
5279 # or make project git URL from git base URL and project name
5280 my $url_tag = "URL";
5281 my @url_list = git_get_project_url_list($project);
5282 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5283 foreach my $git_url (@url_list) {
5284 next unless $git_url;
5285 print format_repo_url($url_tag, $git_url);
5286 $url_tag = "";
5289 # Tag cloud
5290 my $show_ctags = gitweb_check_feature('ctags');
5291 if ($show_ctags) {
5292 my $ctags = git_get_project_ctags($project);
5293 my $cloud = git_populate_project_tagcloud($ctags);
5294 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5295 print "</td>\n<td>" unless %$ctags;
5296 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5297 print "</td>\n<td>" if %$ctags;
5298 print git_show_project_tagcloud($cloud, 48);
5299 print "</td></tr>";
5302 print "</table>\n";
5304 # If XSS prevention is on, we don't include README.html.
5305 # TODO: Allow a readme in some safe format.
5306 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5307 print "<div class=\"title\">readme</div>\n" .
5308 "<div class=\"readme\">\n";
5309 insert_file("$projectroot/$project/README.html");
5310 print "\n</div>\n"; # class="readme"
5313 # we need to request one more than 16 (0..15) to check if
5314 # those 16 are all
5315 my @commitlist = $head ? parse_commits($head, 17) : ();
5316 if (@commitlist) {
5317 git_print_header_div('shortlog');
5318 git_shortlog_body(\@commitlist, 0, 15, $refs,
5319 $#commitlist <= 15 ? undef :
5320 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5323 if (@taglist) {
5324 git_print_header_div('tags');
5325 git_tags_body(\@taglist, 0, 15,
5326 $#taglist <= 15 ? undef :
5327 $cgi->a({-href => href(action=>"tags")}, "..."));
5330 if (@headlist) {
5331 git_print_header_div('heads');
5332 git_heads_body(\@headlist, $head, 0, 15,
5333 $#headlist <= 15 ? undef :
5334 $cgi->a({-href => href(action=>"heads")}, "..."));
5337 if (%remotedata) {
5338 git_print_header_div('remotes');
5339 git_remotes_body(\%remotedata, 15, $head);
5342 if (@forklist) {
5343 git_print_header_div('forks');
5344 git_project_list_body(\@forklist, 'age', 0, 15,
5345 $#forklist <= 15 ? undef :
5346 $cgi->a({-href => href(action=>"forks")}, "..."),
5347 'no_header');
5350 git_footer_html();
5353 sub git_tag {
5354 my %tag = parse_tag($hash);
5356 if (! %tag) {
5357 die_error(404, "Unknown tag object");
5360 my $head = git_get_head_hash($project);
5361 git_header_html();
5362 git_print_page_nav('','', $head,undef,$head);
5363 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5364 print "<div class=\"title_text\">\n" .
5365 "<table class=\"object_header\">\n" .
5366 "<tr>\n" .
5367 "<td>object</td>\n" .
5368 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5369 $tag{'object'}) . "</td>\n" .
5370 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5371 $tag{'type'}) . "</td>\n" .
5372 "</tr>\n";
5373 if (defined($tag{'author'})) {
5374 git_print_authorship_rows(\%tag, 'author');
5376 print "</table>\n\n" .
5377 "</div>\n";
5378 print "<div class=\"page_body\">";
5379 my $comment = $tag{'comment'};
5380 foreach my $line (@$comment) {
5381 chomp $line;
5382 print esc_html($line, -nbsp=>1) . "<br/>\n";
5384 print "</div>\n";
5385 git_footer_html();
5388 sub git_blame_common {
5389 my $format = shift || 'porcelain';
5390 if ($format eq 'porcelain' && $cgi->param('js')) {
5391 $format = 'incremental';
5392 $action = 'blame_incremental'; # for page title etc
5395 # permissions
5396 gitweb_check_feature('blame')
5397 or die_error(403, "Blame view not allowed");
5399 # error checking
5400 die_error(400, "No file name given") unless $file_name;
5401 $hash_base ||= git_get_head_hash($project);
5402 die_error(404, "Couldn't find base commit") unless $hash_base;
5403 my %co = parse_commit($hash_base)
5404 or die_error(404, "Commit not found");
5405 my $ftype = "blob";
5406 if (!defined $hash) {
5407 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5408 or die_error(404, "Error looking up file");
5409 } else {
5410 $ftype = git_get_type($hash);
5411 if ($ftype !~ "blob") {
5412 die_error(400, "Object is not a blob");
5416 my $fd;
5417 if ($format eq 'incremental') {
5418 # get file contents (as base)
5419 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5420 or die_error(500, "Open git-cat-file failed");
5421 } elsif ($format eq 'data') {
5422 # run git-blame --incremental
5423 open $fd, "-|", git_cmd(), "blame", "--incremental",
5424 $hash_base, "--", $file_name
5425 or die_error(500, "Open git-blame --incremental failed");
5426 } else {
5427 # run git-blame --porcelain
5428 open $fd, "-|", git_cmd(), "blame", '-p',
5429 $hash_base, '--', $file_name
5430 or die_error(500, "Open git-blame --porcelain failed");
5433 # incremental blame data returns early
5434 if ($format eq 'data') {
5435 print $cgi->header(
5436 -type=>"text/plain", -charset => "utf-8",
5437 -status=> "200 OK");
5438 local $| = 1; # output autoflush
5439 print while <$fd>;
5440 close $fd
5441 or print "ERROR $!\n";
5443 print 'END';
5444 if (defined $t0 && gitweb_check_feature('timed')) {
5445 print ' '.
5446 tv_interval($t0, [ gettimeofday() ]).
5447 ' '.$number_of_git_cmds;
5449 print "\n";
5451 return;
5454 # page header
5455 git_header_html();
5456 my $formats_nav =
5457 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5458 "blob") .
5459 " | ";
5460 if ($format eq 'incremental') {
5461 $formats_nav .=
5462 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5463 "blame") . " (non-incremental)";
5464 } else {
5465 $formats_nav .=
5466 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5467 "blame") . " (incremental)";
5469 $formats_nav .=
5470 " | " .
5471 $cgi->a({-href => href(action=>"history", -replay=>1)},
5472 "history") .
5473 " | " .
5474 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5475 "HEAD");
5476 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5477 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5478 git_print_page_path($file_name, $ftype, $hash_base);
5480 # page body
5481 if ($format eq 'incremental') {
5482 print "<noscript>\n<div class=\"error\"><center><b>\n".
5483 "This page requires JavaScript to run.\n Use ".
5484 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5485 'this page').
5486 " instead.\n".
5487 "</b></center></div>\n</noscript>\n";
5489 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5492 print qq!<div class="page_body">\n!;
5493 print qq!<div id="progress_info">... / ...</div>\n!
5494 if ($format eq 'incremental');
5495 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5496 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5497 qq!<thead>\n!.
5498 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5499 qq!</thead>\n!.
5500 qq!<tbody>\n!;
5502 my @rev_color = qw(light dark);
5503 my $num_colors = scalar(@rev_color);
5504 my $current_color = 0;
5506 if ($format eq 'incremental') {
5507 my $color_class = $rev_color[$current_color];
5509 #contents of a file
5510 my $linenr = 0;
5511 LINE:
5512 while (my $line = <$fd>) {
5513 chomp $line;
5514 $linenr++;
5516 print qq!<tr id="l$linenr" class="$color_class">!.
5517 qq!<td class="sha1"><a href=""> </a></td>!.
5518 qq!<td class="linenr">!.
5519 qq!<a class="linenr" href="">$linenr</a></td>!;
5520 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5521 print qq!</tr>\n!;
5524 } else { # porcelain, i.e. ordinary blame
5525 my %metainfo = (); # saves information about commits
5527 # blame data
5528 LINE:
5529 while (my $line = <$fd>) {
5530 chomp $line;
5531 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5532 # no <lines in group> for subsequent lines in group of lines
5533 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5534 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5535 if (!exists $metainfo{$full_rev}) {
5536 $metainfo{$full_rev} = { 'nprevious' => 0 };
5538 my $meta = $metainfo{$full_rev};
5539 my $data;
5540 while ($data = <$fd>) {
5541 chomp $data;
5542 last if ($data =~ s/^\t//); # contents of line
5543 if ($data =~ /^(\S+)(?: (.*))?$/) {
5544 $meta->{$1} = $2 unless exists $meta->{$1};
5546 if ($data =~ /^previous /) {
5547 $meta->{'nprevious'}++;
5550 my $short_rev = substr($full_rev, 0, 8);
5551 my $author = $meta->{'author'};
5552 my %date =
5553 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5554 my $date = $date{'iso-tz'};
5555 if ($group_size) {
5556 $current_color = ($current_color + 1) % $num_colors;
5558 my $tr_class = $rev_color[$current_color];
5559 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5560 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5561 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5562 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5563 if ($group_size) {
5564 print "<td class=\"sha1\"";
5565 print " title=\"". esc_html($author) . ", $date\"";
5566 print " rowspan=\"$group_size\"" if ($group_size > 1);
5567 print ">";
5568 print $cgi->a({-href => href(action=>"commit",
5569 hash=>$full_rev,
5570 file_name=>$file_name)},
5571 esc_html($short_rev));
5572 if ($group_size >= 2) {
5573 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5574 if (@author_initials) {
5575 print "<br />" .
5576 esc_html(join('', @author_initials));
5577 # or join('.', ...)
5580 print "</td>\n";
5582 # 'previous' <sha1 of parent commit> <filename at commit>
5583 if (exists $meta->{'previous'} &&
5584 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5585 $meta->{'parent'} = $1;
5586 $meta->{'file_parent'} = unquote($2);
5588 my $linenr_commit =
5589 exists($meta->{'parent'}) ?
5590 $meta->{'parent'} : $full_rev;
5591 my $linenr_filename =
5592 exists($meta->{'file_parent'}) ?
5593 $meta->{'file_parent'} : unquote($meta->{'filename'});
5594 my $blamed = href(action => 'blame',
5595 file_name => $linenr_filename,
5596 hash_base => $linenr_commit);
5597 print "<td class=\"linenr\">";
5598 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5599 -class => "linenr" },
5600 esc_html($lineno));
5601 print "</td>";
5602 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5603 print "</tr>\n";
5604 } # end while
5608 # footer
5609 print "</tbody>\n".
5610 "</table>\n"; # class="blame"
5611 print "</div>\n"; # class="blame_body"
5612 close $fd
5613 or print "Reading blob failed\n";
5615 git_footer_html();
5618 sub git_blame {
5619 git_blame_common();
5622 sub git_blame_incremental {
5623 git_blame_common('incremental');
5626 sub git_blame_data {
5627 git_blame_common('data');
5630 sub git_tags {
5631 my $head = git_get_head_hash($project);
5632 git_header_html();
5633 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
5634 git_print_header_div('summary', $project);
5636 my @tagslist = git_get_tags_list();
5637 if (@tagslist) {
5638 git_tags_body(\@tagslist);
5640 git_footer_html();
5643 sub git_heads {
5644 my $head = git_get_head_hash($project);
5645 git_header_html();
5646 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
5647 git_print_header_div('summary', $project);
5649 my @headslist = git_get_heads_list();
5650 if (@headslist) {
5651 git_heads_body(\@headslist, $head);
5653 git_footer_html();
5656 # used both for single remote view and for list of all the remotes
5657 sub git_remotes {
5658 gitweb_check_feature('remote_heads')
5659 or die_error(403, "Remote heads view is disabled");
5661 my $head = git_get_head_hash($project);
5662 my $remote = $input_params{'hash'};
5664 my $remotedata = git_get_remotes_list($remote);
5665 die_error(500, "Unable to get remote information") unless defined $remotedata;
5667 unless (%$remotedata) {
5668 die_error(404, defined $remote ?
5669 "Remote $remote not found" :
5670 "No remotes found");
5673 git_header_html(undef, undef, -action_extra => $remote);
5674 git_print_page_nav('', '', $head, undef, $head,
5675 format_ref_views($remote ? '' : 'remotes'));
5677 fill_remote_heads($remotedata);
5678 if (defined $remote) {
5679 git_print_header_div('remotes', "$remote remote for $project");
5680 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
5681 } else {
5682 git_print_header_div('summary', "$project remotes");
5683 git_remotes_body($remotedata, undef, $head);
5686 git_footer_html();
5689 sub git_blob_plain {
5690 my $type = shift;
5691 my $expires;
5693 if (!defined $hash) {
5694 if (defined $file_name) {
5695 my $base = $hash_base || git_get_head_hash($project);
5696 $hash = git_get_hash_by_path($base, $file_name, "blob")
5697 or die_error(404, "Cannot find file");
5698 } else {
5699 die_error(400, "No file name defined");
5701 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5702 # blobs defined by non-textual hash id's can be cached
5703 $expires = "+1d";
5706 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5707 or die_error(500, "Open git-cat-file blob '$hash' failed");
5709 # content-type (can include charset)
5710 $type = blob_contenttype($fd, $file_name, $type);
5712 # "save as" filename, even when no $file_name is given
5713 my $save_as = "$hash";
5714 if (defined $file_name) {
5715 $save_as = $file_name;
5716 } elsif ($type =~ m/^text\//) {
5717 $save_as .= '.txt';
5720 # With XSS prevention on, blobs of all types except a few known safe
5721 # ones are served with "Content-Disposition: attachment" to make sure
5722 # they don't run in our security domain. For certain image types,
5723 # blob view writes an <img> tag referring to blob_plain view, and we
5724 # want to be sure not to break that by serving the image as an
5725 # attachment (though Firefox 3 doesn't seem to care).
5726 my $sandbox = $prevent_xss &&
5727 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5729 print $cgi->header(
5730 -type => $type,
5731 -expires => $expires,
5732 -content_disposition =>
5733 ($sandbox ? 'attachment' : 'inline')
5734 . '; filename="' . $save_as . '"');
5735 local $/ = undef;
5736 binmode STDOUT, ':raw';
5737 print <$fd>;
5738 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5739 close $fd;
5742 sub git_blob {
5743 my $expires;
5745 if (!defined $hash) {
5746 if (defined $file_name) {
5747 my $base = $hash_base || git_get_head_hash($project);
5748 $hash = git_get_hash_by_path($base, $file_name, "blob")
5749 or die_error(404, "Cannot find file");
5750 } else {
5751 die_error(400, "No file name defined");
5753 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5754 # blobs defined by non-textual hash id's can be cached
5755 $expires = "+1d";
5758 my $have_blame = gitweb_check_feature('blame');
5759 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5760 or die_error(500, "Couldn't cat $file_name, $hash");
5761 my $mimetype = blob_mimetype($fd, $file_name);
5762 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5763 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5764 close $fd;
5765 return git_blob_plain($mimetype);
5767 # we can have blame only for text/* mimetype
5768 $have_blame &&= ($mimetype =~ m!^text/!);
5770 my $highlight = gitweb_check_feature('highlight');
5771 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5772 $fd = run_highlighter($fd, $highlight, $syntax)
5773 if $syntax;
5775 git_header_html(undef, $expires);
5776 my $formats_nav = '';
5777 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5778 if (defined $file_name) {
5779 if ($have_blame) {
5780 $formats_nav .=
5781 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5782 "blame") .
5783 " | ";
5785 $formats_nav .=
5786 $cgi->a({-href => href(action=>"history", -replay=>1)},
5787 "history") .
5788 " | " .
5789 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5790 "raw") .
5791 " | " .
5792 $cgi->a({-href => href(action=>"blob",
5793 hash_base=>"HEAD", file_name=>$file_name)},
5794 "HEAD");
5795 } else {
5796 $formats_nav .=
5797 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5798 "raw");
5800 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5801 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5802 } else {
5803 print "<div class=\"page_nav\">\n" .
5804 "<br/><br/></div>\n" .
5805 "<div class=\"title\">".esc_html($hash)."</div>\n";
5807 git_print_page_path($file_name, "blob", $hash_base);
5808 print "<div class=\"page_body\">\n";
5809 if ($mimetype =~ m!^image/!) {
5810 print qq!<img type="!.esc_attr($mimetype).qq!"!;
5811 if ($file_name) {
5812 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
5814 print qq! src="! .
5815 href(action=>"blob_plain", hash=>$hash,
5816 hash_base=>$hash_base, file_name=>$file_name) .
5817 qq!" />\n!;
5818 } else {
5819 my $nr;
5820 while (my $line = <$fd>) {
5821 chomp $line;
5822 $nr++;
5823 $line = untabify($line);
5824 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5825 $nr, esc_attr(href(-replay => 1)), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5828 close $fd
5829 or print "Reading blob failed.\n";
5830 print "</div>";
5831 git_footer_html();
5834 sub git_tree {
5835 if (!defined $hash_base) {
5836 $hash_base = "HEAD";
5838 if (!defined $hash) {
5839 if (defined $file_name) {
5840 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5841 } else {
5842 $hash = $hash_base;
5845 die_error(404, "No such tree") unless defined($hash);
5847 my $show_sizes = gitweb_check_feature('show-sizes');
5848 my $have_blame = gitweb_check_feature('blame');
5850 my @entries = ();
5852 local $/ = "\0";
5853 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5854 ($show_sizes ? '-l' : ()), @extra_options, $hash
5855 or die_error(500, "Open git-ls-tree failed");
5856 @entries = map { chomp; $_ } <$fd>;
5857 close $fd
5858 or die_error(404, "Reading tree failed");
5861 my $refs = git_get_references();
5862 my $ref = format_ref_marker($refs, $hash_base);
5863 git_header_html();
5864 my $basedir = '';
5865 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5866 my @views_nav = ();
5867 if (defined $file_name) {
5868 push @views_nav,
5869 $cgi->a({-href => href(action=>"history", -replay=>1)},
5870 "history"),
5871 $cgi->a({-href => href(action=>"tree",
5872 hash_base=>"HEAD", file_name=>$file_name)},
5873 "HEAD"),
5875 my $snapshot_links = format_snapshot_links($hash);
5876 if (defined $snapshot_links) {
5877 # FIXME: Should be available when we have no hash base as well.
5878 push @views_nav, $snapshot_links;
5880 git_print_page_nav('tree','', $hash_base, undef, undef,
5881 join(' | ', @views_nav));
5882 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5883 } else {
5884 undef $hash_base;
5885 print "<div class=\"page_nav\">\n";
5886 print "<br/><br/></div>\n";
5887 print "<div class=\"title\">".esc_html($hash)."</div>\n";
5889 if (defined $file_name) {
5890 $basedir = $file_name;
5891 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5892 $basedir .= '/';
5894 git_print_page_path($file_name, 'tree', $hash_base);
5896 print "<div class=\"page_body\">\n";
5897 print "<table class=\"tree\">\n";
5898 my $alternate = 1;
5899 # '..' (top directory) link if possible
5900 if (defined $hash_base &&
5901 defined $file_name && $file_name =~ m![^/]+$!) {
5902 if ($alternate) {
5903 print "<tr class=\"dark\">\n";
5904 } else {
5905 print "<tr class=\"light\">\n";
5907 $alternate ^= 1;
5909 my $up = $file_name;
5910 $up =~ s!/?[^/]+$!!;
5911 undef $up unless $up;
5912 # based on git_print_tree_entry
5913 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5914 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5915 print '<td class="list">';
5916 print $cgi->a({-href => href(action=>"tree",
5917 hash_base=>$hash_base,
5918 file_name=>$up)},
5919 "..");
5920 print "</td>\n";
5921 print "<td class=\"link\"></td>\n";
5923 print "</tr>\n";
5925 foreach my $line (@entries) {
5926 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5928 if ($alternate) {
5929 print "<tr class=\"dark\">\n";
5930 } else {
5931 print "<tr class=\"light\">\n";
5933 $alternate ^= 1;
5935 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5937 print "</tr>\n";
5939 print "</table>\n" .
5940 "</div>";
5941 git_footer_html();
5944 sub snapshot_name {
5945 my ($project, $hash) = @_;
5947 # path/to/project.git -> project
5948 # path/to/project/.git -> project
5949 my $name = to_utf8($project);
5950 $name =~ s,([^/])/*\.git$,$1,;
5951 $name = basename($name);
5952 # sanitize name
5953 $name =~ s/[[:cntrl:]]/?/g;
5955 my $ver = $hash;
5956 if ($hash =~ /^[0-9a-fA-F]+$/) {
5957 # shorten SHA-1 hash
5958 my $full_hash = git_get_full_hash($project, $hash);
5959 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5960 $ver = git_get_short_hash($project, $hash);
5962 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5963 # tags don't need shortened SHA-1 hash
5964 $ver = $1;
5965 } else {
5966 # branches and other need shortened SHA-1 hash
5967 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5968 $ver = $1;
5970 $ver .= '-' . git_get_short_hash($project, $hash);
5972 # in case of hierarchical branch names
5973 $ver =~ s!/!.!g;
5975 # name = project-version_string
5976 $name = "$name-$ver";
5978 return wantarray ? ($name, $name) : $name;
5981 sub git_snapshot {
5982 my $format = $input_params{'snapshot_format'};
5983 if (!@snapshot_fmts) {
5984 die_error(403, "Snapshots not allowed");
5986 # default to first supported snapshot format
5987 $format ||= $snapshot_fmts[0];
5988 if ($format !~ m/^[a-z0-9]+$/) {
5989 die_error(400, "Invalid snapshot format parameter");
5990 } elsif (!exists($known_snapshot_formats{$format})) {
5991 die_error(400, "Unknown snapshot format");
5992 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5993 die_error(403, "Snapshot format not allowed");
5994 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5995 die_error(403, "Unsupported snapshot format");
5998 my $type = git_get_type("$hash^{}");
5999 if (!$type) {
6000 die_error(404, 'Object does not exist');
6001 } elsif ($type eq 'blob') {
6002 die_error(400, 'Object is not a tree-ish');
6005 my ($name, $prefix) = snapshot_name($project, $hash);
6006 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6007 my $cmd = quote_command(
6008 git_cmd(), 'archive',
6009 "--format=$known_snapshot_formats{$format}{'format'}",
6010 "--prefix=$prefix/", $hash);
6011 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6012 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6015 $filename =~ s/(["\\])/\\$1/g;
6016 print $cgi->header(
6017 -type => $known_snapshot_formats{$format}{'type'},
6018 -content_disposition => 'inline; filename="' . $filename . '"',
6019 -status => '200 OK');
6021 open my $fd, "-|", $cmd
6022 or die_error(500, "Execute git-archive failed");
6023 binmode STDOUT, ':raw';
6024 print <$fd>;
6025 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6026 close $fd;
6029 sub git_log_generic {
6030 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6032 my $head = git_get_head_hash($project);
6033 if (!defined $base) {
6034 $base = $head;
6036 if (!defined $page) {
6037 $page = 0;
6039 my $refs = git_get_references();
6041 my $commit_hash = $base;
6042 if (defined $parent) {
6043 $commit_hash = "$parent..$base";
6045 my @commitlist =
6046 parse_commits($commit_hash, 101, (100 * $page),
6047 defined $file_name ? ($file_name, "--full-history") : ());
6049 my $ftype;
6050 if (!defined $file_hash && defined $file_name) {
6051 # some commits could have deleted file in question,
6052 # and not have it in tree, but one of them has to have it
6053 for (my $i = 0; $i < @commitlist; $i++) {
6054 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6055 last if defined $file_hash;
6058 if (defined $file_hash) {
6059 $ftype = git_get_type($file_hash);
6061 if (defined $file_name && !defined $ftype) {
6062 die_error(500, "Unknown type of object");
6064 my %co;
6065 if (defined $file_name) {
6066 %co = parse_commit($base)
6067 or die_error(404, "Unknown commit object");
6071 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6072 my $next_link = '';
6073 if ($#commitlist >= 100) {
6074 $next_link =
6075 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6076 -accesskey => "n", -title => "Alt-n"}, "next");
6078 my $patch_max = gitweb_get_feature('patches');
6079 if ($patch_max && !defined $file_name) {
6080 if ($patch_max < 0 || @commitlist <= $patch_max) {
6081 $paging_nav .= " &sdot; " .
6082 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6083 "patches");
6087 git_header_html();
6088 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6089 if (defined $file_name) {
6090 git_print_header_div('commit', esc_html($co{'title'}), $base);
6091 } else {
6092 git_print_header_div('summary', $project)
6094 git_print_page_path($file_name, $ftype, $hash_base)
6095 if (defined $file_name);
6097 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6098 $file_name, $file_hash, $ftype);
6100 git_footer_html();
6103 sub git_log {
6104 git_log_generic('log', \&git_log_body,
6105 $hash, $hash_parent);
6108 sub git_commit {
6109 $hash ||= $hash_base || "HEAD";
6110 my %co = parse_commit($hash)
6111 or die_error(404, "Unknown commit object");
6113 my $parent = $co{'parent'};
6114 my $parents = $co{'parents'}; # listref
6116 # we need to prepare $formats_nav before any parameter munging
6117 my $formats_nav;
6118 if (!defined $parent) {
6119 # --root commitdiff
6120 $formats_nav .= '(initial)';
6121 } elsif (@$parents == 1) {
6122 # single parent commit
6123 $formats_nav .=
6124 '(parent: ' .
6125 $cgi->a({-href => href(action=>"commit",
6126 hash=>$parent)},
6127 esc_html(substr($parent, 0, 7))) .
6128 ')';
6129 } else {
6130 # merge commit
6131 $formats_nav .=
6132 '(merge: ' .
6133 join(' ', map {
6134 $cgi->a({-href => href(action=>"commit",
6135 hash=>$_)},
6136 esc_html(substr($_, 0, 7)));
6137 } @$parents ) .
6138 ')';
6140 if (gitweb_check_feature('patches') && @$parents <= 1) {
6141 $formats_nav .= " | " .
6142 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6143 "patch");
6146 if (!defined $parent) {
6147 $parent = "--root";
6149 my @difftree;
6150 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6151 @diff_opts,
6152 (@$parents <= 1 ? $parent : '-c'),
6153 $hash, "--"
6154 or die_error(500, "Open git-diff-tree failed");
6155 @difftree = map { chomp; $_ } <$fd>;
6156 close $fd or die_error(404, "Reading git-diff-tree failed");
6158 # non-textual hash id's can be cached
6159 my $expires;
6160 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6161 $expires = "+1d";
6163 my $refs = git_get_references();
6164 my $ref = format_ref_marker($refs, $co{'id'});
6166 git_header_html(undef, $expires);
6167 git_print_page_nav('commit', '',
6168 $hash, $co{'tree'}, $hash,
6169 $formats_nav);
6171 if (defined $co{'parent'}) {
6172 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6173 } else {
6174 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6176 print "<div class=\"title_text\">\n" .
6177 "<table class=\"object_header\">\n";
6178 git_print_authorship_rows(\%co);
6179 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6180 print "<tr>" .
6181 "<td>tree</td>" .
6182 "<td class=\"sha1\">" .
6183 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6184 class => "list"}, $co{'tree'}) .
6185 "</td>" .
6186 "<td class=\"link\">" .
6187 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6188 "tree");
6189 my $snapshot_links = format_snapshot_links($hash);
6190 if (defined $snapshot_links) {
6191 print " | " . $snapshot_links;
6193 print "</td>" .
6194 "</tr>\n";
6196 foreach my $par (@$parents) {
6197 print "<tr>" .
6198 "<td>parent</td>" .
6199 "<td class=\"sha1\">" .
6200 $cgi->a({-href => href(action=>"commit", hash=>$par),
6201 class => "list"}, $par) .
6202 "</td>" .
6203 "<td class=\"link\">" .
6204 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6205 " | " .
6206 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6207 "</td>" .
6208 "</tr>\n";
6210 print "</table>".
6211 "</div>\n";
6213 print "<div class=\"page_body\">\n";
6214 git_print_log($co{'comment'});
6215 print "</div>\n";
6217 git_difftree_body(\@difftree, $hash, @$parents);
6219 git_footer_html();
6222 sub git_object {
6223 # object is defined by:
6224 # - hash or hash_base alone
6225 # - hash_base and file_name
6226 my $type;
6228 # - hash or hash_base alone
6229 if ($hash || ($hash_base && !defined $file_name)) {
6230 my $object_id = $hash || $hash_base;
6232 open my $fd, "-|", quote_command(
6233 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6234 or die_error(404, "Object does not exist");
6235 $type = <$fd>;
6236 chomp $type;
6237 close $fd
6238 or die_error(404, "Object does not exist");
6240 # - hash_base and file_name
6241 } elsif ($hash_base && defined $file_name) {
6242 $file_name =~ s,/+$,,;
6244 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6245 or die_error(404, "Base object does not exist");
6247 # here errors should not hapen
6248 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6249 or die_error(500, "Open git-ls-tree failed");
6250 my $line = <$fd>;
6251 close $fd;
6253 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6254 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6255 die_error(404, "File or directory for given base does not exist");
6257 $type = $2;
6258 $hash = $3;
6259 } else {
6260 die_error(400, "Not enough information to find object");
6263 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6264 hash=>$hash, hash_base=>$hash_base,
6265 file_name=>$file_name),
6266 -status => '302 Found');
6269 sub git_blobdiff {
6270 my $format = shift || 'html';
6272 my $fd;
6273 my @difftree;
6274 my %diffinfo;
6275 my $expires;
6277 # preparing $fd and %diffinfo for git_patchset_body
6278 # new style URI
6279 if (defined $hash_base && defined $hash_parent_base) {
6280 if (defined $file_name) {
6281 # read raw output
6282 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6283 $hash_parent_base, $hash_base,
6284 "--", (defined $file_parent ? $file_parent : ()), $file_name
6285 or die_error(500, "Open git-diff-tree failed");
6286 @difftree = map { chomp; $_ } <$fd>;
6287 close $fd
6288 or die_error(404, "Reading git-diff-tree failed");
6289 @difftree
6290 or die_error(404, "Blob diff not found");
6292 } elsif (defined $hash &&
6293 $hash =~ /[0-9a-fA-F]{40}/) {
6294 # try to find filename from $hash
6296 # read filtered raw output
6297 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6298 $hash_parent_base, $hash_base, "--"
6299 or die_error(500, "Open git-diff-tree failed");
6300 @difftree =
6301 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6302 # $hash == to_id
6303 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6304 map { chomp; $_ } <$fd>;
6305 close $fd
6306 or die_error(404, "Reading git-diff-tree failed");
6307 @difftree
6308 or die_error(404, "Blob diff not found");
6310 } else {
6311 die_error(400, "Missing one of the blob diff parameters");
6314 if (@difftree > 1) {
6315 die_error(400, "Ambiguous blob diff specification");
6318 %diffinfo = parse_difftree_raw_line($difftree[0]);
6319 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6320 $file_name ||= $diffinfo{'to_file'};
6322 $hash_parent ||= $diffinfo{'from_id'};
6323 $hash ||= $diffinfo{'to_id'};
6325 # non-textual hash id's can be cached
6326 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6327 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6328 $expires = '+1d';
6331 # open patch output
6332 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6333 '-p', ($format eq 'html' ? "--full-index" : ()),
6334 $hash_parent_base, $hash_base,
6335 "--", (defined $file_parent ? $file_parent : ()), $file_name
6336 or die_error(500, "Open git-diff-tree failed");
6339 # old/legacy style URI -- not generated anymore since 1.4.3.
6340 if (!%diffinfo) {
6341 die_error('404 Not Found', "Missing one of the blob diff parameters")
6344 # header
6345 if ($format eq 'html') {
6346 my $formats_nav =
6347 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6348 "raw");
6349 git_header_html(undef, $expires);
6350 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6351 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6352 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6353 } else {
6354 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6355 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
6357 if (defined $file_name) {
6358 git_print_page_path($file_name, "blob", $hash_base);
6359 } else {
6360 print "<div class=\"page_path\"></div>\n";
6363 } elsif ($format eq 'plain') {
6364 print $cgi->header(
6365 -type => 'text/plain',
6366 -charset => 'utf-8',
6367 -expires => $expires,
6368 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6370 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6372 } else {
6373 die_error(400, "Unknown blobdiff format");
6376 # patch
6377 if ($format eq 'html') {
6378 print "<div class=\"page_body\">\n";
6380 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6381 close $fd;
6383 print "</div>\n"; # class="page_body"
6384 git_footer_html();
6386 } else {
6387 while (my $line = <$fd>) {
6388 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6389 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6391 print $line;
6393 last if $line =~ m!^\+\+\+!;
6395 local $/ = undef;
6396 print <$fd>;
6397 close $fd;
6401 sub git_blobdiff_plain {
6402 git_blobdiff('plain');
6405 sub git_commitdiff {
6406 my %params = @_;
6407 my $format = $params{-format} || 'html';
6409 my ($patch_max) = gitweb_get_feature('patches');
6410 if ($format eq 'patch') {
6411 die_error(403, "Patch view not allowed") unless $patch_max;
6414 $hash ||= $hash_base || "HEAD";
6415 my %co = parse_commit($hash)
6416 or die_error(404, "Unknown commit object");
6418 # choose format for commitdiff for merge
6419 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6420 $hash_parent = '--cc';
6422 # we need to prepare $formats_nav before almost any parameter munging
6423 my $formats_nav;
6424 if ($format eq 'html') {
6425 $formats_nav =
6426 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6427 "raw");
6428 if ($patch_max && @{$co{'parents'}} <= 1) {
6429 $formats_nav .= " | " .
6430 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6431 "patch");
6434 if (defined $hash_parent &&
6435 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6436 # commitdiff with two commits given
6437 my $hash_parent_short = $hash_parent;
6438 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6439 $hash_parent_short = substr($hash_parent, 0, 7);
6441 $formats_nav .=
6442 ' (from';
6443 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6444 if ($co{'parents'}[$i] eq $hash_parent) {
6445 $formats_nav .= ' parent ' . ($i+1);
6446 last;
6449 $formats_nav .= ': ' .
6450 $cgi->a({-href => href(action=>"commitdiff",
6451 hash=>$hash_parent)},
6452 esc_html($hash_parent_short)) .
6453 ')';
6454 } elsif (!$co{'parent'}) {
6455 # --root commitdiff
6456 $formats_nav .= ' (initial)';
6457 } elsif (scalar @{$co{'parents'}} == 1) {
6458 # single parent commit
6459 $formats_nav .=
6460 ' (parent: ' .
6461 $cgi->a({-href => href(action=>"commitdiff",
6462 hash=>$co{'parent'})},
6463 esc_html(substr($co{'parent'}, 0, 7))) .
6464 ')';
6465 } else {
6466 # merge commit
6467 if ($hash_parent eq '--cc') {
6468 $formats_nav .= ' | ' .
6469 $cgi->a({-href => href(action=>"commitdiff",
6470 hash=>$hash, hash_parent=>'-c')},
6471 'combined');
6472 } else { # $hash_parent eq '-c'
6473 $formats_nav .= ' | ' .
6474 $cgi->a({-href => href(action=>"commitdiff",
6475 hash=>$hash, hash_parent=>'--cc')},
6476 'compact');
6478 $formats_nav .=
6479 ' (merge: ' .
6480 join(' ', map {
6481 $cgi->a({-href => href(action=>"commitdiff",
6482 hash=>$_)},
6483 esc_html(substr($_, 0, 7)));
6484 } @{$co{'parents'}} ) .
6485 ')';
6489 my $hash_parent_param = $hash_parent;
6490 if (!defined $hash_parent_param) {
6491 # --cc for multiple parents, --root for parentless
6492 $hash_parent_param =
6493 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6496 # read commitdiff
6497 my $fd;
6498 my @difftree;
6499 if ($format eq 'html') {
6500 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6501 "--no-commit-id", "--patch-with-raw", "--full-index",
6502 $hash_parent_param, $hash, "--"
6503 or die_error(500, "Open git-diff-tree failed");
6505 while (my $line = <$fd>) {
6506 chomp $line;
6507 # empty line ends raw part of diff-tree output
6508 last unless $line;
6509 push @difftree, scalar parse_difftree_raw_line($line);
6512 } elsif ($format eq 'plain') {
6513 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6514 '-p', $hash_parent_param, $hash, "--"
6515 or die_error(500, "Open git-diff-tree failed");
6516 } elsif ($format eq 'patch') {
6517 # For commit ranges, we limit the output to the number of
6518 # patches specified in the 'patches' feature.
6519 # For single commits, we limit the output to a single patch,
6520 # diverging from the git-format-patch default.
6521 my @commit_spec = ();
6522 if ($hash_parent) {
6523 if ($patch_max > 0) {
6524 push @commit_spec, "-$patch_max";
6526 push @commit_spec, '-n', "$hash_parent..$hash";
6527 } else {
6528 if ($params{-single}) {
6529 push @commit_spec, '-1';
6530 } else {
6531 if ($patch_max > 0) {
6532 push @commit_spec, "-$patch_max";
6534 push @commit_spec, "-n";
6536 push @commit_spec, '--root', $hash;
6538 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6539 '--encoding=utf8', '--stdout', @commit_spec
6540 or die_error(500, "Open git-format-patch failed");
6541 } else {
6542 die_error(400, "Unknown commitdiff format");
6545 # non-textual hash id's can be cached
6546 my $expires;
6547 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6548 $expires = "+1d";
6551 # write commit message
6552 if ($format eq 'html') {
6553 my $refs = git_get_references();
6554 my $ref = format_ref_marker($refs, $co{'id'});
6556 git_header_html(undef, $expires);
6557 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6558 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6559 print "<div class=\"title_text\">\n" .
6560 "<table class=\"object_header\">\n";
6561 git_print_authorship_rows(\%co);
6562 print "</table>".
6563 "</div>\n";
6564 print "<div class=\"page_body\">\n";
6565 if (@{$co{'comment'}} > 1) {
6566 print "<div class=\"log\">\n";
6567 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6568 print "</div>\n"; # class="log"
6571 } elsif ($format eq 'plain') {
6572 my $refs = git_get_references("tags");
6573 my $tagname = git_get_rev_name_tags($hash);
6574 my $filename = basename($project) . "-$hash.patch";
6576 print $cgi->header(
6577 -type => 'text/plain',
6578 -charset => 'utf-8',
6579 -expires => $expires,
6580 -content_disposition => 'inline; filename="' . "$filename" . '"');
6581 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6582 print "From: " . to_utf8($co{'author'}) . "\n";
6583 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6584 print "Subject: " . to_utf8($co{'title'}) . "\n";
6586 print "X-Git-Tag: $tagname\n" if $tagname;
6587 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6589 foreach my $line (@{$co{'comment'}}) {
6590 print to_utf8($line) . "\n";
6592 print "---\n\n";
6593 } elsif ($format eq 'patch') {
6594 my $filename = basename($project) . "-$hash.patch";
6596 print $cgi->header(
6597 -type => 'text/plain',
6598 -charset => 'utf-8',
6599 -expires => $expires,
6600 -content_disposition => 'inline; filename="' . "$filename" . '"');
6603 # write patch
6604 if ($format eq 'html') {
6605 my $use_parents = !defined $hash_parent ||
6606 $hash_parent eq '-c' || $hash_parent eq '--cc';
6607 git_difftree_body(\@difftree, $hash,
6608 $use_parents ? @{$co{'parents'}} : $hash_parent);
6609 print "<br/>\n";
6611 git_patchset_body($fd, \@difftree, $hash,
6612 $use_parents ? @{$co{'parents'}} : $hash_parent);
6613 close $fd;
6614 print "</div>\n"; # class="page_body"
6615 git_footer_html();
6617 } elsif ($format eq 'plain') {
6618 local $/ = undef;
6619 print <$fd>;
6620 close $fd
6621 or print "Reading git-diff-tree failed\n";
6622 } elsif ($format eq 'patch') {
6623 local $/ = undef;
6624 print <$fd>;
6625 close $fd
6626 or print "Reading git-format-patch failed\n";
6630 sub git_commitdiff_plain {
6631 git_commitdiff(-format => 'plain');
6634 # format-patch-style patches
6635 sub git_patch {
6636 git_commitdiff(-format => 'patch', -single => 1);
6639 sub git_patches {
6640 git_commitdiff(-format => 'patch');
6643 sub git_history {
6644 git_log_generic('history', \&git_history_body,
6645 $hash_base, $hash_parent_base,
6646 $file_name, $hash);
6649 sub git_search {
6650 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6651 if (!defined $searchtext) {
6652 die_error(400, "Text field is empty");
6654 if (!defined $hash) {
6655 $hash = git_get_head_hash($project);
6657 my %co = parse_commit($hash);
6658 if (!%co) {
6659 die_error(404, "Unknown commit object");
6661 if (!defined $page) {
6662 $page = 0;
6665 $searchtype ||= 'commit';
6666 if ($searchtype eq 'pickaxe') {
6667 # pickaxe may take all resources of your box and run for several minutes
6668 # with every query - so decide by yourself how public you make this feature
6669 gitweb_check_feature('pickaxe')
6670 or die_error(403, "Pickaxe is disabled");
6672 if ($searchtype eq 'grep') {
6673 gitweb_check_feature('grep')
6674 or die_error(403, "Grep is disabled");
6677 git_header_html();
6679 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6680 my $greptype;
6681 if ($searchtype eq 'commit') {
6682 $greptype = "--grep=";
6683 } elsif ($searchtype eq 'author') {
6684 $greptype = "--author=";
6685 } elsif ($searchtype eq 'committer') {
6686 $greptype = "--committer=";
6688 $greptype .= $searchtext;
6689 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6690 $greptype, '--regexp-ignore-case',
6691 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6693 my $paging_nav = '';
6694 if ($page > 0) {
6695 $paging_nav .=
6696 $cgi->a({-href => href(action=>"search", hash=>$hash,
6697 searchtext=>$searchtext,
6698 searchtype=>$searchtype)},
6699 "first");
6700 $paging_nav .= " &sdot; " .
6701 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6702 -accesskey => "p", -title => "Alt-p"}, "prev");
6703 } else {
6704 $paging_nav .= "first";
6705 $paging_nav .= " &sdot; prev";
6707 my $next_link = '';
6708 if ($#commitlist >= 100) {
6709 $next_link =
6710 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6711 -accesskey => "n", -title => "Alt-n"}, "next");
6712 $paging_nav .= " &sdot; $next_link";
6713 } else {
6714 $paging_nav .= " &sdot; next";
6717 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6718 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6719 if ($page == 0 && !@commitlist) {
6720 print "<p>No match.</p>\n";
6721 } else {
6722 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6726 if ($searchtype eq 'pickaxe') {
6727 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6728 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6730 print "<table class=\"pickaxe search\">\n";
6731 my $alternate = 1;
6732 local $/ = "\n";
6733 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6734 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6735 ($search_use_regexp ? '--pickaxe-regex' : ());
6736 undef %co;
6737 my @files;
6738 while (my $line = <$fd>) {
6739 chomp $line;
6740 next unless $line;
6742 my %set = parse_difftree_raw_line($line);
6743 if (defined $set{'commit'}) {
6744 # finish previous commit
6745 if (%co) {
6746 print "</td>\n" .
6747 "<td class=\"link\">" .
6748 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6749 " | " .
6750 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6751 print "</td>\n" .
6752 "</tr>\n";
6755 if ($alternate) {
6756 print "<tr class=\"dark\">\n";
6757 } else {
6758 print "<tr class=\"light\">\n";
6760 $alternate ^= 1;
6761 %co = parse_commit($set{'commit'});
6762 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6763 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6764 "<td><i>$author</i></td>\n" .
6765 "<td>" .
6766 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6767 -class => "list subject"},
6768 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6769 } elsif (defined $set{'to_id'}) {
6770 next if ($set{'to_id'} =~ m/^0{40}$/);
6772 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6773 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6774 -class => "list"},
6775 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6776 "<br/>\n";
6779 close $fd;
6781 # finish last commit (warning: repetition!)
6782 if (%co) {
6783 print "</td>\n" .
6784 "<td class=\"link\">" .
6785 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6786 " | " .
6787 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6788 print "</td>\n" .
6789 "</tr>\n";
6792 print "</table>\n";
6795 if ($searchtype eq 'grep') {
6796 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6797 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6799 print "<table class=\"grep_search\">\n";
6800 my $alternate = 1;
6801 my $matches = 0;
6802 local $/ = "\n";
6803 open my $fd, "-|", git_cmd(), 'grep', '-n',
6804 $search_use_regexp ? ('-E', '-i') : '-F',
6805 $searchtext, $co{'tree'};
6806 my $lastfile = '';
6807 while (my $line = <$fd>) {
6808 chomp $line;
6809 my ($file, $lno, $ltext, $binary);
6810 last if ($matches++ > 1000);
6811 if ($line =~ /^Binary file (.+) matches$/) {
6812 $file = $1;
6813 $binary = 1;
6814 } else {
6815 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6817 if ($file ne $lastfile) {
6818 $lastfile and print "</td></tr>\n";
6819 if ($alternate++) {
6820 print "<tr class=\"dark\">\n";
6821 } else {
6822 print "<tr class=\"light\">\n";
6824 print "<td class=\"list\">".
6825 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6826 file_name=>"$file"),
6827 -class => "list"}, esc_path($file));
6828 print "</td><td>\n";
6829 $lastfile = $file;
6831 if ($binary) {
6832 print "<div class=\"binary\">Binary file</div>\n";
6833 } else {
6834 $ltext = untabify($ltext);
6835 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6836 $ltext = esc_html($1, -nbsp=>1);
6837 $ltext .= '<span class="match">';
6838 $ltext .= esc_html($2, -nbsp=>1);
6839 $ltext .= '</span>';
6840 $ltext .= esc_html($3, -nbsp=>1);
6841 } else {
6842 $ltext = esc_html($ltext, -nbsp=>1);
6844 print "<div class=\"pre\">" .
6845 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6846 file_name=>"$file").'#l'.$lno,
6847 -class => "linenr"}, sprintf('%4i', $lno))
6848 . ' ' . $ltext . "</div>\n";
6851 if ($lastfile) {
6852 print "</td></tr>\n";
6853 if ($matches > 1000) {
6854 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6856 } else {
6857 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6859 close $fd;
6861 print "</table>\n";
6863 git_footer_html();
6866 sub git_search_help {
6867 git_header_html();
6868 git_print_page_nav('','', $hash,$hash,$hash);
6869 print <<EOT;
6870 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6871 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6872 the pattern entered is recognized as the POSIX extended
6873 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6874 insensitive).</p>
6875 <dl>
6876 <dt><b>commit</b></dt>
6877 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6879 my $have_grep = gitweb_check_feature('grep');
6880 if ($have_grep) {
6881 print <<EOT;
6882 <dt><b>grep</b></dt>
6883 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6884 a different one) are searched for the given pattern. On large trees, this search can take
6885 a while and put some strain on the server, so please use it with some consideration. Note that
6886 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6887 case-sensitive.</dd>
6890 print <<EOT;
6891 <dt><b>author</b></dt>
6892 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6893 <dt><b>committer</b></dt>
6894 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6896 my $have_pickaxe = gitweb_check_feature('pickaxe');
6897 if ($have_pickaxe) {
6898 print <<EOT;
6899 <dt><b>pickaxe</b></dt>
6900 <dd>All commits that caused the string to appear or disappear from any file (changes that
6901 added, removed or "modified" the string) will be listed. This search can take a while and
6902 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6903 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6906 print "</dl>\n";
6907 git_footer_html();
6910 sub git_shortlog {
6911 git_log_generic('shortlog', \&git_shortlog_body,
6912 $hash, $hash_parent);
6915 ## ......................................................................
6916 ## feeds (RSS, Atom; OPML)
6918 sub git_feed {
6919 my $format = shift || 'atom';
6920 my $have_blame = gitweb_check_feature('blame');
6922 # Atom: http://www.atomenabled.org/developers/syndication/
6923 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6924 if ($format ne 'rss' && $format ne 'atom') {
6925 die_error(400, "Unknown web feed format");
6928 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6929 my $head = $hash || 'HEAD';
6930 my @commitlist = parse_commits($head, 150, 0, $file_name);
6932 my %latest_commit;
6933 my %latest_date;
6934 my $content_type = "application/$format+xml";
6935 if (defined $cgi->http('HTTP_ACCEPT') &&
6936 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6937 # browser (feed reader) prefers text/xml
6938 $content_type = 'text/xml';
6940 if (defined($commitlist[0])) {
6941 %latest_commit = %{$commitlist[0]};
6942 my $latest_epoch = $latest_commit{'committer_epoch'};
6943 %latest_date = parse_date($latest_epoch);
6944 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6945 if (defined $if_modified) {
6946 my $since;
6947 if (eval { require HTTP::Date; 1; }) {
6948 $since = HTTP::Date::str2time($if_modified);
6949 } elsif (eval { require Time::ParseDate; 1; }) {
6950 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6952 if (defined $since && $latest_epoch <= $since) {
6953 print $cgi->header(
6954 -type => $content_type,
6955 -charset => 'utf-8',
6956 -last_modified => $latest_date{'rfc2822'},
6957 -status => '304 Not Modified');
6958 return;
6961 print $cgi->header(
6962 -type => $content_type,
6963 -charset => 'utf-8',
6964 -last_modified => $latest_date{'rfc2822'});
6965 } else {
6966 print $cgi->header(
6967 -type => $content_type,
6968 -charset => 'utf-8');
6971 # Optimization: skip generating the body if client asks only
6972 # for Last-Modified date.
6973 return if ($cgi->request_method() eq 'HEAD');
6975 # header variables
6976 my $title = "$site_name - $project/$action";
6977 my $feed_type = 'log';
6978 if (defined $hash) {
6979 $title .= " - '$hash'";
6980 $feed_type = 'branch log';
6981 if (defined $file_name) {
6982 $title .= " :: $file_name";
6983 $feed_type = 'history';
6985 } elsif (defined $file_name) {
6986 $title .= " - $file_name";
6987 $feed_type = 'history';
6989 $title .= " $feed_type";
6990 my $descr = git_get_project_description($project);
6991 if (defined $descr) {
6992 $descr = esc_html($descr);
6993 } else {
6994 $descr = "$project " .
6995 ($format eq 'rss' ? 'RSS' : 'Atom') .
6996 " feed";
6998 my $owner = git_get_project_owner($project);
6999 $owner = esc_html($owner);
7001 #header
7002 my $alt_url;
7003 if (defined $file_name) {
7004 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7005 } elsif (defined $hash) {
7006 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7007 } else {
7008 $alt_url = href(-full=>1, action=>"summary");
7010 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7011 if ($format eq 'rss') {
7012 print <<XML;
7013 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7014 <channel>
7016 print "<title>$title</title>\n" .
7017 "<link>$alt_url</link>\n" .
7018 "<description>$descr</description>\n" .
7019 "<language>en</language>\n" .
7020 # project owner is responsible for 'editorial' content
7021 "<managingEditor>$owner</managingEditor>\n";
7022 if (defined $logo || defined $favicon) {
7023 # prefer the logo to the favicon, since RSS
7024 # doesn't allow both
7025 my $img = esc_url($logo || $favicon);
7026 print "<image>\n" .
7027 "<url>$img</url>\n" .
7028 "<title>$title</title>\n" .
7029 "<link>$alt_url</link>\n" .
7030 "</image>\n";
7032 if (%latest_date) {
7033 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7034 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7036 print "<generator>gitweb v.$version/$git_version</generator>\n";
7037 } elsif ($format eq 'atom') {
7038 print <<XML;
7039 <feed xmlns="http://www.w3.org/2005/Atom">
7041 print "<title>$title</title>\n" .
7042 "<subtitle>$descr</subtitle>\n" .
7043 '<link rel="alternate" type="text/html" href="' .
7044 $alt_url . '" />' . "\n" .
7045 '<link rel="self" type="' . $content_type . '" href="' .
7046 $cgi->self_url() . '" />' . "\n" .
7047 "<id>" . href(-full=>1) . "</id>\n" .
7048 # use project owner for feed author
7049 "<author><name>$owner</name></author>\n";
7050 if (defined $favicon) {
7051 print "<icon>" . esc_url($favicon) . "</icon>\n";
7053 if (defined $logo) {
7054 # not twice as wide as tall: 72 x 27 pixels
7055 print "<logo>" . esc_url($logo) . "</logo>\n";
7057 if (! %latest_date) {
7058 # dummy date to keep the feed valid until commits trickle in:
7059 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7060 } else {
7061 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7063 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7066 # contents
7067 for (my $i = 0; $i <= $#commitlist; $i++) {
7068 my %co = %{$commitlist[$i]};
7069 my $commit = $co{'id'};
7070 # we read 150, we always show 30 and the ones more recent than 48 hours
7071 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7072 last;
7074 my %cd = parse_date($co{'author_epoch'});
7076 # get list of changed files
7077 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7078 $co{'parent'} || "--root",
7079 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7080 or next;
7081 my @difftree = map { chomp; $_ } <$fd>;
7082 close $fd
7083 or next;
7085 # print element (entry, item)
7086 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7087 if ($format eq 'rss') {
7088 print "<item>\n" .
7089 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7090 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7091 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7092 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7093 "<link>$co_url</link>\n" .
7094 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7095 "<content:encoded>" .
7096 "<![CDATA[\n";
7097 } elsif ($format eq 'atom') {
7098 print "<entry>\n" .
7099 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7100 "<updated>$cd{'iso-8601'}</updated>\n" .
7101 "<author>\n" .
7102 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7103 if ($co{'author_email'}) {
7104 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7106 print "</author>\n" .
7107 # use committer for contributor
7108 "<contributor>\n" .
7109 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7110 if ($co{'committer_email'}) {
7111 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7113 print "</contributor>\n" .
7114 "<published>$cd{'iso-8601'}</published>\n" .
7115 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7116 "<id>$co_url</id>\n" .
7117 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7118 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7120 my $comment = $co{'comment'};
7121 print "<pre>\n";
7122 foreach my $line (@$comment) {
7123 $line = esc_html($line);
7124 print "$line\n";
7126 print "</pre><ul>\n";
7127 foreach my $difftree_line (@difftree) {
7128 my %difftree = parse_difftree_raw_line($difftree_line);
7129 next if !$difftree{'from_id'};
7131 my $file = $difftree{'file'} || $difftree{'to_file'};
7133 print "<li>" .
7134 "[" .
7135 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7136 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7137 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7138 file_name=>$file, file_parent=>$difftree{'from_file'}),
7139 -title => "diff"}, 'D');
7140 if ($have_blame) {
7141 print $cgi->a({-href => href(-full=>1, action=>"blame",
7142 file_name=>$file, hash_base=>$commit),
7143 -title => "blame"}, 'B');
7145 # if this is not a feed of a file history
7146 if (!defined $file_name || $file_name ne $file) {
7147 print $cgi->a({-href => href(-full=>1, action=>"history",
7148 file_name=>$file, hash=>$commit),
7149 -title => "history"}, 'H');
7151 $file = esc_path($file);
7152 print "] ".
7153 "$file</li>\n";
7155 if ($format eq 'rss') {
7156 print "</ul>]]>\n" .
7157 "</content:encoded>\n" .
7158 "</item>\n";
7159 } elsif ($format eq 'atom') {
7160 print "</ul>\n</div>\n" .
7161 "</content>\n" .
7162 "</entry>\n";
7166 # end of feed
7167 if ($format eq 'rss') {
7168 print "</channel>\n</rss>\n";
7169 } elsif ($format eq 'atom') {
7170 print "</feed>\n";
7174 sub git_rss {
7175 git_feed('rss');
7178 sub git_atom {
7179 git_feed('atom');
7182 sub git_opml {
7183 my @list = git_get_projects_list();
7185 print $cgi->header(
7186 -type => 'text/xml',
7187 -charset => 'utf-8',
7188 -content_disposition => 'inline; filename="opml.xml"');
7190 print <<XML;
7191 <?xml version="1.0" encoding="utf-8"?>
7192 <opml version="1.0">
7193 <head>
7194 <title>$site_name OPML Export</title>
7195 </head>
7196 <body>
7197 <outline text="git RSS feeds">
7200 foreach my $pr (@list) {
7201 my %proj = %$pr;
7202 my $head = git_get_head_hash($proj{'path'});
7203 if (!defined $head) {
7204 next;
7206 $git_dir = "$projectroot/$proj{'path'}";
7207 my %co = parse_commit($head);
7208 if (!%co) {
7209 next;
7212 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7213 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7214 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7215 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7217 print <<XML;
7218 </outline>
7219 </body>
7220 </opml>