gitweb: correct 'browse all projects' link
[git/gitweb.git] / gitweb / gitweb.perl
blobf0d78a6f921097a682daf7918b45c07412e500bd
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use 5.008;
11 use strict;
12 use warnings;
13 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
16 use Encode;
17 use Fcntl ':mode';
18 use File::Find qw();
19 use File::Basename qw(basename);
20 use Time::HiRes qw(gettimeofday tv_interval);
21 binmode STDOUT, ':utf8';
23 if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
24 eval 'sub CGI::multi_param { CGI::param(@_) }'
27 our $t0 = [ gettimeofday() ];
28 our $number_of_git_cmds = 0;
30 BEGIN {
31 CGI->compile() if $ENV{'MOD_PERL'};
34 our $version = "++GIT_VERSION++";
36 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
37 sub evaluate_uri {
38 our $cgi;
40 our $my_url = $cgi->url();
41 our $my_uri = $cgi->url(-absolute => 1);
43 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
44 # needed and used only for URLs with nonempty PATH_INFO
45 our $base_url = $my_url;
47 # When the script is used as DirectoryIndex, the URL does not contain the name
48 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
49 # have to do it ourselves. We make $path_info global because it's also used
50 # later on.
52 # Another issue with the script being the DirectoryIndex is that the resulting
53 # $my_url data is not the full script URL: this is good, because we want
54 # generated links to keep implying the script name if it wasn't explicitly
55 # indicated in the URL we're handling, but it means that $my_url cannot be used
56 # as base URL.
57 # Therefore, if we needed to strip PATH_INFO, then we know that we have
58 # to build the base URL ourselves:
59 our $path_info = decode_utf8($ENV{"PATH_INFO"});
60 if ($path_info) {
61 # $path_info has already been URL-decoded by the web server, but
62 # $my_url and $my_uri have not. URL-decode them so we can properly
63 # strip $path_info.
64 $my_url = unescape($my_url);
65 $my_uri = unescape($my_uri);
66 if ($my_url =~ s,\Q$path_info\E$,, &&
67 $my_uri =~ s,\Q$path_info\E$,, &&
68 defined $ENV{'SCRIPT_NAME'}) {
69 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
73 # target of the home link on top of all pages
74 our $home_link = $my_uri || "/";
77 # core git executable to use
78 # this can just be "git" if your webserver has a sensible PATH
79 our $GIT = "++GIT_BINDIR++/git";
81 # absolute fs-path which will be prepended to the project path
82 #our $projectroot = "/pub/scm";
83 our $projectroot = "++GITWEB_PROJECTROOT++";
85 # fs traversing limit for getting project list
86 # the number is relative to the projectroot
87 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
89 # string of the home link on top of all pages
90 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
92 # extra breadcrumbs preceding the home link
93 our @extra_breadcrumbs = ();
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 # html snippet to include in the <head> section of each page
101 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
102 # filename of html text to include at top of each page
103 our $site_header = "++GITWEB_SITE_HEADER++";
104 # html text to include at home page
105 our $home_text = "++GITWEB_HOMETEXT++";
106 # filename of html text to include at bottom of each page
107 our $site_footer = "++GITWEB_SITE_FOOTER++";
109 # URI of stylesheets
110 our @stylesheets = ("++GITWEB_CSS++");
111 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
112 our $stylesheet = undef;
113 # URI of GIT logo (72x27 size)
114 our $logo = "++GITWEB_LOGO++";
115 # URI of GIT favicon, assumed to be image/png type
116 our $favicon = "++GITWEB_FAVICON++";
117 # URI of gitweb.js (JavaScript code for gitweb)
118 our $javascript = "++GITWEB_JS++";
120 # URI and label (title) of GIT logo link
121 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
122 #our $logo_label = "git documentation";
123 our $logo_url = "http://git-scm.com/";
124 our $logo_label = "git homepage";
126 # source of projects list
127 our $projects_list = "++GITWEB_LIST++";
129 # the width (in characters) of the projects list "Description" column
130 our $projects_list_description_width = 25;
132 # group projects by category on the projects list
133 # (enabled if this variable evaluates to true)
134 our $projects_list_group_categories = 0;
136 # default category if none specified
137 # (leave the empty string for no category)
138 our $project_list_default_category = "";
140 # default order of projects list
141 # valid values are none, project, descr, owner, and age
142 our $default_projects_order = "project";
144 # show repository only if this file exists
145 # (only effective if this variable evaluates to true)
146 our $export_ok = "++GITWEB_EXPORT_OK++";
148 # don't generate age column on the projects list page
149 our $omit_age_column = 0;
151 # don't generate information about owners of repositories
152 our $omit_owner=0;
154 # show repository only if this subroutine returns true
155 # when given the path to the project, for example:
156 # sub { return -e "$_[0]/git-daemon-export-ok"; }
157 our $export_auth_hook = undef;
159 # only allow viewing of repositories also shown on the overview page
160 our $strict_export = "++GITWEB_STRICT_EXPORT++";
162 # list of git base URLs used for URL to where fetch project from,
163 # i.e. full URL is "$git_base_url/$project"
164 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
166 # default blob_plain mimetype and default charset for text/plain blob
167 our $default_blob_plain_mimetype = 'text/plain';
168 our $default_text_plain_charset = undef;
170 # file to use for guessing MIME types before trying /etc/mime.types
171 # (relative to the current git repository)
172 our $mimetypes_file = undef;
174 # assume this charset if line contains non-UTF-8 characters;
175 # it should be valid encoding (see Encoding::Supported(3pm) for list),
176 # for which encoding all byte sequences are valid, for example
177 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
178 # could be even 'utf-8' for the old behavior)
179 our $fallback_encoding = 'latin1';
181 # rename detection options for git-diff and git-diff-tree
182 # - default is '-M', with the cost proportional to
183 # (number of removed files) * (number of new files).
184 # - more costly is '-C' (which implies '-M'), with the cost proportional to
185 # (number of changed files + number of removed files) * (number of new files)
186 # - even more costly is '-C', '--find-copies-harder' with cost
187 # (number of files in the original tree) * (number of new files)
188 # - one might want to include '-B' option, e.g. '-B', '-M'
189 our @diff_opts = ('-M'); # taken from git_commit
191 # Disables features that would allow repository owners to inject script into
192 # the gitweb domain.
193 our $prevent_xss = 0;
195 # Path to the highlight executable to use (must be the one from
196 # http://www.andre-simon.de due to assumptions about parameters and output).
197 # Useful if highlight is not installed on your webserver's PATH.
198 # [Default: highlight]
199 our $highlight_bin = "++HIGHLIGHT_BIN++";
201 # Whether to include project list on the gitweb front page; 0 means yes,
202 # 1 means no list but show tag cloud if enabled (all projects still need
203 # to be scanned), 2 means no list and no tag cloud (very fast)
204 our $frontpage_no_project_list = 0;
206 # information about snapshot formats that gitweb is capable of serving
207 our %known_snapshot_formats = (
208 # name => {
209 # 'display' => display name,
210 # 'type' => mime type,
211 # 'suffix' => filename suffix,
212 # 'format' => --format for git-archive,
213 # 'compressor' => [compressor command and arguments]
214 # (array reference, optional)
215 # 'disabled' => boolean (optional)}
217 'tgz' => {
218 'display' => 'tar.gz',
219 'type' => 'application/x-gzip',
220 'suffix' => '.tar.gz',
221 'format' => 'tar',
222 'compressor' => ['gzip', '-n']},
224 'tbz2' => {
225 'display' => 'tar.bz2',
226 'type' => 'application/x-bzip2',
227 'suffix' => '.tar.bz2',
228 'format' => 'tar',
229 'compressor' => ['bzip2']},
231 'txz' => {
232 'display' => 'tar.xz',
233 'type' => 'application/x-xz',
234 'suffix' => '.tar.xz',
235 'format' => 'tar',
236 'compressor' => ['xz'],
237 'disabled' => 1},
239 'zip' => {
240 'display' => 'zip',
241 'type' => 'application/x-zip',
242 'suffix' => '.zip',
243 'format' => 'zip'},
246 # Aliases so we understand old gitweb.snapshot values in repository
247 # configuration.
248 our %known_snapshot_format_aliases = (
249 'gzip' => 'tgz',
250 'bzip2' => 'tbz2',
251 'xz' => 'txz',
253 # backward compatibility: legacy gitweb config support
254 'x-gzip' => undef, 'gz' => undef,
255 'x-bzip2' => undef, 'bz2' => undef,
256 'x-zip' => undef, '' => undef,
259 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
260 # are changed, it may be appropriate to change these values too via
261 # $GITWEB_CONFIG.
262 our %avatar_size = (
263 'default' => 16,
264 'double' => 32
267 # Used to set the maximum load that we will still respond to gitweb queries.
268 # If server load exceed this value then return "503 server busy" error.
269 # If gitweb cannot determined server load, it is taken to be 0.
270 # Leave it undefined (or set to 'undef') to turn off load checking.
271 our $maxload = 300;
273 # configuration for 'highlight' (http://www.andre-simon.de/)
274 # match by basename
275 our %highlight_basename = (
276 #'Program' => 'py',
277 #'Library' => 'py',
278 'SConstruct' => 'py', # SCons equivalent of Makefile
279 'Makefile' => 'make',
281 # match by extension
282 our %highlight_ext = (
283 # main extensions, defining name of syntax;
284 # see files in /usr/share/highlight/langDefs/ directory
285 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
286 # alternate extensions, see /etc/highlight/filetypes.conf
287 (map { $_ => 'c' } qw(c h)),
288 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
289 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
290 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
291 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
292 (map { $_ => 'make'} qw(make mak mk)),
293 (map { $_ => 'xml' } qw(xml xhtml html htm)),
296 # You define site-wide feature defaults here; override them with
297 # $GITWEB_CONFIG as necessary.
298 our %feature = (
299 # feature => {
300 # 'sub' => feature-sub (subroutine),
301 # 'override' => allow-override (boolean),
302 # 'default' => [ default options...] (array reference)}
304 # if feature is overridable (it means that allow-override has true value),
305 # then feature-sub will be called with default options as parameters;
306 # return value of feature-sub indicates if to enable specified feature
308 # if there is no 'sub' key (no feature-sub), then feature cannot be
309 # overridden
311 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
312 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
313 # is enabled
315 # Enable the 'blame' blob view, showing the last commit that modified
316 # each line in the file. This can be very CPU-intensive.
318 # To enable system wide have in $GITWEB_CONFIG
319 # $feature{'blame'}{'default'} = [1];
320 # To have project specific config enable override in $GITWEB_CONFIG
321 # $feature{'blame'}{'override'} = 1;
322 # and in project config gitweb.blame = 0|1;
323 'blame' => {
324 'sub' => sub { feature_bool('blame', @_) },
325 'override' => 0,
326 'default' => [0]},
328 # Enable the 'snapshot' link, providing a compressed archive of any
329 # tree. This can potentially generate high traffic if you have large
330 # project.
332 # Value is a list of formats defined in %known_snapshot_formats that
333 # you wish to offer.
334 # To disable system wide have in $GITWEB_CONFIG
335 # $feature{'snapshot'}{'default'} = [];
336 # To have project specific config enable override in $GITWEB_CONFIG
337 # $feature{'snapshot'}{'override'} = 1;
338 # and in project config, a comma-separated list of formats or "none"
339 # to disable. Example: gitweb.snapshot = tbz2,zip;
340 'snapshot' => {
341 'sub' => \&feature_snapshot,
342 'override' => 0,
343 'default' => ['tgz']},
345 # Enable text search, which will list the commits which match author,
346 # committer or commit text to a given string. Enabled by default.
347 # Project specific override is not supported.
349 # Note that this controls all search features, which means that if
350 # it is disabled, then 'grep' and 'pickaxe' search would also be
351 # disabled.
352 'search' => {
353 'override' => 0,
354 'default' => [1]},
356 # Enable grep search, which will list the files in currently selected
357 # tree containing the given string. Enabled by default. This can be
358 # potentially CPU-intensive, of course.
359 # Note that you need to have 'search' feature enabled too.
361 # To enable system wide have in $GITWEB_CONFIG
362 # $feature{'grep'}{'default'} = [1];
363 # To have project specific config enable override in $GITWEB_CONFIG
364 # $feature{'grep'}{'override'} = 1;
365 # and in project config gitweb.grep = 0|1;
366 'grep' => {
367 'sub' => sub { feature_bool('grep', @_) },
368 'override' => 0,
369 'default' => [1]},
371 # Enable the pickaxe search, which will list the commits that modified
372 # a given string in a file. This can be practical and quite faster
373 # alternative to 'blame', but still potentially CPU-intensive.
374 # Note that you need to have 'search' feature enabled too.
376 # To enable system wide have in $GITWEB_CONFIG
377 # $feature{'pickaxe'}{'default'} = [1];
378 # To have project specific config enable override in $GITWEB_CONFIG
379 # $feature{'pickaxe'}{'override'} = 1;
380 # and in project config gitweb.pickaxe = 0|1;
381 'pickaxe' => {
382 'sub' => sub { feature_bool('pickaxe', @_) },
383 'override' => 0,
384 'default' => [1]},
386 # Enable showing size of blobs in a 'tree' view, in a separate
387 # column, similar to what 'ls -l' does. This cost a bit of IO.
389 # To disable system wide have in $GITWEB_CONFIG
390 # $feature{'show-sizes'}{'default'} = [0];
391 # To have project specific config enable override in $GITWEB_CONFIG
392 # $feature{'show-sizes'}{'override'} = 1;
393 # and in project config gitweb.showsizes = 0|1;
394 'show-sizes' => {
395 'sub' => sub { feature_bool('showsizes', @_) },
396 'override' => 0,
397 'default' => [1]},
399 # Make gitweb use an alternative format of the URLs which can be
400 # more readable and natural-looking: project name is embedded
401 # directly in the path and the query string contains other
402 # auxiliary information. All gitweb installations recognize
403 # URL in either format; this configures in which formats gitweb
404 # generates links.
406 # To enable system wide have in $GITWEB_CONFIG
407 # $feature{'pathinfo'}{'default'} = [1];
408 # Project specific override is not supported.
410 # Note that you will need to change the default location of CSS,
411 # favicon, logo and possibly other files to an absolute URL. Also,
412 # if gitweb.cgi serves as your indexfile, you will need to force
413 # $my_uri to contain the script name in your $GITWEB_CONFIG.
414 'pathinfo' => {
415 'override' => 0,
416 'default' => [0]},
418 # Make gitweb consider projects in project root subdirectories
419 # to be forks of existing projects. Given project $projname.git,
420 # projects matching $projname/*.git will not be shown in the main
421 # projects list, instead a '+' mark will be added to $projname
422 # there and a 'forks' view will be enabled for the project, listing
423 # all the forks. If project list is taken from a file, forks have
424 # to be listed after the main project.
426 # To enable system wide have in $GITWEB_CONFIG
427 # $feature{'forks'}{'default'} = [1];
428 # Project specific override is not supported.
429 'forks' => {
430 'override' => 0,
431 'default' => [0]},
433 # Insert custom links to the action bar of all project pages.
434 # This enables you mainly to link to third-party scripts integrating
435 # into gitweb; e.g. git-browser for graphical history representation
436 # or custom web-based repository administration interface.
438 # The 'default' value consists of a list of triplets in the form
439 # (label, link, position) where position is the label after which
440 # to insert the link and link is a format string where %n expands
441 # to the project name, %f to the project path within the filesystem,
442 # %h to the current hash (h gitweb parameter) and %b to the current
443 # hash base (hb gitweb parameter); %% expands to %.
445 # To enable system wide have in $GITWEB_CONFIG e.g.
446 # $feature{'actions'}{'default'} = [('graphiclog',
447 # '/git-browser/by-commit.html?r=%n', 'summary')];
448 # Project specific override is not supported.
449 'actions' => {
450 'override' => 0,
451 'default' => []},
453 # Allow gitweb scan project content tags of project repository,
454 # and display the popular Web 2.0-ish "tag cloud" near the projects
455 # list. Note that this is something COMPLETELY different from the
456 # normal Git tags.
458 # gitweb by itself can show existing tags, but it does not handle
459 # tagging itself; you need to do it externally, outside gitweb.
460 # The format is described in git_get_project_ctags() subroutine.
461 # You may want to install the HTML::TagCloud Perl module to get
462 # a pretty tag cloud instead of just a list of tags.
464 # To enable system wide have in $GITWEB_CONFIG
465 # $feature{'ctags'}{'default'} = [1];
466 # Project specific override is not supported.
468 # A value of 0 means no ctags display or editing. A value of
469 # 1 enables ctags display but never editing. A non-empty value
470 # that is not a string of digits enables ctags display AND the
471 # ability to add tags using a form that uses method POST and
472 # an action value set to the configured 'ctags' value.
473 'ctags' => {
474 'override' => 0,
475 'default' => [0]},
477 # The maximum number of patches in a patchset generated in patch
478 # view. Set this to 0 or undef to disable patch view, or to a
479 # negative number to remove any limit.
481 # To disable system wide have in $GITWEB_CONFIG
482 # $feature{'patches'}{'default'} = [0];
483 # To have project specific config enable override in $GITWEB_CONFIG
484 # $feature{'patches'}{'override'} = 1;
485 # and in project config gitweb.patches = 0|n;
486 # where n is the maximum number of patches allowed in a patchset.
487 'patches' => {
488 'sub' => \&feature_patches,
489 'override' => 0,
490 'default' => [16]},
492 # Avatar support. When this feature is enabled, views such as
493 # shortlog or commit will display an avatar associated with
494 # the email of the committer(s) and/or author(s).
496 # Currently available providers are gravatar and picon.
497 # If an unknown provider is specified, the feature is disabled.
499 # Gravatar depends on Digest::MD5.
500 # Picon currently relies on the indiana.edu database.
502 # To enable system wide have in $GITWEB_CONFIG
503 # $feature{'avatar'}{'default'} = ['<provider>'];
504 # where <provider> is either gravatar or picon.
505 # To have project specific config enable override in $GITWEB_CONFIG
506 # $feature{'avatar'}{'override'} = 1;
507 # and in project config gitweb.avatar = <provider>;
508 'avatar' => {
509 'sub' => \&feature_avatar,
510 'override' => 0,
511 'default' => ['']},
513 # Enable displaying how much time and how many git commands
514 # it took to generate and display page. Disabled by default.
515 # Project specific override is not supported.
516 'timed' => {
517 'override' => 0,
518 'default' => [0]},
520 # Enable turning some links into links to actions which require
521 # JavaScript to run (like 'blame_incremental'). Not enabled by
522 # default. Project specific override is currently not supported.
523 'javascript-actions' => {
524 'override' => 0,
525 'default' => [0]},
527 # Enable and configure ability to change common timezone for dates
528 # in gitweb output via JavaScript. Enabled by default.
529 # Project specific override is not supported.
530 'javascript-timezone' => {
531 'override' => 0,
532 'default' => [
533 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
534 # or undef to turn off this feature
535 'gitweb_tz', # name of cookie where to store selected timezone
536 'datetime', # CSS class used to mark up dates for manipulation
539 # Syntax highlighting support. This is based on Daniel Svensson's
540 # and Sham Chukoury's work in gitweb-xmms2.git.
541 # It requires the 'highlight' program present in $PATH,
542 # and therefore is disabled by default.
544 # To enable system wide have in $GITWEB_CONFIG
545 # $feature{'highlight'}{'default'} = [1];
547 'highlight' => {
548 'sub' => sub { feature_bool('highlight', @_) },
549 'override' => 0,
550 'default' => [0]},
552 # Enable displaying of remote heads in the heads list
554 # To enable system wide have in $GITWEB_CONFIG
555 # $feature{'remote_heads'}{'default'} = [1];
556 # To have project specific config enable override in $GITWEB_CONFIG
557 # $feature{'remote_heads'}{'override'} = 1;
558 # and in project config gitweb.remoteheads = 0|1;
559 'remote_heads' => {
560 'sub' => sub { feature_bool('remote_heads', @_) },
561 'override' => 0,
562 'default' => [0]},
564 # Enable showing branches under other refs in addition to heads
566 # To set system wide extra branch refs have in $GITWEB_CONFIG
567 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
568 # To have project specific config enable override in $GITWEB_CONFIG
569 # $feature{'extra-branch-refs'}{'override'} = 1;
570 # and in project config gitweb.extrabranchrefs = dirs of choice
571 # Every directory is separated with whitespace.
573 'extra-branch-refs' => {
574 'sub' => \&feature_extra_branch_refs,
575 'override' => 0,
576 'default' => []},
579 sub gitweb_get_feature {
580 my ($name) = @_;
581 return unless exists $feature{$name};
582 my ($sub, $override, @defaults) = (
583 $feature{$name}{'sub'},
584 $feature{$name}{'override'},
585 @{$feature{$name}{'default'}});
586 # project specific override is possible only if we have project
587 our $git_dir; # global variable, declared later
588 if (!$override || !defined $git_dir) {
589 return @defaults;
591 if (!defined $sub) {
592 warn "feature $name is not overridable";
593 return @defaults;
595 return $sub->(@defaults);
598 # A wrapper to check if a given feature is enabled.
599 # With this, you can say
601 # my $bool_feat = gitweb_check_feature('bool_feat');
602 # gitweb_check_feature('bool_feat') or somecode;
604 # instead of
606 # my ($bool_feat) = gitweb_get_feature('bool_feat');
607 # (gitweb_get_feature('bool_feat'))[0] or somecode;
609 sub gitweb_check_feature {
610 return (gitweb_get_feature(@_))[0];
614 sub feature_bool {
615 my $key = shift;
616 my ($val) = git_get_project_config($key, '--bool');
618 if (!defined $val) {
619 return ($_[0]);
620 } elsif ($val eq 'true') {
621 return (1);
622 } elsif ($val eq 'false') {
623 return (0);
627 sub feature_snapshot {
628 my (@fmts) = @_;
630 my ($val) = git_get_project_config('snapshot');
632 if ($val) {
633 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
636 return @fmts;
639 sub feature_patches {
640 my @val = (git_get_project_config('patches', '--int'));
642 if (@val) {
643 return @val;
646 return ($_[0]);
649 sub feature_avatar {
650 my @val = (git_get_project_config('avatar'));
652 return @val ? @val : @_;
655 sub feature_extra_branch_refs {
656 my (@branch_refs) = @_;
657 my $values = git_get_project_config('extrabranchrefs');
659 if ($values) {
660 $values = config_to_multi ($values);
661 @branch_refs = ();
662 foreach my $value (@{$values}) {
663 push @branch_refs, split /\s+/, $value;
667 return @branch_refs;
670 # checking HEAD file with -e is fragile if the repository was
671 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
672 # and then pruned.
673 sub check_head_link {
674 my ($dir) = @_;
675 my $headfile = "$dir/HEAD";
676 return ((-e $headfile) ||
677 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
680 sub check_export_ok {
681 my ($dir) = @_;
682 return (check_head_link($dir) &&
683 (!$export_ok || -e "$dir/$export_ok") &&
684 (!$export_auth_hook || $export_auth_hook->($dir)));
687 # process alternate names for backward compatibility
688 # filter out unsupported (unknown) snapshot formats
689 sub filter_snapshot_fmts {
690 my @fmts = @_;
692 @fmts = map {
693 exists $known_snapshot_format_aliases{$_} ?
694 $known_snapshot_format_aliases{$_} : $_} @fmts;
695 @fmts = grep {
696 exists $known_snapshot_formats{$_} &&
697 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
700 sub filter_and_validate_refs {
701 my @refs = @_;
702 my %unique_refs = ();
704 foreach my $ref (@refs) {
705 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
706 # 'heads' are added implicitly in get_branch_refs().
707 $unique_refs{$ref} = 1 if ($ref ne 'heads');
709 return sort keys %unique_refs;
712 # If it is set to code reference, it is code that it is to be run once per
713 # request, allowing updating configurations that change with each request,
714 # while running other code in config file only once.
716 # Otherwise, if it is false then gitweb would process config file only once;
717 # if it is true then gitweb config would be run for each request.
718 our $per_request_config = 1;
720 # read and parse gitweb config file given by its parameter.
721 # returns true on success, false on recoverable error, allowing
722 # to chain this subroutine, using first file that exists.
723 # dies on errors during parsing config file, as it is unrecoverable.
724 sub read_config_file {
725 my $filename = shift;
726 return unless defined $filename;
727 # die if there are errors parsing config file
728 if (-e $filename) {
729 do $filename;
730 die $@ if $@;
731 return 1;
733 return;
736 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
737 sub evaluate_gitweb_config {
738 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
739 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
740 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
742 # Protect against duplications of file names, to not read config twice.
743 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
744 # there possibility of duplication of filename there doesn't matter.
745 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
746 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
748 # Common system-wide settings for convenience.
749 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
750 read_config_file($GITWEB_CONFIG_COMMON);
752 # Use first config file that exists. This means use the per-instance
753 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
754 read_config_file($GITWEB_CONFIG) and return;
755 read_config_file($GITWEB_CONFIG_SYSTEM);
758 # Get loadavg of system, to compare against $maxload.
759 # Currently it requires '/proc/loadavg' present to get loadavg;
760 # if it is not present it returns 0, which means no load checking.
761 sub get_loadavg {
762 if( -e '/proc/loadavg' ){
763 open my $fd, '<', '/proc/loadavg'
764 or return 0;
765 my @load = split(/\s+/, scalar <$fd>);
766 close $fd;
768 # The first three columns measure CPU and IO utilization of the last one,
769 # five, and 10 minute periods. The fourth column shows the number of
770 # currently running processes and the total number of processes in the m/n
771 # format. The last column displays the last process ID used.
772 return $load[0] || 0;
774 # additional checks for load average should go here for things that don't export
775 # /proc/loadavg
777 return 0;
780 # version of the core git binary
781 our $git_version;
782 sub evaluate_git_version {
783 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
784 $number_of_git_cmds++;
787 sub check_loadavg {
788 if (defined $maxload && get_loadavg() > $maxload) {
789 die_error(503, "The load average on the server is too high");
793 # ======================================================================
794 # input validation and dispatch
796 # input parameters can be collected from a variety of sources (presently, CGI
797 # and PATH_INFO), so we define an %input_params hash that collects them all
798 # together during validation: this allows subsequent uses (e.g. href()) to be
799 # agnostic of the parameter origin
801 our %input_params = ();
803 # input parameters are stored with the long parameter name as key. This will
804 # also be used in the href subroutine to convert parameters to their CGI
805 # equivalent, and since the href() usage is the most frequent one, we store
806 # the name -> CGI key mapping here, instead of the reverse.
808 # XXX: Warning: If you touch this, check the search form for updating,
809 # too.
811 our @cgi_param_mapping = (
812 project => "p",
813 action => "a",
814 file_name => "f",
815 file_parent => "fp",
816 hash => "h",
817 hash_parent => "hp",
818 hash_base => "hb",
819 hash_parent_base => "hpb",
820 page => "pg",
821 order => "o",
822 searchtext => "s",
823 searchtype => "st",
824 snapshot_format => "sf",
825 ctag_filter => 't',
826 extra_options => "opt",
827 search_use_regexp => "sr",
828 ctag => "by_tag",
829 diff_style => "ds",
830 project_filter => "pf",
831 # this must be last entry (for manipulation from JavaScript)
832 javascript => "js"
834 our %cgi_param_mapping = @cgi_param_mapping;
836 # we will also need to know the possible actions, for validation
837 our %actions = (
838 "blame" => \&git_blame,
839 "blame_incremental" => \&git_blame_incremental,
840 "blame_data" => \&git_blame_data,
841 "blobdiff" => \&git_blobdiff,
842 "blobdiff_plain" => \&git_blobdiff_plain,
843 "blob" => \&git_blob,
844 "blob_plain" => \&git_blob_plain,
845 "commitdiff" => \&git_commitdiff,
846 "commitdiff_plain" => \&git_commitdiff_plain,
847 "commit" => \&git_commit,
848 "forks" => \&git_forks,
849 "heads" => \&git_heads,
850 "history" => \&git_history,
851 "log" => \&git_log,
852 "patch" => \&git_patch,
853 "patches" => \&git_patches,
854 "remotes" => \&git_remotes,
855 "rss" => \&git_rss,
856 "atom" => \&git_atom,
857 "search" => \&git_search,
858 "search_help" => \&git_search_help,
859 "shortlog" => \&git_shortlog,
860 "summary" => \&git_summary,
861 "tag" => \&git_tag,
862 "tags" => \&git_tags,
863 "tree" => \&git_tree,
864 "snapshot" => \&git_snapshot,
865 "object" => \&git_object,
866 # those below don't need $project
867 "opml" => \&git_opml,
868 "frontpage" => \&git_frontpage,
869 "project_list" => \&git_project_list,
870 "project_index" => \&git_project_index,
873 # finally, we have the hash of allowed extra_options for the commands that
874 # allow them
875 our %allowed_options = (
876 "--no-merges" => [ qw(rss atom log shortlog history) ],
879 # fill %input_params with the CGI parameters. All values except for 'opt'
880 # should be single values, but opt can be an array. We should probably
881 # build an array of parameters that can be multi-valued, but since for the time
882 # being it's only this one, we just single it out
883 sub evaluate_query_params {
884 our $cgi;
886 while (my ($name, $symbol) = each %cgi_param_mapping) {
887 if ($symbol eq 'opt') {
888 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
889 } else {
890 $input_params{$name} = decode_utf8($cgi->param($symbol));
894 # Backwards compatibility - by_tag= <=> t=
895 if ($input_params{'ctag'}) {
896 $input_params{'ctag_filter'} = $input_params{'ctag'};
900 # now read PATH_INFO and update the parameter list for missing parameters
901 sub evaluate_path_info {
902 return if defined $input_params{'project'};
903 return if !$path_info;
904 $path_info =~ s,^/+,,;
905 return if !$path_info;
907 # find which part of PATH_INFO is project
908 my $project = $path_info;
909 $project =~ s,/+$,,;
910 while ($project && !check_head_link("$projectroot/$project")) {
911 $project =~ s,/*[^/]*$,,;
913 return unless $project;
914 $input_params{'project'} = $project;
916 # do not change any parameters if an action is given using the query string
917 return if $input_params{'action'};
918 $path_info =~ s,^\Q$project\E/*,,;
920 # next, check if we have an action
921 my $action = $path_info;
922 $action =~ s,/.*$,,;
923 if (exists $actions{$action}) {
924 $path_info =~ s,^$action/*,,;
925 $input_params{'action'} = $action;
928 # list of actions that want hash_base instead of hash, but can have no
929 # pathname (f) parameter
930 my @wants_base = (
931 'tree',
932 'history',
935 # we want to catch, among others
936 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
937 my ($parentrefname, $parentpathname, $refname, $pathname) =
938 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
940 # first, analyze the 'current' part
941 if (defined $pathname) {
942 # we got "branch:filename" or "branch:dir/"
943 # we could use git_get_type(branch:pathname), but:
944 # - it needs $git_dir
945 # - it does a git() call
946 # - the convention of terminating directories with a slash
947 # makes it superfluous
948 # - embedding the action in the PATH_INFO would make it even
949 # more superfluous
950 $pathname =~ s,^/+,,;
951 if (!$pathname || substr($pathname, -1) eq "/") {
952 $input_params{'action'} ||= "tree";
953 $pathname =~ s,/$,,;
954 } else {
955 # the default action depends on whether we had parent info
956 # or not
957 if ($parentrefname) {
958 $input_params{'action'} ||= "blobdiff_plain";
959 } else {
960 $input_params{'action'} ||= "blob_plain";
963 $input_params{'hash_base'} ||= $refname;
964 $input_params{'file_name'} ||= $pathname;
965 } elsif (defined $refname) {
966 # we got "branch". In this case we have to choose if we have to
967 # set hash or hash_base.
969 # Most of the actions without a pathname only want hash to be
970 # set, except for the ones specified in @wants_base that want
971 # hash_base instead. It should also be noted that hand-crafted
972 # links having 'history' as an action and no pathname or hash
973 # set will fail, but that happens regardless of PATH_INFO.
974 if (defined $parentrefname) {
975 # if there is parent let the default be 'shortlog' action
976 # (for http://git.example.com/repo.git/A..B links); if there
977 # is no parent, dispatch will detect type of object and set
978 # action appropriately if required (if action is not set)
979 $input_params{'action'} ||= "shortlog";
981 if ($input_params{'action'} &&
982 grep { $_ eq $input_params{'action'} } @wants_base) {
983 $input_params{'hash_base'} ||= $refname;
984 } else {
985 $input_params{'hash'} ||= $refname;
989 # next, handle the 'parent' part, if present
990 if (defined $parentrefname) {
991 # a missing pathspec defaults to the 'current' filename, allowing e.g.
992 # someproject/blobdiff/oldrev..newrev:/filename
993 if ($parentpathname) {
994 $parentpathname =~ s,^/+,,;
995 $parentpathname =~ s,/$,,;
996 $input_params{'file_parent'} ||= $parentpathname;
997 } else {
998 $input_params{'file_parent'} ||= $input_params{'file_name'};
1000 # we assume that hash_parent_base is wanted if a path was specified,
1001 # or if the action wants hash_base instead of hash
1002 if (defined $input_params{'file_parent'} ||
1003 grep { $_ eq $input_params{'action'} } @wants_base) {
1004 $input_params{'hash_parent_base'} ||= $parentrefname;
1005 } else {
1006 $input_params{'hash_parent'} ||= $parentrefname;
1010 # for the snapshot action, we allow URLs in the form
1011 # $project/snapshot/$hash.ext
1012 # where .ext determines the snapshot and gets removed from the
1013 # passed $refname to provide the $hash.
1015 # To be able to tell that $refname includes the format extension, we
1016 # require the following two conditions to be satisfied:
1017 # - the hash input parameter MUST have been set from the $refname part
1018 # of the URL (i.e. they must be equal)
1019 # - the snapshot format MUST NOT have been defined already (e.g. from
1020 # CGI parameter sf)
1021 # It's also useless to try any matching unless $refname has a dot,
1022 # so we check for that too
1023 if (defined $input_params{'action'} &&
1024 $input_params{'action'} eq 'snapshot' &&
1025 defined $refname && index($refname, '.') != -1 &&
1026 $refname eq $input_params{'hash'} &&
1027 !defined $input_params{'snapshot_format'}) {
1028 # We loop over the known snapshot formats, checking for
1029 # extensions. Allowed extensions are both the defined suffix
1030 # (which includes the initial dot already) and the snapshot
1031 # format key itself, with a prepended dot
1032 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1033 my $hash = $refname;
1034 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1035 next;
1037 my $sfx = $1;
1038 # a valid suffix was found, so set the snapshot format
1039 # and reset the hash parameter
1040 $input_params{'snapshot_format'} = $fmt;
1041 $input_params{'hash'} = $hash;
1042 # we also set the format suffix to the one requested
1043 # in the URL: this way a request for e.g. .tgz returns
1044 # a .tgz instead of a .tar.gz
1045 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1046 last;
1051 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1052 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1053 $searchtext, $search_regexp, $project_filter);
1054 sub evaluate_and_validate_params {
1055 our $action = $input_params{'action'};
1056 if (defined $action) {
1057 if (!is_valid_action($action)) {
1058 die_error(400, "Invalid action parameter");
1062 # parameters which are pathnames
1063 our $project = $input_params{'project'};
1064 if (defined $project) {
1065 if (!is_valid_project($project)) {
1066 undef $project;
1067 die_error(404, "No such project");
1071 our $project_filter = $input_params{'project_filter'};
1072 if (defined $project_filter) {
1073 if (!is_valid_pathname($project_filter)) {
1074 die_error(404, "Invalid project_filter parameter");
1078 our $file_name = $input_params{'file_name'};
1079 if (defined $file_name) {
1080 if (!is_valid_pathname($file_name)) {
1081 die_error(400, "Invalid file parameter");
1085 our $file_parent = $input_params{'file_parent'};
1086 if (defined $file_parent) {
1087 if (!is_valid_pathname($file_parent)) {
1088 die_error(400, "Invalid file parent parameter");
1092 # parameters which are refnames
1093 our $hash = $input_params{'hash'};
1094 if (defined $hash) {
1095 if (!is_valid_refname($hash)) {
1096 die_error(400, "Invalid hash parameter");
1100 our $hash_parent = $input_params{'hash_parent'};
1101 if (defined $hash_parent) {
1102 if (!is_valid_refname($hash_parent)) {
1103 die_error(400, "Invalid hash parent parameter");
1107 our $hash_base = $input_params{'hash_base'};
1108 if (defined $hash_base) {
1109 if (!is_valid_refname($hash_base)) {
1110 die_error(400, "Invalid hash base parameter");
1114 our @extra_options = @{$input_params{'extra_options'}};
1115 # @extra_options is always defined, since it can only be (currently) set from
1116 # CGI, and $cgi->param() returns the empty array in array context if the param
1117 # is not set
1118 foreach my $opt (@extra_options) {
1119 if (not exists $allowed_options{$opt}) {
1120 die_error(400, "Invalid option parameter");
1122 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1123 die_error(400, "Invalid option parameter for this action");
1127 our $hash_parent_base = $input_params{'hash_parent_base'};
1128 if (defined $hash_parent_base) {
1129 if (!is_valid_refname($hash_parent_base)) {
1130 die_error(400, "Invalid hash parent base parameter");
1134 # other parameters
1135 our $page = $input_params{'page'};
1136 if (defined $page) {
1137 if ($page =~ m/[^0-9]/) {
1138 die_error(400, "Invalid page parameter");
1142 our $searchtype = $input_params{'searchtype'};
1143 if (defined $searchtype) {
1144 if ($searchtype =~ m/[^a-z]/) {
1145 die_error(400, "Invalid searchtype parameter");
1149 our $search_use_regexp = $input_params{'search_use_regexp'};
1151 our $searchtext = $input_params{'searchtext'};
1152 our $search_regexp = undef;
1153 if (defined $searchtext) {
1154 if (length($searchtext) < 2) {
1155 die_error(403, "At least two characters are required for search parameter");
1157 if ($search_use_regexp) {
1158 $search_regexp = $searchtext;
1159 if (!eval { qr/$search_regexp/; 1; }) {
1160 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1161 die_error(400, "Invalid search regexp '$search_regexp'",
1162 esc_html($error));
1164 } else {
1165 $search_regexp = quotemeta $searchtext;
1170 # path to the current git repository
1171 our $git_dir;
1172 sub evaluate_git_dir {
1173 our $git_dir = "$projectroot/$project" if $project;
1176 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1177 sub configure_gitweb_features {
1178 # list of supported snapshot formats
1179 our @snapshot_fmts = gitweb_get_feature('snapshot');
1180 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1182 # check that the avatar feature is set to a known provider name,
1183 # and for each provider check if the dependencies are satisfied.
1184 # if the provider name is invalid or the dependencies are not met,
1185 # reset $git_avatar to the empty string.
1186 our ($git_avatar) = gitweb_get_feature('avatar');
1187 if ($git_avatar eq 'gravatar') {
1188 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1189 } elsif ($git_avatar eq 'picon') {
1190 # no dependencies
1191 } else {
1192 $git_avatar = '';
1195 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1196 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1199 sub get_branch_refs {
1200 return ('heads', @extra_branch_refs);
1203 # custom error handler: 'die <message>' is Internal Server Error
1204 sub handle_errors_html {
1205 my $msg = shift; # it is already HTML escaped
1207 # to avoid infinite loop where error occurs in die_error,
1208 # change handler to default handler, disabling handle_errors_html
1209 set_message("Error occurred when inside die_error:\n$msg");
1211 # you cannot jump out of die_error when called as error handler;
1212 # the subroutine set via CGI::Carp::set_message is called _after_
1213 # HTTP headers are already written, so it cannot write them itself
1214 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1216 set_message(\&handle_errors_html);
1218 # dispatch
1219 sub dispatch {
1220 if (!defined $action) {
1221 if (defined $hash) {
1222 $action = git_get_type($hash);
1223 $action or die_error(404, "Object does not exist");
1224 } elsif (defined $hash_base && defined $file_name) {
1225 $action = git_get_type("$hash_base:$file_name");
1226 $action or die_error(404, "File or directory does not exist");
1227 } elsif (defined $project) {
1228 $action = 'summary';
1229 } else {
1230 $action = 'frontpage';
1233 if (!defined($actions{$action})) {
1234 die_error(400, "Unknown action");
1236 if ($action !~ m/^(?:opml|frontpage|project_list|project_index)$/ &&
1237 !$project) {
1238 die_error(400, "Project needed");
1240 $actions{$action}->();
1243 sub reset_timer {
1244 our $t0 = [ gettimeofday() ]
1245 if defined $t0;
1246 our $number_of_git_cmds = 0;
1249 our $first_request = 1;
1250 sub run_request {
1251 reset_timer();
1253 evaluate_uri();
1254 if ($first_request) {
1255 evaluate_gitweb_config();
1256 evaluate_git_version();
1258 if ($per_request_config) {
1259 if (ref($per_request_config) eq 'CODE') {
1260 $per_request_config->();
1261 } elsif (!$first_request) {
1262 evaluate_gitweb_config();
1265 check_loadavg();
1267 # $projectroot and $projects_list might be set in gitweb config file
1268 $projects_list ||= $projectroot;
1270 evaluate_query_params();
1271 evaluate_path_info();
1272 evaluate_and_validate_params();
1273 evaluate_git_dir();
1275 configure_gitweb_features();
1277 dispatch();
1280 our $is_last_request = sub { 1 };
1281 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1282 our $CGI = 'CGI';
1283 our $cgi;
1284 sub configure_as_fcgi {
1285 require CGI::Fast;
1286 our $CGI = 'CGI::Fast';
1288 my $request_number = 0;
1289 # let each child service 100 requests
1290 our $is_last_request = sub { ++$request_number > 100 };
1292 sub evaluate_argv {
1293 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1294 configure_as_fcgi()
1295 if $script_name =~ /\.fcgi$/;
1297 return unless (@ARGV);
1299 require Getopt::Long;
1300 Getopt::Long::GetOptions(
1301 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1302 'nproc|n=i' => sub {
1303 my ($arg, $val) = @_;
1304 return unless eval { require FCGI::ProcManager; 1; };
1305 my $proc_manager = FCGI::ProcManager->new({
1306 n_processes => $val,
1308 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1309 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1310 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1315 sub run {
1316 evaluate_argv();
1318 $first_request = 1;
1319 $pre_listen_hook->()
1320 if $pre_listen_hook;
1322 REQUEST:
1323 while ($cgi = $CGI->new()) {
1324 $pre_dispatch_hook->()
1325 if $pre_dispatch_hook;
1327 run_request();
1329 $post_dispatch_hook->()
1330 if $post_dispatch_hook;
1331 $first_request = 0;
1333 last REQUEST if ($is_last_request->());
1336 DONE_GITWEB:
1340 run();
1342 if (defined caller) {
1343 # wrapped in a subroutine processing requests,
1344 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1345 return;
1346 } else {
1347 # pure CGI script, serving single request
1348 exit;
1351 ## ======================================================================
1352 ## action links
1354 # possible values of extra options
1355 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1356 # -replay => 1 - start from a current view (replay with modifications)
1357 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1358 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1359 sub href {
1360 my %params = @_;
1361 # default is to use -absolute url() i.e. $my_uri
1362 my $href = $params{-full} ? $my_url : $my_uri;
1364 # implicit -replay, must be first of implicit params
1365 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1367 $params{'project'} = $project unless exists $params{'project'};
1369 if ($params{-replay}) {
1370 while (my ($name, $symbol) = each %cgi_param_mapping) {
1371 if (!exists $params{$name}) {
1372 $params{$name} = $input_params{$name};
1377 my $use_pathinfo = gitweb_check_feature('pathinfo');
1378 if (defined $params{'project'} &&
1379 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1380 # try to put as many parameters as possible in PATH_INFO:
1381 # - project name
1382 # - action
1383 # - hash_parent or hash_parent_base:/file_parent
1384 # - hash or hash_base:/filename
1385 # - the snapshot_format as an appropriate suffix
1387 # When the script is the root DirectoryIndex for the domain,
1388 # $href here would be something like http://gitweb.example.com/
1389 # Thus, we strip any trailing / from $href, to spare us double
1390 # slashes in the final URL
1391 $href =~ s,/$,,;
1393 # Then add the project name, if present
1394 $href .= "/".esc_path_info($params{'project'});
1395 delete $params{'project'};
1397 # since we destructively absorb parameters, we keep this
1398 # boolean that remembers if we're handling a snapshot
1399 my $is_snapshot = $params{'action'} eq 'snapshot';
1401 # Summary just uses the project path URL, any other action is
1402 # added to the URL
1403 if (defined $params{'action'}) {
1404 $href .= "/".esc_path_info($params{'action'})
1405 unless $params{'action'} eq 'summary';
1406 delete $params{'action'};
1409 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1410 # stripping nonexistent or useless pieces
1411 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1412 || $params{'hash_parent'} || $params{'hash'});
1413 if (defined $params{'hash_base'}) {
1414 if (defined $params{'hash_parent_base'}) {
1415 $href .= esc_path_info($params{'hash_parent_base'});
1416 # skip the file_parent if it's the same as the file_name
1417 if (defined $params{'file_parent'}) {
1418 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1419 delete $params{'file_parent'};
1420 } elsif ($params{'file_parent'} !~ /\.\./) {
1421 $href .= ":/".esc_path_info($params{'file_parent'});
1422 delete $params{'file_parent'};
1425 $href .= "..";
1426 delete $params{'hash_parent'};
1427 delete $params{'hash_parent_base'};
1428 } elsif (defined $params{'hash_parent'}) {
1429 $href .= esc_path_info($params{'hash_parent'}). "..";
1430 delete $params{'hash_parent'};
1433 $href .= esc_path_info($params{'hash_base'});
1434 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1435 $href .= ":/".esc_path_info($params{'file_name'});
1436 delete $params{'file_name'};
1438 delete $params{'hash'};
1439 delete $params{'hash_base'};
1440 } elsif (defined $params{'hash'}) {
1441 $href .= esc_path_info($params{'hash'});
1442 delete $params{'hash'};
1445 # If the action was a snapshot, we can absorb the
1446 # snapshot_format parameter too
1447 if ($is_snapshot) {
1448 my $fmt = $params{'snapshot_format'};
1449 # snapshot_format should always be defined when href()
1450 # is called, but just in case some code forgets, we
1451 # fall back to the default
1452 $fmt ||= $snapshot_fmts[0];
1453 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1454 delete $params{'snapshot_format'};
1458 # now encode the parameters explicitly
1459 my @result = ();
1460 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1461 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1462 if (defined $params{$name}) {
1463 if (ref($params{$name}) eq "ARRAY") {
1464 foreach my $par (@{$params{$name}}) {
1465 push @result, $symbol . "=" . esc_param($par);
1467 } else {
1468 push @result, $symbol . "=" . esc_param($params{$name});
1472 $href .= "?" . join(';', @result) if scalar @result;
1474 # final transformation: trailing spaces must be escaped (URI-encoded)
1475 $href =~ s/(\s+)$/CGI::escape($1)/e;
1477 if ($params{-anchor}) {
1478 $href .= "#".esc_param($params{-anchor});
1481 return $href;
1485 ## ======================================================================
1486 ## validation, quoting/unquoting and escaping
1488 sub is_valid_action {
1489 my $input = shift;
1490 return undef unless exists $actions{$input};
1491 return 1;
1494 sub is_valid_project {
1495 my $input = shift;
1497 return unless defined $input;
1498 if (!is_valid_pathname($input) ||
1499 !(-d "$projectroot/$input") ||
1500 !check_export_ok("$projectroot/$input") ||
1501 ($strict_export && !project_in_list($input))) {
1502 return undef;
1503 } else {
1504 return 1;
1508 sub is_valid_pathname {
1509 my $input = shift;
1511 return undef unless defined $input;
1512 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1513 # at the beginning, at the end, and between slashes.
1514 # also this catches doubled slashes
1515 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1516 return undef;
1518 # no null characters
1519 if ($input =~ m!\0!) {
1520 return undef;
1522 return 1;
1525 sub is_valid_ref_format {
1526 my $input = shift;
1528 return undef unless defined $input;
1529 # restrictions on ref name according to git-check-ref-format
1530 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1531 return undef;
1533 return 1;
1536 sub is_valid_refname {
1537 my $input = shift;
1539 return undef unless defined $input;
1540 # textual hashes are O.K.
1541 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1542 return 1;
1544 # it must be correct pathname
1545 is_valid_pathname($input) or return undef;
1546 # check git-check-ref-format restrictions
1547 is_valid_ref_format($input) or return undef;
1548 return 1;
1551 # decode sequences of octets in utf8 into Perl's internal form,
1552 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1553 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1554 sub to_utf8 {
1555 my $str = shift;
1556 return undef unless defined $str;
1558 if (utf8::is_utf8($str) || utf8::decode($str)) {
1559 return $str;
1560 } else {
1561 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1565 # quote unsafe chars, but keep the slash, even when it's not
1566 # correct, but quoted slashes look too horrible in bookmarks
1567 sub esc_param {
1568 my $str = shift;
1569 return undef unless defined $str;
1570 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1571 $str =~ s/ /\+/g;
1572 return $str;
1575 # the quoting rules for path_info fragment are slightly different
1576 sub esc_path_info {
1577 my $str = shift;
1578 return undef unless defined $str;
1580 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1581 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1583 return $str;
1586 # quote unsafe chars in whole URL, so some characters cannot be quoted
1587 sub esc_url {
1588 my $str = shift;
1589 return undef unless defined $str;
1590 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1591 $str =~ s/ /\+/g;
1592 return $str;
1595 # quote unsafe characters in HTML attributes
1596 sub esc_attr {
1598 # for XHTML conformance escaping '"' to '&quot;' is not enough
1599 return esc_html(@_);
1602 # replace invalid utf8 character with SUBSTITUTION sequence
1603 sub esc_html {
1604 my $str = shift;
1605 my %opts = @_;
1607 return undef unless defined $str;
1609 $str = to_utf8($str);
1610 $str = $cgi->escapeHTML($str);
1611 if ($opts{'-nbsp'}) {
1612 $str =~ s/ /&nbsp;/g;
1614 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1615 return $str;
1618 # quote control characters and escape filename to HTML
1619 sub esc_path {
1620 my $str = shift;
1621 my %opts = @_;
1623 return undef unless defined $str;
1625 $str = to_utf8($str);
1626 $str = $cgi->escapeHTML($str);
1627 if ($opts{'-nbsp'}) {
1628 $str =~ s/ /&nbsp;/g;
1630 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1631 return $str;
1634 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1635 sub sanitize {
1636 my $str = shift;
1638 return undef unless defined $str;
1640 $str = to_utf8($str);
1641 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1642 return $str;
1645 # Make control characters "printable", using character escape codes (CEC)
1646 sub quot_cec {
1647 my $cntrl = shift;
1648 my %opts = @_;
1649 my %es = ( # character escape codes, aka escape sequences
1650 "\t" => '\t', # tab (HT)
1651 "\n" => '\n', # line feed (LF)
1652 "\r" => '\r', # carrige return (CR)
1653 "\f" => '\f', # form feed (FF)
1654 "\b" => '\b', # backspace (BS)
1655 "\a" => '\a', # alarm (bell) (BEL)
1656 "\e" => '\e', # escape (ESC)
1657 "\013" => '\v', # vertical tab (VT)
1658 "\000" => '\0', # nul character (NUL)
1660 my $chr = ( (exists $es{$cntrl})
1661 ? $es{$cntrl}
1662 : sprintf('\%2x', ord($cntrl)) );
1663 if ($opts{-nohtml}) {
1664 return $chr;
1665 } else {
1666 return "<span class=\"cntrl\">$chr</span>";
1670 # Alternatively use unicode control pictures codepoints,
1671 # Unicode "printable representation" (PR)
1672 sub quot_upr {
1673 my $cntrl = shift;
1674 my %opts = @_;
1676 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1677 if ($opts{-nohtml}) {
1678 return $chr;
1679 } else {
1680 return "<span class=\"cntrl\">$chr</span>";
1684 # git may return quoted and escaped filenames
1685 sub unquote {
1686 my $str = shift;
1688 sub unq {
1689 my $seq = shift;
1690 my %es = ( # character escape codes, aka escape sequences
1691 't' => "\t", # tab (HT, TAB)
1692 'n' => "\n", # newline (NL)
1693 'r' => "\r", # return (CR)
1694 'f' => "\f", # form feed (FF)
1695 'b' => "\b", # backspace (BS)
1696 'a' => "\a", # alarm (bell) (BEL)
1697 'e' => "\e", # escape (ESC)
1698 'v' => "\013", # vertical tab (VT)
1701 if ($seq =~ m/^[0-7]{1,3}$/) {
1702 # octal char sequence
1703 return chr(oct($seq));
1704 } elsif (exists $es{$seq}) {
1705 # C escape sequence, aka character escape code
1706 return $es{$seq};
1708 # quoted ordinary character
1709 return $seq;
1712 if ($str =~ m/^"(.*)"$/) {
1713 # needs unquoting
1714 $str = $1;
1715 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1717 return $str;
1720 # escape tabs (convert tabs to spaces)
1721 sub untabify {
1722 my $line = shift;
1724 while ((my $pos = index($line, "\t")) != -1) {
1725 if (my $count = (8 - ($pos % 8))) {
1726 my $spaces = ' ' x $count;
1727 $line =~ s/\t/$spaces/;
1731 return $line;
1734 sub project_in_list {
1735 my $project = shift;
1736 my @list = git_get_projects_list();
1737 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1740 ## ----------------------------------------------------------------------
1741 ## HTML aware string manipulation
1743 # Try to chop given string on a word boundary between position
1744 # $len and $len+$add_len. If there is no word boundary there,
1745 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1746 # (marking chopped part) would be longer than given string.
1747 sub chop_str {
1748 my $str = shift;
1749 my $len = shift;
1750 my $add_len = shift || 10;
1751 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1753 # Make sure perl knows it is utf8 encoded so we don't
1754 # cut in the middle of a utf8 multibyte char.
1755 $str = to_utf8($str);
1757 # allow only $len chars, but don't cut a word if it would fit in $add_len
1758 # if it doesn't fit, cut it if it's still longer than the dots we would add
1759 # remove chopped character entities entirely
1761 # when chopping in the middle, distribute $len into left and right part
1762 # return early if chopping wouldn't make string shorter
1763 if ($where eq 'center') {
1764 return $str if ($len + 5 >= length($str)); # filler is length 5
1765 $len = int($len/2);
1766 } else {
1767 return $str if ($len + 4 >= length($str)); # filler is length 4
1770 # regexps: ending and beginning with word part up to $add_len
1771 my $endre = qr/.{$len}\w{0,$add_len}/;
1772 my $begre = qr/\w{0,$add_len}.{$len}/;
1774 if ($where eq 'left') {
1775 $str =~ m/^(.*?)($begre)$/;
1776 my ($lead, $body) = ($1, $2);
1777 if (length($lead) > 4) {
1778 $lead = " ...";
1780 return "$lead$body";
1782 } elsif ($where eq 'center') {
1783 $str =~ m/^($endre)(.*)$/;
1784 my ($left, $str) = ($1, $2);
1785 $str =~ m/^(.*?)($begre)$/;
1786 my ($mid, $right) = ($1, $2);
1787 if (length($mid) > 5) {
1788 $mid = " ... ";
1790 return "$left$mid$right";
1792 } else {
1793 $str =~ m/^($endre)(.*)$/;
1794 my $body = $1;
1795 my $tail = $2;
1796 if (length($tail) > 4) {
1797 $tail = "... ";
1799 return "$body$tail";
1803 # takes the same arguments as chop_str, but also wraps a <span> around the
1804 # result with a title attribute if it does get chopped. Additionally, the
1805 # string is HTML-escaped.
1806 sub chop_and_escape_str {
1807 my ($str) = @_;
1809 my $chopped = chop_str(@_);
1810 $str = to_utf8($str);
1811 if ($chopped eq $str) {
1812 return esc_html($chopped);
1813 } else {
1814 $str =~ s/[[:cntrl:]]/?/g;
1815 return $cgi->span({-title=>$str}, esc_html($chopped));
1819 # Highlight selected fragments of string, using given CSS class,
1820 # and escape HTML. It is assumed that fragments do not overlap.
1821 # Regions are passed as list of pairs (array references).
1823 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1824 # '<span class="mark">foo</span>bar'
1825 sub esc_html_hl_regions {
1826 my ($str, $css_class, @sel) = @_;
1827 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1828 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1829 return esc_html($str, %opts) unless @sel;
1831 my $out = '';
1832 my $pos = 0;
1834 for my $s (@sel) {
1835 my ($begin, $end) = @$s;
1837 # Don't create empty <span> elements.
1838 next if $end <= $begin;
1840 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1841 %opts);
1843 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1844 if ($begin - $pos > 0);
1845 $out .= $cgi->span({-class => $css_class}, $escaped);
1847 $pos = $end;
1849 $out .= esc_html(substr($str, $pos), %opts)
1850 if ($pos < length($str));
1852 return $out;
1855 # return positions of beginning and end of each match
1856 sub matchpos_list {
1857 my ($str, $regexp) = @_;
1858 return unless (defined $str && defined $regexp);
1860 my @matches;
1861 while ($str =~ /$regexp/g) {
1862 push @matches, [$-[0], $+[0]];
1864 return @matches;
1867 # highlight match (if any), and escape HTML
1868 sub esc_html_match_hl {
1869 my ($str, $regexp) = @_;
1870 return esc_html($str) unless defined $regexp;
1872 my @matches = matchpos_list($str, $regexp);
1873 return esc_html($str) unless @matches;
1875 return esc_html_hl_regions($str, 'match', @matches);
1879 # highlight match (if any) of shortened string, and escape HTML
1880 sub esc_html_match_hl_chopped {
1881 my ($str, $chopped, $regexp) = @_;
1882 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1884 my @matches = matchpos_list($str, $regexp);
1885 return esc_html($chopped) unless @matches;
1887 # filter matches so that we mark chopped string
1888 my $tail = "... "; # see chop_str
1889 unless ($chopped =~ s/\Q$tail\E$//) {
1890 $tail = '';
1892 my $chop_len = length($chopped);
1893 my $tail_len = length($tail);
1894 my @filtered;
1896 for my $m (@matches) {
1897 if ($m->[0] > $chop_len) {
1898 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1899 last;
1900 } elsif ($m->[1] > $chop_len) {
1901 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1902 last;
1904 push @filtered, $m;
1907 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1910 ## ----------------------------------------------------------------------
1911 ## functions returning short strings
1913 # CSS class for given age value (in seconds)
1914 sub age_class {
1915 my $age = shift;
1917 if (!defined $age) {
1918 return "noage";
1919 } elsif ($age < 60*60*2) {
1920 return "age0";
1921 } elsif ($age < 60*60*24*2) {
1922 return "age1";
1923 } else {
1924 return "age2";
1928 # convert age in seconds to "nn units ago" string
1929 sub age_string {
1930 my $age = shift;
1931 my $age_str;
1933 if ($age > 60*60*24*365*2) {
1934 $age_str = (int $age/60/60/24/365);
1935 $age_str .= " years ago";
1936 } elsif ($age > 60*60*24*(365/12)*2) {
1937 $age_str = int $age/60/60/24/(365/12);
1938 $age_str .= " months ago";
1939 } elsif ($age > 60*60*24*7*2) {
1940 $age_str = int $age/60/60/24/7;
1941 $age_str .= " weeks ago";
1942 } elsif ($age > 60*60*24*2) {
1943 $age_str = int $age/60/60/24;
1944 $age_str .= " days ago";
1945 } elsif ($age > 60*60*2) {
1946 $age_str = int $age/60/60;
1947 $age_str .= " hours ago";
1948 } elsif ($age > 60*2) {
1949 $age_str = int $age/60;
1950 $age_str .= " min ago";
1951 } elsif ($age > 2) {
1952 $age_str = int $age;
1953 $age_str .= " sec ago";
1954 } else {
1955 $age_str .= " right now";
1957 return $age_str;
1960 use constant {
1961 S_IFINVALID => 0030000,
1962 S_IFGITLINK => 0160000,
1965 # submodule/subproject, a commit object reference
1966 sub S_ISGITLINK {
1967 my $mode = shift;
1969 return (($mode & S_IFMT) == S_IFGITLINK)
1972 # convert file mode in octal to symbolic file mode string
1973 sub mode_str {
1974 my $mode = oct shift;
1976 if (S_ISGITLINK($mode)) {
1977 return 'm---------';
1978 } elsif (S_ISDIR($mode & S_IFMT)) {
1979 return 'drwxr-xr-x';
1980 } elsif (S_ISLNK($mode)) {
1981 return 'lrwxrwxrwx';
1982 } elsif (S_ISREG($mode)) {
1983 # git cares only about the executable bit
1984 if ($mode & S_IXUSR) {
1985 return '-rwxr-xr-x';
1986 } else {
1987 return '-rw-r--r--';
1989 } else {
1990 return '----------';
1994 # convert file mode in octal to file type string
1995 sub file_type {
1996 my $mode = shift;
1998 if ($mode !~ m/^[0-7]+$/) {
1999 return $mode;
2000 } else {
2001 $mode = oct $mode;
2004 if (S_ISGITLINK($mode)) {
2005 return "submodule";
2006 } elsif (S_ISDIR($mode & S_IFMT)) {
2007 return "directory";
2008 } elsif (S_ISLNK($mode)) {
2009 return "symlink";
2010 } elsif (S_ISREG($mode)) {
2011 return "file";
2012 } else {
2013 return "unknown";
2017 # convert file mode in octal to file type description string
2018 sub file_type_long {
2019 my $mode = shift;
2021 if ($mode !~ m/^[0-7]+$/) {
2022 return $mode;
2023 } else {
2024 $mode = oct $mode;
2027 if (S_ISGITLINK($mode)) {
2028 return "submodule";
2029 } elsif (S_ISDIR($mode & S_IFMT)) {
2030 return "directory";
2031 } elsif (S_ISLNK($mode)) {
2032 return "symlink";
2033 } elsif (S_ISREG($mode)) {
2034 if ($mode & S_IXUSR) {
2035 return "executable";
2036 } else {
2037 return "file";
2039 } else {
2040 return "unknown";
2045 ## ----------------------------------------------------------------------
2046 ## functions returning short HTML fragments, or transforming HTML fragments
2047 ## which don't belong to other sections
2049 # format line of commit message.
2050 sub format_log_line_html {
2051 my $line = shift;
2053 $line = esc_html($line, -nbsp=>1);
2054 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2055 $cgi->a({-href => href(action=>"object", hash=>$1),
2056 -class => "text"}, $1);
2057 }eg;
2059 return $line;
2062 # format marker of refs pointing to given object
2064 # the destination action is chosen based on object type and current context:
2065 # - for annotated tags, we choose the tag view unless it's the current view
2066 # already, in which case we go to shortlog view
2067 # - for other refs, we keep the current view if we're in history, shortlog or
2068 # log view, and select shortlog otherwise
2069 sub format_ref_marker {
2070 my ($refs, $id) = @_;
2071 my $markers = '';
2073 if (defined $refs->{$id}) {
2074 foreach my $ref (@{$refs->{$id}}) {
2075 # this code exploits the fact that non-lightweight tags are the
2076 # only indirect objects, and that they are the only objects for which
2077 # we want to use tag instead of shortlog as action
2078 my ($type, $name) = qw();
2079 my $indirect = ($ref =~ s/\^\{\}$//);
2080 # e.g. tags/v2.6.11 or heads/next
2081 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2082 $type = $1;
2083 $name = $2;
2084 } else {
2085 $type = "ref";
2086 $name = $ref;
2089 my $class = $type;
2090 $class .= " indirect" if $indirect;
2092 my $dest_action = "shortlog";
2094 if ($indirect) {
2095 $dest_action = "tag" unless $action eq "tag";
2096 } elsif ($action =~ /^(history|(short)?log)$/) {
2097 $dest_action = $action;
2100 my $dest = "";
2101 $dest .= "refs/" unless $ref =~ m!^refs/!;
2102 $dest .= $ref;
2104 my $link = $cgi->a({
2105 -href => href(
2106 action=>$dest_action,
2107 hash=>$dest
2108 )}, $name);
2110 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2111 $link . "</span>";
2115 if ($markers) {
2116 return ' <span class="refs">'. $markers . '</span>';
2117 } else {
2118 return "";
2122 # format, perhaps shortened and with markers, title line
2123 sub format_subject_html {
2124 my ($long, $short, $href, $extra) = @_;
2125 $extra = '' unless defined($extra);
2127 if (length($short) < length($long)) {
2128 $long =~ s/[[:cntrl:]]/?/g;
2129 return $cgi->a({-href => $href, -class => "list subject",
2130 -title => to_utf8($long)},
2131 esc_html($short)) . $extra;
2132 } else {
2133 return $cgi->a({-href => $href, -class => "list subject"},
2134 esc_html($long)) . $extra;
2138 # Rather than recomputing the url for an email multiple times, we cache it
2139 # after the first hit. This gives a visible benefit in views where the avatar
2140 # for the same email is used repeatedly (e.g. shortlog).
2141 # The cache is shared by all avatar engines (currently gravatar only), which
2142 # are free to use it as preferred. Since only one avatar engine is used for any
2143 # given page, there's no risk for cache conflicts.
2144 our %avatar_cache = ();
2146 # Compute the picon url for a given email, by using the picon search service over at
2147 # http://www.cs.indiana.edu/picons/search.html
2148 sub picon_url {
2149 my $email = lc shift;
2150 if (!$avatar_cache{$email}) {
2151 my ($user, $domain) = split('@', $email);
2152 $avatar_cache{$email} =
2153 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2154 "$domain/$user/" .
2155 "users+domains+unknown/up/single";
2157 return $avatar_cache{$email};
2160 # Compute the gravatar url for a given email, if it's not in the cache already.
2161 # Gravatar stores only the part of the URL before the size, since that's the
2162 # one computationally more expensive. This also allows reuse of the cache for
2163 # different sizes (for this particular engine).
2164 sub gravatar_url {
2165 my $email = lc shift;
2166 my $size = shift;
2167 $avatar_cache{$email} ||=
2168 "//www.gravatar.com/avatar/" .
2169 Digest::MD5::md5_hex($email) . "?s=";
2170 return $avatar_cache{$email} . $size;
2173 # Insert an avatar for the given $email at the given $size if the feature
2174 # is enabled.
2175 sub git_get_avatar {
2176 my ($email, %opts) = @_;
2177 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2178 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2179 $opts{-size} ||= 'default';
2180 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2181 my $url = "";
2182 if ($git_avatar eq 'gravatar') {
2183 $url = gravatar_url($email, $size);
2184 } elsif ($git_avatar eq 'picon') {
2185 $url = picon_url($email);
2187 # Other providers can be added by extending the if chain, defining $url
2188 # as needed. If no variant puts something in $url, we assume avatars
2189 # are completely disabled/unavailable.
2190 if ($url) {
2191 return $pre_white .
2192 "<img width=\"$size\" " .
2193 "class=\"avatar\" " .
2194 "src=\"".esc_url($url)."\" " .
2195 "alt=\"\" " .
2196 "/>" . $post_white;
2197 } else {
2198 return "";
2202 sub format_search_author {
2203 my ($author, $searchtype, $displaytext) = @_;
2204 my $have_search = gitweb_check_feature('search');
2206 if ($have_search) {
2207 my $performed = "";
2208 if ($searchtype eq 'author') {
2209 $performed = "authored";
2210 } elsif ($searchtype eq 'committer') {
2211 $performed = "committed";
2214 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2215 searchtext=>$author,
2216 searchtype=>$searchtype), class=>"list",
2217 title=>"Search for commits $performed by $author"},
2218 $displaytext);
2220 } else {
2221 return $displaytext;
2225 # format the author name of the given commit with the given tag
2226 # the author name is chopped and escaped according to the other
2227 # optional parameters (see chop_str).
2228 sub format_author_html {
2229 my $tag = shift;
2230 my $co = shift;
2231 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2232 return "<$tag class=\"author\">" .
2233 format_search_author($co->{'author_name'}, "author",
2234 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2235 $author) .
2236 "</$tag>";
2239 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2240 sub format_git_diff_header_line {
2241 my $line = shift;
2242 my $diffinfo = shift;
2243 my ($from, $to) = @_;
2245 if ($diffinfo->{'nparents'}) {
2246 # combined diff
2247 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2248 if ($to->{'href'}) {
2249 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2250 esc_path($to->{'file'}));
2251 } else { # file was deleted (no href)
2252 $line .= esc_path($to->{'file'});
2254 } else {
2255 # "ordinary" diff
2256 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2257 if ($from->{'href'}) {
2258 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2259 'a/' . esc_path($from->{'file'}));
2260 } else { # file was added (no href)
2261 $line .= 'a/' . esc_path($from->{'file'});
2263 $line .= ' ';
2264 if ($to->{'href'}) {
2265 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2266 'b/' . esc_path($to->{'file'}));
2267 } else { # file was deleted
2268 $line .= 'b/' . esc_path($to->{'file'});
2272 return "<div class=\"diff header\">$line</div>\n";
2275 # format extended diff header line, before patch itself
2276 sub format_extended_diff_header_line {
2277 my $line = shift;
2278 my $diffinfo = shift;
2279 my ($from, $to) = @_;
2281 # match <path>
2282 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2283 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2284 esc_path($from->{'file'}));
2286 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2287 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2288 esc_path($to->{'file'}));
2290 # match single <mode>
2291 if ($line =~ m/\s(\d{6})$/) {
2292 $line .= '<span class="info"> (' .
2293 file_type_long($1) .
2294 ')</span>';
2296 # match <hash>
2297 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2298 # can match only for combined diff
2299 $line = 'index ';
2300 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2301 if ($from->{'href'}[$i]) {
2302 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2303 -class=>"hash"},
2304 substr($diffinfo->{'from_id'}[$i],0,7));
2305 } else {
2306 $line .= '0' x 7;
2308 # separator
2309 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2311 $line .= '..';
2312 if ($to->{'href'}) {
2313 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2314 substr($diffinfo->{'to_id'},0,7));
2315 } else {
2316 $line .= '0' x 7;
2319 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2320 # can match only for ordinary diff
2321 my ($from_link, $to_link);
2322 if ($from->{'href'}) {
2323 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2324 substr($diffinfo->{'from_id'},0,7));
2325 } else {
2326 $from_link = '0' x 7;
2328 if ($to->{'href'}) {
2329 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2330 substr($diffinfo->{'to_id'},0,7));
2331 } else {
2332 $to_link = '0' x 7;
2334 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2335 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2338 return $line . "<br/>\n";
2341 # format from-file/to-file diff header
2342 sub format_diff_from_to_header {
2343 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2344 my $line;
2345 my $result = '';
2347 $line = $from_line;
2348 #assert($line =~ m/^---/) if DEBUG;
2349 # no extra formatting for "^--- /dev/null"
2350 if (! $diffinfo->{'nparents'}) {
2351 # ordinary (single parent) diff
2352 if ($line =~ m!^--- "?a/!) {
2353 if ($from->{'href'}) {
2354 $line = '--- a/' .
2355 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2356 esc_path($from->{'file'}));
2357 } else {
2358 $line = '--- a/' .
2359 esc_path($from->{'file'});
2362 $result .= qq!<div class="diff from_file">$line</div>\n!;
2364 } else {
2365 # combined diff (merge commit)
2366 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2367 if ($from->{'href'}[$i]) {
2368 $line = '--- ' .
2369 $cgi->a({-href=>href(action=>"blobdiff",
2370 hash_parent=>$diffinfo->{'from_id'}[$i],
2371 hash_parent_base=>$parents[$i],
2372 file_parent=>$from->{'file'}[$i],
2373 hash=>$diffinfo->{'to_id'},
2374 hash_base=>$hash,
2375 file_name=>$to->{'file'}),
2376 -class=>"path",
2377 -title=>"diff" . ($i+1)},
2378 $i+1) .
2379 '/' .
2380 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2381 esc_path($from->{'file'}[$i]));
2382 } else {
2383 $line = '--- /dev/null';
2385 $result .= qq!<div class="diff from_file">$line</div>\n!;
2389 $line = $to_line;
2390 #assert($line =~ m/^\+\+\+/) if DEBUG;
2391 # no extra formatting for "^+++ /dev/null"
2392 if ($line =~ m!^\+\+\+ "?b/!) {
2393 if ($to->{'href'}) {
2394 $line = '+++ b/' .
2395 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2396 esc_path($to->{'file'}));
2397 } else {
2398 $line = '+++ b/' .
2399 esc_path($to->{'file'});
2402 $result .= qq!<div class="diff to_file">$line</div>\n!;
2404 return $result;
2407 # create note for patch simplified by combined diff
2408 sub format_diff_cc_simplified {
2409 my ($diffinfo, @parents) = @_;
2410 my $result = '';
2412 $result .= "<div class=\"diff header\">" .
2413 "diff --cc ";
2414 if (!is_deleted($diffinfo)) {
2415 $result .= $cgi->a({-href => href(action=>"blob",
2416 hash_base=>$hash,
2417 hash=>$diffinfo->{'to_id'},
2418 file_name=>$diffinfo->{'to_file'}),
2419 -class => "path"},
2420 esc_path($diffinfo->{'to_file'}));
2421 } else {
2422 $result .= esc_path($diffinfo->{'to_file'});
2424 $result .= "</div>\n" . # class="diff header"
2425 "<div class=\"diff nodifferences\">" .
2426 "Simple merge" .
2427 "</div>\n"; # class="diff nodifferences"
2429 return $result;
2432 sub diff_line_class {
2433 my ($line, $from, $to) = @_;
2435 # ordinary diff
2436 my $num_sign = 1;
2437 # combined diff
2438 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2439 $num_sign = scalar @{$from->{'href'}};
2442 my @diff_line_classifier = (
2443 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2444 { regexp => qr/^\\/, class => "incomplete" },
2445 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2446 # classifier for context must come before classifier add/rem,
2447 # or we would have to use more complicated regexp, for example
2448 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2449 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2450 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2452 for my $clsfy (@diff_line_classifier) {
2453 return $clsfy->{'class'}
2454 if ($line =~ $clsfy->{'regexp'});
2457 # fallback
2458 return "";
2461 # assumes that $from and $to are defined and correctly filled,
2462 # and that $line holds a line of chunk header for unified diff
2463 sub format_unidiff_chunk_header {
2464 my ($line, $from, $to) = @_;
2466 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2467 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2469 $from_lines = 0 unless defined $from_lines;
2470 $to_lines = 0 unless defined $to_lines;
2472 if ($from->{'href'}) {
2473 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2474 -class=>"list"}, $from_text);
2476 if ($to->{'href'}) {
2477 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2478 -class=>"list"}, $to_text);
2480 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2481 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2482 return $line;
2485 # assumes that $from and $to are defined and correctly filled,
2486 # and that $line holds a line of chunk header for combined diff
2487 sub format_cc_diff_chunk_header {
2488 my ($line, $from, $to) = @_;
2490 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2491 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2493 @from_text = split(' ', $ranges);
2494 for (my $i = 0; $i < @from_text; ++$i) {
2495 ($from_start[$i], $from_nlines[$i]) =
2496 (split(',', substr($from_text[$i], 1)), 0);
2499 $to_text = pop @from_text;
2500 $to_start = pop @from_start;
2501 $to_nlines = pop @from_nlines;
2503 $line = "<span class=\"chunk_info\">$prefix ";
2504 for (my $i = 0; $i < @from_text; ++$i) {
2505 if ($from->{'href'}[$i]) {
2506 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2507 -class=>"list"}, $from_text[$i]);
2508 } else {
2509 $line .= $from_text[$i];
2511 $line .= " ";
2513 if ($to->{'href'}) {
2514 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2515 -class=>"list"}, $to_text);
2516 } else {
2517 $line .= $to_text;
2519 $line .= " $prefix</span>" .
2520 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2521 return $line;
2524 # process patch (diff) line (not to be used for diff headers),
2525 # returning HTML-formatted (but not wrapped) line.
2526 # If the line is passed as a reference, it is treated as HTML and not
2527 # esc_html()'ed.
2528 sub format_diff_line {
2529 my ($line, $diff_class, $from, $to) = @_;
2531 if (ref($line)) {
2532 $line = $$line;
2533 } else {
2534 chomp $line;
2535 $line = untabify($line);
2537 if ($from && $to && $line =~ m/^\@{2} /) {
2538 $line = format_unidiff_chunk_header($line, $from, $to);
2539 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2540 $line = format_cc_diff_chunk_header($line, $from, $to);
2541 } else {
2542 $line = esc_html($line, -nbsp=>1);
2546 my $diff_classes = "diff";
2547 $diff_classes .= " $diff_class" if ($diff_class);
2548 $line = "<div class=\"$diff_classes\">$line</div>\n";
2550 return $line;
2553 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2554 # linked. Pass the hash of the tree/commit to snapshot.
2555 sub format_snapshot_links {
2556 my ($hash) = @_;
2557 my $num_fmts = @snapshot_fmts;
2558 if ($num_fmts > 1) {
2559 # A parenthesized list of links bearing format names.
2560 # e.g. "snapshot (_tar.gz_ _zip_)"
2561 return "snapshot (" . join(' ', map
2562 $cgi->a({
2563 -href => href(
2564 action=>"snapshot",
2565 hash=>$hash,
2566 snapshot_format=>$_
2568 }, $known_snapshot_formats{$_}{'display'})
2569 , @snapshot_fmts) . ")";
2570 } elsif ($num_fmts == 1) {
2571 # A single "snapshot" link whose tooltip bears the format name.
2572 # i.e. "_snapshot_"
2573 my ($fmt) = @snapshot_fmts;
2574 return
2575 $cgi->a({
2576 -href => href(
2577 action=>"snapshot",
2578 hash=>$hash,
2579 snapshot_format=>$fmt
2581 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2582 }, "snapshot");
2583 } else { # $num_fmts == 0
2584 return undef;
2588 ## ......................................................................
2589 ## functions returning values to be passed, perhaps after some
2590 ## transformation, to other functions; e.g. returning arguments to href()
2592 # returns hash to be passed to href to generate gitweb URL
2593 # in -title key it returns description of link
2594 sub get_feed_info {
2595 my $format = shift || 'Atom';
2596 my %res = (action => lc($format));
2597 my $matched_ref = 0;
2599 # feed links are possible only for project views
2600 return unless (defined $project);
2601 # some views should link to OPML, or to generic project feed,
2602 # or don't have specific feed yet (so they should use generic)
2603 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2605 my $branch = undef;
2606 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2607 # (fullname) to differentiate from tag links; this also makes
2608 # possible to detect branch links
2609 for my $ref (get_branch_refs()) {
2610 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2611 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2612 $branch = $1;
2613 $matched_ref = $ref;
2614 last;
2617 # find log type for feed description (title)
2618 my $type = 'log';
2619 if (defined $file_name) {
2620 $type = "history of $file_name";
2621 $type .= "/" if ($action eq 'tree');
2622 $type .= " on '$branch'" if (defined $branch);
2623 } else {
2624 $type = "log of $branch" if (defined $branch);
2627 $res{-title} = $type;
2628 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2629 $res{'file_name'} = $file_name;
2631 return %res;
2634 ## ----------------------------------------------------------------------
2635 ## git utility subroutines, invoking git commands
2637 # returns path to the core git executable and the --git-dir parameter as list
2638 sub git_cmd {
2639 $number_of_git_cmds++;
2640 return $GIT, '--git-dir='.$git_dir;
2643 # quote the given arguments for passing them to the shell
2644 # quote_command("command", "arg 1", "arg with ' and ! characters")
2645 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2646 # Try to avoid using this function wherever possible.
2647 sub quote_command {
2648 return join(' ',
2649 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2652 # get HEAD ref of given project as hash
2653 sub git_get_head_hash {
2654 return git_get_full_hash(shift, 'HEAD');
2657 sub git_get_full_hash {
2658 return git_get_hash(@_);
2661 sub git_get_short_hash {
2662 return git_get_hash(@_, '--short=7');
2665 sub git_get_hash {
2666 my ($project, $hash, @options) = @_;
2667 my $o_git_dir = $git_dir;
2668 my $retval = undef;
2669 $git_dir = "$projectroot/$project";
2670 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2671 '--verify', '-q', @options, $hash) {
2672 $retval = <$fd>;
2673 chomp $retval if defined $retval;
2674 close $fd;
2676 if (defined $o_git_dir) {
2677 $git_dir = $o_git_dir;
2679 return $retval;
2682 # get type of given object
2683 sub git_get_type {
2684 my $hash = shift;
2686 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2687 my $type = <$fd>;
2688 close $fd or return;
2689 chomp $type;
2690 return $type;
2693 # repository configuration
2694 our $config_file = '';
2695 our %config;
2697 # store multiple values for single key as anonymous array reference
2698 # single values stored directly in the hash, not as [ <value> ]
2699 sub hash_set_multi {
2700 my ($hash, $key, $value) = @_;
2702 if (!exists $hash->{$key}) {
2703 $hash->{$key} = $value;
2704 } elsif (!ref $hash->{$key}) {
2705 $hash->{$key} = [ $hash->{$key}, $value ];
2706 } else {
2707 push @{$hash->{$key}}, $value;
2711 # return hash of git project configuration
2712 # optionally limited to some section, e.g. 'gitweb'
2713 sub git_parse_project_config {
2714 my $section_regexp = shift;
2715 my %config;
2717 local $/ = "\0";
2719 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2720 or return;
2722 while (my $keyval = <$fh>) {
2723 chomp $keyval;
2724 my ($key, $value) = split(/\n/, $keyval, 2);
2726 hash_set_multi(\%config, $key, $value)
2727 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2729 close $fh;
2731 return %config;
2734 # convert config value to boolean: 'true' or 'false'
2735 # no value, number > 0, 'true' and 'yes' values are true
2736 # rest of values are treated as false (never as error)
2737 sub config_to_bool {
2738 my $val = shift;
2740 return 1 if !defined $val; # section.key
2742 # strip leading and trailing whitespace
2743 $val =~ s/^\s+//;
2744 $val =~ s/\s+$//;
2746 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2747 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2750 # convert config value to simple decimal number
2751 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2752 # to be multiplied by 1024, 1048576, or 1073741824
2753 sub config_to_int {
2754 my $val = shift;
2756 # strip leading and trailing whitespace
2757 $val =~ s/^\s+//;
2758 $val =~ s/\s+$//;
2760 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2761 $unit = lc($unit);
2762 # unknown unit is treated as 1
2763 return $num * ($unit eq 'g' ? 1073741824 :
2764 $unit eq 'm' ? 1048576 :
2765 $unit eq 'k' ? 1024 : 1);
2767 return $val;
2770 # convert config value to array reference, if needed
2771 sub config_to_multi {
2772 my $val = shift;
2774 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2777 sub git_get_project_config {
2778 my ($key, $type) = @_;
2780 return unless defined $git_dir;
2782 # key sanity check
2783 return unless ($key);
2784 # only subsection, if exists, is case sensitive,
2785 # and not lowercased by 'git config -z -l'
2786 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2787 $lo =~ s/_//g;
2788 $key = join(".", lc($hi), $mi, lc($lo));
2789 return if ($lo =~ /\W/ || $hi =~ /\W/);
2790 } else {
2791 $key = lc($key);
2792 $key =~ s/_//g;
2793 return if ($key =~ /\W/);
2795 $key =~ s/^gitweb\.//;
2797 # type sanity check
2798 if (defined $type) {
2799 $type =~ s/^--//;
2800 $type = undef
2801 unless ($type eq 'bool' || $type eq 'int');
2804 # get config
2805 if (!defined $config_file ||
2806 $config_file ne "$git_dir/config") {
2807 %config = git_parse_project_config('gitweb');
2808 $config_file = "$git_dir/config";
2811 # check if config variable (key) exists
2812 return unless exists $config{"gitweb.$key"};
2814 # ensure given type
2815 if (!defined $type) {
2816 return $config{"gitweb.$key"};
2817 } elsif ($type eq 'bool') {
2818 # backward compatibility: 'git config --bool' returns true/false
2819 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2820 } elsif ($type eq 'int') {
2821 return config_to_int($config{"gitweb.$key"});
2823 return $config{"gitweb.$key"};
2826 # get hash of given path at given ref
2827 sub git_get_hash_by_path {
2828 my $base = shift;
2829 my $path = shift || return undef;
2830 my $type = shift;
2832 $path =~ s,/+$,,;
2834 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2835 or die_error(500, "Open git-ls-tree failed");
2836 my $line = <$fd>;
2837 close $fd or return undef;
2839 if (!defined $line) {
2840 # there is no tree or hash given by $path at $base
2841 return undef;
2844 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2845 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2846 if (defined $type && $type ne $2) {
2847 # type doesn't match
2848 return undef;
2850 return $3;
2853 # get path of entry with given hash at given tree-ish (ref)
2854 # used to get 'from' filename for combined diff (merge commit) for renames
2855 sub git_get_path_by_hash {
2856 my $base = shift || return;
2857 my $hash = shift || return;
2859 local $/ = "\0";
2861 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2862 or return undef;
2863 while (my $line = <$fd>) {
2864 chomp $line;
2866 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2867 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2868 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2869 close $fd;
2870 return $1;
2873 close $fd;
2874 return undef;
2877 ## ......................................................................
2878 ## git utility functions, directly accessing git repository
2880 # get the value of config variable either from file named as the variable
2881 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2882 # configuration variable in the repository config file.
2883 sub git_get_file_or_project_config {
2884 my ($path, $name) = @_;
2886 $git_dir = "$projectroot/$path";
2887 open my $fd, '<', "$git_dir/$name"
2888 or return git_get_project_config($name);
2889 my $conf = <$fd>;
2890 close $fd;
2891 if (defined $conf) {
2892 chomp $conf;
2894 return $conf;
2897 sub git_get_project_description {
2898 my $path = shift;
2899 return git_get_file_or_project_config($path, 'description');
2902 sub git_get_project_category {
2903 my $path = shift;
2904 return git_get_file_or_project_config($path, 'category');
2908 # supported formats:
2909 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2910 # - if its contents is a number, use it as tag weight,
2911 # - otherwise add a tag with weight 1
2912 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2913 # the same value multiple times increases tag weight
2914 # * `gitweb.ctag' multi-valued repo config variable
2915 sub git_get_project_ctags {
2916 my $project = shift;
2917 my $ctags = {};
2919 $git_dir = "$projectroot/$project";
2920 if (opendir my $dh, "$git_dir/ctags") {
2921 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2922 foreach my $tagfile (@files) {
2923 open my $ct, '<', $tagfile
2924 or next;
2925 my $val = <$ct>;
2926 chomp $val if $val;
2927 close $ct;
2929 (my $ctag = $tagfile) =~ s#.*/##;
2930 if ($val =~ /^\d+$/) {
2931 $ctags->{$ctag} = $val;
2932 } else {
2933 $ctags->{$ctag} = 1;
2936 closedir $dh;
2938 } elsif (open my $fh, '<', "$git_dir/ctags") {
2939 while (my $line = <$fh>) {
2940 chomp $line;
2941 $ctags->{$line}++ if $line;
2943 close $fh;
2945 } else {
2946 my $taglist = config_to_multi(git_get_project_config('ctag'));
2947 foreach my $tag (@$taglist) {
2948 $ctags->{$tag}++;
2952 return $ctags;
2955 # return hash, where keys are content tags ('ctags'),
2956 # and values are sum of weights of given tag in every project
2957 sub git_gather_all_ctags {
2958 my $projects = shift;
2959 my $ctags = {};
2961 foreach my $p (@$projects) {
2962 foreach my $ct (keys %{$p->{'ctags'}}) {
2963 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2967 return $ctags;
2970 sub git_populate_project_tagcloud {
2971 my ($ctags, $action) = @_;
2973 # First, merge different-cased tags; tags vote on casing
2974 my %ctags_lc;
2975 foreach (keys %$ctags) {
2976 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2977 if (not $ctags_lc{lc $_}->{topcount}
2978 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2979 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2980 $ctags_lc{lc $_}->{topname} = $_;
2984 my $cloud;
2985 my $matched = $input_params{'ctag_filter'};
2986 if (eval { require HTML::TagCloud; 1; }) {
2987 $cloud = HTML::TagCloud->new;
2988 foreach my $ctag (sort keys %ctags_lc) {
2989 # Pad the title with spaces so that the cloud looks
2990 # less crammed.
2991 my $title = esc_html($ctags_lc{$ctag}->{topname});
2992 $title =~ s/ /&nbsp;/g;
2993 $title =~ s/^/&nbsp;/g;
2994 $title =~ s/$/&nbsp;/g;
2995 if (defined $matched && $matched eq $ctag) {
2996 $title = qq(<span class="match">$title</span>);
2998 $cloud->add($title, href(-replay=>1, action=>$action, ctag_filter=>$ctag),
2999 $ctags_lc{$ctag}->{count});
3001 } else {
3002 $cloud = {};
3003 foreach my $ctag (keys %ctags_lc) {
3004 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3005 if (defined $matched && $matched eq $ctag) {
3006 $title = qq(<span class="match">$title</span>);
3008 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3009 $cloud->{$ctag}{ctag} =
3010 $cgi->a({-href=>href(-replay=>1, action=>$action, ctag_filter=>$ctag)}, $title);
3013 return $cloud;
3016 sub git_show_project_tagcloud {
3017 my ($cloud, $count) = @_;
3018 if (ref $cloud eq 'HTML::TagCloud') {
3019 return $cloud->html_and_css($count);
3020 } else {
3021 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3022 return
3023 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3024 join (', ', map {
3025 $cloud->{$_}->{'ctag'}
3026 } splice(@tags, 0, $count)) .
3027 '</div>';
3031 sub git_get_project_url_list {
3032 my $path = shift;
3034 $git_dir = "$projectroot/$path";
3035 open my $fd, '<', "$git_dir/cloneurl"
3036 or return wantarray ?
3037 @{ config_to_multi(git_get_project_config('url')) } :
3038 config_to_multi(git_get_project_config('url'));
3039 my @git_project_url_list = map { chomp; $_ } <$fd>;
3040 close $fd;
3042 return wantarray ? @git_project_url_list : \@git_project_url_list;
3045 sub git_get_projects_list {
3046 my $filter = shift || '';
3047 my $paranoid = shift;
3048 my @list;
3050 if (-d $projects_list) {
3051 # search in directory
3052 my $dir = $projects_list;
3053 # remove the trailing "/"
3054 $dir =~ s!/+$!!;
3055 my $pfxlen = length("$dir");
3056 my $pfxdepth = ($dir =~ tr!/!!);
3057 # when filtering, search only given subdirectory
3058 if ($filter && !$paranoid) {
3059 $dir .= "/$filter";
3060 $dir =~ s!/+$!!;
3063 File::Find::find({
3064 follow_fast => 1, # follow symbolic links
3065 follow_skip => 2, # ignore duplicates
3066 dangling_symlinks => 0, # ignore dangling symlinks, silently
3067 wanted => sub {
3068 # global variables
3069 our $project_maxdepth;
3070 our $projectroot;
3071 # skip project-list toplevel, if we get it.
3072 return if (m!^[/.]$!);
3073 # only directories can be git repositories
3074 return unless (-d $_);
3075 # don't traverse too deep (Find is super slow on os x)
3076 # $project_maxdepth excludes depth of $projectroot
3077 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3078 $File::Find::prune = 1;
3079 return;
3082 my $path = substr($File::Find::name, $pfxlen + 1);
3083 # paranoidly only filter here
3084 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3085 next;
3087 # we check related file in $projectroot
3088 if (check_export_ok("$projectroot/$path")) {
3089 push @list, { path => $path };
3090 $File::Find::prune = 1;
3093 }, "$dir");
3095 } elsif (-f $projects_list) {
3096 # read from file(url-encoded):
3097 # 'git%2Fgit.git Linus+Torvalds'
3098 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3099 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3100 open my $fd, '<', $projects_list or return;
3101 PROJECT:
3102 while (my $line = <$fd>) {
3103 chomp $line;
3104 my ($path, $owner) = split ' ', $line;
3105 $path = unescape($path);
3106 $owner = unescape($owner);
3107 if (!defined $path) {
3108 next;
3110 # if $filter is rpovided, check if $path begins with $filter
3111 if ($filter && $path !~ m!^\Q$filter\E/!) {
3112 next;
3114 if (check_export_ok("$projectroot/$path")) {
3115 my $pr = {
3116 path => $path
3118 if ($owner) {
3119 $pr->{'owner'} = to_utf8($owner);
3121 push @list, $pr;
3124 close $fd;
3126 return @list;
3129 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3130 # as side effects it sets 'forks' field to list of forks for forked projects
3131 sub filter_forks_from_projects_list {
3132 my $projects = shift;
3134 my %trie; # prefix tree of directories (path components)
3135 # generate trie out of those directories that might contain forks
3136 foreach my $pr (@$projects) {
3137 my $path = $pr->{'path'};
3138 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3139 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3140 next unless ($path); # skip '.git' repository: tests, git-instaweb
3141 next unless (-d "$projectroot/$path"); # containing directory exists
3142 $pr->{'forks'} = []; # there can be 0 or more forks of project
3144 # add to trie
3145 my @dirs = split('/', $path);
3146 # walk the trie, until either runs out of components or out of trie
3147 my $ref = \%trie;
3148 while (scalar @dirs &&
3149 exists($ref->{$dirs[0]})) {
3150 $ref = $ref->{shift @dirs};
3152 # create rest of trie structure from rest of components
3153 foreach my $dir (@dirs) {
3154 $ref = $ref->{$dir} = {};
3156 # create end marker, store $pr as a data
3157 $ref->{''} = $pr if (!exists $ref->{''});
3160 # filter out forks, by finding shortest prefix match for paths
3161 my @filtered;
3162 PROJECT:
3163 foreach my $pr (@$projects) {
3164 # trie lookup
3165 my $ref = \%trie;
3166 DIR:
3167 foreach my $dir (split('/', $pr->{'path'})) {
3168 if (exists $ref->{''}) {
3169 # found [shortest] prefix, is a fork - skip it
3170 push @{$ref->{''}{'forks'}}, $pr;
3171 next PROJECT;
3173 if (!exists $ref->{$dir}) {
3174 # not in trie, cannot have prefix, not a fork
3175 push @filtered, $pr;
3176 next PROJECT;
3178 # If the dir is there, we just walk one step down the trie.
3179 $ref = $ref->{$dir};
3181 # we ran out of trie
3182 # (shouldn't happen: it's either no match, or end marker)
3183 push @filtered, $pr;
3186 return @filtered;
3189 # note: fill_project_list_info must be run first,
3190 # for 'descr_long' and 'ctags' to be filled
3191 sub search_projects_list {
3192 my ($projlist, %opts) = @_;
3193 my $tagfilter = $opts{'tagfilter'};
3194 my $search_re = $opts{'search_regexp'};
3196 return @$projlist
3197 unless ($tagfilter || $search_re);
3199 # searching projects require filling to be run before it;
3200 fill_project_list_info($projlist,
3201 $tagfilter ? 'ctags' : (),
3202 $search_re ? ('path', 'descr') : ());
3203 my @projects;
3204 PROJECT:
3205 foreach my $pr (@$projlist) {
3207 if ($tagfilter) {
3208 next unless ref($pr->{'ctags'}) eq 'HASH';
3209 next unless
3210 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3213 if ($search_re) {
3214 next unless
3215 $pr->{'path'} =~ /$search_re/ ||
3216 $pr->{'descr_long'} =~ /$search_re/;
3219 push @projects, $pr;
3222 return @projects;
3225 our $gitweb_project_owner = undef;
3226 sub git_get_project_list_from_file {
3228 return if (defined $gitweb_project_owner);
3230 $gitweb_project_owner = {};
3231 # read from file (url-encoded):
3232 # 'git%2Fgit.git Linus+Torvalds'
3233 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3234 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3235 if (-f $projects_list) {
3236 open(my $fd, '<', $projects_list);
3237 while (my $line = <$fd>) {
3238 chomp $line;
3239 my ($pr, $ow) = split ' ', $line;
3240 $pr = unescape($pr);
3241 $ow = unescape($ow);
3242 $gitweb_project_owner->{$pr} = to_utf8($ow);
3244 close $fd;
3248 sub git_get_project_owner {
3249 my $project = shift;
3250 my $owner;
3252 return undef unless $project;
3253 $git_dir = "$projectroot/$project";
3255 if (!defined $gitweb_project_owner) {
3256 git_get_project_list_from_file();
3259 if (exists $gitweb_project_owner->{$project}) {
3260 $owner = $gitweb_project_owner->{$project};
3262 if (!defined $owner){
3263 $owner = git_get_project_config('owner');
3265 if (!defined $owner) {
3266 $owner = get_file_owner("$git_dir");
3269 return $owner;
3272 sub git_get_last_activity {
3273 my ($path) = @_;
3274 my $fd;
3276 $git_dir = "$projectroot/$path";
3277 open($fd, "-|", git_cmd(), 'for-each-ref',
3278 '--format=%(committer)',
3279 '--sort=-committerdate',
3280 '--count=1',
3281 map { "refs/$_" } get_branch_refs ()) or return;
3282 my $most_recent = <$fd>;
3283 close $fd or return;
3284 if (defined $most_recent &&
3285 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3286 my $timestamp = $1;
3287 my $age = time - $timestamp;
3288 return ($age, age_string($age));
3290 return (undef, undef);
3293 # Implementation note: when a single remote is wanted, we cannot use 'git
3294 # remote show -n' because that command always work (assuming it's a remote URL
3295 # if it's not defined), and we cannot use 'git remote show' because that would
3296 # try to make a network roundtrip. So the only way to find if that particular
3297 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3298 # and when we find what we want.
3299 sub git_get_remotes_list {
3300 my $wanted = shift;
3301 my %remotes = ();
3303 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3304 return unless $fd;
3305 while (my $remote = <$fd>) {
3306 chomp $remote;
3307 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3308 next if $wanted and not $remote eq $wanted;
3309 my ($url, $key) = ($1, $2);
3311 $remotes{$remote} ||= { 'heads' => () };
3312 $remotes{$remote}{$key} = $url;
3314 close $fd or return;
3315 return wantarray ? %remotes : \%remotes;
3318 # Takes a hash of remotes as first parameter and fills it by adding the
3319 # available remote heads for each of the indicated remotes.
3320 sub fill_remote_heads {
3321 my $remotes = shift;
3322 my @heads = map { "remotes/$_" } keys %$remotes;
3323 my @remoteheads = git_get_heads_list(undef, @heads);
3324 foreach my $remote (keys %$remotes) {
3325 $remotes->{$remote}{'heads'} = [ grep {
3326 $_->{'name'} =~ s!^$remote/!!
3327 } @remoteheads ];
3331 sub git_get_references {
3332 my $type = shift || "";
3333 my %refs;
3334 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3335 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3336 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3337 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3338 or return;
3340 while (my $line = <$fd>) {
3341 chomp $line;
3342 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3343 if (defined $refs{$1}) {
3344 push @{$refs{$1}}, $2;
3345 } else {
3346 $refs{$1} = [ $2 ];
3350 close $fd or return;
3351 return \%refs;
3354 sub git_get_rev_name_tags {
3355 my $hash = shift || return undef;
3357 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3358 or return;
3359 my $name_rev = <$fd>;
3360 close $fd;
3362 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3363 return $1;
3364 } else {
3365 # catches also '$hash undefined' output
3366 return undef;
3370 ## ----------------------------------------------------------------------
3371 ## parse to hash functions
3373 sub parse_date {
3374 my $epoch = shift;
3375 my $tz = shift || "-0000";
3377 my %date;
3378 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3379 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3380 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3381 $date{'hour'} = $hour;
3382 $date{'minute'} = $min;
3383 $date{'mday'} = $mday;
3384 $date{'day'} = $days[$wday];
3385 $date{'month'} = $months[$mon];
3386 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3387 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3388 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3389 $mday, $months[$mon], $hour ,$min;
3390 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3391 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3393 my ($tz_sign, $tz_hour, $tz_min) =
3394 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3395 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3396 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3397 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3398 $date{'hour_local'} = $hour;
3399 $date{'minute_local'} = $min;
3400 $date{'tz_local'} = $tz;
3401 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3402 1900+$year, $mon+1, $mday,
3403 $hour, $min, $sec, $tz);
3404 return %date;
3407 sub parse_tag {
3408 my $tag_id = shift;
3409 my %tag;
3410 my @comment;
3412 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3413 $tag{'id'} = $tag_id;
3414 while (my $line = <$fd>) {
3415 chomp $line;
3416 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3417 $tag{'object'} = $1;
3418 } elsif ($line =~ m/^type (.+)$/) {
3419 $tag{'type'} = $1;
3420 } elsif ($line =~ m/^tag (.+)$/) {
3421 $tag{'name'} = $1;
3422 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3423 $tag{'author'} = $1;
3424 $tag{'author_epoch'} = $2;
3425 $tag{'author_tz'} = $3;
3426 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3427 $tag{'author_name'} = $1;
3428 $tag{'author_email'} = $2;
3429 } else {
3430 $tag{'author_name'} = $tag{'author'};
3432 } elsif ($line =~ m/--BEGIN/) {
3433 push @comment, $line;
3434 last;
3435 } elsif ($line eq "") {
3436 last;
3439 push @comment, <$fd>;
3440 $tag{'comment'} = \@comment;
3441 close $fd or return;
3442 if (!defined $tag{'name'}) {
3443 return
3445 return %tag
3448 sub parse_commit_text {
3449 my ($commit_text, $withparents) = @_;
3450 my @commit_lines = split '\n', $commit_text;
3451 my %co;
3453 pop @commit_lines; # Remove '\0'
3455 if (! @commit_lines) {
3456 return;
3459 my $header = shift @commit_lines;
3460 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3461 return;
3463 ($co{'id'}, my @parents) = split ' ', $header;
3464 while (my $line = shift @commit_lines) {
3465 last if $line eq "\n";
3466 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3467 $co{'tree'} = $1;
3468 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3469 push @parents, $1;
3470 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3471 $co{'author'} = to_utf8($1);
3472 $co{'author_epoch'} = $2;
3473 $co{'author_tz'} = $3;
3474 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3475 $co{'author_name'} = $1;
3476 $co{'author_email'} = $2;
3477 } else {
3478 $co{'author_name'} = $co{'author'};
3480 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3481 $co{'committer'} = to_utf8($1);
3482 $co{'committer_epoch'} = $2;
3483 $co{'committer_tz'} = $3;
3484 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3485 $co{'committer_name'} = $1;
3486 $co{'committer_email'} = $2;
3487 } else {
3488 $co{'committer_name'} = $co{'committer'};
3492 if (!defined $co{'tree'}) {
3493 return;
3495 $co{'parents'} = \@parents;
3496 $co{'parent'} = $parents[0];
3498 foreach my $title (@commit_lines) {
3499 $title =~ s/^ //;
3500 if ($title ne "") {
3501 $co{'title'} = chop_str($title, 80, 5);
3502 # remove leading stuff of merges to make the interesting part visible
3503 if (length($title) > 50) {
3504 $title =~ s/^Automatic //;
3505 $title =~ s/^merge (of|with) /Merge ... /i;
3506 if (length($title) > 50) {
3507 $title =~ s/(http|rsync):\/\///;
3509 if (length($title) > 50) {
3510 $title =~ s/(master|www|rsync)\.//;
3512 if (length($title) > 50) {
3513 $title =~ s/kernel.org:?//;
3515 if (length($title) > 50) {
3516 $title =~ s/\/pub\/scm//;
3519 $co{'title_short'} = chop_str($title, 50, 5);
3520 last;
3523 if (! defined $co{'title'} || $co{'title'} eq "") {
3524 $co{'title'} = $co{'title_short'} = '(no commit message)';
3526 # remove added spaces
3527 foreach my $line (@commit_lines) {
3528 $line =~ s/^ //;
3530 $co{'comment'} = \@commit_lines;
3532 my $age = time - $co{'committer_epoch'};
3533 $co{'age'} = $age;
3534 $co{'age_string'} = age_string($age);
3535 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3536 if ($age > 60*60*24*7*2) {
3537 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3538 $co{'age_string_age'} = $co{'age_string'};
3539 } else {
3540 $co{'age_string_date'} = $co{'age_string'};
3541 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3543 return %co;
3546 sub parse_commit {
3547 my ($commit_id) = @_;
3548 my %co;
3550 local $/ = "\0";
3552 open my $fd, "-|", git_cmd(), "rev-list",
3553 "--parents",
3554 "--header",
3555 "--max-count=1",
3556 $commit_id,
3557 "--",
3558 or die_error(500, "Open git-rev-list failed");
3559 %co = parse_commit_text(<$fd>, 1);
3560 close $fd;
3562 return %co;
3565 sub parse_commits {
3566 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3567 my @cos;
3569 $maxcount ||= 1;
3570 $skip ||= 0;
3572 local $/ = "\0";
3574 open my $fd, "-|", git_cmd(), "rev-list",
3575 "--header",
3576 @args,
3577 ("--max-count=" . $maxcount),
3578 ("--skip=" . $skip),
3579 @extra_options,
3580 $commit_id,
3581 "--",
3582 ($filename ? ($filename) : ())
3583 or die_error(500, "Open git-rev-list failed");
3584 while (my $line = <$fd>) {
3585 my %co = parse_commit_text($line);
3586 push @cos, \%co;
3588 close $fd;
3590 return wantarray ? @cos : \@cos;
3593 # parse line of git-diff-tree "raw" output
3594 sub parse_difftree_raw_line {
3595 my $line = shift;
3596 my %res;
3598 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3599 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3600 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3601 $res{'from_mode'} = $1;
3602 $res{'to_mode'} = $2;
3603 $res{'from_id'} = $3;
3604 $res{'to_id'} = $4;
3605 $res{'status'} = $5;
3606 $res{'similarity'} = $6;
3607 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3608 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3609 } else {
3610 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3613 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3614 # combined diff (for merge commit)
3615 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3616 $res{'nparents'} = length($1);
3617 $res{'from_mode'} = [ split(' ', $2) ];
3618 $res{'to_mode'} = pop @{$res{'from_mode'}};
3619 $res{'from_id'} = [ split(' ', $3) ];
3620 $res{'to_id'} = pop @{$res{'from_id'}};
3621 $res{'status'} = [ split('', $4) ];
3622 $res{'to_file'} = unquote($5);
3624 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3625 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3626 $res{'commit'} = $1;
3629 return wantarray ? %res : \%res;
3632 # wrapper: return parsed line of git-diff-tree "raw" output
3633 # (the argument might be raw line, or parsed info)
3634 sub parsed_difftree_line {
3635 my $line_or_ref = shift;
3637 if (ref($line_or_ref) eq "HASH") {
3638 # pre-parsed (or generated by hand)
3639 return $line_or_ref;
3640 } else {
3641 return parse_difftree_raw_line($line_or_ref);
3645 # parse line of git-ls-tree output
3646 sub parse_ls_tree_line {
3647 my $line = shift;
3648 my %opts = @_;
3649 my %res;
3651 if ($opts{'-l'}) {
3652 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3653 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3655 $res{'mode'} = $1;
3656 $res{'type'} = $2;
3657 $res{'hash'} = $3;
3658 $res{'size'} = $4;
3659 if ($opts{'-z'}) {
3660 $res{'name'} = $5;
3661 } else {
3662 $res{'name'} = unquote($5);
3664 } else {
3665 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3666 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3668 $res{'mode'} = $1;
3669 $res{'type'} = $2;
3670 $res{'hash'} = $3;
3671 if ($opts{'-z'}) {
3672 $res{'name'} = $4;
3673 } else {
3674 $res{'name'} = unquote($4);
3678 return wantarray ? %res : \%res;
3681 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3682 sub parse_from_to_diffinfo {
3683 my ($diffinfo, $from, $to, @parents) = @_;
3685 if ($diffinfo->{'nparents'}) {
3686 # combined diff
3687 $from->{'file'} = [];
3688 $from->{'href'} = [];
3689 fill_from_file_info($diffinfo, @parents)
3690 unless exists $diffinfo->{'from_file'};
3691 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3692 $from->{'file'}[$i] =
3693 defined $diffinfo->{'from_file'}[$i] ?
3694 $diffinfo->{'from_file'}[$i] :
3695 $diffinfo->{'to_file'};
3696 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3697 $from->{'href'}[$i] = href(action=>"blob",
3698 hash_base=>$parents[$i],
3699 hash=>$diffinfo->{'from_id'}[$i],
3700 file_name=>$from->{'file'}[$i]);
3701 } else {
3702 $from->{'href'}[$i] = undef;
3705 } else {
3706 # ordinary (not combined) diff
3707 $from->{'file'} = $diffinfo->{'from_file'};
3708 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3709 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3710 hash=>$diffinfo->{'from_id'},
3711 file_name=>$from->{'file'});
3712 } else {
3713 delete $from->{'href'};
3717 $to->{'file'} = $diffinfo->{'to_file'};
3718 if (!is_deleted($diffinfo)) { # file exists in result
3719 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3720 hash=>$diffinfo->{'to_id'},
3721 file_name=>$to->{'file'});
3722 } else {
3723 delete $to->{'href'};
3727 ## ......................................................................
3728 ## parse to array of hashes functions
3730 sub git_get_heads_list {
3731 my ($limit, @classes) = @_;
3732 @classes = get_branch_refs() unless @classes;
3733 my @patterns = map { "refs/$_" } @classes;
3734 my @headslist;
3736 open my $fd, '-|', git_cmd(), 'for-each-ref',
3737 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3738 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3739 @patterns
3740 or return;
3741 while (my $line = <$fd>) {
3742 my %ref_item;
3744 chomp $line;
3745 my ($refinfo, $committerinfo) = split(/\0/, $line);
3746 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3747 my ($committer, $epoch, $tz) =
3748 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3749 $ref_item{'fullname'} = $name;
3750 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3751 $name =~ s!^refs/($strip_refs|remotes)/!!;
3752 $ref_item{'name'} = $name;
3753 # for refs neither in 'heads' nor 'remotes' we want to
3754 # show their ref dir
3755 my $ref_dir = (defined $1) ? $1 : '';
3756 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3757 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3760 $ref_item{'id'} = $hash;
3761 $ref_item{'title'} = $title || '(no commit message)';
3762 $ref_item{'epoch'} = $epoch;
3763 if ($epoch) {
3764 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3765 } else {
3766 $ref_item{'age'} = "unknown";
3769 push @headslist, \%ref_item;
3771 close $fd;
3773 return wantarray ? @headslist : \@headslist;
3776 sub git_get_tags_list {
3777 my $limit = shift;
3778 my @tagslist;
3780 open my $fd, '-|', git_cmd(), 'for-each-ref',
3781 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3782 '--format=%(objectname) %(objecttype) %(refname) '.
3783 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3784 'refs/tags'
3785 or return;
3786 while (my $line = <$fd>) {
3787 my %ref_item;
3789 chomp $line;
3790 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3791 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3792 my ($creator, $epoch, $tz) =
3793 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3794 $ref_item{'fullname'} = $name;
3795 $name =~ s!^refs/tags/!!;
3797 $ref_item{'type'} = $type;
3798 $ref_item{'id'} = $id;
3799 $ref_item{'name'} = $name;
3800 if ($type eq "tag") {
3801 $ref_item{'subject'} = $title;
3802 $ref_item{'reftype'} = $reftype;
3803 $ref_item{'refid'} = $refid;
3804 } else {
3805 $ref_item{'reftype'} = $type;
3806 $ref_item{'refid'} = $id;
3809 if ($type eq "tag" || $type eq "commit") {
3810 $ref_item{'epoch'} = $epoch;
3811 if ($epoch) {
3812 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3813 } else {
3814 $ref_item{'age'} = "unknown";
3818 push @tagslist, \%ref_item;
3820 close $fd;
3822 return wantarray ? @tagslist : \@tagslist;
3825 ## ----------------------------------------------------------------------
3826 ## filesystem-related functions
3828 sub get_file_owner {
3829 my $path = shift;
3831 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3832 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3833 if (!defined $gcos) {
3834 return undef;
3836 my $owner = $gcos;
3837 $owner =~ s/[,;].*$//;
3838 return to_utf8($owner);
3841 # assume that file exists
3842 sub insert_file {
3843 my $filename = shift;
3845 open my $fd, '<', $filename;
3846 print map { to_utf8($_) } <$fd>;
3847 close $fd;
3850 ## ......................................................................
3851 ## mimetype related functions
3853 sub mimetype_guess_file {
3854 my $filename = shift;
3855 my $mimemap = shift;
3856 -r $mimemap or return undef;
3858 my %mimemap;
3859 open(my $mh, '<', $mimemap) or return undef;
3860 while (<$mh>) {
3861 next if m/^#/; # skip comments
3862 my ($mimetype, @exts) = split(/\s+/);
3863 foreach my $ext (@exts) {
3864 $mimemap{$ext} = $mimetype;
3867 close($mh);
3869 $filename =~ /\.([^.]*)$/;
3870 return $mimemap{$1};
3873 sub mimetype_guess {
3874 my $filename = shift;
3875 my $mime;
3876 $filename =~ /\./ or return undef;
3878 if ($mimetypes_file) {
3879 my $file = $mimetypes_file;
3880 if ($file !~ m!^/!) { # if it is relative path
3881 # it is relative to project
3882 $file = "$projectroot/$project/$file";
3884 $mime = mimetype_guess_file($filename, $file);
3886 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3887 return $mime;
3890 sub blob_mimetype {
3891 my $fd = shift;
3892 my $filename = shift;
3894 if ($filename) {
3895 my $mime = mimetype_guess($filename);
3896 $mime and return $mime;
3899 # just in case
3900 return $default_blob_plain_mimetype unless $fd;
3902 if (-T $fd) {
3903 return 'text/plain';
3904 } elsif (! $filename) {
3905 return 'application/octet-stream';
3906 } elsif ($filename =~ m/\.png$/i) {
3907 return 'image/png';
3908 } elsif ($filename =~ m/\.gif$/i) {
3909 return 'image/gif';
3910 } elsif ($filename =~ m/\.jpe?g$/i) {
3911 return 'image/jpeg';
3912 } else {
3913 return 'application/octet-stream';
3917 sub blob_contenttype {
3918 my ($fd, $file_name, $type) = @_;
3920 $type ||= blob_mimetype($fd, $file_name);
3921 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3922 $type .= "; charset=$default_text_plain_charset";
3925 return $type;
3928 # guess file syntax for syntax highlighting; return undef if no highlighting
3929 # the name of syntax can (in the future) depend on syntax highlighter used
3930 sub guess_file_syntax {
3931 my ($highlight, $mimetype, $file_name) = @_;
3932 return undef unless ($highlight && defined $file_name);
3933 my $basename = basename($file_name, '.in');
3934 return $highlight_basename{$basename}
3935 if exists $highlight_basename{$basename};
3937 $basename =~ /\.([^.]*)$/;
3938 my $ext = $1 or return undef;
3939 return $highlight_ext{$ext}
3940 if exists $highlight_ext{$ext};
3942 return undef;
3945 # run highlighter and return FD of its output,
3946 # or return original FD if no highlighting
3947 sub run_highlighter {
3948 my ($fd, $highlight, $syntax) = @_;
3949 return $fd unless ($highlight && defined $syntax);
3951 close $fd;
3952 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3953 quote_command($highlight_bin).
3954 " --replace-tabs=8 --fragment --syntax $syntax |"
3955 or die_error(500, "Couldn't open file or run syntax highlighter");
3956 return $fd;
3959 ## ======================================================================
3960 ## functions printing HTML: header, footer, error page
3962 sub get_page_title {
3963 my $title = to_utf8($site_name);
3965 unless (defined $project) {
3966 if (defined $project_filter) {
3967 $title .= " - projects in '" . esc_path($project_filter) . "'";
3969 return $title;
3971 $title .= " - " . to_utf8($project);
3973 return $title unless (defined $action);
3974 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3976 return $title unless (defined $file_name);
3977 $title .= " - " . esc_path($file_name);
3978 if ($action eq "tree" && $file_name !~ m|/$|) {
3979 $title .= "/";
3982 return $title;
3985 sub get_content_type_html {
3986 # require explicit support from the UA if we are to send the page as
3987 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3988 # we have to do this because MSIE sometimes globs '*/*', pretending to
3989 # support xhtml+xml but choking when it gets what it asked for.
3990 if (defined $cgi->http('HTTP_ACCEPT') &&
3991 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3992 $cgi->Accept('application/xhtml+xml') != 0) {
3993 return 'application/xhtml+xml';
3994 } else {
3995 return 'text/html';
3999 sub print_feed_meta {
4000 if (defined $project) {
4001 my %href_params = get_feed_info();
4002 if (!exists $href_params{'-title'}) {
4003 $href_params{'-title'} = 'log';
4006 foreach my $format (qw(RSS Atom)) {
4007 my $type = lc($format);
4008 my %link_attr = (
4009 '-rel' => 'alternate',
4010 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4011 '-type' => "application/$type+xml"
4014 $href_params{'extra_options'} = undef;
4015 $href_params{'action'} = $type;
4016 $link_attr{'-href'} = href(%href_params);
4017 print "<link ".
4018 "rel=\"$link_attr{'-rel'}\" ".
4019 "title=\"$link_attr{'-title'}\" ".
4020 "href=\"$link_attr{'-href'}\" ".
4021 "type=\"$link_attr{'-type'}\" ".
4022 "/>\n";
4024 $href_params{'extra_options'} = '--no-merges';
4025 $link_attr{'-href'} = href(%href_params);
4026 $link_attr{'-title'} .= ' (no merges)';
4027 print "<link ".
4028 "rel=\"$link_attr{'-rel'}\" ".
4029 "title=\"$link_attr{'-title'}\" ".
4030 "href=\"$link_attr{'-href'}\" ".
4031 "type=\"$link_attr{'-type'}\" ".
4032 "/>\n";
4035 } else {
4036 printf('<link rel="alternate" title="%s projects list" '.
4037 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4038 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4039 printf('<link rel="alternate" title="%s projects feeds" '.
4040 'href="%s" type="text/x-opml" />'."\n",
4041 esc_attr($site_name), href(project=>undef, action=>"opml"));
4045 sub print_header_links {
4046 my $status = shift;
4048 # print out each stylesheet that exist, providing backwards capability
4049 # for those people who defined $stylesheet in a config file
4050 if (defined $stylesheet) {
4051 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4052 } else {
4053 foreach my $stylesheet (@stylesheets) {
4054 next unless $stylesheet;
4055 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4058 print_feed_meta()
4059 if ($status eq '200 OK');
4060 if (defined $favicon) {
4061 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4065 sub print_nav_breadcrumbs_path {
4066 my $dirprefix = undef;
4067 while (my $part = shift) {
4068 $dirprefix .= "/" if defined $dirprefix;
4069 $dirprefix .= $part;
4070 print $cgi->a({-href => href(project => undef,
4071 project_filter => $dirprefix,
4072 action => "project_list")},
4073 esc_html($part)) . " / ";
4077 sub print_nav_breadcrumbs {
4078 my %opts = @_;
4080 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4081 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4083 if (defined $project) {
4084 my @dirname = split '/', $project;
4085 my $projectbasename = pop @dirname;
4086 print_nav_breadcrumbs_path(@dirname);
4087 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4088 if (defined $action) {
4089 my $action_print = $action ;
4090 if (defined $opts{-action_extra}) {
4091 $action_print = $cgi->a({-href => href(action=>$action)},
4092 $action);
4094 print " / $action_print";
4096 if (defined $opts{-action_extra}) {
4097 print " / $opts{-action_extra}";
4099 print "\n";
4100 } elsif (defined $project_filter) {
4101 print_nav_breadcrumbs_path(split '/', $project_filter);
4105 sub print_search_form {
4106 if (!defined $searchtext) {
4107 $searchtext = "";
4109 my $search_hash;
4110 if (defined $hash_base) {
4111 $search_hash = $hash_base;
4112 } elsif (defined $hash) {
4113 $search_hash = $hash;
4114 } else {
4115 $search_hash = "HEAD";
4117 my $action = $my_uri;
4118 my $use_pathinfo = gitweb_check_feature('pathinfo');
4119 if ($use_pathinfo) {
4120 $action .= "/".esc_url($project);
4122 print $cgi->start_form(-method => "get", -action => $action) .
4123 "<div class=\"search\">\n" .
4124 (!$use_pathinfo &&
4125 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4126 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4127 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4128 $cgi->popup_menu(-name => 'st', -default => 'commit',
4129 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4130 " " . $cgi->a({-href => href(action=>"search_help"),
4131 -title => "search help" }, "?") . " search:\n",
4132 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4133 "<span title=\"Extended regular expression\">" .
4134 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4135 -checked => $search_use_regexp) .
4136 "</span>" .
4137 "</div>" .
4138 $cgi->end_form() . "\n";
4141 sub git_header_html {
4142 my $status = shift || "200 OK";
4143 my $expires = shift;
4144 my %opts = @_;
4146 my $title = get_page_title();
4147 my $content_type = get_content_type_html();
4148 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4149 -status=> $status, -expires => $expires)
4150 unless ($opts{'-no_http_header'});
4151 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4152 print <<EOF;
4153 <?xml version="1.0" encoding="utf-8"?>
4154 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4155 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4156 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4157 <!-- git core binaries version $git_version -->
4158 <head>
4159 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4160 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4161 <meta name="robots" content="index, nofollow"/>
4162 <title>$title</title>
4164 # the stylesheet, favicon etc urls won't work correctly with path_info
4165 # unless we set the appropriate base URL
4166 if ($ENV{'PATH_INFO'}) {
4167 print "<base href=\"".esc_url($base_url)."\" />\n";
4169 print_header_links($status);
4171 if (defined $site_html_head_string) {
4172 print to_utf8($site_html_head_string);
4175 print "</head>\n" .
4176 "<body>\n";
4178 if (defined $site_header && -f $site_header) {
4179 insert_file($site_header);
4182 print "<div class=\"page_header\">\n";
4183 if (defined $logo) {
4184 print $cgi->a({-href => esc_url($logo_url),
4185 -title => $logo_label},
4186 $cgi->img({-src => esc_url($logo),
4187 -width => 72, -height => 27,
4188 -alt => "git",
4189 -class => "logo"}));
4191 print_nav_breadcrumbs(%opts);
4192 print "</div>\n";
4194 my $have_search = gitweb_check_feature('search');
4195 if (defined $project && $have_search) {
4196 print_search_form();
4200 sub git_footer_html {
4201 my $feed_class = 'rss_logo';
4203 print "<div class=\"page_footer\">\n";
4204 if (defined $project) {
4205 my $descr = git_get_project_description($project);
4206 if (defined $descr) {
4207 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4210 my %href_params = get_feed_info();
4211 if (!%href_params) {
4212 $feed_class .= ' generic';
4214 $href_params{'-title'} ||= 'log';
4216 foreach my $format (qw(RSS Atom)) {
4217 $href_params{'action'} = lc($format);
4218 print $cgi->a({-href => href(%href_params),
4219 -title => "$href_params{'-title'} $format feed",
4220 -class => $feed_class}, $format)."\n";
4223 } else {
4224 print $cgi->a({-href => href(project=>undef, action=>"opml",
4225 project_filter => $project_filter),
4226 -class => $feed_class}, "OPML") . " ";
4227 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4228 project_filter => $project_filter),
4229 -class => $feed_class}, "TXT") . "\n";
4231 print "</div>\n"; # class="page_footer"
4233 if (defined $t0 && gitweb_check_feature('timed')) {
4234 print "<div id=\"generating_info\">\n";
4235 print 'This page took '.
4236 '<span id="generating_time" class="time_span">'.
4237 tv_interval($t0, [ gettimeofday() ]).
4238 ' seconds </span>'.
4239 ' and '.
4240 '<span id="generating_cmd">'.
4241 $number_of_git_cmds.
4242 '</span> git commands '.
4243 " to generate.\n";
4244 print "</div>\n"; # class="page_footer"
4247 if (defined $site_footer && -f $site_footer) {
4248 insert_file($site_footer);
4251 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4252 if (defined $action &&
4253 $action eq 'blame_incremental') {
4254 print qq!<script type="text/javascript">\n!.
4255 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4256 qq! "!. href() .qq!");\n!.
4257 qq!</script>\n!;
4258 } else {
4259 my ($jstimezone, $tz_cookie, $datetime_class) =
4260 gitweb_get_feature('javascript-timezone');
4262 print qq!<script type="text/javascript">\n!.
4263 qq!window.onload = function () {\n!;
4264 if (gitweb_check_feature('javascript-actions')) {
4265 print qq! fixLinks();\n!;
4267 if ($jstimezone && $tz_cookie && $datetime_class) {
4268 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4269 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4271 print qq!};\n!.
4272 qq!</script>\n!;
4275 print "</body>\n" .
4276 "</html>";
4279 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4280 # Example: die_error(404, 'Hash not found')
4281 # By convention, use the following status codes (as defined in RFC 2616):
4282 # 400: Invalid or missing CGI parameters, or
4283 # requested object exists but has wrong type.
4284 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4285 # this server or project.
4286 # 404: Requested object/revision/project doesn't exist.
4287 # 500: The server isn't configured properly, or
4288 # an internal error occurred (e.g. failed assertions caused by bugs), or
4289 # an unknown error occurred (e.g. the git binary died unexpectedly).
4290 # 503: The server is currently unavailable (because it is overloaded,
4291 # or down for maintenance). Generally, this is a temporary state.
4292 sub die_error {
4293 my $status = shift || 500;
4294 my $error = esc_html(shift) || "Internal Server Error";
4295 my $extra = shift;
4296 my %opts = @_;
4298 my %http_responses = (
4299 400 => '400 Bad Request',
4300 403 => '403 Forbidden',
4301 404 => '404 Not Found',
4302 500 => '500 Internal Server Error',
4303 503 => '503 Service Unavailable',
4305 git_header_html($http_responses{$status}, undef, %opts);
4306 print <<EOF;
4307 <div class="page_body">
4308 <br /><br />
4309 $status - $error
4310 <br />
4312 if (defined $extra) {
4313 print "<hr />\n" .
4314 "$extra\n";
4316 print "</div>\n";
4318 git_footer_html();
4319 goto DONE_GITWEB
4320 unless ($opts{'-error_handler'});
4323 ## ----------------------------------------------------------------------
4324 ## functions printing or outputting HTML: navigation
4326 sub git_print_page_nav {
4327 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4328 $extra = '' if !defined $extra; # pager or formats
4330 my @navs = qw(summary shortlog log commit commitdiff tree);
4331 if ($suppress) {
4332 @navs = grep { $_ ne $suppress } @navs;
4335 my %arg = map { $_ => {action=>$_} } @navs;
4336 if (defined $head) {
4337 for (qw(commit commitdiff)) {
4338 $arg{$_}{'hash'} = $head;
4340 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4341 for (qw(shortlog log)) {
4342 $arg{$_}{'hash'} = $head;
4347 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4348 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4350 my @actions = gitweb_get_feature('actions');
4351 my %repl = (
4352 '%' => '%',
4353 'n' => $project, # project name
4354 'f' => $git_dir, # project path within filesystem
4355 'h' => $treehead || '', # current hash ('h' parameter)
4356 'b' => $treebase || '', # hash base ('hb' parameter)
4358 while (@actions) {
4359 my ($label, $link, $pos) = splice(@actions,0,3);
4360 # insert
4361 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4362 # munch munch
4363 $link =~ s/%([%nfhb])/$repl{$1}/g;
4364 $arg{$label}{'_href'} = $link;
4367 print "<div class=\"page_nav\">\n" .
4368 (join " | ",
4369 map { $_ eq $current ?
4370 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4371 } @navs);
4372 print "<br/>\n$extra<br/>\n" .
4373 "</div>\n";
4376 # returns a submenu for the nagivation of the refs views (tags, heads,
4377 # remotes) with the current view disabled and the remotes view only
4378 # available if the feature is enabled
4379 sub format_ref_views {
4380 my ($current) = @_;
4381 my @ref_views = qw{tags heads};
4382 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4383 return join " | ", map {
4384 $_ eq $current ? $_ :
4385 $cgi->a({-href => href(action=>$_)}, $_)
4386 } @ref_views
4389 sub format_paging_nav {
4390 my ($action, $page, $has_next_link) = @_;
4391 my $paging_nav;
4394 if ($page > 0) {
4395 $paging_nav .=
4396 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4397 " &sdot; " .
4398 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4399 -accesskey => "p", -title => "Alt-p"}, "prev");
4400 } else {
4401 $paging_nav .= "first &sdot; prev";
4404 if ($has_next_link) {
4405 $paging_nav .= " &sdot; " .
4406 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4407 -accesskey => "n", -title => "Alt-n"}, "next");
4408 } else {
4409 $paging_nav .= " &sdot; next";
4412 return $paging_nav;
4415 ## ......................................................................
4416 ## functions printing or outputting HTML: div
4418 sub git_print_header_div {
4419 my ($action, $title, $hash, $hash_base) = @_;
4420 my %args = ();
4422 $args{'action'} = $action;
4423 $args{'hash'} = $hash if $hash;
4424 $args{'hash_base'} = $hash_base if $hash_base;
4426 print "<div class=\"header\">\n" .
4427 $cgi->a({-href => href(%args), -class => "title"},
4428 $title ? $title : $action) .
4429 "\n</div>\n";
4432 sub format_repo_url {
4433 my ($name, $url) = @_;
4434 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4437 # Group output by placing it in a DIV element and adding a header.
4438 # Options for start_div() can be provided by passing a hash reference as the
4439 # first parameter to the function.
4440 # Options to git_print_header_div() can be provided by passing an array
4441 # reference. This must follow the options to start_div if they are present.
4442 # The content can be a scalar, which is output as-is, a scalar reference, which
4443 # is output after html escaping, an IO handle passed either as *handle or
4444 # *handle{IO}, or a function reference. In the latter case all following
4445 # parameters will be taken as argument to the content function call.
4446 sub git_print_section {
4447 my ($div_args, $header_args, $content);
4448 my $arg = shift;
4449 if (ref($arg) eq 'HASH') {
4450 $div_args = $arg;
4451 $arg = shift;
4453 if (ref($arg) eq 'ARRAY') {
4454 $header_args = $arg;
4455 $arg = shift;
4457 $content = $arg;
4459 print $cgi->start_div($div_args);
4460 git_print_header_div(@$header_args);
4462 if (ref($content) eq 'CODE') {
4463 $content->(@_);
4464 } elsif (ref($content) eq 'SCALAR') {
4465 print esc_html($$content);
4466 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4467 print <$content>;
4468 } elsif (!ref($content) && defined($content)) {
4469 print $content;
4472 print $cgi->end_div;
4475 sub format_timestamp_html {
4476 my $date = shift;
4477 my $strtime = $date->{'rfc2822'};
4479 my (undef, undef, $datetime_class) =
4480 gitweb_get_feature('javascript-timezone');
4481 if ($datetime_class) {
4482 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4485 my $localtime_format = '(%02d:%02d %s)';
4486 if ($date->{'hour_local'} < 6) {
4487 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4489 $strtime .= ' ' .
4490 sprintf($localtime_format,
4491 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4493 return $strtime;
4496 # Outputs the author name and date in long form
4497 sub git_print_authorship {
4498 my $co = shift;
4499 my %opts = @_;
4500 my $tag = $opts{-tag} || 'div';
4501 my $author = $co->{'author_name'};
4503 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4504 print "<$tag class=\"author_date\">" .
4505 format_search_author($author, "author", esc_html($author)) .
4506 " [".format_timestamp_html(\%ad)."]".
4507 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4508 "</$tag>\n";
4511 # Outputs table rows containing the full author or committer information,
4512 # in the format expected for 'commit' view (& similar).
4513 # Parameters are a commit hash reference, followed by the list of people
4514 # to output information for. If the list is empty it defaults to both
4515 # author and committer.
4516 sub git_print_authorship_rows {
4517 my $co = shift;
4518 # too bad we can't use @people = @_ || ('author', 'committer')
4519 my @people = @_;
4520 @people = ('author', 'committer') unless @people;
4521 foreach my $who (@people) {
4522 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4523 print "<tr><td>$who</td><td>" .
4524 format_search_author($co->{"${who}_name"}, $who,
4525 esc_html($co->{"${who}_name"})) . " " .
4526 format_search_author($co->{"${who}_email"}, $who,
4527 esc_html("<" . $co->{"${who}_email"} . ">")) .
4528 "</td><td rowspan=\"2\">" .
4529 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4530 "</td></tr>\n" .
4531 "<tr>" .
4532 "<td></td><td>" .
4533 format_timestamp_html(\%wd) .
4534 "</td>" .
4535 "</tr>\n";
4539 sub git_print_page_path {
4540 my $name = shift;
4541 my $type = shift;
4542 my $hb = shift;
4545 print "<div class=\"page_path\">";
4546 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4547 -title => 'tree root'}, to_utf8("[$project]"));
4548 print " / ";
4549 if (defined $name) {
4550 my @dirname = split '/', $name;
4551 my $basename = pop @dirname;
4552 my $fullname = '';
4554 foreach my $dir (@dirname) {
4555 $fullname .= ($fullname ? '/' : '') . $dir;
4556 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4557 hash_base=>$hb),
4558 -title => $fullname}, esc_path($dir));
4559 print " / ";
4561 if (defined $type && $type eq 'blob') {
4562 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4563 hash_base=>$hb),
4564 -title => $name}, esc_path($basename));
4565 } elsif (defined $type && $type eq 'tree') {
4566 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4567 hash_base=>$hb),
4568 -title => $name}, esc_path($basename));
4569 print " / ";
4570 } else {
4571 print esc_path($basename);
4574 print "<br/></div>\n";
4577 sub git_print_log {
4578 my $log = shift;
4579 my %opts = @_;
4581 if ($opts{'-remove_title'}) {
4582 # remove title, i.e. first line of log
4583 shift @$log;
4585 # remove leading empty lines
4586 while (defined $log->[0] && $log->[0] eq "") {
4587 shift @$log;
4590 # print log
4591 my $skip_blank_line = 0;
4592 foreach my $line (@$log) {
4593 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4594 if (! $opts{'-remove_signoff'}) {
4595 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4596 $skip_blank_line = 1;
4598 next;
4601 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4602 if (! $opts{'-remove_signoff'}) {
4603 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4604 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4605 "</span><br/>\n";
4606 $skip_blank_line = 1;
4608 next;
4611 # print only one empty line
4612 # do not print empty line after signoff
4613 if ($line eq "") {
4614 next if ($skip_blank_line);
4615 $skip_blank_line = 1;
4616 } else {
4617 $skip_blank_line = 0;
4620 print format_log_line_html($line) . "<br/>\n";
4623 if ($opts{'-final_empty_line'}) {
4624 # end with single empty line
4625 print "<br/>\n" unless $skip_blank_line;
4629 # return link target (what link points to)
4630 sub git_get_link_target {
4631 my $hash = shift;
4632 my $link_target;
4634 # read link
4635 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4636 or return;
4638 local $/ = undef;
4639 $link_target = <$fd>;
4641 close $fd
4642 or return;
4644 return $link_target;
4647 # given link target, and the directory (basedir) the link is in,
4648 # return target of link relative to top directory (top tree);
4649 # return undef if it is not possible (including absolute links).
4650 sub normalize_link_target {
4651 my ($link_target, $basedir) = @_;
4653 # absolute symlinks (beginning with '/') cannot be normalized
4654 return if (substr($link_target, 0, 1) eq '/');
4656 # normalize link target to path from top (root) tree (dir)
4657 my $path;
4658 if ($basedir) {
4659 $path = $basedir . '/' . $link_target;
4660 } else {
4661 # we are in top (root) tree (dir)
4662 $path = $link_target;
4665 # remove //, /./, and /../
4666 my @path_parts;
4667 foreach my $part (split('/', $path)) {
4668 # discard '.' and ''
4669 next if (!$part || $part eq '.');
4670 # handle '..'
4671 if ($part eq '..') {
4672 if (@path_parts) {
4673 pop @path_parts;
4674 } else {
4675 # link leads outside repository (outside top dir)
4676 return;
4678 } else {
4679 push @path_parts, $part;
4682 $path = join('/', @path_parts);
4684 return $path;
4687 # print tree entry (row of git_tree), but without encompassing <tr> element
4688 sub git_print_tree_entry {
4689 my ($t, $basedir, $hash_base, $have_blame) = @_;
4691 my %base_key = ();
4692 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4694 # The format of a table row is: mode list link. Where mode is
4695 # the mode of the entry, list is the name of the entry, an href,
4696 # and link is the action links of the entry.
4698 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4699 if (exists $t->{'size'}) {
4700 print "<td class=\"size\">$t->{'size'}</td>\n";
4702 if ($t->{'type'} eq "blob") {
4703 print "<td class=\"list\">" .
4704 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4705 file_name=>"$basedir$t->{'name'}", %base_key),
4706 -class => "list"}, esc_path($t->{'name'}));
4707 if (S_ISLNK(oct $t->{'mode'})) {
4708 my $link_target = git_get_link_target($t->{'hash'});
4709 if ($link_target) {
4710 my $norm_target = normalize_link_target($link_target, $basedir);
4711 if (defined $norm_target) {
4712 print " -> " .
4713 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4714 file_name=>$norm_target),
4715 -title => $norm_target}, esc_path($link_target));
4716 } else {
4717 print " -> " . esc_path($link_target);
4721 print "</td>\n";
4722 print "<td class=\"link\">";
4723 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4724 file_name=>"$basedir$t->{'name'}", %base_key)},
4725 "blob");
4726 if ($have_blame) {
4727 print " | " .
4728 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4729 file_name=>"$basedir$t->{'name'}", %base_key)},
4730 "blame");
4732 if (defined $hash_base) {
4733 print " | " .
4734 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4735 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4736 "history");
4738 print " | " .
4739 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4740 file_name=>"$basedir$t->{'name'}")},
4741 "raw");
4742 print "</td>\n";
4744 } elsif ($t->{'type'} eq "tree") {
4745 print "<td class=\"list\">";
4746 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4747 file_name=>"$basedir$t->{'name'}",
4748 %base_key)},
4749 esc_path($t->{'name'}));
4750 print "</td>\n";
4751 print "<td class=\"link\">";
4752 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4753 file_name=>"$basedir$t->{'name'}",
4754 %base_key)},
4755 "tree");
4756 if (defined $hash_base) {
4757 print " | " .
4758 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4759 file_name=>"$basedir$t->{'name'}")},
4760 "history");
4762 print "</td>\n";
4763 } else {
4764 # unknown object: we can only present history for it
4765 # (this includes 'commit' object, i.e. submodule support)
4766 print "<td class=\"list\">" .
4767 esc_path($t->{'name'}) .
4768 "</td>\n";
4769 print "<td class=\"link\">";
4770 if (defined $hash_base) {
4771 print $cgi->a({-href => href(action=>"history",
4772 hash_base=>$hash_base,
4773 file_name=>"$basedir$t->{'name'}")},
4774 "history");
4776 print "</td>\n";
4780 ## ......................................................................
4781 ## functions printing large fragments of HTML
4783 # get pre-image filenames for merge (combined) diff
4784 sub fill_from_file_info {
4785 my ($diff, @parents) = @_;
4787 $diff->{'from_file'} = [ ];
4788 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4789 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4790 if ($diff->{'status'}[$i] eq 'R' ||
4791 $diff->{'status'}[$i] eq 'C') {
4792 $diff->{'from_file'}[$i] =
4793 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4797 return $diff;
4800 # is current raw difftree line of file deletion
4801 sub is_deleted {
4802 my $diffinfo = shift;
4804 return $diffinfo->{'to_id'} eq ('0' x 40);
4807 # does patch correspond to [previous] difftree raw line
4808 # $diffinfo - hashref of parsed raw diff format
4809 # $patchinfo - hashref of parsed patch diff format
4810 # (the same keys as in $diffinfo)
4811 sub is_patch_split {
4812 my ($diffinfo, $patchinfo) = @_;
4814 return defined $diffinfo && defined $patchinfo
4815 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4819 sub git_difftree_body {
4820 my ($difftree, $hash, @parents) = @_;
4821 my ($parent) = $parents[0];
4822 my $have_blame = gitweb_check_feature('blame');
4823 print "<div class=\"list_head\">\n";
4824 if ($#{$difftree} > 10) {
4825 print(($#{$difftree} + 1) . " files changed:\n");
4827 print "</div>\n";
4829 print "<table class=\"" .
4830 (@parents > 1 ? "combined " : "") .
4831 "diff_tree\">\n";
4833 # header only for combined diff in 'commitdiff' view
4834 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4835 if ($has_header) {
4836 # table header
4837 print "<thead><tr>\n" .
4838 "<th></th><th></th>\n"; # filename, patchN link
4839 for (my $i = 0; $i < @parents; $i++) {
4840 my $par = $parents[$i];
4841 print "<th>" .
4842 $cgi->a({-href => href(action=>"commitdiff",
4843 hash=>$hash, hash_parent=>$par),
4844 -title => 'commitdiff to parent number ' .
4845 ($i+1) . ': ' . substr($par,0,7)},
4846 $i+1) .
4847 "&nbsp;</th>\n";
4849 print "</tr></thead>\n<tbody>\n";
4852 my $alternate = 1;
4853 my $patchno = 0;
4854 foreach my $line (@{$difftree}) {
4855 my $diff = parsed_difftree_line($line);
4857 if ($alternate) {
4858 print "<tr class=\"dark\">\n";
4859 } else {
4860 print "<tr class=\"light\">\n";
4862 $alternate ^= 1;
4864 if (exists $diff->{'nparents'}) { # combined diff
4866 fill_from_file_info($diff, @parents)
4867 unless exists $diff->{'from_file'};
4869 if (!is_deleted($diff)) {
4870 # file exists in the result (child) commit
4871 print "<td>" .
4872 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4873 file_name=>$diff->{'to_file'},
4874 hash_base=>$hash),
4875 -class => "list"}, esc_path($diff->{'to_file'})) .
4876 "</td>\n";
4877 } else {
4878 print "<td>" .
4879 esc_path($diff->{'to_file'}) .
4880 "</td>\n";
4883 if ($action eq 'commitdiff') {
4884 # link to patch
4885 $patchno++;
4886 print "<td class=\"link\">" .
4887 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4888 "patch") .
4889 " | " .
4890 "</td>\n";
4893 my $has_history = 0;
4894 my $not_deleted = 0;
4895 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4896 my $hash_parent = $parents[$i];
4897 my $from_hash = $diff->{'from_id'}[$i];
4898 my $from_path = $diff->{'from_file'}[$i];
4899 my $status = $diff->{'status'}[$i];
4901 $has_history ||= ($status ne 'A');
4902 $not_deleted ||= ($status ne 'D');
4904 if ($status eq 'A') {
4905 print "<td class=\"link\" align=\"right\"> | </td>\n";
4906 } elsif ($status eq 'D') {
4907 print "<td class=\"link\">" .
4908 $cgi->a({-href => href(action=>"blob",
4909 hash_base=>$hash,
4910 hash=>$from_hash,
4911 file_name=>$from_path)},
4912 "blob" . ($i+1)) .
4913 " | </td>\n";
4914 } else {
4915 if ($diff->{'to_id'} eq $from_hash) {
4916 print "<td class=\"link nochange\">";
4917 } else {
4918 print "<td class=\"link\">";
4920 print $cgi->a({-href => href(action=>"blobdiff",
4921 hash=>$diff->{'to_id'},
4922 hash_parent=>$from_hash,
4923 hash_base=>$hash,
4924 hash_parent_base=>$hash_parent,
4925 file_name=>$diff->{'to_file'},
4926 file_parent=>$from_path)},
4927 "diff" . ($i+1)) .
4928 " | </td>\n";
4932 print "<td class=\"link\">";
4933 if ($not_deleted) {
4934 print $cgi->a({-href => href(action=>"blob",
4935 hash=>$diff->{'to_id'},
4936 file_name=>$diff->{'to_file'},
4937 hash_base=>$hash)},
4938 "blob");
4939 print " | " if ($has_history);
4941 if ($has_history) {
4942 print $cgi->a({-href => href(action=>"history",
4943 file_name=>$diff->{'to_file'},
4944 hash_base=>$hash)},
4945 "history");
4947 print "</td>\n";
4949 print "</tr>\n";
4950 next; # instead of 'else' clause, to avoid extra indent
4952 # else ordinary diff
4954 my ($to_mode_oct, $to_mode_str, $to_file_type);
4955 my ($from_mode_oct, $from_mode_str, $from_file_type);
4956 if ($diff->{'to_mode'} ne ('0' x 6)) {
4957 $to_mode_oct = oct $diff->{'to_mode'};
4958 if (S_ISREG($to_mode_oct)) { # only for regular file
4959 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4961 $to_file_type = file_type($diff->{'to_mode'});
4963 if ($diff->{'from_mode'} ne ('0' x 6)) {
4964 $from_mode_oct = oct $diff->{'from_mode'};
4965 if (S_ISREG($from_mode_oct)) { # only for regular file
4966 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4968 $from_file_type = file_type($diff->{'from_mode'});
4971 if ($diff->{'status'} eq "A") { # created
4972 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4973 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4974 $mode_chng .= "]</span>";
4975 print "<td>";
4976 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4977 hash_base=>$hash, file_name=>$diff->{'file'}),
4978 -class => "list"}, esc_path($diff->{'file'}));
4979 print "</td>\n";
4980 print "<td>$mode_chng</td>\n";
4981 print "<td class=\"link\">";
4982 if ($action eq 'commitdiff') {
4983 # link to patch
4984 $patchno++;
4985 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4986 "patch") .
4987 " | ";
4989 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4990 hash_base=>$hash, file_name=>$diff->{'file'})},
4991 "blob");
4992 print "</td>\n";
4994 } elsif ($diff->{'status'} eq "D") { # deleted
4995 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4996 print "<td>";
4997 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4998 hash_base=>$parent, file_name=>$diff->{'file'}),
4999 -class => "list"}, esc_path($diff->{'file'}));
5000 print "</td>\n";
5001 print "<td>$mode_chng</td>\n";
5002 print "<td class=\"link\">";
5003 if ($action eq 'commitdiff') {
5004 # link to patch
5005 $patchno++;
5006 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5007 "patch") .
5008 " | ";
5010 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5011 hash_base=>$parent, file_name=>$diff->{'file'})},
5012 "blob") . " | ";
5013 if ($have_blame) {
5014 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5015 file_name=>$diff->{'file'})},
5016 "blame") . " | ";
5018 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5019 file_name=>$diff->{'file'})},
5020 "history");
5021 print "</td>\n";
5023 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5024 my $mode_chnge = "";
5025 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5026 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5027 if ($from_file_type ne $to_file_type) {
5028 $mode_chnge .= " from $from_file_type to $to_file_type";
5030 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5031 if ($from_mode_str && $to_mode_str) {
5032 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5033 } elsif ($to_mode_str) {
5034 $mode_chnge .= " mode: $to_mode_str";
5037 $mode_chnge .= "]</span>\n";
5039 print "<td>";
5040 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5041 hash_base=>$hash, file_name=>$diff->{'file'}),
5042 -class => "list"}, esc_path($diff->{'file'}));
5043 print "</td>\n";
5044 print "<td>$mode_chnge</td>\n";
5045 print "<td class=\"link\">";
5046 if ($action eq 'commitdiff') {
5047 # link to patch
5048 $patchno++;
5049 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5050 "patch") .
5051 " | ";
5052 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5053 # "commit" view and modified file (not onlu mode changed)
5054 print $cgi->a({-href => href(action=>"blobdiff",
5055 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5056 hash_base=>$hash, hash_parent_base=>$parent,
5057 file_name=>$diff->{'file'})},
5058 "diff") .
5059 " | ";
5061 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5062 hash_base=>$hash, file_name=>$diff->{'file'})},
5063 "blob") . " | ";
5064 if ($have_blame) {
5065 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5066 file_name=>$diff->{'file'})},
5067 "blame") . " | ";
5069 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5070 file_name=>$diff->{'file'})},
5071 "history");
5072 print "</td>\n";
5074 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5075 my %status_name = ('R' => 'moved', 'C' => 'copied');
5076 my $nstatus = $status_name{$diff->{'status'}};
5077 my $mode_chng = "";
5078 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5079 # mode also for directories, so we cannot use $to_mode_str
5080 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5082 print "<td>" .
5083 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5084 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5085 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5086 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5087 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5088 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5089 -class => "list"}, esc_path($diff->{'from_file'})) .
5090 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5091 "<td class=\"link\">";
5092 if ($action eq 'commitdiff') {
5093 # link to patch
5094 $patchno++;
5095 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5096 "patch") .
5097 " | ";
5098 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5099 # "commit" view and modified file (not only pure rename or copy)
5100 print $cgi->a({-href => href(action=>"blobdiff",
5101 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5102 hash_base=>$hash, hash_parent_base=>$parent,
5103 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5104 "diff") .
5105 " | ";
5107 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5108 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5109 "blob") . " | ";
5110 if ($have_blame) {
5111 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5112 file_name=>$diff->{'to_file'})},
5113 "blame") . " | ";
5115 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5116 file_name=>$diff->{'to_file'})},
5117 "history");
5118 print "</td>\n";
5120 } # we should not encounter Unmerged (U) or Unknown (X) status
5121 print "</tr>\n";
5123 print "</tbody>" if $has_header;
5124 print "</table>\n";
5127 # Print context lines and then rem/add lines in a side-by-side manner.
5128 sub print_sidebyside_diff_lines {
5129 my ($ctx, $rem, $add) = @_;
5131 # print context block before add/rem block
5132 if (@$ctx) {
5133 print join '',
5134 '<div class="chunk_block ctx">',
5135 '<div class="old">',
5136 @$ctx,
5137 '</div>',
5138 '<div class="new">',
5139 @$ctx,
5140 '</div>',
5141 '</div>';
5144 if (!@$add) {
5145 # pure removal
5146 print join '',
5147 '<div class="chunk_block rem">',
5148 '<div class="old">',
5149 @$rem,
5150 '</div>',
5151 '</div>';
5152 } elsif (!@$rem) {
5153 # pure addition
5154 print join '',
5155 '<div class="chunk_block add">',
5156 '<div class="new">',
5157 @$add,
5158 '</div>',
5159 '</div>';
5160 } else {
5161 print join '',
5162 '<div class="chunk_block chg">',
5163 '<div class="old">',
5164 @$rem,
5165 '</div>',
5166 '<div class="new">',
5167 @$add,
5168 '</div>',
5169 '</div>';
5173 # Print context lines and then rem/add lines in inline manner.
5174 sub print_inline_diff_lines {
5175 my ($ctx, $rem, $add) = @_;
5177 print @$ctx, @$rem, @$add;
5180 # Format removed and added line, mark changed part and HTML-format them.
5181 # Implementation is based on contrib/diff-highlight
5182 sub format_rem_add_lines_pair {
5183 my ($rem, $add, $num_parents) = @_;
5185 # We need to untabify lines before split()'ing them;
5186 # otherwise offsets would be invalid.
5187 chomp $rem;
5188 chomp $add;
5189 $rem = untabify($rem);
5190 $add = untabify($add);
5192 my @rem = split(//, $rem);
5193 my @add = split(//, $add);
5194 my ($esc_rem, $esc_add);
5195 # Ignore leading +/- characters for each parent.
5196 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5197 my ($prefix_has_nonspace, $suffix_has_nonspace);
5199 my $shorter = (@rem < @add) ? @rem : @add;
5200 while ($prefix_len < $shorter) {
5201 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5203 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5204 $prefix_len++;
5207 while ($prefix_len + $suffix_len < $shorter) {
5208 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5210 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5211 $suffix_len++;
5214 # Mark lines that are different from each other, but have some common
5215 # part that isn't whitespace. If lines are completely different, don't
5216 # mark them because that would make output unreadable, especially if
5217 # diff consists of multiple lines.
5218 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5219 $esc_rem = esc_html_hl_regions($rem, 'marked',
5220 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5221 $esc_add = esc_html_hl_regions($add, 'marked',
5222 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5223 } else {
5224 $esc_rem = esc_html($rem, -nbsp=>1);
5225 $esc_add = esc_html($add, -nbsp=>1);
5228 return format_diff_line(\$esc_rem, 'rem'),
5229 format_diff_line(\$esc_add, 'add');
5232 # HTML-format diff context, removed and added lines.
5233 sub format_ctx_rem_add_lines {
5234 my ($ctx, $rem, $add, $num_parents) = @_;
5235 my (@new_ctx, @new_rem, @new_add);
5236 my $can_highlight = 0;
5237 my $is_combined = ($num_parents > 1);
5239 # Highlight if every removed line has a corresponding added line.
5240 if (@$add > 0 && @$add == @$rem) {
5241 $can_highlight = 1;
5243 # Highlight lines in combined diff only if the chunk contains
5244 # diff between the same version, e.g.
5246 # - a
5247 # - b
5248 # + c
5249 # + d
5251 # Otherwise the highlightling would be confusing.
5252 if ($is_combined) {
5253 for (my $i = 0; $i < @$add; $i++) {
5254 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5255 my $prefix_add = substr($add->[$i], 0, $num_parents);
5257 $prefix_rem =~ s/-/+/g;
5259 if ($prefix_rem ne $prefix_add) {
5260 $can_highlight = 0;
5261 last;
5267 if ($can_highlight) {
5268 for (my $i = 0; $i < @$add; $i++) {
5269 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5270 $rem->[$i], $add->[$i], $num_parents);
5271 push @new_rem, $line_rem;
5272 push @new_add, $line_add;
5274 } else {
5275 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5276 @new_add = map { format_diff_line($_, 'add') } @$add;
5279 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5281 return (\@new_ctx, \@new_rem, \@new_add);
5284 # Print context lines and then rem/add lines.
5285 sub print_diff_lines {
5286 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5287 my $is_combined = $num_parents > 1;
5289 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5290 $num_parents);
5292 if ($diff_style eq 'sidebyside' && !$is_combined) {
5293 print_sidebyside_diff_lines($ctx, $rem, $add);
5294 } else {
5295 # default 'inline' style and unknown styles
5296 print_inline_diff_lines($ctx, $rem, $add);
5300 sub print_diff_chunk {
5301 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5302 my (@ctx, @rem, @add);
5304 # The class of the previous line.
5305 my $prev_class = '';
5307 return unless @chunk;
5309 # incomplete last line might be among removed or added lines,
5310 # or both, or among context lines: find which
5311 for (my $i = 1; $i < @chunk; $i++) {
5312 if ($chunk[$i][0] eq 'incomplete') {
5313 $chunk[$i][0] = $chunk[$i-1][0];
5317 # guardian
5318 push @chunk, ["", ""];
5320 foreach my $line_info (@chunk) {
5321 my ($class, $line) = @$line_info;
5323 # print chunk headers
5324 if ($class && $class eq 'chunk_header') {
5325 print format_diff_line($line, $class, $from, $to);
5326 next;
5329 ## print from accumulator when have some add/rem lines or end
5330 # of chunk (flush context lines), or when have add and rem
5331 # lines and new block is reached (otherwise add/rem lines could
5332 # be reordered)
5333 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5334 (@rem && @add && $class ne $prev_class)) {
5335 print_diff_lines(\@ctx, \@rem, \@add,
5336 $diff_style, $num_parents);
5337 @ctx = @rem = @add = ();
5340 ## adding lines to accumulator
5341 # guardian value
5342 last unless $line;
5343 # rem, add or change
5344 if ($class eq 'rem') {
5345 push @rem, $line;
5346 } elsif ($class eq 'add') {
5347 push @add, $line;
5349 # context line
5350 if ($class eq 'ctx') {
5351 push @ctx, $line;
5354 $prev_class = $class;
5358 sub git_patchset_body {
5359 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5360 my ($hash_parent) = $hash_parents[0];
5362 my $is_combined = (@hash_parents > 1);
5363 my $patch_idx = 0;
5364 my $patch_number = 0;
5365 my $patch_line;
5366 my $diffinfo;
5367 my $to_name;
5368 my (%from, %to);
5369 my @chunk; # for side-by-side diff
5371 print "<div class=\"patchset\">\n";
5373 # skip to first patch
5374 while ($patch_line = <$fd>) {
5375 chomp $patch_line;
5377 last if ($patch_line =~ m/^diff /);
5380 PATCH:
5381 while ($patch_line) {
5383 # parse "git diff" header line
5384 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5385 # $1 is from_name, which we do not use
5386 $to_name = unquote($2);
5387 $to_name =~ s!^b/!!;
5388 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5389 # $1 is 'cc' or 'combined', which we do not use
5390 $to_name = unquote($2);
5391 } else {
5392 $to_name = undef;
5395 # check if current patch belong to current raw line
5396 # and parse raw git-diff line if needed
5397 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5398 # this is continuation of a split patch
5399 print "<div class=\"patch cont\">\n";
5400 } else {
5401 # advance raw git-diff output if needed
5402 $patch_idx++ if defined $diffinfo;
5404 # read and prepare patch information
5405 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5407 # compact combined diff output can have some patches skipped
5408 # find which patch (using pathname of result) we are at now;
5409 if ($is_combined) {
5410 while ($to_name ne $diffinfo->{'to_file'}) {
5411 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5412 format_diff_cc_simplified($diffinfo, @hash_parents) .
5413 "</div>\n"; # class="patch"
5415 $patch_idx++;
5416 $patch_number++;
5418 last if $patch_idx > $#$difftree;
5419 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5423 # modifies %from, %to hashes
5424 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5426 # this is first patch for raw difftree line with $patch_idx index
5427 # we index @$difftree array from 0, but number patches from 1
5428 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5431 # git diff header
5432 #assert($patch_line =~ m/^diff /) if DEBUG;
5433 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5434 $patch_number++;
5435 # print "git diff" header
5436 print format_git_diff_header_line($patch_line, $diffinfo,
5437 \%from, \%to);
5439 # print extended diff header
5440 print "<div class=\"diff extended_header\">\n";
5441 EXTENDED_HEADER:
5442 while ($patch_line = <$fd>) {
5443 chomp $patch_line;
5445 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5447 print format_extended_diff_header_line($patch_line, $diffinfo,
5448 \%from, \%to);
5450 print "</div>\n"; # class="diff extended_header"
5452 # from-file/to-file diff header
5453 if (! $patch_line) {
5454 print "</div>\n"; # class="patch"
5455 last PATCH;
5457 next PATCH if ($patch_line =~ m/^diff /);
5458 #assert($patch_line =~ m/^---/) if DEBUG;
5460 my $last_patch_line = $patch_line;
5461 $patch_line = <$fd>;
5462 chomp $patch_line;
5463 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5465 print format_diff_from_to_header($last_patch_line, $patch_line,
5466 $diffinfo, \%from, \%to,
5467 @hash_parents);
5469 # the patch itself
5470 LINE:
5471 while ($patch_line = <$fd>) {
5472 chomp $patch_line;
5474 next PATCH if ($patch_line =~ m/^diff /);
5476 my $class = diff_line_class($patch_line, \%from, \%to);
5478 if ($class eq 'chunk_header') {
5479 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5480 @chunk = ();
5483 push @chunk, [ $class, $patch_line ];
5486 } continue {
5487 if (@chunk) {
5488 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5489 @chunk = ();
5491 print "</div>\n"; # class="patch"
5494 # for compact combined (--cc) format, with chunk and patch simplification
5495 # the patchset might be empty, but there might be unprocessed raw lines
5496 for (++$patch_idx if $patch_number > 0;
5497 $patch_idx < @$difftree;
5498 ++$patch_idx) {
5499 # read and prepare patch information
5500 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5502 # generate anchor for "patch" links in difftree / whatchanged part
5503 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5504 format_diff_cc_simplified($diffinfo, @hash_parents) .
5505 "</div>\n"; # class="patch"
5507 $patch_number++;
5510 if ($patch_number == 0) {
5511 if (@hash_parents > 1) {
5512 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5513 } else {
5514 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5518 print "</div>\n"; # class="patchset"
5521 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5523 sub git_project_search_form {
5524 my ($searchtext, $search_use_regexp) = @_;
5526 my $limit = '';
5527 if ($project_filter) {
5528 $limit = " in '$project_filter/'";
5531 print "<div class=\"projsearch\">\n";
5532 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5533 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5534 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5535 if (defined $project_filter);
5536 print $cgi->textfield(-name => 's', -value => $searchtext,
5537 -title => "Search project by name and description$limit",
5538 -size => 60) . "\n" .
5539 "<span title=\"Extended regular expression\">" .
5540 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5541 -checked => $search_use_regexp) .
5542 "</span>\n" .
5543 $cgi->submit(-name => 'btnS', -value => 'Search') .
5544 $cgi->end_form() . "\n";
5545 print "</div>\n";
5548 # entry for given @keys needs filling if at least one of keys in list
5549 # is not present in %$project_info
5550 sub project_info_needs_filling {
5551 my ($project_info, @keys) = @_;
5553 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5554 foreach my $key (@keys) {
5555 if (!exists $project_info->{$key}) {
5556 return 1;
5559 return;
5562 # fills project list info (age, description, owner, category, forks, etc.)
5563 # for each project in the list, removing invalid projects from
5564 # returned list, or fill only specified info.
5566 # Invalid projects are removed from the returned list if and only if you
5567 # ask 'age' or 'age_string' to be filled, because they are the only fields
5568 # that run unconditionally git command that requires repository, and
5569 # therefore do always check if project repository is invalid.
5571 # USAGE:
5572 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5573 # ensures that 'descr_long' and 'ctags' fields are filled
5574 # * @project_list = fill_project_list_info(\@project_list)
5575 # ensures that all fields are filled (and invalid projects removed)
5577 # NOTE: modifies $projlist, but does not remove entries from it
5578 sub fill_project_list_info {
5579 my ($projlist, @wanted_keys) = @_;
5580 my @projects;
5581 my $filter_set = sub { return @_; };
5582 if (@wanted_keys) {
5583 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5584 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5587 my $show_ctags = gitweb_check_feature('ctags');
5588 PROJECT:
5589 foreach my $pr (@$projlist) {
5590 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5591 my (@activity) = git_get_last_activity($pr->{'path'});
5592 unless (@activity) {
5593 next PROJECT;
5595 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5597 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5598 my $descr = git_get_project_description($pr->{'path'}) || "";
5599 $descr = to_utf8($descr);
5600 $pr->{'descr_long'} = $descr;
5601 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5603 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5604 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5606 if ($show_ctags &&
5607 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5608 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5610 if ($projects_list_group_categories &&
5611 project_info_needs_filling($pr, $filter_set->('category'))) {
5612 my $cat = git_get_project_category($pr->{'path'}) ||
5613 $project_list_default_category;
5614 $pr->{'category'} = to_utf8($cat);
5617 push @projects, $pr;
5620 return @projects;
5623 sub sort_projects_list {
5624 my ($projlist, $order) = @_;
5626 sub order_str {
5627 my $key = shift;
5628 return sub { $a->{$key} cmp $b->{$key} };
5631 sub order_num_then_undef {
5632 my $key = shift;
5633 return sub {
5634 defined $a->{$key} ?
5635 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5636 (defined $b->{$key} ? 1 : 0)
5640 my %orderings = (
5641 project => order_str('path'),
5642 descr => order_str('descr_long'),
5643 owner => order_str('owner'),
5644 age => order_num_then_undef('age'),
5647 my $ordering = $orderings{$order};
5648 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5651 # returns a hash of categories, containing the list of project
5652 # belonging to each category
5653 sub build_projlist_by_category {
5654 my ($projlist, $from, $to) = @_;
5655 my %categories;
5657 $from = 0 unless defined $from;
5658 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5660 for (my $i = $from; $i <= $to; $i++) {
5661 my $pr = $projlist->[$i];
5662 push @{$categories{ $pr->{'category'} }}, $pr;
5665 return wantarray ? %categories : \%categories;
5668 # print 'sort by' <th> element, generating 'sort by $name' replay link
5669 # if that order is not selected
5670 sub print_sort_th {
5671 print format_sort_th(@_);
5674 sub format_sort_th {
5675 my ($name, $order, $header) = @_;
5676 my $sort_th = "";
5677 $header ||= ucfirst($name);
5679 if ($order eq $name) {
5680 $sort_th .= "<th>$header</th>\n";
5681 } else {
5682 $sort_th .= "<th>" .
5683 $cgi->a({-href => href(-replay=>1, order=>$name),
5684 -class => "header"}, $header) .
5685 "</th>\n";
5688 return $sort_th;
5691 sub git_project_list_rows {
5692 my ($projlist, $from, $to, $check_forks) = @_;
5694 $from = 0 unless defined $from;
5695 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5697 my $alternate = 1;
5698 for (my $i = $from; $i <= $to; $i++) {
5699 my $pr = $projlist->[$i];
5701 if ($alternate) {
5702 print "<tr class=\"dark\">\n";
5703 } else {
5704 print "<tr class=\"light\">\n";
5706 $alternate ^= 1;
5708 if ($check_forks) {
5709 print "<td>";
5710 if ($pr->{'forks'}) {
5711 my $nforks = scalar @{$pr->{'forks'}};
5712 if ($nforks > 0) {
5713 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5714 -title => "$nforks forks"}, "+");
5715 } else {
5716 print $cgi->span({-title => "$nforks forks"}, "+");
5719 print "</td>\n";
5721 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5722 -class => "list"},
5723 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5724 "</td>\n" .
5725 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5726 -class => "list",
5727 -title => $pr->{'descr_long'}},
5728 $search_regexp
5729 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5730 $pr->{'descr'}, $search_regexp)
5731 : esc_html($pr->{'descr'})) .
5732 "</td>\n";
5733 unless ($omit_owner) {
5734 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5736 unless ($omit_age_column) {
5737 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5738 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5740 print"<td class=\"link\">" .
5741 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5742 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5743 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5744 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5745 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5746 "</td>\n" .
5747 "</tr>\n";
5751 sub git_project_list_body {
5752 # actually uses global variable $project
5753 my ($projlist, $order, $from, $to, $extra, $no_header, $ctags_action) = @_;
5754 my @projects = @$projlist;
5756 my $check_forks = gitweb_check_feature('forks');
5757 my $show_ctags = gitweb_check_feature('ctags');
5758 my $tagfilter = $show_ctags ? $input_params{'ctag_filter'} : undef;
5759 $check_forks = undef
5760 if ($tagfilter || $search_regexp);
5762 # filtering out forks before filling info allows to do less work
5763 @projects = filter_forks_from_projects_list(\@projects)
5764 if ($check_forks);
5765 # search_projects_list pre-fills required info
5766 @projects = search_projects_list(\@projects,
5767 'search_regexp' => $search_regexp,
5768 'tagfilter' => $tagfilter)
5769 if ($tagfilter || $search_regexp);
5770 # fill the rest
5771 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5772 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5773 push @all_fields, 'owner' unless($omit_owner);
5774 @projects = fill_project_list_info(\@projects, @all_fields);
5776 $order ||= $default_projects_order;
5777 $from = 0 unless defined $from;
5778 $to = $#projects if (!defined $to || $#projects < $to);
5780 # short circuit
5781 if ($from > $to) {
5782 print "<center>\n".
5783 "<b>No such projects found</b><br />\n".
5784 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5785 "</center>\n<br />\n";
5786 return;
5789 @projects = sort_projects_list(\@projects, $order);
5791 if ($show_ctags) {
5792 my $ctags = git_gather_all_ctags(\@projects);
5793 my $cloud = git_populate_project_tagcloud($ctags, $ctags_action||'project_list');
5794 print git_show_project_tagcloud($cloud, 64);
5797 print "<table class=\"project_list\">\n";
5798 unless ($no_header) {
5799 print "<tr>\n";
5800 if ($check_forks) {
5801 print "<th></th>\n";
5803 print_sort_th('project', $order, 'Project');
5804 print_sort_th('descr', $order, 'Description');
5805 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5806 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5807 print "<th></th>\n" . # for links
5808 "</tr>\n";
5811 if ($projects_list_group_categories) {
5812 # only display categories with projects in the $from-$to window
5813 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5814 my %categories = build_projlist_by_category(\@projects, $from, $to);
5815 foreach my $cat (sort keys %categories) {
5816 unless ($cat eq "") {
5817 print "<tr>\n";
5818 if ($check_forks) {
5819 print "<td></td>\n";
5821 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5822 print "</tr>\n";
5825 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5827 } else {
5828 git_project_list_rows(\@projects, $from, $to, $check_forks);
5831 if (defined $extra) {
5832 print "<tr>\n";
5833 if ($check_forks) {
5834 print "<td></td>\n";
5836 print "<td colspan=\"5\">$extra</td>\n" .
5837 "</tr>\n";
5839 print "</table>\n";
5842 sub git_log_body {
5843 # uses global variable $project
5844 my ($commitlist, $from, $to, $refs, $extra) = @_;
5846 $from = 0 unless defined $from;
5847 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5849 for (my $i = 0; $i <= $to; $i++) {
5850 my %co = %{$commitlist->[$i]};
5851 next if !%co;
5852 my $commit = $co{'id'};
5853 my $ref = format_ref_marker($refs, $commit);
5854 git_print_header_div('commit',
5855 "<span class=\"age\">$co{'age_string'}</span>" .
5856 esc_html($co{'title'}) . $ref,
5857 $commit);
5858 print "<div class=\"title_text\">\n" .
5859 "<div class=\"log_link\">\n" .
5860 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5861 " | " .
5862 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5863 " | " .
5864 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5865 "<br/>\n" .
5866 "</div>\n";
5867 git_print_authorship(\%co, -tag => 'span');
5868 print "<br/>\n</div>\n";
5870 print "<div class=\"log_body\">\n";
5871 git_print_log($co{'comment'}, -final_empty_line=> 1);
5872 print "</div>\n";
5874 if ($extra) {
5875 print "<div class=\"page_nav\">\n";
5876 print "$extra\n";
5877 print "</div>\n";
5881 sub git_shortlog_body {
5882 # uses global variable $project
5883 my ($commitlist, $from, $to, $refs, $extra) = @_;
5885 $from = 0 unless defined $from;
5886 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5888 print "<table class=\"shortlog\">\n";
5889 my $alternate = 1;
5890 for (my $i = $from; $i <= $to; $i++) {
5891 my %co = %{$commitlist->[$i]};
5892 my $commit = $co{'id'};
5893 my $ref = format_ref_marker($refs, $commit);
5894 if ($alternate) {
5895 print "<tr class=\"dark\">\n";
5896 } else {
5897 print "<tr class=\"light\">\n";
5899 $alternate ^= 1;
5900 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5901 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5902 format_author_html('td', \%co, 10) . "<td>";
5903 print format_subject_html($co{'title'}, $co{'title_short'},
5904 href(action=>"commit", hash=>$commit), $ref);
5905 print "</td>\n" .
5906 "<td class=\"link\">" .
5907 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5908 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5909 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5910 my $snapshot_links = format_snapshot_links($commit);
5911 if (defined $snapshot_links) {
5912 print " | " . $snapshot_links;
5914 print "</td>\n" .
5915 "</tr>\n";
5917 if (defined $extra) {
5918 print "<tr>\n" .
5919 "<td colspan=\"4\">$extra</td>\n" .
5920 "</tr>\n";
5922 print "</table>\n";
5925 sub git_history_body {
5926 # Warning: assumes constant type (blob or tree) during history
5927 my ($commitlist, $from, $to, $refs, $extra,
5928 $file_name, $file_hash, $ftype) = @_;
5930 $from = 0 unless defined $from;
5931 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5933 print "<table class=\"history\">\n";
5934 my $alternate = 1;
5935 for (my $i = $from; $i <= $to; $i++) {
5936 my %co = %{$commitlist->[$i]};
5937 if (!%co) {
5938 next;
5940 my $commit = $co{'id'};
5942 my $ref = format_ref_marker($refs, $commit);
5944 if ($alternate) {
5945 print "<tr class=\"dark\">\n";
5946 } else {
5947 print "<tr class=\"light\">\n";
5949 $alternate ^= 1;
5950 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5951 # shortlog: format_author_html('td', \%co, 10)
5952 format_author_html('td', \%co, 15, 3) . "<td>";
5953 # originally git_history used chop_str($co{'title'}, 50)
5954 print format_subject_html($co{'title'}, $co{'title_short'},
5955 href(action=>"commit", hash=>$commit), $ref);
5956 print "</td>\n" .
5957 "<td class=\"link\">" .
5958 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5959 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5961 if ($ftype eq 'blob') {
5962 my $blob_current = $file_hash;
5963 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5964 if (defined $blob_current && defined $blob_parent &&
5965 $blob_current ne $blob_parent) {
5966 print " | " .
5967 $cgi->a({-href => href(action=>"blobdiff",
5968 hash=>$blob_current, hash_parent=>$blob_parent,
5969 hash_base=>$hash_base, hash_parent_base=>$commit,
5970 file_name=>$file_name)},
5971 "diff to current");
5974 print "</td>\n" .
5975 "</tr>\n";
5977 if (defined $extra) {
5978 print "<tr>\n" .
5979 "<td colspan=\"4\">$extra</td>\n" .
5980 "</tr>\n";
5982 print "</table>\n";
5985 sub git_tags_body {
5986 # uses global variable $project
5987 my ($taglist, $from, $to, $extra) = @_;
5988 $from = 0 unless defined $from;
5989 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5991 print "<table class=\"tags\">\n";
5992 my $alternate = 1;
5993 for (my $i = $from; $i <= $to; $i++) {
5994 my $entry = $taglist->[$i];
5995 my %tag = %$entry;
5996 my $comment = $tag{'subject'};
5997 my $comment_short;
5998 if (defined $comment) {
5999 $comment_short = chop_str($comment, 30, 5);
6001 if ($alternate) {
6002 print "<tr class=\"dark\">\n";
6003 } else {
6004 print "<tr class=\"light\">\n";
6006 $alternate ^= 1;
6007 if (defined $tag{'age'}) {
6008 print "<td><i>$tag{'age'}</i></td>\n";
6009 } else {
6010 print "<td></td>\n";
6012 print "<td>" .
6013 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6014 -class => "list name"}, esc_html($tag{'name'})) .
6015 "</td>\n" .
6016 "<td>";
6017 if (defined $comment) {
6018 print format_subject_html($comment, $comment_short,
6019 href(action=>"tag", hash=>$tag{'id'}));
6021 print "</td>\n" .
6022 "<td class=\"selflink\">";
6023 if ($tag{'type'} eq "tag") {
6024 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6025 } else {
6026 print "&nbsp;";
6028 print "</td>\n" .
6029 "<td class=\"link\">" . " | " .
6030 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6031 if ($tag{'reftype'} eq "commit") {
6032 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6033 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6034 } elsif ($tag{'reftype'} eq "blob") {
6035 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6037 print "</td>\n" .
6038 "</tr>";
6040 if (defined $extra) {
6041 print "<tr>\n" .
6042 "<td colspan=\"5\">$extra</td>\n" .
6043 "</tr>\n";
6045 print "</table>\n";
6048 sub git_heads_body {
6049 # uses global variable $project
6050 my ($headlist, $head_at, $from, $to, $extra) = @_;
6051 $from = 0 unless defined $from;
6052 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6054 print "<table class=\"heads\">\n";
6055 my $alternate = 1;
6056 for (my $i = $from; $i <= $to; $i++) {
6057 my $entry = $headlist->[$i];
6058 my %ref = %$entry;
6059 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6060 if ($alternate) {
6061 print "<tr class=\"dark\">\n";
6062 } else {
6063 print "<tr class=\"light\">\n";
6065 $alternate ^= 1;
6066 print "<td><i>$ref{'age'}</i></td>\n" .
6067 ($curr ? "<td class=\"current_head\">" : "<td>") .
6068 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6069 -class => "list name"},esc_html($ref{'name'})) .
6070 "</td>\n" .
6071 "<td class=\"link\">" .
6072 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6073 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6074 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6075 "</td>\n" .
6076 "</tr>";
6078 if (defined $extra) {
6079 print "<tr>\n" .
6080 "<td colspan=\"3\">$extra</td>\n" .
6081 "</tr>\n";
6083 print "</table>\n";
6086 # Display a single remote block
6087 sub git_remote_block {
6088 my ($remote, $rdata, $limit, $head) = @_;
6090 my $heads = $rdata->{'heads'};
6091 my $fetch = $rdata->{'fetch'};
6092 my $push = $rdata->{'push'};
6094 my $urls_table = "<table class=\"projects_list\">\n" ;
6096 if (defined $fetch) {
6097 if ($fetch eq $push) {
6098 $urls_table .= format_repo_url("URL", $fetch);
6099 } else {
6100 $urls_table .= format_repo_url("Fetch URL", $fetch);
6101 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6103 } elsif (defined $push) {
6104 $urls_table .= format_repo_url("Push URL", $push);
6105 } else {
6106 $urls_table .= format_repo_url("", "No remote URL");
6109 $urls_table .= "</table>\n";
6111 my $dots;
6112 if (defined $limit && $limit < @$heads) {
6113 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6116 print $urls_table;
6117 git_heads_body($heads, $head, 0, $limit, $dots);
6120 # Display a list of remote names with the respective fetch and push URLs
6121 sub git_remotes_list {
6122 my ($remotedata, $limit) = @_;
6123 print "<table class=\"heads\">\n";
6124 my $alternate = 1;
6125 my @remotes = sort keys %$remotedata;
6127 my $limited = $limit && $limit < @remotes;
6129 $#remotes = $limit - 1 if $limited;
6131 while (my $remote = shift @remotes) {
6132 my $rdata = $remotedata->{$remote};
6133 my $fetch = $rdata->{'fetch'};
6134 my $push = $rdata->{'push'};
6135 if ($alternate) {
6136 print "<tr class=\"dark\">\n";
6137 } else {
6138 print "<tr class=\"light\">\n";
6140 $alternate ^= 1;
6141 print "<td>" .
6142 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6143 -class=> "list name"},esc_html($remote)) .
6144 "</td>";
6145 print "<td class=\"link\">" .
6146 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6147 " | " .
6148 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6149 "</td>";
6151 print "</tr>\n";
6154 if ($limited) {
6155 print "<tr>\n" .
6156 "<td colspan=\"3\">" .
6157 $cgi->a({-href => href(action=>"remotes")}, "...") .
6158 "</td>\n" . "</tr>\n";
6161 print "</table>";
6164 # Display remote heads grouped by remote, unless there are too many
6165 # remotes, in which case we only display the remote names
6166 sub git_remotes_body {
6167 my ($remotedata, $limit, $head) = @_;
6168 if ($limit and $limit < keys %$remotedata) {
6169 git_remotes_list($remotedata, $limit);
6170 } else {
6171 fill_remote_heads($remotedata);
6172 while (my ($remote, $rdata) = each %$remotedata) {
6173 git_print_section({-class=>"remote", -id=>$remote},
6174 ["remotes", $remote, $remote], sub {
6175 git_remote_block($remote, $rdata, $limit, $head);
6181 sub git_search_message {
6182 my %co = @_;
6184 my $greptype;
6185 if ($searchtype eq 'commit') {
6186 $greptype = "--grep=";
6187 } elsif ($searchtype eq 'author') {
6188 $greptype = "--author=";
6189 } elsif ($searchtype eq 'committer') {
6190 $greptype = "--committer=";
6192 $greptype .= $searchtext;
6193 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6194 $greptype, '--regexp-ignore-case',
6195 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6197 my $paging_nav = '';
6198 if ($page > 0) {
6199 $paging_nav .=
6200 $cgi->a({-href => href(-replay=>1, page=>undef)},
6201 "first") .
6202 " &sdot; " .
6203 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6204 -accesskey => "p", -title => "Alt-p"}, "prev");
6205 } else {
6206 $paging_nav .= "first &sdot; prev";
6208 my $next_link = '';
6209 if ($#commitlist >= 100) {
6210 $next_link =
6211 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6212 -accesskey => "n", -title => "Alt-n"}, "next");
6213 $paging_nav .= " &sdot; $next_link";
6214 } else {
6215 $paging_nav .= " &sdot; next";
6218 git_header_html();
6220 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6221 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6222 if ($page == 0 && !@commitlist) {
6223 print "<p>No match.</p>\n";
6224 } else {
6225 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6228 git_footer_html();
6231 sub git_search_changes {
6232 my %co = @_;
6234 local $/ = "\n";
6235 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6236 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6237 ($search_use_regexp ? '--pickaxe-regex' : ())
6238 or die_error(500, "Open git-log failed");
6240 git_header_html();
6242 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6243 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6245 print "<table class=\"pickaxe search\">\n";
6246 my $alternate = 1;
6247 undef %co;
6248 my @files;
6249 while (my $line = <$fd>) {
6250 chomp $line;
6251 next unless $line;
6253 my %set = parse_difftree_raw_line($line);
6254 if (defined $set{'commit'}) {
6255 # finish previous commit
6256 if (%co) {
6257 print "</td>\n" .
6258 "<td class=\"link\">" .
6259 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6260 "commit") .
6261 " | " .
6262 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6263 hash_base=>$co{'id'})},
6264 "tree") .
6265 "</td>\n" .
6266 "</tr>\n";
6269 if ($alternate) {
6270 print "<tr class=\"dark\">\n";
6271 } else {
6272 print "<tr class=\"light\">\n";
6274 $alternate ^= 1;
6275 %co = parse_commit($set{'commit'});
6276 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6277 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6278 "<td><i>$author</i></td>\n" .
6279 "<td>" .
6280 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6281 -class => "list subject"},
6282 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6283 } elsif (defined $set{'to_id'}) {
6284 next if ($set{'to_id'} =~ m/^0{40}$/);
6286 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6287 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6288 -class => "list"},
6289 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6290 "<br/>\n";
6293 close $fd;
6295 # finish last commit (warning: repetition!)
6296 if (%co) {
6297 print "</td>\n" .
6298 "<td class=\"link\">" .
6299 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6300 "commit") .
6301 " | " .
6302 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6303 hash_base=>$co{'id'})},
6304 "tree") .
6305 "</td>\n" .
6306 "</tr>\n";
6309 print "</table>\n";
6311 git_footer_html();
6314 sub git_search_files {
6315 my %co = @_;
6317 local $/ = "\n";
6318 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6319 $search_use_regexp ? ('-E', '-i') : '-F',
6320 $searchtext, $co{'tree'}
6321 or die_error(500, "Open git-grep failed");
6323 git_header_html();
6325 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6326 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6328 print "<table class=\"grep_search\">\n";
6329 my $alternate = 1;
6330 my $matches = 0;
6331 my $lastfile = '';
6332 my $file_href;
6333 while (my $line = <$fd>) {
6334 chomp $line;
6335 my ($file, $lno, $ltext, $binary);
6336 last if ($matches++ > 1000);
6337 if ($line =~ /^Binary file (.+) matches$/) {
6338 $file = $1;
6339 $binary = 1;
6340 } else {
6341 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6342 $file =~ s/^$co{'tree'}://;
6344 if ($file ne $lastfile) {
6345 $lastfile and print "</td></tr>\n";
6346 if ($alternate++) {
6347 print "<tr class=\"dark\">\n";
6348 } else {
6349 print "<tr class=\"light\">\n";
6351 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6352 file_name=>$file);
6353 print "<td class=\"list\">".
6354 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6355 print "</td><td>\n";
6356 $lastfile = $file;
6358 if ($binary) {
6359 print "<div class=\"binary\">Binary file</div>\n";
6360 } else {
6361 $ltext = untabify($ltext);
6362 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6363 $ltext = esc_html($1, -nbsp=>1);
6364 $ltext .= '<span class="match">';
6365 $ltext .= esc_html($2, -nbsp=>1);
6366 $ltext .= '</span>';
6367 $ltext .= esc_html($3, -nbsp=>1);
6368 } else {
6369 $ltext = esc_html($ltext, -nbsp=>1);
6371 print "<div class=\"pre\">" .
6372 $cgi->a({-href => $file_href.'#l'.$lno,
6373 -class => "linenr"}, sprintf('%4i', $lno)) .
6374 ' ' . $ltext . "</div>\n";
6377 if ($lastfile) {
6378 print "</td></tr>\n";
6379 if ($matches > 1000) {
6380 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6382 } else {
6383 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6385 close $fd;
6387 print "</table>\n";
6389 git_footer_html();
6392 sub git_search_grep_body {
6393 my ($commitlist, $from, $to, $extra) = @_;
6394 $from = 0 unless defined $from;
6395 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6397 print "<table class=\"commit_search\">\n";
6398 my $alternate = 1;
6399 for (my $i = $from; $i <= $to; $i++) {
6400 my %co = %{$commitlist->[$i]};
6401 if (!%co) {
6402 next;
6404 my $commit = $co{'id'};
6405 if ($alternate) {
6406 print "<tr class=\"dark\">\n";
6407 } else {
6408 print "<tr class=\"light\">\n";
6410 $alternate ^= 1;
6411 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6412 format_author_html('td', \%co, 15, 5) .
6413 "<td>" .
6414 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6415 -class => "list subject"},
6416 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6417 my $comment = $co{'comment'};
6418 foreach my $line (@$comment) {
6419 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6420 my ($lead, $match, $trail) = ($1, $2, $3);
6421 $match = chop_str($match, 70, 5, 'center');
6422 my $contextlen = int((80 - length($match))/2);
6423 $contextlen = 30 if ($contextlen > 30);
6424 $lead = chop_str($lead, $contextlen, 10, 'left');
6425 $trail = chop_str($trail, $contextlen, 10, 'right');
6427 $lead = esc_html($lead);
6428 $match = esc_html($match);
6429 $trail = esc_html($trail);
6431 print "$lead<span class=\"match\">$match</span>$trail<br />";
6434 print "</td>\n" .
6435 "<td class=\"link\">" .
6436 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6437 " | " .
6438 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6439 " | " .
6440 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6441 print "</td>\n" .
6442 "</tr>\n";
6444 if (defined $extra) {
6445 print "<tr>\n" .
6446 "<td colspan=\"3\">$extra</td>\n" .
6447 "</tr>\n";
6449 print "</table>\n";
6452 ## ======================================================================
6453 ## ======================================================================
6454 ## actions
6456 sub git_project_list_load {
6457 my $empty_list_ok = shift;
6458 my $order = $input_params{'order'};
6459 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6460 die_error(400, "Unknown order parameter");
6463 my @list = git_get_projects_list($project_filter, $strict_export);
6464 if (!@list) {
6465 die_error(404, "No projects found") unless $empty_list_ok;
6468 return (\@list, $order);
6471 sub git_frontpage {
6472 my ($projlist, $order);
6473 ($projlist, $order) = git_project_list_load(1) if not $frontpage_no_project_list;
6475 my $limit = '';
6476 if ($project_filter) {
6477 $limit = " in '$project_filter/'";
6479 my $browse_link = "<p class=\"projectlist_link\">" .
6480 $cgi->a({-href => href(project => undef, searchtext => undef,
6481 action=>'project_list', project_filter => $project_filter)},
6482 esc_html("Browse all projects$limit")) . "</p>\n";
6484 git_header_html();
6485 if (defined $home_text && -f $home_text) {
6486 print "<div class=\"index_include\">\n";
6487 insert_file($home_text);
6488 print "</div>\n";
6490 git_project_search_form($searchtext, $search_use_regexp);
6491 if (not $frontpage_no_project_list) {
6492 print $browse_link;
6493 git_project_list_body($projlist, $order);
6494 } else {
6495 my $show_ctags = gitweb_check_feature('ctags');
6496 if ($frontpage_no_project_list == 1 and $show_ctags) {
6497 my @projects = git_get_projects_list($project_filter, $strict_export);
6498 @projects = filter_forks_from_projects_list(\@projects) if gitweb_check_feature('forks');
6499 @projects = fill_project_list_info(\@projects, 'ctags');
6500 my $ctags = git_gather_all_ctags(\@projects);
6501 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
6502 print git_show_project_tagcloud($cloud, 64);
6504 print $browse_link;
6506 git_footer_html();
6509 sub git_project_list {
6510 my ($projlist, $order) = git_project_list_load();
6511 git_header_html();
6512 git_project_search_form();
6513 git_project_list_body($projlist, $order);
6514 git_footer_html();
6517 sub git_forks {
6518 my $order = $input_params{'order'};
6519 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6520 die_error(400, "Unknown order parameter");
6523 my $filter = $project;
6524 $filter =~ s/\.git$//;
6525 my @list = git_get_projects_list($filter);
6526 if (!@list) {
6527 die_error(404, "No forks found");
6530 git_header_html();
6531 git_print_page_nav('','');
6532 git_print_header_div('summary', "$project forks");
6533 git_project_list_body(\@list, $order, undef, undef, undef, undef, 'forks');
6534 git_footer_html();
6537 sub git_project_index {
6538 my @projects = git_get_projects_list($project_filter, $strict_export);
6539 if (!@projects) {
6540 die_error(404, "No projects found");
6543 print $cgi->header(
6544 -type => 'text/plain',
6545 -charset => 'utf-8',
6546 -content_disposition => 'inline; filename="index.aux"');
6548 foreach my $pr (@projects) {
6549 if (!exists $pr->{'owner'}) {
6550 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6553 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6554 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6555 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6556 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6557 $path =~ s/ /\+/g;
6558 $owner =~ s/ /\+/g;
6560 print "$path $owner\n";
6564 sub git_summary {
6565 my $descr = git_get_project_description($project) || "none";
6566 my %co = parse_commit("HEAD");
6567 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6568 my $head = $co{'id'};
6569 my $remote_heads = gitweb_check_feature('remote_heads');
6571 my $owner = git_get_project_owner($project);
6573 my $refs = git_get_references();
6574 # These get_*_list functions return one more to allow us to see if
6575 # there are more ...
6576 my @taglist = git_get_tags_list(16);
6577 my @headlist = git_get_heads_list(16);
6578 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6579 my @forklist;
6580 my $check_forks = gitweb_check_feature('forks');
6582 if ($check_forks) {
6583 # find forks of a project
6584 my $filter = $project;
6585 $filter =~ s/\.git$//;
6586 @forklist = git_get_projects_list($filter);
6587 # filter out forks of forks
6588 @forklist = filter_forks_from_projects_list(\@forklist)
6589 if (@forklist);
6592 git_header_html();
6593 git_print_page_nav('summary','', $head);
6595 print "<div class=\"title\">&nbsp;</div>\n";
6596 print "<table class=\"projects_list\">\n" .
6597 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6598 if ($owner and not $omit_owner) {
6599 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6601 if (defined $cd{'rfc2822'}) {
6602 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6603 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6606 # use per project git URL list in $projectroot/$project/cloneurl
6607 # or make project git URL from git base URL and project name
6608 my $url_tag = "URL";
6609 my @url_list = git_get_project_url_list($project);
6610 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6611 foreach my $git_url (@url_list) {
6612 next unless $git_url;
6613 print format_repo_url($url_tag, $git_url);
6614 $url_tag = "";
6617 # Tag cloud
6618 my $show_ctags = gitweb_check_feature('ctags');
6619 if ($show_ctags) {
6620 my $ctags = git_get_project_ctags($project);
6621 if (%$ctags || $show_ctags !~ /^\d+$/) {
6622 # without ability to add tags, don't show if there are none
6623 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
6624 print "<tr id=\"metadata_ctags\">" .
6625 "<td style=\"vertical-align:middle\">content tags<br />";
6626 print "</td>\n<td>" unless %$ctags;
6627 print "<form action=\"$show_ctags\" method=\"post\">" .
6628 "<input type=\"hidden\" name=\"p\" value=\"$project\"/>" .
6629 "add: <input type=\"text\" name=\"t\" size=\"10\" /></form>"
6630 unless $show_ctags =~ /^\d+$/;
6631 print "</td>\n<td>" if %$ctags;
6632 print git_show_project_tagcloud($cloud, 48)."</td>" .
6633 "</tr>\n";
6637 print "</table>\n";
6639 # If XSS prevention is on, we don't include README.html.
6640 # TODO: Allow a readme in some safe format.
6641 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6642 print "<div class=\"title\">readme</div>\n" .
6643 "<div class=\"readme\">\n";
6644 insert_file("$projectroot/$project/README.html");
6645 print "\n</div>\n"; # class="readme"
6648 # we need to request one more than 16 (0..15) to check if
6649 # those 16 are all
6650 my @commitlist = $head ? parse_commits($head, 17) : ();
6651 if (@commitlist) {
6652 git_print_header_div('shortlog');
6653 git_shortlog_body(\@commitlist, 0, 15, $refs,
6654 $#commitlist <= 15 ? undef :
6655 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6658 if (@taglist) {
6659 git_print_header_div('tags');
6660 git_tags_body(\@taglist, 0, 15,
6661 $#taglist <= 15 ? undef :
6662 $cgi->a({-href => href(action=>"tags")}, "..."));
6665 if (@headlist) {
6666 git_print_header_div('heads');
6667 git_heads_body(\@headlist, $head, 0, 15,
6668 $#headlist <= 15 ? undef :
6669 $cgi->a({-href => href(action=>"heads")}, "..."));
6672 if (%remotedata) {
6673 git_print_header_div('remotes');
6674 git_remotes_body(\%remotedata, 15, $head);
6677 if (@forklist) {
6678 git_print_header_div('forks');
6679 git_project_list_body(\@forklist, 'age', 0, 15,
6680 $#forklist <= 15 ? undef :
6681 $cgi->a({-href => href(action=>"forks")}, "..."),
6682 'no_header', 'forks');
6685 git_footer_html();
6688 sub git_tag {
6689 my %tag = parse_tag($hash);
6691 if (! %tag) {
6692 die_error(404, "Unknown tag object");
6695 my $head = git_get_head_hash($project);
6696 git_header_html();
6697 git_print_page_nav('','', $head,undef,$head);
6698 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6699 print "<div class=\"title_text\">\n" .
6700 "<table class=\"object_header\">\n" .
6701 "<tr>\n" .
6702 "<td>object</td>\n" .
6703 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6704 $tag{'object'}) . "</td>\n" .
6705 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6706 $tag{'type'}) . "</td>\n" .
6707 "</tr>\n";
6708 if (defined($tag{'author'})) {
6709 git_print_authorship_rows(\%tag, 'author');
6711 print "</table>\n\n" .
6712 "</div>\n";
6713 print "<div class=\"page_body\">";
6714 my $comment = $tag{'comment'};
6715 foreach my $line (@$comment) {
6716 chomp $line;
6717 print esc_html($line, -nbsp=>1) . "<br/>\n";
6719 print "</div>\n";
6720 git_footer_html();
6723 sub git_blame_common {
6724 my $format = shift || 'porcelain';
6725 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6726 $format = 'incremental';
6727 $action = 'blame_incremental'; # for page title etc
6730 # permissions
6731 gitweb_check_feature('blame')
6732 or die_error(403, "Blame view not allowed");
6734 # error checking
6735 die_error(400, "No file name given") unless $file_name;
6736 $hash_base ||= git_get_head_hash($project);
6737 die_error(404, "Couldn't find base commit") unless $hash_base;
6738 my %co = parse_commit($hash_base)
6739 or die_error(404, "Commit not found");
6740 my $ftype = "blob";
6741 if (!defined $hash) {
6742 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6743 or die_error(404, "Error looking up file");
6744 } else {
6745 $ftype = git_get_type($hash);
6746 if ($ftype !~ "blob") {
6747 die_error(400, "Object is not a blob");
6751 my $fd;
6752 if ($format eq 'incremental') {
6753 # get file contents (as base)
6754 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6755 or die_error(500, "Open git-cat-file failed");
6756 } elsif ($format eq 'data') {
6757 # run git-blame --incremental
6758 open $fd, "-|", git_cmd(), "blame", "--incremental",
6759 $hash_base, "--", $file_name
6760 or die_error(500, "Open git-blame --incremental failed");
6761 } else {
6762 # run git-blame --porcelain
6763 open $fd, "-|", git_cmd(), "blame", '-p',
6764 $hash_base, '--', $file_name
6765 or die_error(500, "Open git-blame --porcelain failed");
6767 binmode $fd, ':utf8';
6769 # incremental blame data returns early
6770 if ($format eq 'data') {
6771 print $cgi->header(
6772 -type=>"text/plain", -charset => "utf-8",
6773 -status=> "200 OK");
6774 local $| = 1; # output autoflush
6775 while (my $line = <$fd>) {
6776 print to_utf8($line);
6778 close $fd
6779 or print "ERROR $!\n";
6781 print 'END';
6782 if (defined $t0 && gitweb_check_feature('timed')) {
6783 print ' '.
6784 tv_interval($t0, [ gettimeofday() ]).
6785 ' '.$number_of_git_cmds;
6787 print "\n";
6789 return;
6792 # page header
6793 git_header_html();
6794 my $formats_nav =
6795 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6796 "blob") .
6797 " | ";
6798 if ($format eq 'incremental') {
6799 $formats_nav .=
6800 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6801 "blame") . " (non-incremental)";
6802 } else {
6803 $formats_nav .=
6804 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6805 "blame") . " (incremental)";
6807 $formats_nav .=
6808 " | " .
6809 $cgi->a({-href => href(action=>"history", -replay=>1)},
6810 "history") .
6811 " | " .
6812 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6813 "HEAD");
6814 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6815 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6816 git_print_page_path($file_name, $ftype, $hash_base);
6818 # page body
6819 if ($format eq 'incremental') {
6820 print "<noscript>\n<div class=\"error\"><center><b>\n".
6821 "This page requires JavaScript to run.\n Use ".
6822 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6823 'this page').
6824 " instead.\n".
6825 "</b></center></div>\n</noscript>\n";
6827 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6830 print qq!<div class="page_body">\n!;
6831 print qq!<div id="progress_info">... / ...</div>\n!
6832 if ($format eq 'incremental');
6833 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6834 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6835 qq!<thead>\n!.
6836 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6837 qq!</thead>\n!.
6838 qq!<tbody>\n!;
6840 my @rev_color = qw(light dark);
6841 my $num_colors = scalar(@rev_color);
6842 my $current_color = 0;
6844 if ($format eq 'incremental') {
6845 my $color_class = $rev_color[$current_color];
6847 #contents of a file
6848 my $linenr = 0;
6849 LINE:
6850 while (my $line = <$fd>) {
6851 chomp $line;
6852 $linenr++;
6854 print qq!<tr id="l$linenr" class="$color_class">!.
6855 qq!<td class="sha1"><a href=""> </a></td>!.
6856 qq!<td class="linenr">!.
6857 qq!<a class="linenr" href="">$linenr</a></td>!;
6858 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6859 print qq!</tr>\n!;
6862 } else { # porcelain, i.e. ordinary blame
6863 my %metainfo = (); # saves information about commits
6865 # blame data
6866 LINE:
6867 while (my $line = <$fd>) {
6868 chomp $line;
6869 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6870 # no <lines in group> for subsequent lines in group of lines
6871 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6872 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6873 if (!exists $metainfo{$full_rev}) {
6874 $metainfo{$full_rev} = { 'nprevious' => 0 };
6876 my $meta = $metainfo{$full_rev};
6877 my $data;
6878 while ($data = <$fd>) {
6879 chomp $data;
6880 last if ($data =~ s/^\t//); # contents of line
6881 if ($data =~ /^(\S+)(?: (.*))?$/) {
6882 $meta->{$1} = $2 unless exists $meta->{$1};
6884 if ($data =~ /^previous /) {
6885 $meta->{'nprevious'}++;
6888 my $short_rev = substr($full_rev, 0, 8);
6889 my $author = $meta->{'author'};
6890 my %date =
6891 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6892 my $date = $date{'iso-tz'};
6893 if ($group_size) {
6894 $current_color = ($current_color + 1) % $num_colors;
6896 my $tr_class = $rev_color[$current_color];
6897 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6898 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6899 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6900 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6901 if ($group_size) {
6902 print "<td class=\"sha1\"";
6903 print " title=\"". esc_html($author) . ", $date\"";
6904 print " rowspan=\"$group_size\"" if ($group_size > 1);
6905 print ">";
6906 print $cgi->a({-href => href(action=>"commit",
6907 hash=>$full_rev,
6908 file_name=>$file_name)},
6909 esc_html($short_rev));
6910 if ($group_size >= 2) {
6911 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6912 if (@author_initials) {
6913 print "<br />" .
6914 esc_html(join('', @author_initials));
6915 # or join('.', ...)
6918 print "</td>\n";
6920 # 'previous' <sha1 of parent commit> <filename at commit>
6921 if (exists $meta->{'previous'} &&
6922 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6923 $meta->{'parent'} = $1;
6924 $meta->{'file_parent'} = unquote($2);
6926 my $linenr_commit =
6927 exists($meta->{'parent'}) ?
6928 $meta->{'parent'} : $full_rev;
6929 my $linenr_filename =
6930 exists($meta->{'file_parent'}) ?
6931 $meta->{'file_parent'} : unquote($meta->{'filename'});
6932 my $blamed = href(action => 'blame',
6933 file_name => $linenr_filename,
6934 hash_base => $linenr_commit);
6935 print "<td class=\"linenr\">";
6936 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6937 -class => "linenr" },
6938 esc_html($lineno));
6939 print "</td>";
6940 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6941 print "</tr>\n";
6942 } # end while
6946 # footer
6947 print "</tbody>\n".
6948 "</table>\n"; # class="blame"
6949 print "</div>\n"; # class="blame_body"
6950 close $fd
6951 or print "Reading blob failed\n";
6953 git_footer_html();
6956 sub git_blame {
6957 git_blame_common();
6960 sub git_blame_incremental {
6961 git_blame_common('incremental');
6964 sub git_blame_data {
6965 git_blame_common('data');
6968 sub git_tags {
6969 my $head = git_get_head_hash($project);
6970 git_header_html();
6971 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6972 git_print_header_div('summary', $project);
6974 my @tagslist = git_get_tags_list();
6975 if (@tagslist) {
6976 git_tags_body(\@tagslist);
6978 git_footer_html();
6981 sub git_heads {
6982 my $head = git_get_head_hash($project);
6983 git_header_html();
6984 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6985 git_print_header_div('summary', $project);
6987 my @headslist = git_get_heads_list();
6988 if (@headslist) {
6989 git_heads_body(\@headslist, $head);
6991 git_footer_html();
6994 # used both for single remote view and for list of all the remotes
6995 sub git_remotes {
6996 gitweb_check_feature('remote_heads')
6997 or die_error(403, "Remote heads view is disabled");
6999 my $head = git_get_head_hash($project);
7000 my $remote = $input_params{'hash'};
7002 my $remotedata = git_get_remotes_list($remote);
7003 die_error(500, "Unable to get remote information") unless defined $remotedata;
7005 unless (%$remotedata) {
7006 die_error(404, defined $remote ?
7007 "Remote $remote not found" :
7008 "No remotes found");
7011 git_header_html(undef, undef, -action_extra => $remote);
7012 git_print_page_nav('', '', $head, undef, $head,
7013 format_ref_views($remote ? '' : 'remotes'));
7015 fill_remote_heads($remotedata);
7016 if (defined $remote) {
7017 git_print_header_div('remotes', "$remote remote for $project");
7018 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7019 } else {
7020 git_print_header_div('summary', "$project remotes");
7021 git_remotes_body($remotedata, undef, $head);
7024 git_footer_html();
7027 sub git_blob_plain {
7028 my $type = shift;
7029 my $expires;
7031 if (!defined $hash) {
7032 if (defined $file_name) {
7033 my $base = $hash_base || git_get_head_hash($project);
7034 $hash = git_get_hash_by_path($base, $file_name, "blob")
7035 or die_error(404, "Cannot find file");
7036 } else {
7037 die_error(400, "No file name defined");
7039 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7040 # blobs defined by non-textual hash id's can be cached
7041 $expires = "+1d";
7044 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7045 or die_error(500, "Open git-cat-file blob '$hash' failed");
7047 # content-type (can include charset)
7048 $type = blob_contenttype($fd, $file_name, $type);
7050 # "save as" filename, even when no $file_name is given
7051 my $save_as = "$hash";
7052 if (defined $file_name) {
7053 $save_as = $file_name;
7054 } elsif ($type =~ m/^text\//) {
7055 $save_as .= '.txt';
7058 # With XSS prevention on, blobs of all types except a few known safe
7059 # ones are served with "Content-Disposition: attachment" to make sure
7060 # they don't run in our security domain. For certain image types,
7061 # blob view writes an <img> tag referring to blob_plain view, and we
7062 # want to be sure not to break that by serving the image as an
7063 # attachment (though Firefox 3 doesn't seem to care).
7064 my $sandbox = $prevent_xss &&
7065 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7067 # serve text/* as text/plain
7068 if ($prevent_xss &&
7069 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7070 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7071 my $rest = $1;
7072 $rest = defined $rest ? $rest : '';
7073 $type = "text/plain$rest";
7076 print $cgi->header(
7077 -type => $type,
7078 -expires => $expires,
7079 -content_disposition =>
7080 ($sandbox ? 'attachment' : 'inline')
7081 . '; filename="' . $save_as . '"');
7082 local $/ = undef;
7083 binmode STDOUT, ':raw';
7084 print <$fd>;
7085 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7086 close $fd;
7089 sub git_blob {
7090 my $expires;
7092 if (!defined $hash) {
7093 if (defined $file_name) {
7094 my $base = $hash_base || git_get_head_hash($project);
7095 $hash = git_get_hash_by_path($base, $file_name, "blob")
7096 or die_error(404, "Cannot find file");
7097 } else {
7098 die_error(400, "No file name defined");
7100 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7101 # blobs defined by non-textual hash id's can be cached
7102 $expires = "+1d";
7105 my $have_blame = gitweb_check_feature('blame');
7106 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7107 or die_error(500, "Couldn't cat $file_name, $hash");
7108 my $mimetype = blob_mimetype($fd, $file_name);
7109 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7110 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7111 close $fd;
7112 return git_blob_plain($mimetype);
7114 # we can have blame only for text/* mimetype
7115 $have_blame &&= ($mimetype =~ m!^text/!);
7117 my $highlight = gitweb_check_feature('highlight');
7118 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7119 $fd = run_highlighter($fd, $highlight, $syntax)
7120 if $syntax;
7122 git_header_html(undef, $expires);
7123 my $formats_nav = '';
7124 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7125 if (defined $file_name) {
7126 if ($have_blame) {
7127 $formats_nav .=
7128 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7129 "blame") .
7130 " | ";
7132 $formats_nav .=
7133 $cgi->a({-href => href(action=>"history", -replay=>1)},
7134 "history") .
7135 " | " .
7136 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7137 "raw") .
7138 " | " .
7139 $cgi->a({-href => href(action=>"blob",
7140 hash_base=>"HEAD", file_name=>$file_name)},
7141 "HEAD");
7142 } else {
7143 $formats_nav .=
7144 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7145 "raw");
7147 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7148 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7149 } else {
7150 print "<div class=\"page_nav\">\n" .
7151 "<br/><br/></div>\n" .
7152 "<div class=\"title\">".esc_html($hash)."</div>\n";
7154 git_print_page_path($file_name, "blob", $hash_base);
7155 print "<div class=\"page_body\">\n";
7156 if ($mimetype =~ m!^image/!) {
7157 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7158 if ($file_name) {
7159 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7161 print qq! src="! .
7162 href(action=>"blob_plain", hash=>$hash,
7163 hash_base=>$hash_base, file_name=>$file_name) .
7164 qq!" />\n!;
7165 } else {
7166 my $nr;
7167 while (my $line = <$fd>) {
7168 chomp $line;
7169 $nr++;
7170 $line = untabify($line);
7171 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7172 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7173 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7176 close $fd
7177 or print "Reading blob failed.\n";
7178 print "</div>";
7179 git_footer_html();
7182 sub git_tree {
7183 if (!defined $hash_base) {
7184 $hash_base = "HEAD";
7186 if (!defined $hash) {
7187 if (defined $file_name) {
7188 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7189 } else {
7190 $hash = $hash_base;
7193 die_error(404, "No such tree") unless defined($hash);
7195 my $show_sizes = gitweb_check_feature('show-sizes');
7196 my $have_blame = gitweb_check_feature('blame');
7198 my @entries = ();
7200 local $/ = "\0";
7201 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7202 ($show_sizes ? '-l' : ()), @extra_options, $hash
7203 or die_error(500, "Open git-ls-tree failed");
7204 @entries = map { chomp; $_ } <$fd>;
7205 close $fd
7206 or die_error(404, "Reading tree failed");
7209 my $refs = git_get_references();
7210 my $ref = format_ref_marker($refs, $hash_base);
7211 git_header_html();
7212 my $basedir = '';
7213 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7214 my @views_nav = ();
7215 if (defined $file_name) {
7216 push @views_nav,
7217 $cgi->a({-href => href(action=>"history", -replay=>1)},
7218 "history"),
7219 $cgi->a({-href => href(action=>"tree",
7220 hash_base=>"HEAD", file_name=>$file_name)},
7221 "HEAD"),
7223 my $snapshot_links = format_snapshot_links($hash);
7224 if (defined $snapshot_links) {
7225 # FIXME: Should be available when we have no hash base as well.
7226 push @views_nav, $snapshot_links;
7228 git_print_page_nav('tree','', $hash_base, undef, undef,
7229 join(' | ', @views_nav));
7230 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7231 } else {
7232 undef $hash_base;
7233 print "<div class=\"page_nav\">\n";
7234 print "<br/><br/></div>\n";
7235 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7237 if (defined $file_name) {
7238 $basedir = $file_name;
7239 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7240 $basedir .= '/';
7242 git_print_page_path($file_name, 'tree', $hash_base);
7244 print "<div class=\"page_body\">\n";
7245 print "<table class=\"tree\">\n";
7246 my $alternate = 1;
7247 # '..' (top directory) link if possible
7248 if (defined $hash_base &&
7249 defined $file_name && $file_name =~ m![^/]+$!) {
7250 if ($alternate) {
7251 print "<tr class=\"dark\">\n";
7252 } else {
7253 print "<tr class=\"light\">\n";
7255 $alternate ^= 1;
7257 my $up = $file_name;
7258 $up =~ s!/?[^/]+$!!;
7259 undef $up unless $up;
7260 # based on git_print_tree_entry
7261 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7262 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7263 print '<td class="list">';
7264 print $cgi->a({-href => href(action=>"tree",
7265 hash_base=>$hash_base,
7266 file_name=>$up)},
7267 "..");
7268 print "</td>\n";
7269 print "<td class=\"link\"></td>\n";
7271 print "</tr>\n";
7273 foreach my $line (@entries) {
7274 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7276 if ($alternate) {
7277 print "<tr class=\"dark\">\n";
7278 } else {
7279 print "<tr class=\"light\">\n";
7281 $alternate ^= 1;
7283 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7285 print "</tr>\n";
7287 print "</table>\n" .
7288 "</div>";
7289 git_footer_html();
7292 sub sanitize_for_filename {
7293 my $name = shift;
7295 $name =~ s!/!-!g;
7296 $name =~ s/[^[:alnum:]_.-]//g;
7298 return $name;
7301 sub snapshot_name {
7302 my ($project, $hash) = @_;
7304 # path/to/project.git -> project
7305 # path/to/project/.git -> project
7306 my $name = to_utf8($project);
7307 $name =~ s,([^/])/*\.git$,$1,;
7308 $name = sanitize_for_filename(basename($name));
7310 my $ver = $hash;
7311 if ($hash =~ /^[0-9a-fA-F]+$/) {
7312 # shorten SHA-1 hash
7313 my $full_hash = git_get_full_hash($project, $hash);
7314 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7315 $ver = git_get_short_hash($project, $hash);
7317 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7318 # tags don't need shortened SHA-1 hash
7319 $ver = $1;
7320 } else {
7321 # branches and other need shortened SHA-1 hash
7322 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7323 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7324 my $ref_dir = (defined $1) ? $1 : '';
7325 $ver = $2;
7327 $ref_dir = sanitize_for_filename($ref_dir);
7328 # for refs neither in heads nor remotes we want to
7329 # add a ref dir to archive name
7330 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7331 $ver = $ref_dir . '-' . $ver;
7334 $ver .= '-' . git_get_short_hash($project, $hash);
7336 # special case of sanitization for filename - we change
7337 # slashes to dots instead of dashes
7338 # in case of hierarchical branch names
7339 $ver =~ s!/!.!g;
7340 $ver =~ s/[^[:alnum:]_.-]//g;
7342 # name = project-version_string
7343 $name = "$name-$ver";
7345 return wantarray ? ($name, $name) : $name;
7348 sub exit_if_unmodified_since {
7349 my ($latest_epoch) = @_;
7350 our $cgi;
7352 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7353 if (defined $if_modified) {
7354 my $since;
7355 if (eval { require HTTP::Date; 1; }) {
7356 $since = HTTP::Date::str2time($if_modified);
7357 } elsif (eval { require Time::ParseDate; 1; }) {
7358 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7360 if (defined $since && $latest_epoch <= $since) {
7361 my %latest_date = parse_date($latest_epoch);
7362 print $cgi->header(
7363 -last_modified => $latest_date{'rfc2822'},
7364 -status => '304 Not Modified');
7365 goto DONE_GITWEB;
7370 sub git_snapshot {
7371 my $format = $input_params{'snapshot_format'};
7372 if (!@snapshot_fmts) {
7373 die_error(403, "Snapshots not allowed");
7375 # default to first supported snapshot format
7376 $format ||= $snapshot_fmts[0];
7377 if ($format !~ m/^[a-z0-9]+$/) {
7378 die_error(400, "Invalid snapshot format parameter");
7379 } elsif (!exists($known_snapshot_formats{$format})) {
7380 die_error(400, "Unknown snapshot format");
7381 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7382 die_error(403, "Snapshot format not allowed");
7383 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7384 die_error(403, "Unsupported snapshot format");
7387 my $type = git_get_type("$hash^{}");
7388 if (!$type) {
7389 die_error(404, 'Object does not exist');
7390 } elsif ($type eq 'blob') {
7391 die_error(400, 'Object is not a tree-ish');
7394 my ($name, $prefix) = snapshot_name($project, $hash);
7395 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7397 my %co = parse_commit($hash);
7398 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7400 my $cmd = quote_command(
7401 git_cmd(), 'archive',
7402 "--format=$known_snapshot_formats{$format}{'format'}",
7403 "--prefix=$prefix/", $hash);
7404 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7405 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7408 $filename =~ s/(["\\])/\\$1/g;
7409 my %latest_date;
7410 if (%co) {
7411 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7414 print $cgi->header(
7415 -type => $known_snapshot_formats{$format}{'type'},
7416 -content_disposition => 'inline; filename="' . $filename . '"',
7417 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7418 -status => '200 OK');
7420 open my $fd, "-|", $cmd
7421 or die_error(500, "Execute git-archive failed");
7422 binmode STDOUT, ':raw';
7423 print <$fd>;
7424 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7425 close $fd;
7428 sub git_log_generic {
7429 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7431 my $head = git_get_head_hash($project);
7432 if (!defined $base) {
7433 $base = $head;
7435 if (!defined $page) {
7436 $page = 0;
7438 my $refs = git_get_references();
7440 my $commit_hash = $base;
7441 if (defined $parent) {
7442 $commit_hash = "$parent..$base";
7444 my @commitlist =
7445 parse_commits($commit_hash, 101, (100 * $page),
7446 defined $file_name ? ($file_name, "--full-history") : ());
7448 my $ftype;
7449 if (!defined $file_hash && defined $file_name) {
7450 # some commits could have deleted file in question,
7451 # and not have it in tree, but one of them has to have it
7452 for (my $i = 0; $i < @commitlist; $i++) {
7453 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7454 last if defined $file_hash;
7457 if (defined $file_hash) {
7458 $ftype = git_get_type($file_hash);
7460 if (defined $file_name && !defined $ftype) {
7461 die_error(500, "Unknown type of object");
7463 my %co;
7464 if (defined $file_name) {
7465 %co = parse_commit($base)
7466 or die_error(404, "Unknown commit object");
7470 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7471 my $next_link = '';
7472 if ($#commitlist >= 100) {
7473 $next_link =
7474 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7475 -accesskey => "n", -title => "Alt-n"}, "next");
7477 my $patch_max = gitweb_get_feature('patches');
7478 if ($patch_max && !defined $file_name) {
7479 if ($patch_max < 0 || @commitlist <= $patch_max) {
7480 $paging_nav .= " &sdot; " .
7481 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7482 "patches");
7486 git_header_html();
7487 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7488 if (defined $file_name) {
7489 git_print_header_div('commit', esc_html($co{'title'}), $base);
7490 } else {
7491 git_print_header_div('summary', $project)
7493 git_print_page_path($file_name, $ftype, $hash_base)
7494 if (defined $file_name);
7496 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7497 $file_name, $file_hash, $ftype);
7499 git_footer_html();
7502 sub git_log {
7503 git_log_generic('log', \&git_log_body,
7504 $hash, $hash_parent);
7507 sub git_commit {
7508 $hash ||= $hash_base || "HEAD";
7509 my %co = parse_commit($hash)
7510 or die_error(404, "Unknown commit object");
7512 my $parent = $co{'parent'};
7513 my $parents = $co{'parents'}; # listref
7515 # we need to prepare $formats_nav before any parameter munging
7516 my $formats_nav;
7517 if (!defined $parent) {
7518 # --root commitdiff
7519 $formats_nav .= '(initial)';
7520 } elsif (@$parents == 1) {
7521 # single parent commit
7522 $formats_nav .=
7523 '(parent: ' .
7524 $cgi->a({-href => href(action=>"commit",
7525 hash=>$parent)},
7526 esc_html(substr($parent, 0, 7))) .
7527 ')';
7528 } else {
7529 # merge commit
7530 $formats_nav .=
7531 '(merge: ' .
7532 join(' ', map {
7533 $cgi->a({-href => href(action=>"commit",
7534 hash=>$_)},
7535 esc_html(substr($_, 0, 7)));
7536 } @$parents ) .
7537 ')';
7539 if (gitweb_check_feature('patches') && @$parents <= 1) {
7540 $formats_nav .= " | " .
7541 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7542 "patch");
7545 if (!defined $parent) {
7546 $parent = "--root";
7548 my @difftree;
7549 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7550 @diff_opts,
7551 (@$parents <= 1 ? $parent : '-c'),
7552 $hash, "--"
7553 or die_error(500, "Open git-diff-tree failed");
7554 @difftree = map { chomp; $_ } <$fd>;
7555 close $fd or die_error(404, "Reading git-diff-tree failed");
7557 # non-textual hash id's can be cached
7558 my $expires;
7559 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7560 $expires = "+1d";
7562 my $refs = git_get_references();
7563 my $ref = format_ref_marker($refs, $co{'id'});
7565 git_header_html(undef, $expires);
7566 git_print_page_nav('commit', '',
7567 $hash, $co{'tree'}, $hash,
7568 $formats_nav);
7570 if (defined $co{'parent'}) {
7571 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7572 } else {
7573 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7575 print "<div class=\"title_text\">\n" .
7576 "<table class=\"object_header\">\n";
7577 git_print_authorship_rows(\%co);
7578 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7579 print "<tr>" .
7580 "<td>tree</td>" .
7581 "<td class=\"sha1\">" .
7582 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7583 class => "list"}, $co{'tree'}) .
7584 "</td>" .
7585 "<td class=\"link\">" .
7586 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7587 "tree");
7588 my $snapshot_links = format_snapshot_links($hash);
7589 if (defined $snapshot_links) {
7590 print " | " . $snapshot_links;
7592 print "</td>" .
7593 "</tr>\n";
7595 foreach my $par (@$parents) {
7596 print "<tr>" .
7597 "<td>parent</td>" .
7598 "<td class=\"sha1\">" .
7599 $cgi->a({-href => href(action=>"commit", hash=>$par),
7600 class => "list"}, $par) .
7601 "</td>" .
7602 "<td class=\"link\">" .
7603 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7604 " | " .
7605 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7606 "</td>" .
7607 "</tr>\n";
7609 print "</table>".
7610 "</div>\n";
7612 print "<div class=\"page_body\">\n";
7613 git_print_log($co{'comment'});
7614 print "</div>\n";
7616 git_difftree_body(\@difftree, $hash, @$parents);
7618 git_footer_html();
7621 sub git_object {
7622 # object is defined by:
7623 # - hash or hash_base alone
7624 # - hash_base and file_name
7625 my $type;
7627 # - hash or hash_base alone
7628 if ($hash || ($hash_base && !defined $file_name)) {
7629 my $object_id = $hash || $hash_base;
7631 open my $fd, "-|", quote_command(
7632 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7633 or die_error(404, "Object does not exist");
7634 $type = <$fd>;
7635 chomp $type;
7636 close $fd
7637 or die_error(404, "Object does not exist");
7639 # - hash_base and file_name
7640 } elsif ($hash_base && defined $file_name) {
7641 $file_name =~ s,/+$,,;
7643 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7644 or die_error(404, "Base object does not exist");
7646 # here errors should not happen
7647 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7648 or die_error(500, "Open git-ls-tree failed");
7649 my $line = <$fd>;
7650 close $fd;
7652 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7653 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7654 die_error(404, "File or directory for given base does not exist");
7656 $type = $2;
7657 $hash = $3;
7658 } else {
7659 die_error(400, "Not enough information to find object");
7662 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7663 hash=>$hash, hash_base=>$hash_base,
7664 file_name=>$file_name),
7665 -status => '302 Found');
7668 sub git_blobdiff {
7669 my $format = shift || 'html';
7670 my $diff_style = $input_params{'diff_style'} || 'inline';
7672 my $fd;
7673 my @difftree;
7674 my %diffinfo;
7675 my $expires;
7677 # preparing $fd and %diffinfo for git_patchset_body
7678 # new style URI
7679 if (defined $hash_base && defined $hash_parent_base) {
7680 if (defined $file_name) {
7681 # read raw output
7682 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7683 $hash_parent_base, $hash_base,
7684 "--", (defined $file_parent ? $file_parent : ()), $file_name
7685 or die_error(500, "Open git-diff-tree failed");
7686 @difftree = map { chomp; $_ } <$fd>;
7687 close $fd
7688 or die_error(404, "Reading git-diff-tree failed");
7689 @difftree
7690 or die_error(404, "Blob diff not found");
7692 } elsif (defined $hash &&
7693 $hash =~ /[0-9a-fA-F]{40}/) {
7694 # try to find filename from $hash
7696 # read filtered raw output
7697 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7698 $hash_parent_base, $hash_base, "--"
7699 or die_error(500, "Open git-diff-tree failed");
7700 @difftree =
7701 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7702 # $hash == to_id
7703 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7704 map { chomp; $_ } <$fd>;
7705 close $fd
7706 or die_error(404, "Reading git-diff-tree failed");
7707 @difftree
7708 or die_error(404, "Blob diff not found");
7710 } else {
7711 die_error(400, "Missing one of the blob diff parameters");
7714 if (@difftree > 1) {
7715 die_error(400, "Ambiguous blob diff specification");
7718 %diffinfo = parse_difftree_raw_line($difftree[0]);
7719 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7720 $file_name ||= $diffinfo{'to_file'};
7722 $hash_parent ||= $diffinfo{'from_id'};
7723 $hash ||= $diffinfo{'to_id'};
7725 # non-textual hash id's can be cached
7726 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7727 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7728 $expires = '+1d';
7731 # open patch output
7732 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7733 '-p', ($format eq 'html' ? "--full-index" : ()),
7734 $hash_parent_base, $hash_base,
7735 "--", (defined $file_parent ? $file_parent : ()), $file_name
7736 or die_error(500, "Open git-diff-tree failed");
7739 # old/legacy style URI -- not generated anymore since 1.4.3.
7740 if (!%diffinfo) {
7741 die_error('404 Not Found', "Missing one of the blob diff parameters")
7744 # header
7745 if ($format eq 'html') {
7746 my $formats_nav =
7747 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7748 "raw");
7749 $formats_nav .= diff_style_nav($diff_style);
7750 git_header_html(undef, $expires);
7751 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7752 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7753 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7754 } else {
7755 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7756 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7758 if (defined $file_name) {
7759 git_print_page_path($file_name, "blob", $hash_base);
7760 } else {
7761 print "<div class=\"page_path\"></div>\n";
7764 } elsif ($format eq 'plain') {
7765 print $cgi->header(
7766 -type => 'text/plain',
7767 -charset => 'utf-8',
7768 -expires => $expires,
7769 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7771 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7773 } else {
7774 die_error(400, "Unknown blobdiff format");
7777 # patch
7778 if ($format eq 'html') {
7779 print "<div class=\"page_body\">\n";
7781 git_patchset_body($fd, $diff_style,
7782 [ \%diffinfo ], $hash_base, $hash_parent_base);
7783 close $fd;
7785 print "</div>\n"; # class="page_body"
7786 git_footer_html();
7788 } else {
7789 while (my $line = <$fd>) {
7790 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7791 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7793 print $line;
7795 last if $line =~ m!^\+\+\+!;
7797 local $/ = undef;
7798 print <$fd>;
7799 close $fd;
7803 sub git_blobdiff_plain {
7804 git_blobdiff('plain');
7807 # assumes that it is added as later part of already existing navigation,
7808 # so it returns "| foo | bar" rather than just "foo | bar"
7809 sub diff_style_nav {
7810 my ($diff_style, $is_combined) = @_;
7811 $diff_style ||= 'inline';
7813 return "" if ($is_combined);
7815 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7816 my %styles = @styles;
7817 @styles =
7818 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7820 return join '',
7821 map { " | ".$_ }
7822 map {
7823 $_ eq $diff_style ? $styles{$_} :
7824 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7825 } @styles;
7828 sub git_commitdiff {
7829 my %params = @_;
7830 my $format = $params{-format} || 'html';
7831 my $diff_style = $input_params{'diff_style'} || 'inline';
7833 my ($patch_max) = gitweb_get_feature('patches');
7834 if ($format eq 'patch') {
7835 die_error(403, "Patch view not allowed") unless $patch_max;
7838 $hash ||= $hash_base || "HEAD";
7839 my %co = parse_commit($hash)
7840 or die_error(404, "Unknown commit object");
7842 # choose format for commitdiff for merge
7843 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7844 $hash_parent = '--cc';
7846 # we need to prepare $formats_nav before almost any parameter munging
7847 my $formats_nav;
7848 if ($format eq 'html') {
7849 $formats_nav =
7850 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7851 "raw");
7852 if ($patch_max && @{$co{'parents'}} <= 1) {
7853 $formats_nav .= " | " .
7854 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7855 "patch");
7857 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7859 if (defined $hash_parent &&
7860 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7861 # commitdiff with two commits given
7862 my $hash_parent_short = $hash_parent;
7863 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7864 $hash_parent_short = substr($hash_parent, 0, 7);
7866 $formats_nav .=
7867 ' (from';
7868 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7869 if ($co{'parents'}[$i] eq $hash_parent) {
7870 $formats_nav .= ' parent ' . ($i+1);
7871 last;
7874 $formats_nav .= ': ' .
7875 $cgi->a({-href => href(-replay=>1,
7876 hash=>$hash_parent, hash_base=>undef)},
7877 esc_html($hash_parent_short)) .
7878 ')';
7879 } elsif (!$co{'parent'}) {
7880 # --root commitdiff
7881 $formats_nav .= ' (initial)';
7882 } elsif (scalar @{$co{'parents'}} == 1) {
7883 # single parent commit
7884 $formats_nav .=
7885 ' (parent: ' .
7886 $cgi->a({-href => href(-replay=>1,
7887 hash=>$co{'parent'}, hash_base=>undef)},
7888 esc_html(substr($co{'parent'}, 0, 7))) .
7889 ')';
7890 } else {
7891 # merge commit
7892 if ($hash_parent eq '--cc') {
7893 $formats_nav .= ' | ' .
7894 $cgi->a({-href => href(-replay=>1,
7895 hash=>$hash, hash_parent=>'-c')},
7896 'combined');
7897 } else { # $hash_parent eq '-c'
7898 $formats_nav .= ' | ' .
7899 $cgi->a({-href => href(-replay=>1,
7900 hash=>$hash, hash_parent=>'--cc')},
7901 'compact');
7903 $formats_nav .=
7904 ' (merge: ' .
7905 join(' ', map {
7906 $cgi->a({-href => href(-replay=>1,
7907 hash=>$_, hash_base=>undef)},
7908 esc_html(substr($_, 0, 7)));
7909 } @{$co{'parents'}} ) .
7910 ')';
7914 my $hash_parent_param = $hash_parent;
7915 if (!defined $hash_parent_param) {
7916 # --cc for multiple parents, --root for parentless
7917 $hash_parent_param =
7918 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7921 # read commitdiff
7922 my $fd;
7923 my @difftree;
7924 if ($format eq 'html') {
7925 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7926 "--no-commit-id", "--patch-with-raw", "--full-index",
7927 $hash_parent_param, $hash, "--"
7928 or die_error(500, "Open git-diff-tree failed");
7930 while (my $line = <$fd>) {
7931 chomp $line;
7932 # empty line ends raw part of diff-tree output
7933 last unless $line;
7934 push @difftree, scalar parse_difftree_raw_line($line);
7937 } elsif ($format eq 'plain') {
7938 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7939 '-p', $hash_parent_param, $hash, "--"
7940 or die_error(500, "Open git-diff-tree failed");
7941 } elsif ($format eq 'patch') {
7942 # For commit ranges, we limit the output to the number of
7943 # patches specified in the 'patches' feature.
7944 # For single commits, we limit the output to a single patch,
7945 # diverging from the git-format-patch default.
7946 my @commit_spec = ();
7947 if ($hash_parent) {
7948 if ($patch_max > 0) {
7949 push @commit_spec, "-$patch_max";
7951 push @commit_spec, '-n', "$hash_parent..$hash";
7952 } else {
7953 if ($params{-single}) {
7954 push @commit_spec, '-1';
7955 } else {
7956 if ($patch_max > 0) {
7957 push @commit_spec, "-$patch_max";
7959 push @commit_spec, "-n";
7961 push @commit_spec, '--root', $hash;
7963 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7964 '--encoding=utf8', '--stdout', @commit_spec
7965 or die_error(500, "Open git-format-patch failed");
7966 } else {
7967 die_error(400, "Unknown commitdiff format");
7970 # non-textual hash id's can be cached
7971 my $expires;
7972 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7973 $expires = "+1d";
7976 # write commit message
7977 if ($format eq 'html') {
7978 my $refs = git_get_references();
7979 my $ref = format_ref_marker($refs, $co{'id'});
7981 git_header_html(undef, $expires);
7982 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7983 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7984 print "<div class=\"title_text\">\n" .
7985 "<table class=\"object_header\">\n";
7986 git_print_authorship_rows(\%co);
7987 print "</table>".
7988 "</div>\n";
7989 print "<div class=\"page_body\">\n";
7990 if (@{$co{'comment'}} > 1) {
7991 print "<div class=\"log\">\n";
7992 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7993 print "</div>\n"; # class="log"
7996 } elsif ($format eq 'plain') {
7997 my $refs = git_get_references("tags");
7998 my $tagname = git_get_rev_name_tags($hash);
7999 my $filename = basename($project) . "-$hash.patch";
8001 print $cgi->header(
8002 -type => 'text/plain',
8003 -charset => 'utf-8',
8004 -expires => $expires,
8005 -content_disposition => 'inline; filename="' . "$filename" . '"');
8006 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8007 print "From: " . to_utf8($co{'author'}) . "\n";
8008 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8009 print "Subject: " . to_utf8($co{'title'}) . "\n";
8011 print "X-Git-Tag: $tagname\n" if $tagname;
8012 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8014 foreach my $line (@{$co{'comment'}}) {
8015 print to_utf8($line) . "\n";
8017 print "---\n\n";
8018 } elsif ($format eq 'patch') {
8019 my $filename = basename($project) . "-$hash.patch";
8021 print $cgi->header(
8022 -type => 'text/plain',
8023 -charset => 'utf-8',
8024 -expires => $expires,
8025 -content_disposition => 'inline; filename="' . "$filename" . '"');
8028 # write patch
8029 if ($format eq 'html') {
8030 my $use_parents = !defined $hash_parent ||
8031 $hash_parent eq '-c' || $hash_parent eq '--cc';
8032 git_difftree_body(\@difftree, $hash,
8033 $use_parents ? @{$co{'parents'}} : $hash_parent);
8034 print "<br/>\n";
8036 git_patchset_body($fd, $diff_style,
8037 \@difftree, $hash,
8038 $use_parents ? @{$co{'parents'}} : $hash_parent);
8039 close $fd;
8040 print "</div>\n"; # class="page_body"
8041 git_footer_html();
8043 } elsif ($format eq 'plain') {
8044 local $/ = undef;
8045 print <$fd>;
8046 close $fd
8047 or print "Reading git-diff-tree failed\n";
8048 } elsif ($format eq 'patch') {
8049 local $/ = undef;
8050 print <$fd>;
8051 close $fd
8052 or print "Reading git-format-patch failed\n";
8056 sub git_commitdiff_plain {
8057 git_commitdiff(-format => 'plain');
8060 # format-patch-style patches
8061 sub git_patch {
8062 git_commitdiff(-format => 'patch', -single => 1);
8065 sub git_patches {
8066 git_commitdiff(-format => 'patch');
8069 sub git_history {
8070 git_log_generic('history', \&git_history_body,
8071 $hash_base, $hash_parent_base,
8072 $file_name, $hash);
8075 sub git_search {
8076 $searchtype ||= 'commit';
8078 # check if appropriate features are enabled
8079 gitweb_check_feature('search')
8080 or die_error(403, "Search is disabled");
8081 if ($searchtype eq 'pickaxe') {
8082 # pickaxe may take all resources of your box and run for several minutes
8083 # with every query - so decide by yourself how public you make this feature
8084 gitweb_check_feature('pickaxe')
8085 or die_error(403, "Pickaxe search is disabled");
8087 if ($searchtype eq 'grep') {
8088 # grep search might be potentially CPU-intensive, too
8089 gitweb_check_feature('grep')
8090 or die_error(403, "Grep search is disabled");
8093 if (!defined $searchtext) {
8094 die_error(400, "Text field is empty");
8096 if (!defined $hash) {
8097 $hash = git_get_head_hash($project);
8099 my %co = parse_commit($hash);
8100 if (!%co) {
8101 die_error(404, "Unknown commit object");
8103 if (!defined $page) {
8104 $page = 0;
8107 if ($searchtype eq 'commit' ||
8108 $searchtype eq 'author' ||
8109 $searchtype eq 'committer') {
8110 git_search_message(%co);
8111 } elsif ($searchtype eq 'pickaxe') {
8112 git_search_changes(%co);
8113 } elsif ($searchtype eq 'grep') {
8114 git_search_files(%co);
8115 } else {
8116 die_error(400, "Unknown search type");
8120 sub git_search_help {
8121 git_header_html();
8122 git_print_page_nav('','', $hash,$hash,$hash);
8123 print <<EOT;
8124 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8125 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8126 the pattern entered is recognized as the POSIX extended
8127 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8128 insensitive).</p>
8129 <dl>
8130 <dt><b>commit</b></dt>
8131 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8133 my $have_grep = gitweb_check_feature('grep');
8134 if ($have_grep) {
8135 print <<EOT;
8136 <dt><b>grep</b></dt>
8137 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8138 a different one) are searched for the given pattern. On large trees, this search can take
8139 a while and put some strain on the server, so please use it with some consideration. Note that
8140 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8141 case-sensitive.</dd>
8144 print <<EOT;
8145 <dt><b>author</b></dt>
8146 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8147 <dt><b>committer</b></dt>
8148 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8150 my $have_pickaxe = gitweb_check_feature('pickaxe');
8151 if ($have_pickaxe) {
8152 print <<EOT;
8153 <dt><b>pickaxe</b></dt>
8154 <dd>All commits that caused the string to appear or disappear from any file (changes that
8155 added, removed or "modified" the string) will be listed. This search can take a while and
8156 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8157 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8160 print "</dl>\n";
8161 git_footer_html();
8164 sub git_shortlog {
8165 git_log_generic('shortlog', \&git_shortlog_body,
8166 $hash, $hash_parent);
8169 ## ......................................................................
8170 ## feeds (RSS, Atom; OPML)
8172 sub git_feed {
8173 my $format = shift || 'atom';
8174 my $have_blame = gitweb_check_feature('blame');
8176 # Atom: http://www.atomenabled.org/developers/syndication/
8177 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8178 if ($format ne 'rss' && $format ne 'atom') {
8179 die_error(400, "Unknown web feed format");
8182 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8183 my $head = $hash || 'HEAD';
8184 my @commitlist = parse_commits($head, 150, 0, $file_name);
8186 my %latest_commit;
8187 my %latest_date;
8188 my $content_type = "application/$format+xml";
8189 if (defined $cgi->http('HTTP_ACCEPT') &&
8190 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8191 # browser (feed reader) prefers text/xml
8192 $content_type = 'text/xml';
8194 if (defined($commitlist[0])) {
8195 %latest_commit = %{$commitlist[0]};
8196 my $latest_epoch = $latest_commit{'committer_epoch'};
8197 exit_if_unmodified_since($latest_epoch);
8198 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8200 print $cgi->header(
8201 -type => $content_type,
8202 -charset => 'utf-8',
8203 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8204 -status => '200 OK');
8206 # Optimization: skip generating the body if client asks only
8207 # for Last-Modified date.
8208 return if ($cgi->request_method() eq 'HEAD');
8210 # header variables
8211 my $title = "$site_name - $project/$action";
8212 my $feed_type = 'log';
8213 if (defined $hash) {
8214 $title .= " - '$hash'";
8215 $feed_type = 'branch log';
8216 if (defined $file_name) {
8217 $title .= " :: $file_name";
8218 $feed_type = 'history';
8220 } elsif (defined $file_name) {
8221 $title .= " - $file_name";
8222 $feed_type = 'history';
8224 $title .= " $feed_type";
8225 $title = esc_html($title);
8226 my $descr = git_get_project_description($project);
8227 if (defined $descr) {
8228 $descr = esc_html($descr);
8229 } else {
8230 $descr = "$project " .
8231 ($format eq 'rss' ? 'RSS' : 'Atom') .
8232 " feed";
8234 my $owner = git_get_project_owner($project);
8235 $owner = esc_html($owner);
8237 #header
8238 my $alt_url;
8239 if (defined $file_name) {
8240 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8241 } elsif (defined $hash) {
8242 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8243 } else {
8244 $alt_url = href(-full=>1, action=>"summary");
8246 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8247 if ($format eq 'rss') {
8248 print <<XML;
8249 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8250 <channel>
8252 print "<title>$title</title>\n" .
8253 "<link>$alt_url</link>\n" .
8254 "<description>$descr</description>\n" .
8255 "<language>en</language>\n" .
8256 # project owner is responsible for 'editorial' content
8257 "<managingEditor>$owner</managingEditor>\n";
8258 if (defined $logo || defined $favicon) {
8259 # prefer the logo to the favicon, since RSS
8260 # doesn't allow both
8261 my $img = esc_url($logo || $favicon);
8262 print "<image>\n" .
8263 "<url>$img</url>\n" .
8264 "<title>$title</title>\n" .
8265 "<link>$alt_url</link>\n" .
8266 "</image>\n";
8268 if (%latest_date) {
8269 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8270 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8272 print "<generator>gitweb v.$version/$git_version</generator>\n";
8273 } elsif ($format eq 'atom') {
8274 print <<XML;
8275 <feed xmlns="http://www.w3.org/2005/Atom">
8277 print "<title>$title</title>\n" .
8278 "<subtitle>$descr</subtitle>\n" .
8279 '<link rel="alternate" type="text/html" href="' .
8280 $alt_url . '" />' . "\n" .
8281 '<link rel="self" type="' . $content_type . '" href="' .
8282 $cgi->self_url() . '" />' . "\n" .
8283 "<id>" . href(-full=>1) . "</id>\n" .
8284 # use project owner for feed author
8285 "<author><name>$owner</name></author>\n";
8286 if (defined $favicon) {
8287 print "<icon>" . esc_url($favicon) . "</icon>\n";
8289 if (defined $logo) {
8290 # not twice as wide as tall: 72 x 27 pixels
8291 print "<logo>" . esc_url($logo) . "</logo>\n";
8293 if (! %latest_date) {
8294 # dummy date to keep the feed valid until commits trickle in:
8295 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8296 } else {
8297 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8299 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8302 # contents
8303 for (my $i = 0; $i <= $#commitlist; $i++) {
8304 my %co = %{$commitlist[$i]};
8305 my $commit = $co{'id'};
8306 # we read 150, we always show 30 and the ones more recent than 48 hours
8307 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8308 last;
8310 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8312 # get list of changed files
8313 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8314 $co{'parent'} || "--root",
8315 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8316 or next;
8317 my @difftree = map { chomp; $_ } <$fd>;
8318 close $fd
8319 or next;
8321 # print element (entry, item)
8322 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8323 if ($format eq 'rss') {
8324 print "<item>\n" .
8325 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8326 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8327 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8328 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8329 "<link>$co_url</link>\n" .
8330 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8331 "<content:encoded>" .
8332 "<![CDATA[\n";
8333 } elsif ($format eq 'atom') {
8334 print "<entry>\n" .
8335 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8336 "<updated>$cd{'iso-8601'}</updated>\n" .
8337 "<author>\n" .
8338 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8339 if ($co{'author_email'}) {
8340 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8342 print "</author>\n" .
8343 # use committer for contributor
8344 "<contributor>\n" .
8345 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8346 if ($co{'committer_email'}) {
8347 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8349 print "</contributor>\n" .
8350 "<published>$cd{'iso-8601'}</published>\n" .
8351 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8352 "<id>$co_url</id>\n" .
8353 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8354 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8356 my $comment = $co{'comment'};
8357 print "<pre>\n";
8358 foreach my $line (@$comment) {
8359 $line = esc_html($line);
8360 print "$line\n";
8362 print "</pre><ul>\n";
8363 foreach my $difftree_line (@difftree) {
8364 my %difftree = parse_difftree_raw_line($difftree_line);
8365 next if !$difftree{'from_id'};
8367 my $file = $difftree{'file'} || $difftree{'to_file'};
8369 print "<li>" .
8370 "[" .
8371 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8372 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8373 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8374 file_name=>$file, file_parent=>$difftree{'from_file'}),
8375 -title => "diff"}, 'D');
8376 if ($have_blame) {
8377 print $cgi->a({-href => href(-full=>1, action=>"blame",
8378 file_name=>$file, hash_base=>$commit),
8379 -title => "blame"}, 'B');
8381 # if this is not a feed of a file history
8382 if (!defined $file_name || $file_name ne $file) {
8383 print $cgi->a({-href => href(-full=>1, action=>"history",
8384 file_name=>$file, hash=>$commit),
8385 -title => "history"}, 'H');
8387 $file = esc_path($file);
8388 print "] ".
8389 "$file</li>\n";
8391 if ($format eq 'rss') {
8392 print "</ul>]]>\n" .
8393 "</content:encoded>\n" .
8394 "</item>\n";
8395 } elsif ($format eq 'atom') {
8396 print "</ul>\n</div>\n" .
8397 "</content>\n" .
8398 "</entry>\n";
8402 # end of feed
8403 if ($format eq 'rss') {
8404 print "</channel>\n</rss>\n";
8405 } elsif ($format eq 'atom') {
8406 print "</feed>\n";
8410 sub git_rss {
8411 git_feed('rss');
8414 sub git_atom {
8415 git_feed('atom');
8418 sub git_opml {
8419 my @list = git_get_projects_list($project_filter, $strict_export);
8420 if (!@list) {
8421 die_error(404, "No projects found");
8424 print $cgi->header(
8425 -type => 'text/xml',
8426 -charset => 'utf-8',
8427 -content_disposition => 'inline; filename="opml.xml"');
8429 my $title = esc_html($site_name);
8430 my $filter = " within subdirectory ";
8431 if (defined $project_filter) {
8432 $filter .= esc_html($project_filter);
8433 } else {
8434 $filter = "";
8436 print <<XML;
8437 <?xml version="1.0" encoding="utf-8"?>
8438 <opml version="1.0">
8439 <head>
8440 <title>$title OPML Export$filter</title>
8441 </head>
8442 <body>
8443 <outline text="git RSS feeds">
8446 foreach my $pr (@list) {
8447 my %proj = %$pr;
8448 my $head = git_get_head_hash($proj{'path'});
8449 if (!defined $head) {
8450 next;
8452 $git_dir = "$projectroot/$proj{'path'}";
8453 my %co = parse_commit($head);
8454 if (!%co) {
8455 next;
8458 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8459 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8460 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8461 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8463 print <<XML;
8464 </outline>
8465 </body>
8466 </opml>