gitweb.perl: use die not goto
[git/gitweb.git] / gitweb / gitweb.perl
blob84f05b7842d9dbc84cdd06fe73a39a75d43e0b6c
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 # information about snapshot formats that gitweb is capable of serving
202 our %known_snapshot_formats = (
203 # name => {
204 # 'display' => display name,
205 # 'type' => mime type,
206 # 'suffix' => filename suffix,
207 # 'format' => --format for git-archive,
208 # 'compressor' => [compressor command and arguments]
209 # (array reference, optional)
210 # 'disabled' => boolean (optional)}
212 'tgz' => {
213 'display' => 'tar.gz',
214 'type' => 'application/x-gzip',
215 'suffix' => '.tar.gz',
216 'format' => 'tar',
217 'compressor' => ['gzip', '-n']},
219 'tbz2' => {
220 'display' => 'tar.bz2',
221 'type' => 'application/x-bzip2',
222 'suffix' => '.tar.bz2',
223 'format' => 'tar',
224 'compressor' => ['bzip2']},
226 'txz' => {
227 'display' => 'tar.xz',
228 'type' => 'application/x-xz',
229 'suffix' => '.tar.xz',
230 'format' => 'tar',
231 'compressor' => ['xz'],
232 'disabled' => 1},
234 'zip' => {
235 'display' => 'zip',
236 'type' => 'application/x-zip',
237 'suffix' => '.zip',
238 'format' => 'zip'},
241 # Aliases so we understand old gitweb.snapshot values in repository
242 # configuration.
243 our %known_snapshot_format_aliases = (
244 'gzip' => 'tgz',
245 'bzip2' => 'tbz2',
246 'xz' => 'txz',
248 # backward compatibility: legacy gitweb config support
249 'x-gzip' => undef, 'gz' => undef,
250 'x-bzip2' => undef, 'bz2' => undef,
251 'x-zip' => undef, '' => undef,
254 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
255 # are changed, it may be appropriate to change these values too via
256 # $GITWEB_CONFIG.
257 our %avatar_size = (
258 'default' => 16,
259 'double' => 32
262 # Used to set the maximum load that we will still respond to gitweb queries.
263 # If server load exceed this value then return "503 server busy" error.
264 # If gitweb cannot determined server load, it is taken to be 0.
265 # Leave it undefined (or set to 'undef') to turn off load checking.
266 our $maxload = 300;
268 # configuration for 'highlight' (http://www.andre-simon.de/)
269 # match by basename
270 our %highlight_basename = (
271 #'Program' => 'py',
272 #'Library' => 'py',
273 'SConstruct' => 'py', # SCons equivalent of Makefile
274 'Makefile' => 'make',
276 # match by extension
277 our %highlight_ext = (
278 # main extensions, defining name of syntax;
279 # see files in /usr/share/highlight/langDefs/ directory
280 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
281 # alternate extensions, see /etc/highlight/filetypes.conf
282 (map { $_ => 'c' } qw(c h)),
283 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
284 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
285 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
286 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
287 (map { $_ => 'make'} qw(make mak mk)),
288 (map { $_ => 'xml' } qw(xml xhtml html htm)),
291 # You define site-wide feature defaults here; override them with
292 # $GITWEB_CONFIG as necessary.
293 our %feature = (
294 # feature => {
295 # 'sub' => feature-sub (subroutine),
296 # 'override' => allow-override (boolean),
297 # 'default' => [ default options...] (array reference)}
299 # if feature is overridable (it means that allow-override has true value),
300 # then feature-sub will be called with default options as parameters;
301 # return value of feature-sub indicates if to enable specified feature
303 # if there is no 'sub' key (no feature-sub), then feature cannot be
304 # overridden
306 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
307 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
308 # is enabled
310 # Enable the 'blame' blob view, showing the last commit that modified
311 # each line in the file. This can be very CPU-intensive.
313 # To enable system wide have in $GITWEB_CONFIG
314 # $feature{'blame'}{'default'} = [1];
315 # To have project specific config enable override in $GITWEB_CONFIG
316 # $feature{'blame'}{'override'} = 1;
317 # and in project config gitweb.blame = 0|1;
318 'blame' => {
319 'sub' => sub { feature_bool('blame', @_) },
320 'override' => 0,
321 'default' => [0]},
323 # Enable the 'snapshot' link, providing a compressed archive of any
324 # tree. This can potentially generate high traffic if you have large
325 # project.
327 # Value is a list of formats defined in %known_snapshot_formats that
328 # you wish to offer.
329 # To disable system wide have in $GITWEB_CONFIG
330 # $feature{'snapshot'}{'default'} = [];
331 # To have project specific config enable override in $GITWEB_CONFIG
332 # $feature{'snapshot'}{'override'} = 1;
333 # and in project config, a comma-separated list of formats or "none"
334 # to disable. Example: gitweb.snapshot = tbz2,zip;
335 'snapshot' => {
336 'sub' => \&feature_snapshot,
337 'override' => 0,
338 'default' => ['tgz']},
340 # Enable text search, which will list the commits which match author,
341 # committer or commit text to a given string. Enabled by default.
342 # Project specific override is not supported.
344 # Note that this controls all search features, which means that if
345 # it is disabled, then 'grep' and 'pickaxe' search would also be
346 # disabled.
347 'search' => {
348 'override' => 0,
349 'default' => [1]},
351 # Enable grep search, which will list the files in currently selected
352 # tree containing the given string. Enabled by default. This can be
353 # potentially CPU-intensive, of course.
354 # Note that you need to have 'search' feature enabled too.
356 # To enable system wide have in $GITWEB_CONFIG
357 # $feature{'grep'}{'default'} = [1];
358 # To have project specific config enable override in $GITWEB_CONFIG
359 # $feature{'grep'}{'override'} = 1;
360 # and in project config gitweb.grep = 0|1;
361 'grep' => {
362 'sub' => sub { feature_bool('grep', @_) },
363 'override' => 0,
364 'default' => [1]},
366 # Enable the pickaxe search, which will list the commits that modified
367 # a given string in a file. This can be practical and quite faster
368 # alternative to 'blame', but still potentially CPU-intensive.
369 # Note that you need to have 'search' feature enabled too.
371 # To enable system wide have in $GITWEB_CONFIG
372 # $feature{'pickaxe'}{'default'} = [1];
373 # To have project specific config enable override in $GITWEB_CONFIG
374 # $feature{'pickaxe'}{'override'} = 1;
375 # and in project config gitweb.pickaxe = 0|1;
376 'pickaxe' => {
377 'sub' => sub { feature_bool('pickaxe', @_) },
378 'override' => 0,
379 'default' => [1]},
381 # Enable showing size of blobs in a 'tree' view, in a separate
382 # column, similar to what 'ls -l' does. This cost a bit of IO.
384 # To disable system wide have in $GITWEB_CONFIG
385 # $feature{'show-sizes'}{'default'} = [0];
386 # To have project specific config enable override in $GITWEB_CONFIG
387 # $feature{'show-sizes'}{'override'} = 1;
388 # and in project config gitweb.showsizes = 0|1;
389 'show-sizes' => {
390 'sub' => sub { feature_bool('showsizes', @_) },
391 'override' => 0,
392 'default' => [1]},
394 # Make gitweb use an alternative format of the URLs which can be
395 # more readable and natural-looking: project name is embedded
396 # directly in the path and the query string contains other
397 # auxiliary information. All gitweb installations recognize
398 # URL in either format; this configures in which formats gitweb
399 # generates links.
401 # To enable system wide have in $GITWEB_CONFIG
402 # $feature{'pathinfo'}{'default'} = [1];
403 # Project specific override is not supported.
405 # Note that you will need to change the default location of CSS,
406 # favicon, logo and possibly other files to an absolute URL. Also,
407 # if gitweb.cgi serves as your indexfile, you will need to force
408 # $my_uri to contain the script name in your $GITWEB_CONFIG.
409 'pathinfo' => {
410 'override' => 0,
411 'default' => [0]},
413 # Make gitweb consider projects in project root subdirectories
414 # to be forks of existing projects. Given project $projname.git,
415 # projects matching $projname/*.git will not be shown in the main
416 # projects list, instead a '+' mark will be added to $projname
417 # there and a 'forks' view will be enabled for the project, listing
418 # all the forks. If project list is taken from a file, forks have
419 # to be listed after the main project.
421 # To enable system wide have in $GITWEB_CONFIG
422 # $feature{'forks'}{'default'} = [1];
423 # Project specific override is not supported.
424 'forks' => {
425 'override' => 0,
426 'default' => [0]},
428 # Insert custom links to the action bar of all project pages.
429 # This enables you mainly to link to third-party scripts integrating
430 # into gitweb; e.g. git-browser for graphical history representation
431 # or custom web-based repository administration interface.
433 # The 'default' value consists of a list of triplets in the form
434 # (label, link, position) where position is the label after which
435 # to insert the link and link is a format string where %n expands
436 # to the project name, %f to the project path within the filesystem,
437 # %h to the current hash (h gitweb parameter) and %b to the current
438 # hash base (hb gitweb parameter); %% expands to %.
440 # To enable system wide have in $GITWEB_CONFIG e.g.
441 # $feature{'actions'}{'default'} = [('graphiclog',
442 # '/git-browser/by-commit.html?r=%n', 'summary')];
443 # Project specific override is not supported.
444 'actions' => {
445 'override' => 0,
446 'default' => []},
448 # Allow gitweb scan project content tags of project repository,
449 # and display the popular Web 2.0-ish "tag cloud" near the projects
450 # list. Note that this is something COMPLETELY different from the
451 # normal Git tags.
453 # gitweb by itself can show existing tags, but it does not handle
454 # tagging itself; you need to do it externally, outside gitweb.
455 # The format is described in git_get_project_ctags() subroutine.
456 # You may want to install the HTML::TagCloud Perl module to get
457 # a pretty tag cloud instead of just a list of tags.
459 # To enable system wide have in $GITWEB_CONFIG
460 # $feature{'ctags'}{'default'} = [1];
461 # Project specific override is not supported.
463 # In the future whether ctags editing is enabled might depend
464 # on the value, but using 1 should always mean no editing of ctags.
465 'ctags' => {
466 'override' => 0,
467 'default' => [0]},
469 # The maximum number of patches in a patchset generated in patch
470 # view. Set this to 0 or undef to disable patch view, or to a
471 # negative number to remove any limit.
473 # To disable system wide have in $GITWEB_CONFIG
474 # $feature{'patches'}{'default'} = [0];
475 # To have project specific config enable override in $GITWEB_CONFIG
476 # $feature{'patches'}{'override'} = 1;
477 # and in project config gitweb.patches = 0|n;
478 # where n is the maximum number of patches allowed in a patchset.
479 'patches' => {
480 'sub' => \&feature_patches,
481 'override' => 0,
482 'default' => [16]},
484 # Avatar support. When this feature is enabled, views such as
485 # shortlog or commit will display an avatar associated with
486 # the email of the committer(s) and/or author(s).
488 # Currently available providers are gravatar and picon.
489 # If an unknown provider is specified, the feature is disabled.
491 # Gravatar depends on Digest::MD5.
492 # Picon currently relies on the indiana.edu database.
494 # To enable system wide have in $GITWEB_CONFIG
495 # $feature{'avatar'}{'default'} = ['<provider>'];
496 # where <provider> is either gravatar or picon.
497 # To have project specific config enable override in $GITWEB_CONFIG
498 # $feature{'avatar'}{'override'} = 1;
499 # and in project config gitweb.avatar = <provider>;
500 'avatar' => {
501 'sub' => \&feature_avatar,
502 'override' => 0,
503 'default' => ['']},
505 # Enable displaying how much time and how many git commands
506 # it took to generate and display page. Disabled by default.
507 # Project specific override is not supported.
508 'timed' => {
509 'override' => 0,
510 'default' => [0]},
512 # Enable turning some links into links to actions which require
513 # JavaScript to run (like 'blame_incremental'). Not enabled by
514 # default. Project specific override is currently not supported.
515 'javascript-actions' => {
516 'override' => 0,
517 'default' => [0]},
519 # Enable and configure ability to change common timezone for dates
520 # in gitweb output via JavaScript. Enabled by default.
521 # Project specific override is not supported.
522 'javascript-timezone' => {
523 'override' => 0,
524 'default' => [
525 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
526 # or undef to turn off this feature
527 'gitweb_tz', # name of cookie where to store selected timezone
528 'datetime', # CSS class used to mark up dates for manipulation
531 # Syntax highlighting support. This is based on Daniel Svensson's
532 # and Sham Chukoury's work in gitweb-xmms2.git.
533 # It requires the 'highlight' program present in $PATH,
534 # and therefore is disabled by default.
536 # To enable system wide have in $GITWEB_CONFIG
537 # $feature{'highlight'}{'default'} = [1];
539 'highlight' => {
540 'sub' => sub { feature_bool('highlight', @_) },
541 'override' => 0,
542 'default' => [0]},
544 # Enable displaying of remote heads in the heads list
546 # To enable system wide have in $GITWEB_CONFIG
547 # $feature{'remote_heads'}{'default'} = [1];
548 # To have project specific config enable override in $GITWEB_CONFIG
549 # $feature{'remote_heads'}{'override'} = 1;
550 # and in project config gitweb.remoteheads = 0|1;
551 'remote_heads' => {
552 'sub' => sub { feature_bool('remote_heads', @_) },
553 'override' => 0,
554 'default' => [0]},
556 # Enable showing branches under other refs in addition to heads
558 # To set system wide extra branch refs have in $GITWEB_CONFIG
559 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
560 # To have project specific config enable override in $GITWEB_CONFIG
561 # $feature{'extra-branch-refs'}{'override'} = 1;
562 # and in project config gitweb.extrabranchrefs = dirs of choice
563 # Every directory is separated with whitespace.
565 'extra-branch-refs' => {
566 'sub' => \&feature_extra_branch_refs,
567 'override' => 0,
568 'default' => []},
571 sub gitweb_get_feature {
572 my ($name) = @_;
573 return unless exists $feature{$name};
574 my ($sub, $override, @defaults) = (
575 $feature{$name}{'sub'},
576 $feature{$name}{'override'},
577 @{$feature{$name}{'default'}});
578 # project specific override is possible only if we have project
579 our $git_dir; # global variable, declared later
580 if (!$override || !defined $git_dir) {
581 return @defaults;
583 if (!defined $sub) {
584 warn "feature $name is not overridable";
585 return @defaults;
587 return $sub->(@defaults);
590 # A wrapper to check if a given feature is enabled.
591 # With this, you can say
593 # my $bool_feat = gitweb_check_feature('bool_feat');
594 # gitweb_check_feature('bool_feat') or somecode;
596 # instead of
598 # my ($bool_feat) = gitweb_get_feature('bool_feat');
599 # (gitweb_get_feature('bool_feat'))[0] or somecode;
601 sub gitweb_check_feature {
602 return (gitweb_get_feature(@_))[0];
606 sub feature_bool {
607 my $key = shift;
608 my ($val) = git_get_project_config($key, '--bool');
610 if (!defined $val) {
611 return ($_[0]);
612 } elsif ($val eq 'true') {
613 return (1);
614 } elsif ($val eq 'false') {
615 return (0);
619 sub feature_snapshot {
620 my (@fmts) = @_;
622 my ($val) = git_get_project_config('snapshot');
624 if ($val) {
625 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
628 return @fmts;
631 sub feature_patches {
632 my @val = (git_get_project_config('patches', '--int'));
634 if (@val) {
635 return @val;
638 return ($_[0]);
641 sub feature_avatar {
642 my @val = (git_get_project_config('avatar'));
644 return @val ? @val : @_;
647 sub feature_extra_branch_refs {
648 my (@branch_refs) = @_;
649 my $values = git_get_project_config('extrabranchrefs');
651 if ($values) {
652 $values = config_to_multi ($values);
653 @branch_refs = ();
654 foreach my $value (@{$values}) {
655 push @branch_refs, split /\s+/, $value;
659 return @branch_refs;
662 # checking HEAD file with -e is fragile if the repository was
663 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
664 # and then pruned.
665 sub check_head_link {
666 my ($dir) = @_;
667 my $headfile = "$dir/HEAD";
668 return ((-e $headfile) ||
669 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
672 sub check_export_ok {
673 my ($dir) = @_;
674 return (check_head_link($dir) &&
675 (!$export_ok || -e "$dir/$export_ok") &&
676 (!$export_auth_hook || $export_auth_hook->($dir)));
679 # process alternate names for backward compatibility
680 # filter out unsupported (unknown) snapshot formats
681 sub filter_snapshot_fmts {
682 my @fmts = @_;
684 @fmts = map {
685 exists $known_snapshot_format_aliases{$_} ?
686 $known_snapshot_format_aliases{$_} : $_} @fmts;
687 @fmts = grep {
688 exists $known_snapshot_formats{$_} &&
689 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
692 sub filter_and_validate_refs {
693 my @refs = @_;
694 my %unique_refs = ();
696 foreach my $ref (@refs) {
697 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
698 # 'heads' are added implicitly in get_branch_refs().
699 $unique_refs{$ref} = 1 if ($ref ne 'heads');
701 return sort keys %unique_refs;
704 # If it is set to code reference, it is code that it is to be run once per
705 # request, allowing updating configurations that change with each request,
706 # while running other code in config file only once.
708 # Otherwise, if it is false then gitweb would process config file only once;
709 # if it is true then gitweb config would be run for each request.
710 our $per_request_config = 1;
712 # read and parse gitweb config file given by its parameter.
713 # returns true on success, false on recoverable error, allowing
714 # to chain this subroutine, using first file that exists.
715 # dies on errors during parsing config file, as it is unrecoverable.
716 sub read_config_file {
717 my $filename = shift;
718 return unless defined $filename;
719 # die if there are errors parsing config file
720 if (-e $filename) {
721 do $filename;
722 die $@ if $@;
723 return 1;
725 return;
728 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
729 sub evaluate_gitweb_config {
730 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
731 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
732 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
734 # Protect against duplications of file names, to not read config twice.
735 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
736 # there possibility of duplication of filename there doesn't matter.
737 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
738 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
740 # Common system-wide settings for convenience.
741 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
742 read_config_file($GITWEB_CONFIG_COMMON);
744 # Use first config file that exists. This means use the per-instance
745 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
746 read_config_file($GITWEB_CONFIG) and return;
747 read_config_file($GITWEB_CONFIG_SYSTEM);
750 # Get loadavg of system, to compare against $maxload.
751 # Currently it requires '/proc/loadavg' present to get loadavg;
752 # if it is not present it returns 0, which means no load checking.
753 sub get_loadavg {
754 if( -e '/proc/loadavg' ){
755 open my $fd, '<', '/proc/loadavg'
756 or return 0;
757 my @load = split(/\s+/, scalar <$fd>);
758 close $fd;
760 # The first three columns measure CPU and IO utilization of the last one,
761 # five, and 10 minute periods. The fourth column shows the number of
762 # currently running processes and the total number of processes in the m/n
763 # format. The last column displays the last process ID used.
764 return $load[0] || 0;
766 # additional checks for load average should go here for things that don't export
767 # /proc/loadavg
769 return 0;
772 # version of the core git binary
773 our $git_version;
774 sub evaluate_git_version {
775 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
776 $number_of_git_cmds++;
779 sub check_loadavg {
780 if (defined $maxload && get_loadavg() > $maxload) {
781 die_error(503, "The load average on the server is too high");
785 # ======================================================================
786 # input validation and dispatch
788 # input parameters can be collected from a variety of sources (presently, CGI
789 # and PATH_INFO), so we define an %input_params hash that collects them all
790 # together during validation: this allows subsequent uses (e.g. href()) to be
791 # agnostic of the parameter origin
793 our %input_params = ();
795 # input parameters are stored with the long parameter name as key. This will
796 # also be used in the href subroutine to convert parameters to their CGI
797 # equivalent, and since the href() usage is the most frequent one, we store
798 # the name -> CGI key mapping here, instead of the reverse.
800 # XXX: Warning: If you touch this, check the search form for updating,
801 # too.
803 our @cgi_param_mapping = (
804 project => "p",
805 action => "a",
806 file_name => "f",
807 file_parent => "fp",
808 hash => "h",
809 hash_parent => "hp",
810 hash_base => "hb",
811 hash_parent_base => "hpb",
812 page => "pg",
813 order => "o",
814 searchtext => "s",
815 searchtype => "st",
816 snapshot_format => "sf",
817 extra_options => "opt",
818 search_use_regexp => "sr",
819 ctag => "by_tag",
820 diff_style => "ds",
821 project_filter => "pf",
822 # this must be last entry (for manipulation from JavaScript)
823 javascript => "js"
825 our %cgi_param_mapping = @cgi_param_mapping;
827 # we will also need to know the possible actions, for validation
828 our %actions = (
829 "blame" => \&git_blame,
830 "blame_incremental" => \&git_blame_incremental,
831 "blame_data" => \&git_blame_data,
832 "blobdiff" => \&git_blobdiff,
833 "blobdiff_plain" => \&git_blobdiff_plain,
834 "blob" => \&git_blob,
835 "blob_plain" => \&git_blob_plain,
836 "commitdiff" => \&git_commitdiff,
837 "commitdiff_plain" => \&git_commitdiff_plain,
838 "commit" => \&git_commit,
839 "forks" => \&git_forks,
840 "heads" => \&git_heads,
841 "history" => \&git_history,
842 "log" => \&git_log,
843 "patch" => \&git_patch,
844 "patches" => \&git_patches,
845 "remotes" => \&git_remotes,
846 "rss" => \&git_rss,
847 "atom" => \&git_atom,
848 "search" => \&git_search,
849 "search_help" => \&git_search_help,
850 "shortlog" => \&git_shortlog,
851 "summary" => \&git_summary,
852 "tag" => \&git_tag,
853 "tags" => \&git_tags,
854 "tree" => \&git_tree,
855 "snapshot" => \&git_snapshot,
856 "object" => \&git_object,
857 # those below don't need $project
858 "opml" => \&git_opml,
859 "project_list" => \&git_project_list,
860 "project_index" => \&git_project_index,
863 # finally, we have the hash of allowed extra_options for the commands that
864 # allow them
865 our %allowed_options = (
866 "--no-merges" => [ qw(rss atom log shortlog history) ],
869 # fill %input_params with the CGI parameters. All values except for 'opt'
870 # should be single values, but opt can be an array. We should probably
871 # build an array of parameters that can be multi-valued, but since for the time
872 # being it's only this one, we just single it out
873 sub evaluate_query_params {
874 our $cgi;
876 while (my ($name, $symbol) = each %cgi_param_mapping) {
877 if ($symbol eq 'opt') {
878 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
879 } else {
880 $input_params{$name} = decode_utf8($cgi->param($symbol));
885 # now read PATH_INFO and update the parameter list for missing parameters
886 sub evaluate_path_info {
887 return if defined $input_params{'project'};
888 return if !$path_info;
889 $path_info =~ s,^/+,,;
890 return if !$path_info;
892 # find which part of PATH_INFO is project
893 my $project = $path_info;
894 $project =~ s,/+$,,;
895 while ($project && !check_head_link("$projectroot/$project")) {
896 $project =~ s,/*[^/]*$,,;
898 return unless $project;
899 $input_params{'project'} = $project;
901 # do not change any parameters if an action is given using the query string
902 return if $input_params{'action'};
903 $path_info =~ s,^\Q$project\E/*,,;
905 # next, check if we have an action
906 my $action = $path_info;
907 $action =~ s,/.*$,,;
908 if (exists $actions{$action}) {
909 $path_info =~ s,^$action/*,,;
910 $input_params{'action'} = $action;
913 # list of actions that want hash_base instead of hash, but can have no
914 # pathname (f) parameter
915 my @wants_base = (
916 'tree',
917 'history',
920 # we want to catch, among others
921 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
922 my ($parentrefname, $parentpathname, $refname, $pathname) =
923 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
925 # first, analyze the 'current' part
926 if (defined $pathname) {
927 # we got "branch:filename" or "branch:dir/"
928 # we could use git_get_type(branch:pathname), but:
929 # - it needs $git_dir
930 # - it does a git() call
931 # - the convention of terminating directories with a slash
932 # makes it superfluous
933 # - embedding the action in the PATH_INFO would make it even
934 # more superfluous
935 $pathname =~ s,^/+,,;
936 if (!$pathname || substr($pathname, -1) eq "/") {
937 $input_params{'action'} ||= "tree";
938 $pathname =~ s,/$,,;
939 } else {
940 # the default action depends on whether we had parent info
941 # or not
942 if ($parentrefname) {
943 $input_params{'action'} ||= "blobdiff_plain";
944 } else {
945 $input_params{'action'} ||= "blob_plain";
948 $input_params{'hash_base'} ||= $refname;
949 $input_params{'file_name'} ||= $pathname;
950 } elsif (defined $refname) {
951 # we got "branch". In this case we have to choose if we have to
952 # set hash or hash_base.
954 # Most of the actions without a pathname only want hash to be
955 # set, except for the ones specified in @wants_base that want
956 # hash_base instead. It should also be noted that hand-crafted
957 # links having 'history' as an action and no pathname or hash
958 # set will fail, but that happens regardless of PATH_INFO.
959 if (defined $parentrefname) {
960 # if there is parent let the default be 'shortlog' action
961 # (for http://git.example.com/repo.git/A..B links); if there
962 # is no parent, dispatch will detect type of object and set
963 # action appropriately if required (if action is not set)
964 $input_params{'action'} ||= "shortlog";
966 if ($input_params{'action'} &&
967 grep { $_ eq $input_params{'action'} } @wants_base) {
968 $input_params{'hash_base'} ||= $refname;
969 } else {
970 $input_params{'hash'} ||= $refname;
974 # next, handle the 'parent' part, if present
975 if (defined $parentrefname) {
976 # a missing pathspec defaults to the 'current' filename, allowing e.g.
977 # someproject/blobdiff/oldrev..newrev:/filename
978 if ($parentpathname) {
979 $parentpathname =~ s,^/+,,;
980 $parentpathname =~ s,/$,,;
981 $input_params{'file_parent'} ||= $parentpathname;
982 } else {
983 $input_params{'file_parent'} ||= $input_params{'file_name'};
985 # we assume that hash_parent_base is wanted if a path was specified,
986 # or if the action wants hash_base instead of hash
987 if (defined $input_params{'file_parent'} ||
988 grep { $_ eq $input_params{'action'} } @wants_base) {
989 $input_params{'hash_parent_base'} ||= $parentrefname;
990 } else {
991 $input_params{'hash_parent'} ||= $parentrefname;
995 # for the snapshot action, we allow URLs in the form
996 # $project/snapshot/$hash.ext
997 # where .ext determines the snapshot and gets removed from the
998 # passed $refname to provide the $hash.
1000 # To be able to tell that $refname includes the format extension, we
1001 # require the following two conditions to be satisfied:
1002 # - the hash input parameter MUST have been set from the $refname part
1003 # of the URL (i.e. they must be equal)
1004 # - the snapshot format MUST NOT have been defined already (e.g. from
1005 # CGI parameter sf)
1006 # It's also useless to try any matching unless $refname has a dot,
1007 # so we check for that too
1008 if (defined $input_params{'action'} &&
1009 $input_params{'action'} eq 'snapshot' &&
1010 defined $refname && index($refname, '.') != -1 &&
1011 $refname eq $input_params{'hash'} &&
1012 !defined $input_params{'snapshot_format'}) {
1013 # We loop over the known snapshot formats, checking for
1014 # extensions. Allowed extensions are both the defined suffix
1015 # (which includes the initial dot already) and the snapshot
1016 # format key itself, with a prepended dot
1017 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1018 my $hash = $refname;
1019 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1020 next;
1022 my $sfx = $1;
1023 # a valid suffix was found, so set the snapshot format
1024 # and reset the hash parameter
1025 $input_params{'snapshot_format'} = $fmt;
1026 $input_params{'hash'} = $hash;
1027 # we also set the format suffix to the one requested
1028 # in the URL: this way a request for e.g. .tgz returns
1029 # a .tgz instead of a .tar.gz
1030 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1031 last;
1036 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1037 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1038 $searchtext, $search_regexp, $project_filter);
1039 sub evaluate_and_validate_params {
1040 our $action = $input_params{'action'};
1041 if (defined $action) {
1042 if (!is_valid_action($action)) {
1043 die_error(400, "Invalid action parameter");
1047 # parameters which are pathnames
1048 our $project = $input_params{'project'};
1049 if (defined $project) {
1050 if (!is_valid_project($project)) {
1051 undef $project;
1052 die_error(404, "No such project");
1056 our $project_filter = $input_params{'project_filter'};
1057 if (defined $project_filter) {
1058 if (!is_valid_pathname($project_filter)) {
1059 die_error(404, "Invalid project_filter parameter");
1063 our $file_name = $input_params{'file_name'};
1064 if (defined $file_name) {
1065 if (!is_valid_pathname($file_name)) {
1066 die_error(400, "Invalid file parameter");
1070 our $file_parent = $input_params{'file_parent'};
1071 if (defined $file_parent) {
1072 if (!is_valid_pathname($file_parent)) {
1073 die_error(400, "Invalid file parent parameter");
1077 # parameters which are refnames
1078 our $hash = $input_params{'hash'};
1079 if (defined $hash) {
1080 if (!is_valid_refname($hash)) {
1081 die_error(400, "Invalid hash parameter");
1085 our $hash_parent = $input_params{'hash_parent'};
1086 if (defined $hash_parent) {
1087 if (!is_valid_refname($hash_parent)) {
1088 die_error(400, "Invalid hash parent parameter");
1092 our $hash_base = $input_params{'hash_base'};
1093 if (defined $hash_base) {
1094 if (!is_valid_refname($hash_base)) {
1095 die_error(400, "Invalid hash base parameter");
1099 our @extra_options = @{$input_params{'extra_options'}};
1100 # @extra_options is always defined, since it can only be (currently) set from
1101 # CGI, and $cgi->param() returns the empty array in array context if the param
1102 # is not set
1103 foreach my $opt (@extra_options) {
1104 if (not exists $allowed_options{$opt}) {
1105 die_error(400, "Invalid option parameter");
1107 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1108 die_error(400, "Invalid option parameter for this action");
1112 our $hash_parent_base = $input_params{'hash_parent_base'};
1113 if (defined $hash_parent_base) {
1114 if (!is_valid_refname($hash_parent_base)) {
1115 die_error(400, "Invalid hash parent base parameter");
1119 # other parameters
1120 our $page = $input_params{'page'};
1121 if (defined $page) {
1122 if ($page =~ m/[^0-9]/) {
1123 die_error(400, "Invalid page parameter");
1127 our $searchtype = $input_params{'searchtype'};
1128 if (defined $searchtype) {
1129 if ($searchtype =~ m/[^a-z]/) {
1130 die_error(400, "Invalid searchtype parameter");
1134 our $search_use_regexp = $input_params{'search_use_regexp'};
1136 our $searchtext = $input_params{'searchtext'};
1137 our $search_regexp = undef;
1138 if (defined $searchtext) {
1139 if (length($searchtext) < 2) {
1140 die_error(403, "At least two characters are required for search parameter");
1142 if ($search_use_regexp) {
1143 $search_regexp = $searchtext;
1144 if (!eval { qr/$search_regexp/; 1; }) {
1145 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1146 die_error(400, "Invalid search regexp '$search_regexp'",
1147 esc_html($error));
1149 } else {
1150 $search_regexp = quotemeta $searchtext;
1155 # path to the current git repository
1156 our $git_dir;
1157 sub evaluate_git_dir {
1158 our $git_dir = "$projectroot/$project" if $project;
1161 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1162 sub configure_gitweb_features {
1163 # list of supported snapshot formats
1164 our @snapshot_fmts = gitweb_get_feature('snapshot');
1165 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1167 # check that the avatar feature is set to a known provider name,
1168 # and for each provider check if the dependencies are satisfied.
1169 # if the provider name is invalid or the dependencies are not met,
1170 # reset $git_avatar to the empty string.
1171 our ($git_avatar) = gitweb_get_feature('avatar');
1172 if ($git_avatar eq 'gravatar') {
1173 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1174 } elsif ($git_avatar eq 'picon') {
1175 # no dependencies
1176 } else {
1177 $git_avatar = '';
1180 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1181 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1184 sub get_branch_refs {
1185 return ('heads', @extra_branch_refs);
1188 # custom error handler: 'die <message>' is Internal Server Error
1189 sub handle_errors_html {
1190 my $msg = shift; # it is already HTML escaped
1192 # to avoid infinite loop where error occurs in die_error,
1193 # change handler to default handler, disabling handle_errors_html
1194 set_message("Error occurred when inside die_error:\n$msg");
1196 # you cannot jump out of die_error when called as error handler;
1197 # the subroutine set via CGI::Carp::set_message is called _after_
1198 # HTTP headers are already written, so it cannot write them itself
1199 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1201 set_message(\&handle_errors_html);
1203 # dispatch
1204 sub dispatch {
1205 if (!defined $action) {
1206 if (defined $hash) {
1207 $action = git_get_type($hash);
1208 $action or die_error(404, "Object does not exist");
1209 } elsif (defined $hash_base && defined $file_name) {
1210 $action = git_get_type("$hash_base:$file_name");
1211 $action or die_error(404, "File or directory does not exist");
1212 } elsif (defined $project) {
1213 $action = 'summary';
1214 } else {
1215 $action = 'project_list';
1218 if (!defined($actions{$action})) {
1219 die_error(400, "Unknown action");
1221 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1222 !$project) {
1223 die_error(400, "Project needed");
1225 $actions{$action}->();
1228 sub reset_timer {
1229 our $t0 = [ gettimeofday() ]
1230 if defined $t0;
1231 our $number_of_git_cmds = 0;
1234 our $first_request = 1;
1235 sub run_request {
1236 reset_timer();
1238 evaluate_uri();
1239 if ($first_request) {
1240 evaluate_gitweb_config();
1241 evaluate_git_version();
1243 if ($per_request_config) {
1244 if (ref($per_request_config) eq 'CODE') {
1245 $per_request_config->();
1246 } elsif (!$first_request) {
1247 evaluate_gitweb_config();
1250 check_loadavg();
1252 # $projectroot and $projects_list might be set in gitweb config file
1253 $projects_list ||= $projectroot;
1255 evaluate_query_params();
1256 evaluate_path_info();
1257 evaluate_and_validate_params();
1258 evaluate_git_dir();
1260 configure_gitweb_features();
1262 dispatch();
1265 our $is_last_request = sub { 1 };
1266 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1267 our $CGI = 'CGI';
1268 our $cgi;
1269 sub configure_as_fcgi {
1270 require CGI::Fast;
1271 our $CGI = 'CGI::Fast';
1273 my $request_number = 0;
1274 # let each child service 100 requests
1275 our $is_last_request = sub { ++$request_number > 100 };
1277 sub evaluate_argv {
1278 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1279 configure_as_fcgi()
1280 if $script_name =~ /\.fcgi$/;
1282 return unless (@ARGV);
1284 require Getopt::Long;
1285 Getopt::Long::GetOptions(
1286 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1287 'nproc|n=i' => sub {
1288 my ($arg, $val) = @_;
1289 return unless eval { require FCGI::ProcManager; 1; };
1290 my $proc_manager = FCGI::ProcManager->new({
1291 n_processes => $val,
1293 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1294 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1295 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1300 sub run {
1301 evaluate_argv();
1303 $first_request = 1;
1304 $pre_listen_hook->()
1305 if $pre_listen_hook;
1307 REQUEST:
1308 while ($cgi = $CGI->new()) {
1309 $pre_dispatch_hook->()
1310 if $pre_dispatch_hook;
1312 eval {run_request()};
1314 $post_dispatch_hook->()
1315 if $post_dispatch_hook;
1316 $first_request = 0;
1318 last REQUEST if ($is_last_request->());
1324 run();
1326 if (defined caller) {
1327 # wrapped in a subroutine processing requests,
1328 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1329 return;
1330 } else {
1331 # pure CGI script, serving single request
1332 exit;
1335 ## ======================================================================
1336 ## action links
1338 # possible values of extra options
1339 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1340 # -replay => 1 - start from a current view (replay with modifications)
1341 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1342 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1343 sub href {
1344 my %params = @_;
1345 # default is to use -absolute url() i.e. $my_uri
1346 my $href = $params{-full} ? $my_url : $my_uri;
1348 # implicit -replay, must be first of implicit params
1349 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1351 $params{'project'} = $project unless exists $params{'project'};
1353 if ($params{-replay}) {
1354 while (my ($name, $symbol) = each %cgi_param_mapping) {
1355 if (!exists $params{$name}) {
1356 $params{$name} = $input_params{$name};
1361 my $use_pathinfo = gitweb_check_feature('pathinfo');
1362 if (defined $params{'project'} &&
1363 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1364 # try to put as many parameters as possible in PATH_INFO:
1365 # - project name
1366 # - action
1367 # - hash_parent or hash_parent_base:/file_parent
1368 # - hash or hash_base:/filename
1369 # - the snapshot_format as an appropriate suffix
1371 # When the script is the root DirectoryIndex for the domain,
1372 # $href here would be something like http://gitweb.example.com/
1373 # Thus, we strip any trailing / from $href, to spare us double
1374 # slashes in the final URL
1375 $href =~ s,/$,,;
1377 # Then add the project name, if present
1378 $href .= "/".esc_path_info($params{'project'});
1379 delete $params{'project'};
1381 # since we destructively absorb parameters, we keep this
1382 # boolean that remembers if we're handling a snapshot
1383 my $is_snapshot = $params{'action'} eq 'snapshot';
1385 # Summary just uses the project path URL, any other action is
1386 # added to the URL
1387 if (defined $params{'action'}) {
1388 $href .= "/".esc_path_info($params{'action'})
1389 unless $params{'action'} eq 'summary';
1390 delete $params{'action'};
1393 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1394 # stripping nonexistent or useless pieces
1395 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1396 || $params{'hash_parent'} || $params{'hash'});
1397 if (defined $params{'hash_base'}) {
1398 if (defined $params{'hash_parent_base'}) {
1399 $href .= esc_path_info($params{'hash_parent_base'});
1400 # skip the file_parent if it's the same as the file_name
1401 if (defined $params{'file_parent'}) {
1402 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1403 delete $params{'file_parent'};
1404 } elsif ($params{'file_parent'} !~ /\.\./) {
1405 $href .= ":/".esc_path_info($params{'file_parent'});
1406 delete $params{'file_parent'};
1409 $href .= "..";
1410 delete $params{'hash_parent'};
1411 delete $params{'hash_parent_base'};
1412 } elsif (defined $params{'hash_parent'}) {
1413 $href .= esc_path_info($params{'hash_parent'}). "..";
1414 delete $params{'hash_parent'};
1417 $href .= esc_path_info($params{'hash_base'});
1418 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1419 $href .= ":/".esc_path_info($params{'file_name'});
1420 delete $params{'file_name'};
1422 delete $params{'hash'};
1423 delete $params{'hash_base'};
1424 } elsif (defined $params{'hash'}) {
1425 $href .= esc_path_info($params{'hash'});
1426 delete $params{'hash'};
1429 # If the action was a snapshot, we can absorb the
1430 # snapshot_format parameter too
1431 if ($is_snapshot) {
1432 my $fmt = $params{'snapshot_format'};
1433 # snapshot_format should always be defined when href()
1434 # is called, but just in case some code forgets, we
1435 # fall back to the default
1436 $fmt ||= $snapshot_fmts[0];
1437 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1438 delete $params{'snapshot_format'};
1442 # now encode the parameters explicitly
1443 my @result = ();
1444 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1445 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1446 if (defined $params{$name}) {
1447 if (ref($params{$name}) eq "ARRAY") {
1448 foreach my $par (@{$params{$name}}) {
1449 push @result, $symbol . "=" . esc_param($par);
1451 } else {
1452 push @result, $symbol . "=" . esc_param($params{$name});
1456 $href .= "?" . join(';', @result) if scalar @result;
1458 # final transformation: trailing spaces must be escaped (URI-encoded)
1459 $href =~ s/(\s+)$/CGI::escape($1)/e;
1461 if ($params{-anchor}) {
1462 $href .= "#".esc_param($params{-anchor});
1465 return $href;
1469 ## ======================================================================
1470 ## validation, quoting/unquoting and escaping
1472 sub is_valid_action {
1473 my $input = shift;
1474 return undef unless exists $actions{$input};
1475 return 1;
1478 sub is_valid_project {
1479 my $input = shift;
1481 return unless defined $input;
1482 if (!is_valid_pathname($input) ||
1483 !(-d "$projectroot/$input") ||
1484 !check_export_ok("$projectroot/$input") ||
1485 ($strict_export && !project_in_list($input))) {
1486 return undef;
1487 } else {
1488 return 1;
1492 sub is_valid_pathname {
1493 my $input = shift;
1495 return undef unless defined $input;
1496 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1497 # at the beginning, at the end, and between slashes.
1498 # also this catches doubled slashes
1499 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1500 return undef;
1502 # no null characters
1503 if ($input =~ m!\0!) {
1504 return undef;
1506 return 1;
1509 sub is_valid_ref_format {
1510 my $input = shift;
1512 return undef unless defined $input;
1513 # restrictions on ref name according to git-check-ref-format
1514 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1515 return undef;
1517 return 1;
1520 sub is_valid_refname {
1521 my $input = shift;
1523 return undef unless defined $input;
1524 # textual hashes are O.K.
1525 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1526 return 1;
1528 # it must be correct pathname
1529 is_valid_pathname($input) or return undef;
1530 # check git-check-ref-format restrictions
1531 is_valid_ref_format($input) or return undef;
1532 return 1;
1535 # decode sequences of octets in utf8 into Perl's internal form,
1536 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1537 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1538 sub to_utf8 {
1539 my $str = shift;
1540 return undef unless defined $str;
1542 if (utf8::is_utf8($str) || utf8::decode($str)) {
1543 return $str;
1544 } else {
1545 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1549 # quote unsafe chars, but keep the slash, even when it's not
1550 # correct, but quoted slashes look too horrible in bookmarks
1551 sub esc_param {
1552 my $str = shift;
1553 return undef unless defined $str;
1554 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1555 $str =~ s/ /\+/g;
1556 return $str;
1559 # the quoting rules for path_info fragment are slightly different
1560 sub esc_path_info {
1561 my $str = shift;
1562 return undef unless defined $str;
1564 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1565 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1567 return $str;
1570 # quote unsafe chars in whole URL, so some characters cannot be quoted
1571 sub esc_url {
1572 my $str = shift;
1573 return undef unless defined $str;
1574 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1575 $str =~ s/ /\+/g;
1576 return $str;
1579 # quote unsafe characters in HTML attributes
1580 sub esc_attr {
1582 # for XHTML conformance escaping '"' to '&quot;' is not enough
1583 return esc_html(@_);
1586 # replace invalid utf8 character with SUBSTITUTION sequence
1587 sub esc_html {
1588 my $str = shift;
1589 my %opts = @_;
1591 return undef unless defined $str;
1593 $str = to_utf8($str);
1594 $str = $cgi->escapeHTML($str);
1595 if ($opts{'-nbsp'}) {
1596 $str =~ s/ /&nbsp;/g;
1598 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1599 return $str;
1602 # quote control characters and escape filename to HTML
1603 sub esc_path {
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:]])|quot_cec($1)|eg;
1615 return $str;
1618 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1619 sub sanitize {
1620 my $str = shift;
1622 return undef unless defined $str;
1624 $str = to_utf8($str);
1625 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1626 return $str;
1629 # Make control characters "printable", using character escape codes (CEC)
1630 sub quot_cec {
1631 my $cntrl = shift;
1632 my %opts = @_;
1633 my %es = ( # character escape codes, aka escape sequences
1634 "\t" => '\t', # tab (HT)
1635 "\n" => '\n', # line feed (LF)
1636 "\r" => '\r', # carrige return (CR)
1637 "\f" => '\f', # form feed (FF)
1638 "\b" => '\b', # backspace (BS)
1639 "\a" => '\a', # alarm (bell) (BEL)
1640 "\e" => '\e', # escape (ESC)
1641 "\013" => '\v', # vertical tab (VT)
1642 "\000" => '\0', # nul character (NUL)
1644 my $chr = ( (exists $es{$cntrl})
1645 ? $es{$cntrl}
1646 : sprintf('\%2x', ord($cntrl)) );
1647 if ($opts{-nohtml}) {
1648 return $chr;
1649 } else {
1650 return "<span class=\"cntrl\">$chr</span>";
1654 # Alternatively use unicode control pictures codepoints,
1655 # Unicode "printable representation" (PR)
1656 sub quot_upr {
1657 my $cntrl = shift;
1658 my %opts = @_;
1660 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1661 if ($opts{-nohtml}) {
1662 return $chr;
1663 } else {
1664 return "<span class=\"cntrl\">$chr</span>";
1668 # git may return quoted and escaped filenames
1669 sub unquote {
1670 my $str = shift;
1672 sub unq {
1673 my $seq = shift;
1674 my %es = ( # character escape codes, aka escape sequences
1675 't' => "\t", # tab (HT, TAB)
1676 'n' => "\n", # newline (NL)
1677 'r' => "\r", # return (CR)
1678 'f' => "\f", # form feed (FF)
1679 'b' => "\b", # backspace (BS)
1680 'a' => "\a", # alarm (bell) (BEL)
1681 'e' => "\e", # escape (ESC)
1682 'v' => "\013", # vertical tab (VT)
1685 if ($seq =~ m/^[0-7]{1,3}$/) {
1686 # octal char sequence
1687 return chr(oct($seq));
1688 } elsif (exists $es{$seq}) {
1689 # C escape sequence, aka character escape code
1690 return $es{$seq};
1692 # quoted ordinary character
1693 return $seq;
1696 if ($str =~ m/^"(.*)"$/) {
1697 # needs unquoting
1698 $str = $1;
1699 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1701 return $str;
1704 # escape tabs (convert tabs to spaces)
1705 sub untabify {
1706 my $line = shift;
1708 while ((my $pos = index($line, "\t")) != -1) {
1709 if (my $count = (8 - ($pos % 8))) {
1710 my $spaces = ' ' x $count;
1711 $line =~ s/\t/$spaces/;
1715 return $line;
1718 sub project_in_list {
1719 my $project = shift;
1720 my @list = git_get_projects_list();
1721 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1724 ## ----------------------------------------------------------------------
1725 ## HTML aware string manipulation
1727 # Try to chop given string on a word boundary between position
1728 # $len and $len+$add_len. If there is no word boundary there,
1729 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1730 # (marking chopped part) would be longer than given string.
1731 sub chop_str {
1732 my $str = shift;
1733 my $len = shift;
1734 my $add_len = shift || 10;
1735 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1737 # Make sure perl knows it is utf8 encoded so we don't
1738 # cut in the middle of a utf8 multibyte char.
1739 $str = to_utf8($str);
1741 # allow only $len chars, but don't cut a word if it would fit in $add_len
1742 # if it doesn't fit, cut it if it's still longer than the dots we would add
1743 # remove chopped character entities entirely
1745 # when chopping in the middle, distribute $len into left and right part
1746 # return early if chopping wouldn't make string shorter
1747 if ($where eq 'center') {
1748 return $str if ($len + 5 >= length($str)); # filler is length 5
1749 $len = int($len/2);
1750 } else {
1751 return $str if ($len + 4 >= length($str)); # filler is length 4
1754 # regexps: ending and beginning with word part up to $add_len
1755 my $endre = qr/.{$len}\w{0,$add_len}/;
1756 my $begre = qr/\w{0,$add_len}.{$len}/;
1758 if ($where eq 'left') {
1759 $str =~ m/^(.*?)($begre)$/;
1760 my ($lead, $body) = ($1, $2);
1761 if (length($lead) > 4) {
1762 $lead = " ...";
1764 return "$lead$body";
1766 } elsif ($where eq 'center') {
1767 $str =~ m/^($endre)(.*)$/;
1768 my ($left, $str) = ($1, $2);
1769 $str =~ m/^(.*?)($begre)$/;
1770 my ($mid, $right) = ($1, $2);
1771 if (length($mid) > 5) {
1772 $mid = " ... ";
1774 return "$left$mid$right";
1776 } else {
1777 $str =~ m/^($endre)(.*)$/;
1778 my $body = $1;
1779 my $tail = $2;
1780 if (length($tail) > 4) {
1781 $tail = "... ";
1783 return "$body$tail";
1787 # takes the same arguments as chop_str, but also wraps a <span> around the
1788 # result with a title attribute if it does get chopped. Additionally, the
1789 # string is HTML-escaped.
1790 sub chop_and_escape_str {
1791 my ($str) = @_;
1793 my $chopped = chop_str(@_);
1794 $str = to_utf8($str);
1795 if ($chopped eq $str) {
1796 return esc_html($chopped);
1797 } else {
1798 $str =~ s/[[:cntrl:]]/?/g;
1799 return $cgi->span({-title=>$str}, esc_html($chopped));
1803 # Highlight selected fragments of string, using given CSS class,
1804 # and escape HTML. It is assumed that fragments do not overlap.
1805 # Regions are passed as list of pairs (array references).
1807 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1808 # '<span class="mark">foo</span>bar'
1809 sub esc_html_hl_regions {
1810 my ($str, $css_class, @sel) = @_;
1811 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1812 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1813 return esc_html($str, %opts) unless @sel;
1815 my $out = '';
1816 my $pos = 0;
1818 for my $s (@sel) {
1819 my ($begin, $end) = @$s;
1821 # Don't create empty <span> elements.
1822 next if $end <= $begin;
1824 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1825 %opts);
1827 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1828 if ($begin - $pos > 0);
1829 $out .= $cgi->span({-class => $css_class}, $escaped);
1831 $pos = $end;
1833 $out .= esc_html(substr($str, $pos), %opts)
1834 if ($pos < length($str));
1836 return $out;
1839 # return positions of beginning and end of each match
1840 sub matchpos_list {
1841 my ($str, $regexp) = @_;
1842 return unless (defined $str && defined $regexp);
1844 my @matches;
1845 while ($str =~ /$regexp/g) {
1846 push @matches, [$-[0], $+[0]];
1848 return @matches;
1851 # highlight match (if any), and escape HTML
1852 sub esc_html_match_hl {
1853 my ($str, $regexp) = @_;
1854 return esc_html($str) unless defined $regexp;
1856 my @matches = matchpos_list($str, $regexp);
1857 return esc_html($str) unless @matches;
1859 return esc_html_hl_regions($str, 'match', @matches);
1863 # highlight match (if any) of shortened string, and escape HTML
1864 sub esc_html_match_hl_chopped {
1865 my ($str, $chopped, $regexp) = @_;
1866 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1868 my @matches = matchpos_list($str, $regexp);
1869 return esc_html($chopped) unless @matches;
1871 # filter matches so that we mark chopped string
1872 my $tail = "... "; # see chop_str
1873 unless ($chopped =~ s/\Q$tail\E$//) {
1874 $tail = '';
1876 my $chop_len = length($chopped);
1877 my $tail_len = length($tail);
1878 my @filtered;
1880 for my $m (@matches) {
1881 if ($m->[0] > $chop_len) {
1882 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1883 last;
1884 } elsif ($m->[1] > $chop_len) {
1885 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1886 last;
1888 push @filtered, $m;
1891 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1894 ## ----------------------------------------------------------------------
1895 ## functions returning short strings
1897 # CSS class for given age value (in seconds)
1898 sub age_class {
1899 my $age = shift;
1901 if (!defined $age) {
1902 return "noage";
1903 } elsif ($age < 60*60*2) {
1904 return "age0";
1905 } elsif ($age < 60*60*24*2) {
1906 return "age1";
1907 } else {
1908 return "age2";
1912 # convert age in seconds to "nn units ago" string
1913 sub age_string {
1914 my $age = shift;
1915 my $age_str;
1917 if ($age > 60*60*24*365*2) {
1918 $age_str = (int $age/60/60/24/365);
1919 $age_str .= " years ago";
1920 } elsif ($age > 60*60*24*(365/12)*2) {
1921 $age_str = int $age/60/60/24/(365/12);
1922 $age_str .= " months ago";
1923 } elsif ($age > 60*60*24*7*2) {
1924 $age_str = int $age/60/60/24/7;
1925 $age_str .= " weeks ago";
1926 } elsif ($age > 60*60*24*2) {
1927 $age_str = int $age/60/60/24;
1928 $age_str .= " days ago";
1929 } elsif ($age > 60*60*2) {
1930 $age_str = int $age/60/60;
1931 $age_str .= " hours ago";
1932 } elsif ($age > 60*2) {
1933 $age_str = int $age/60;
1934 $age_str .= " min ago";
1935 } elsif ($age > 2) {
1936 $age_str = int $age;
1937 $age_str .= " sec ago";
1938 } else {
1939 $age_str .= " right now";
1941 return $age_str;
1944 use constant {
1945 S_IFINVALID => 0030000,
1946 S_IFGITLINK => 0160000,
1949 # submodule/subproject, a commit object reference
1950 sub S_ISGITLINK {
1951 my $mode = shift;
1953 return (($mode & S_IFMT) == S_IFGITLINK)
1956 # convert file mode in octal to symbolic file mode string
1957 sub mode_str {
1958 my $mode = oct shift;
1960 if (S_ISGITLINK($mode)) {
1961 return 'm---------';
1962 } elsif (S_ISDIR($mode & S_IFMT)) {
1963 return 'drwxr-xr-x';
1964 } elsif (S_ISLNK($mode)) {
1965 return 'lrwxrwxrwx';
1966 } elsif (S_ISREG($mode)) {
1967 # git cares only about the executable bit
1968 if ($mode & S_IXUSR) {
1969 return '-rwxr-xr-x';
1970 } else {
1971 return '-rw-r--r--';
1973 } else {
1974 return '----------';
1978 # convert file mode in octal to file type string
1979 sub file_type {
1980 my $mode = shift;
1982 if ($mode !~ m/^[0-7]+$/) {
1983 return $mode;
1984 } else {
1985 $mode = oct $mode;
1988 if (S_ISGITLINK($mode)) {
1989 return "submodule";
1990 } elsif (S_ISDIR($mode & S_IFMT)) {
1991 return "directory";
1992 } elsif (S_ISLNK($mode)) {
1993 return "symlink";
1994 } elsif (S_ISREG($mode)) {
1995 return "file";
1996 } else {
1997 return "unknown";
2001 # convert file mode in octal to file type description string
2002 sub file_type_long {
2003 my $mode = shift;
2005 if ($mode !~ m/^[0-7]+$/) {
2006 return $mode;
2007 } else {
2008 $mode = oct $mode;
2011 if (S_ISGITLINK($mode)) {
2012 return "submodule";
2013 } elsif (S_ISDIR($mode & S_IFMT)) {
2014 return "directory";
2015 } elsif (S_ISLNK($mode)) {
2016 return "symlink";
2017 } elsif (S_ISREG($mode)) {
2018 if ($mode & S_IXUSR) {
2019 return "executable";
2020 } else {
2021 return "file";
2023 } else {
2024 return "unknown";
2029 ## ----------------------------------------------------------------------
2030 ## functions returning short HTML fragments, or transforming HTML fragments
2031 ## which don't belong to other sections
2033 # format line of commit message.
2034 sub format_log_line_html {
2035 my $line = shift;
2037 $line = esc_html($line, -nbsp=>1);
2038 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2039 $cgi->a({-href => href(action=>"object", hash=>$1),
2040 -class => "text"}, $1);
2041 }eg;
2043 return $line;
2046 # format marker of refs pointing to given object
2048 # the destination action is chosen based on object type and current context:
2049 # - for annotated tags, we choose the tag view unless it's the current view
2050 # already, in which case we go to shortlog view
2051 # - for other refs, we keep the current view if we're in history, shortlog or
2052 # log view, and select shortlog otherwise
2053 sub format_ref_marker {
2054 my ($refs, $id) = @_;
2055 my $markers = '';
2057 if (defined $refs->{$id}) {
2058 foreach my $ref (@{$refs->{$id}}) {
2059 # this code exploits the fact that non-lightweight tags are the
2060 # only indirect objects, and that they are the only objects for which
2061 # we want to use tag instead of shortlog as action
2062 my ($type, $name) = qw();
2063 my $indirect = ($ref =~ s/\^\{\}$//);
2064 # e.g. tags/v2.6.11 or heads/next
2065 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2066 $type = $1;
2067 $name = $2;
2068 } else {
2069 $type = "ref";
2070 $name = $ref;
2073 my $class = $type;
2074 $class .= " indirect" if $indirect;
2076 my $dest_action = "shortlog";
2078 if ($indirect) {
2079 $dest_action = "tag" unless $action eq "tag";
2080 } elsif ($action =~ /^(history|(short)?log)$/) {
2081 $dest_action = $action;
2084 my $dest = "";
2085 $dest .= "refs/" unless $ref =~ m!^refs/!;
2086 $dest .= $ref;
2088 my $link = $cgi->a({
2089 -href => href(
2090 action=>$dest_action,
2091 hash=>$dest
2092 )}, $name);
2094 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2095 $link . "</span>";
2099 if ($markers) {
2100 return ' <span class="refs">'. $markers . '</span>';
2101 } else {
2102 return "";
2106 # format, perhaps shortened and with markers, title line
2107 sub format_subject_html {
2108 my ($long, $short, $href, $extra) = @_;
2109 $extra = '' unless defined($extra);
2111 if (length($short) < length($long)) {
2112 $long =~ s/[[:cntrl:]]/?/g;
2113 return $cgi->a({-href => $href, -class => "list subject",
2114 -title => to_utf8($long)},
2115 esc_html($short)) . $extra;
2116 } else {
2117 return $cgi->a({-href => $href, -class => "list subject"},
2118 esc_html($long)) . $extra;
2122 # Rather than recomputing the url for an email multiple times, we cache it
2123 # after the first hit. This gives a visible benefit in views where the avatar
2124 # for the same email is used repeatedly (e.g. shortlog).
2125 # The cache is shared by all avatar engines (currently gravatar only), which
2126 # are free to use it as preferred. Since only one avatar engine is used for any
2127 # given page, there's no risk for cache conflicts.
2128 our %avatar_cache = ();
2130 # Compute the picon url for a given email, by using the picon search service over at
2131 # http://www.cs.indiana.edu/picons/search.html
2132 sub picon_url {
2133 my $email = lc shift;
2134 if (!$avatar_cache{$email}) {
2135 my ($user, $domain) = split('@', $email);
2136 $avatar_cache{$email} =
2137 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2138 "$domain/$user/" .
2139 "users+domains+unknown/up/single";
2141 return $avatar_cache{$email};
2144 # Compute the gravatar url for a given email, if it's not in the cache already.
2145 # Gravatar stores only the part of the URL before the size, since that's the
2146 # one computationally more expensive. This also allows reuse of the cache for
2147 # different sizes (for this particular engine).
2148 sub gravatar_url {
2149 my $email = lc shift;
2150 my $size = shift;
2151 $avatar_cache{$email} ||=
2152 "//www.gravatar.com/avatar/" .
2153 Digest::MD5::md5_hex($email) . "?s=";
2154 return $avatar_cache{$email} . $size;
2157 # Insert an avatar for the given $email at the given $size if the feature
2158 # is enabled.
2159 sub git_get_avatar {
2160 my ($email, %opts) = @_;
2161 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2162 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2163 $opts{-size} ||= 'default';
2164 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2165 my $url = "";
2166 if ($git_avatar eq 'gravatar') {
2167 $url = gravatar_url($email, $size);
2168 } elsif ($git_avatar eq 'picon') {
2169 $url = picon_url($email);
2171 # Other providers can be added by extending the if chain, defining $url
2172 # as needed. If no variant puts something in $url, we assume avatars
2173 # are completely disabled/unavailable.
2174 if ($url) {
2175 return $pre_white .
2176 "<img width=\"$size\" " .
2177 "class=\"avatar\" " .
2178 "src=\"".esc_url($url)."\" " .
2179 "alt=\"\" " .
2180 "/>" . $post_white;
2181 } else {
2182 return "";
2186 sub format_search_author {
2187 my ($author, $searchtype, $displaytext) = @_;
2188 my $have_search = gitweb_check_feature('search');
2190 if ($have_search) {
2191 my $performed = "";
2192 if ($searchtype eq 'author') {
2193 $performed = "authored";
2194 } elsif ($searchtype eq 'committer') {
2195 $performed = "committed";
2198 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2199 searchtext=>$author,
2200 searchtype=>$searchtype), class=>"list",
2201 title=>"Search for commits $performed by $author"},
2202 $displaytext);
2204 } else {
2205 return $displaytext;
2209 # format the author name of the given commit with the given tag
2210 # the author name is chopped and escaped according to the other
2211 # optional parameters (see chop_str).
2212 sub format_author_html {
2213 my $tag = shift;
2214 my $co = shift;
2215 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2216 return "<$tag class=\"author\">" .
2217 format_search_author($co->{'author_name'}, "author",
2218 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2219 $author) .
2220 "</$tag>";
2223 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2224 sub format_git_diff_header_line {
2225 my $line = shift;
2226 my $diffinfo = shift;
2227 my ($from, $to) = @_;
2229 if ($diffinfo->{'nparents'}) {
2230 # combined diff
2231 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2232 if ($to->{'href'}) {
2233 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2234 esc_path($to->{'file'}));
2235 } else { # file was deleted (no href)
2236 $line .= esc_path($to->{'file'});
2238 } else {
2239 # "ordinary" diff
2240 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2241 if ($from->{'href'}) {
2242 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2243 'a/' . esc_path($from->{'file'}));
2244 } else { # file was added (no href)
2245 $line .= 'a/' . esc_path($from->{'file'});
2247 $line .= ' ';
2248 if ($to->{'href'}) {
2249 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2250 'b/' . esc_path($to->{'file'}));
2251 } else { # file was deleted
2252 $line .= 'b/' . esc_path($to->{'file'});
2256 return "<div class=\"diff header\">$line</div>\n";
2259 # format extended diff header line, before patch itself
2260 sub format_extended_diff_header_line {
2261 my $line = shift;
2262 my $diffinfo = shift;
2263 my ($from, $to) = @_;
2265 # match <path>
2266 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2267 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2268 esc_path($from->{'file'}));
2270 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2271 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2272 esc_path($to->{'file'}));
2274 # match single <mode>
2275 if ($line =~ m/\s(\d{6})$/) {
2276 $line .= '<span class="info"> (' .
2277 file_type_long($1) .
2278 ')</span>';
2280 # match <hash>
2281 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2282 # can match only for combined diff
2283 $line = 'index ';
2284 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2285 if ($from->{'href'}[$i]) {
2286 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2287 -class=>"hash"},
2288 substr($diffinfo->{'from_id'}[$i],0,7));
2289 } else {
2290 $line .= '0' x 7;
2292 # separator
2293 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2295 $line .= '..';
2296 if ($to->{'href'}) {
2297 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2298 substr($diffinfo->{'to_id'},0,7));
2299 } else {
2300 $line .= '0' x 7;
2303 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2304 # can match only for ordinary diff
2305 my ($from_link, $to_link);
2306 if ($from->{'href'}) {
2307 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2308 substr($diffinfo->{'from_id'},0,7));
2309 } else {
2310 $from_link = '0' x 7;
2312 if ($to->{'href'}) {
2313 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2314 substr($diffinfo->{'to_id'},0,7));
2315 } else {
2316 $to_link = '0' x 7;
2318 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2319 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2322 return $line . "<br/>\n";
2325 # format from-file/to-file diff header
2326 sub format_diff_from_to_header {
2327 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2328 my $line;
2329 my $result = '';
2331 $line = $from_line;
2332 #assert($line =~ m/^---/) if DEBUG;
2333 # no extra formatting for "^--- /dev/null"
2334 if (! $diffinfo->{'nparents'}) {
2335 # ordinary (single parent) diff
2336 if ($line =~ m!^--- "?a/!) {
2337 if ($from->{'href'}) {
2338 $line = '--- a/' .
2339 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2340 esc_path($from->{'file'}));
2341 } else {
2342 $line = '--- a/' .
2343 esc_path($from->{'file'});
2346 $result .= qq!<div class="diff from_file">$line</div>\n!;
2348 } else {
2349 # combined diff (merge commit)
2350 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2351 if ($from->{'href'}[$i]) {
2352 $line = '--- ' .
2353 $cgi->a({-href=>href(action=>"blobdiff",
2354 hash_parent=>$diffinfo->{'from_id'}[$i],
2355 hash_parent_base=>$parents[$i],
2356 file_parent=>$from->{'file'}[$i],
2357 hash=>$diffinfo->{'to_id'},
2358 hash_base=>$hash,
2359 file_name=>$to->{'file'}),
2360 -class=>"path",
2361 -title=>"diff" . ($i+1)},
2362 $i+1) .
2363 '/' .
2364 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2365 esc_path($from->{'file'}[$i]));
2366 } else {
2367 $line = '--- /dev/null';
2369 $result .= qq!<div class="diff from_file">$line</div>\n!;
2373 $line = $to_line;
2374 #assert($line =~ m/^\+\+\+/) if DEBUG;
2375 # no extra formatting for "^+++ /dev/null"
2376 if ($line =~ m!^\+\+\+ "?b/!) {
2377 if ($to->{'href'}) {
2378 $line = '+++ b/' .
2379 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2380 esc_path($to->{'file'}));
2381 } else {
2382 $line = '+++ b/' .
2383 esc_path($to->{'file'});
2386 $result .= qq!<div class="diff to_file">$line</div>\n!;
2388 return $result;
2391 # create note for patch simplified by combined diff
2392 sub format_diff_cc_simplified {
2393 my ($diffinfo, @parents) = @_;
2394 my $result = '';
2396 $result .= "<div class=\"diff header\">" .
2397 "diff --cc ";
2398 if (!is_deleted($diffinfo)) {
2399 $result .= $cgi->a({-href => href(action=>"blob",
2400 hash_base=>$hash,
2401 hash=>$diffinfo->{'to_id'},
2402 file_name=>$diffinfo->{'to_file'}),
2403 -class => "path"},
2404 esc_path($diffinfo->{'to_file'}));
2405 } else {
2406 $result .= esc_path($diffinfo->{'to_file'});
2408 $result .= "</div>\n" . # class="diff header"
2409 "<div class=\"diff nodifferences\">" .
2410 "Simple merge" .
2411 "</div>\n"; # class="diff nodifferences"
2413 return $result;
2416 sub diff_line_class {
2417 my ($line, $from, $to) = @_;
2419 # ordinary diff
2420 my $num_sign = 1;
2421 # combined diff
2422 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2423 $num_sign = scalar @{$from->{'href'}};
2426 my @diff_line_classifier = (
2427 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2428 { regexp => qr/^\\/, class => "incomplete" },
2429 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2430 # classifier for context must come before classifier add/rem,
2431 # or we would have to use more complicated regexp, for example
2432 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2433 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2434 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2436 for my $clsfy (@diff_line_classifier) {
2437 return $clsfy->{'class'}
2438 if ($line =~ $clsfy->{'regexp'});
2441 # fallback
2442 return "";
2445 # assumes that $from and $to are defined and correctly filled,
2446 # and that $line holds a line of chunk header for unified diff
2447 sub format_unidiff_chunk_header {
2448 my ($line, $from, $to) = @_;
2450 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2451 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2453 $from_lines = 0 unless defined $from_lines;
2454 $to_lines = 0 unless defined $to_lines;
2456 if ($from->{'href'}) {
2457 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2458 -class=>"list"}, $from_text);
2460 if ($to->{'href'}) {
2461 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2462 -class=>"list"}, $to_text);
2464 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2465 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2466 return $line;
2469 # assumes that $from and $to are defined and correctly filled,
2470 # and that $line holds a line of chunk header for combined diff
2471 sub format_cc_diff_chunk_header {
2472 my ($line, $from, $to) = @_;
2474 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2475 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2477 @from_text = split(' ', $ranges);
2478 for (my $i = 0; $i < @from_text; ++$i) {
2479 ($from_start[$i], $from_nlines[$i]) =
2480 (split(',', substr($from_text[$i], 1)), 0);
2483 $to_text = pop @from_text;
2484 $to_start = pop @from_start;
2485 $to_nlines = pop @from_nlines;
2487 $line = "<span class=\"chunk_info\">$prefix ";
2488 for (my $i = 0; $i < @from_text; ++$i) {
2489 if ($from->{'href'}[$i]) {
2490 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2491 -class=>"list"}, $from_text[$i]);
2492 } else {
2493 $line .= $from_text[$i];
2495 $line .= " ";
2497 if ($to->{'href'}) {
2498 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2499 -class=>"list"}, $to_text);
2500 } else {
2501 $line .= $to_text;
2503 $line .= " $prefix</span>" .
2504 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2505 return $line;
2508 # process patch (diff) line (not to be used for diff headers),
2509 # returning HTML-formatted (but not wrapped) line.
2510 # If the line is passed as a reference, it is treated as HTML and not
2511 # esc_html()'ed.
2512 sub format_diff_line {
2513 my ($line, $diff_class, $from, $to) = @_;
2515 if (ref($line)) {
2516 $line = $$line;
2517 } else {
2518 chomp $line;
2519 $line = untabify($line);
2521 if ($from && $to && $line =~ m/^\@{2} /) {
2522 $line = format_unidiff_chunk_header($line, $from, $to);
2523 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2524 $line = format_cc_diff_chunk_header($line, $from, $to);
2525 } else {
2526 $line = esc_html($line, -nbsp=>1);
2530 my $diff_classes = "diff";
2531 $diff_classes .= " $diff_class" if ($diff_class);
2532 $line = "<div class=\"$diff_classes\">$line</div>\n";
2534 return $line;
2537 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2538 # linked. Pass the hash of the tree/commit to snapshot.
2539 sub format_snapshot_links {
2540 my ($hash) = @_;
2541 my $num_fmts = @snapshot_fmts;
2542 if ($num_fmts > 1) {
2543 # A parenthesized list of links bearing format names.
2544 # e.g. "snapshot (_tar.gz_ _zip_)"
2545 return "snapshot (" . join(' ', map
2546 $cgi->a({
2547 -href => href(
2548 action=>"snapshot",
2549 hash=>$hash,
2550 snapshot_format=>$_
2552 }, $known_snapshot_formats{$_}{'display'})
2553 , @snapshot_fmts) . ")";
2554 } elsif ($num_fmts == 1) {
2555 # A single "snapshot" link whose tooltip bears the format name.
2556 # i.e. "_snapshot_"
2557 my ($fmt) = @snapshot_fmts;
2558 return
2559 $cgi->a({
2560 -href => href(
2561 action=>"snapshot",
2562 hash=>$hash,
2563 snapshot_format=>$fmt
2565 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2566 }, "snapshot");
2567 } else { # $num_fmts == 0
2568 return undef;
2572 ## ......................................................................
2573 ## functions returning values to be passed, perhaps after some
2574 ## transformation, to other functions; e.g. returning arguments to href()
2576 # returns hash to be passed to href to generate gitweb URL
2577 # in -title key it returns description of link
2578 sub get_feed_info {
2579 my $format = shift || 'Atom';
2580 my %res = (action => lc($format));
2581 my $matched_ref = 0;
2583 # feed links are possible only for project views
2584 return unless (defined $project);
2585 # some views should link to OPML, or to generic project feed,
2586 # or don't have specific feed yet (so they should use generic)
2587 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2589 my $branch = undef;
2590 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2591 # (fullname) to differentiate from tag links; this also makes
2592 # possible to detect branch links
2593 for my $ref (get_branch_refs()) {
2594 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2595 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2596 $branch = $1;
2597 $matched_ref = $ref;
2598 last;
2601 # find log type for feed description (title)
2602 my $type = 'log';
2603 if (defined $file_name) {
2604 $type = "history of $file_name";
2605 $type .= "/" if ($action eq 'tree');
2606 $type .= " on '$branch'" if (defined $branch);
2607 } else {
2608 $type = "log of $branch" if (defined $branch);
2611 $res{-title} = $type;
2612 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2613 $res{'file_name'} = $file_name;
2615 return %res;
2618 ## ----------------------------------------------------------------------
2619 ## git utility subroutines, invoking git commands
2621 # returns path to the core git executable and the --git-dir parameter as list
2622 sub git_cmd {
2623 $number_of_git_cmds++;
2624 return $GIT, '--git-dir='.$git_dir;
2627 # quote the given arguments for passing them to the shell
2628 # quote_command("command", "arg 1", "arg with ' and ! characters")
2629 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2630 # Try to avoid using this function wherever possible.
2631 sub quote_command {
2632 return join(' ',
2633 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2636 # get HEAD ref of given project as hash
2637 sub git_get_head_hash {
2638 return git_get_full_hash(shift, 'HEAD');
2641 sub git_get_full_hash {
2642 return git_get_hash(@_);
2645 sub git_get_short_hash {
2646 return git_get_hash(@_, '--short=7');
2649 sub git_get_hash {
2650 my ($project, $hash, @options) = @_;
2651 my $o_git_dir = $git_dir;
2652 my $retval = undef;
2653 $git_dir = "$projectroot/$project";
2654 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2655 '--verify', '-q', @options, $hash) {
2656 $retval = <$fd>;
2657 chomp $retval if defined $retval;
2658 close $fd;
2660 if (defined $o_git_dir) {
2661 $git_dir = $o_git_dir;
2663 return $retval;
2666 # get type of given object
2667 sub git_get_type {
2668 my $hash = shift;
2670 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2671 my $type = <$fd>;
2672 close $fd or return;
2673 chomp $type;
2674 return $type;
2677 # repository configuration
2678 our $config_file = '';
2679 our %config;
2681 # store multiple values for single key as anonymous array reference
2682 # single values stored directly in the hash, not as [ <value> ]
2683 sub hash_set_multi {
2684 my ($hash, $key, $value) = @_;
2686 if (!exists $hash->{$key}) {
2687 $hash->{$key} = $value;
2688 } elsif (!ref $hash->{$key}) {
2689 $hash->{$key} = [ $hash->{$key}, $value ];
2690 } else {
2691 push @{$hash->{$key}}, $value;
2695 # return hash of git project configuration
2696 # optionally limited to some section, e.g. 'gitweb'
2697 sub git_parse_project_config {
2698 my $section_regexp = shift;
2699 my %config;
2701 local $/ = "\0";
2703 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2704 or return;
2706 while (my $keyval = <$fh>) {
2707 chomp $keyval;
2708 my ($key, $value) = split(/\n/, $keyval, 2);
2710 hash_set_multi(\%config, $key, $value)
2711 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2713 close $fh;
2715 return %config;
2718 # convert config value to boolean: 'true' or 'false'
2719 # no value, number > 0, 'true' and 'yes' values are true
2720 # rest of values are treated as false (never as error)
2721 sub config_to_bool {
2722 my $val = shift;
2724 return 1 if !defined $val; # section.key
2726 # strip leading and trailing whitespace
2727 $val =~ s/^\s+//;
2728 $val =~ s/\s+$//;
2730 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2731 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2734 # convert config value to simple decimal number
2735 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2736 # to be multiplied by 1024, 1048576, or 1073741824
2737 sub config_to_int {
2738 my $val = shift;
2740 # strip leading and trailing whitespace
2741 $val =~ s/^\s+//;
2742 $val =~ s/\s+$//;
2744 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2745 $unit = lc($unit);
2746 # unknown unit is treated as 1
2747 return $num * ($unit eq 'g' ? 1073741824 :
2748 $unit eq 'm' ? 1048576 :
2749 $unit eq 'k' ? 1024 : 1);
2751 return $val;
2754 # convert config value to array reference, if needed
2755 sub config_to_multi {
2756 my $val = shift;
2758 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2761 sub git_get_project_config {
2762 my ($key, $type) = @_;
2764 return unless defined $git_dir;
2766 # key sanity check
2767 return unless ($key);
2768 # only subsection, if exists, is case sensitive,
2769 # and not lowercased by 'git config -z -l'
2770 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2771 $lo =~ s/_//g;
2772 $key = join(".", lc($hi), $mi, lc($lo));
2773 return if ($lo =~ /\W/ || $hi =~ /\W/);
2774 } else {
2775 $key = lc($key);
2776 $key =~ s/_//g;
2777 return if ($key =~ /\W/);
2779 $key =~ s/^gitweb\.//;
2781 # type sanity check
2782 if (defined $type) {
2783 $type =~ s/^--//;
2784 $type = undef
2785 unless ($type eq 'bool' || $type eq 'int');
2788 # get config
2789 if (!defined $config_file ||
2790 $config_file ne "$git_dir/config") {
2791 %config = git_parse_project_config('gitweb');
2792 $config_file = "$git_dir/config";
2795 # check if config variable (key) exists
2796 return unless exists $config{"gitweb.$key"};
2798 # ensure given type
2799 if (!defined $type) {
2800 return $config{"gitweb.$key"};
2801 } elsif ($type eq 'bool') {
2802 # backward compatibility: 'git config --bool' returns true/false
2803 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2804 } elsif ($type eq 'int') {
2805 return config_to_int($config{"gitweb.$key"});
2807 return $config{"gitweb.$key"};
2810 # get hash of given path at given ref
2811 sub git_get_hash_by_path {
2812 my $base = shift;
2813 my $path = shift || return undef;
2814 my $type = shift;
2816 $path =~ s,/+$,,;
2818 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2819 or die_error(500, "Open git-ls-tree failed");
2820 my $line = <$fd>;
2821 close $fd or return undef;
2823 if (!defined $line) {
2824 # there is no tree or hash given by $path at $base
2825 return undef;
2828 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2829 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2830 if (defined $type && $type ne $2) {
2831 # type doesn't match
2832 return undef;
2834 return $3;
2837 # get path of entry with given hash at given tree-ish (ref)
2838 # used to get 'from' filename for combined diff (merge commit) for renames
2839 sub git_get_path_by_hash {
2840 my $base = shift || return;
2841 my $hash = shift || return;
2843 local $/ = "\0";
2845 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2846 or return undef;
2847 while (my $line = <$fd>) {
2848 chomp $line;
2850 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2851 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2852 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2853 close $fd;
2854 return $1;
2857 close $fd;
2858 return undef;
2861 ## ......................................................................
2862 ## git utility functions, directly accessing git repository
2864 # get the value of config variable either from file named as the variable
2865 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2866 # configuration variable in the repository config file.
2867 sub git_get_file_or_project_config {
2868 my ($path, $name) = @_;
2870 $git_dir = "$projectroot/$path";
2871 open my $fd, '<', "$git_dir/$name"
2872 or return git_get_project_config($name);
2873 my $conf = <$fd>;
2874 close $fd;
2875 if (defined $conf) {
2876 chomp $conf;
2878 return $conf;
2881 sub git_get_project_description {
2882 my $path = shift;
2883 return git_get_file_or_project_config($path, 'description');
2886 sub git_get_project_category {
2887 my $path = shift;
2888 return git_get_file_or_project_config($path, 'category');
2892 # supported formats:
2893 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2894 # - if its contents is a number, use it as tag weight,
2895 # - otherwise add a tag with weight 1
2896 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2897 # the same value multiple times increases tag weight
2898 # * `gitweb.ctag' multi-valued repo config variable
2899 sub git_get_project_ctags {
2900 my $project = shift;
2901 my $ctags = {};
2903 $git_dir = "$projectroot/$project";
2904 if (opendir my $dh, "$git_dir/ctags") {
2905 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2906 foreach my $tagfile (@files) {
2907 open my $ct, '<', $tagfile
2908 or next;
2909 my $val = <$ct>;
2910 chomp $val if $val;
2911 close $ct;
2913 (my $ctag = $tagfile) =~ s#.*/##;
2914 if ($val =~ /^\d+$/) {
2915 $ctags->{$ctag} = $val;
2916 } else {
2917 $ctags->{$ctag} = 1;
2920 closedir $dh;
2922 } elsif (open my $fh, '<', "$git_dir/ctags") {
2923 while (my $line = <$fh>) {
2924 chomp $line;
2925 $ctags->{$line}++ if $line;
2927 close $fh;
2929 } else {
2930 my $taglist = config_to_multi(git_get_project_config('ctag'));
2931 foreach my $tag (@$taglist) {
2932 $ctags->{$tag}++;
2936 return $ctags;
2939 # return hash, where keys are content tags ('ctags'),
2940 # and values are sum of weights of given tag in every project
2941 sub git_gather_all_ctags {
2942 my $projects = shift;
2943 my $ctags = {};
2945 foreach my $p (@$projects) {
2946 foreach my $ct (keys %{$p->{'ctags'}}) {
2947 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2951 return $ctags;
2954 sub git_populate_project_tagcloud {
2955 my $ctags = shift;
2957 # First, merge different-cased tags; tags vote on casing
2958 my %ctags_lc;
2959 foreach (keys %$ctags) {
2960 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2961 if (not $ctags_lc{lc $_}->{topcount}
2962 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2963 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2964 $ctags_lc{lc $_}->{topname} = $_;
2968 my $cloud;
2969 my $matched = $input_params{'ctag'};
2970 if (eval { require HTML::TagCloud; 1; }) {
2971 $cloud = HTML::TagCloud->new;
2972 foreach my $ctag (sort keys %ctags_lc) {
2973 # Pad the title with spaces so that the cloud looks
2974 # less crammed.
2975 my $title = esc_html($ctags_lc{$ctag}->{topname});
2976 $title =~ s/ /&nbsp;/g;
2977 $title =~ s/^/&nbsp;/g;
2978 $title =~ s/$/&nbsp;/g;
2979 if (defined $matched && $matched eq $ctag) {
2980 $title = qq(<span class="match">$title</span>);
2982 $cloud->add($title, href(project=>undef, ctag=>$ctag),
2983 $ctags_lc{$ctag}->{count});
2985 } else {
2986 $cloud = {};
2987 foreach my $ctag (keys %ctags_lc) {
2988 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
2989 if (defined $matched && $matched eq $ctag) {
2990 $title = qq(<span class="match">$title</span>);
2992 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
2993 $cloud->{$ctag}{ctag} =
2994 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
2997 return $cloud;
3000 sub git_show_project_tagcloud {
3001 my ($cloud, $count) = @_;
3002 if (ref $cloud eq 'HTML::TagCloud') {
3003 return $cloud->html_and_css($count);
3004 } else {
3005 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3006 return
3007 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3008 join (', ', map {
3009 $cloud->{$_}->{'ctag'}
3010 } splice(@tags, 0, $count)) .
3011 '</div>';
3015 sub git_get_project_url_list {
3016 my $path = shift;
3018 $git_dir = "$projectroot/$path";
3019 open my $fd, '<', "$git_dir/cloneurl"
3020 or return wantarray ?
3021 @{ config_to_multi(git_get_project_config('url')) } :
3022 config_to_multi(git_get_project_config('url'));
3023 my @git_project_url_list = map { chomp; $_ } <$fd>;
3024 close $fd;
3026 return wantarray ? @git_project_url_list : \@git_project_url_list;
3029 sub git_get_projects_list {
3030 my $filter = shift || '';
3031 my $paranoid = shift;
3032 my @list;
3034 if (-d $projects_list) {
3035 # search in directory
3036 my $dir = $projects_list;
3037 # remove the trailing "/"
3038 $dir =~ s!/+$!!;
3039 my $pfxlen = length("$dir");
3040 my $pfxdepth = ($dir =~ tr!/!!);
3041 # when filtering, search only given subdirectory
3042 if ($filter && !$paranoid) {
3043 $dir .= "/$filter";
3044 $dir =~ s!/+$!!;
3047 File::Find::find({
3048 follow_fast => 1, # follow symbolic links
3049 follow_skip => 2, # ignore duplicates
3050 dangling_symlinks => 0, # ignore dangling symlinks, silently
3051 wanted => sub {
3052 # global variables
3053 our $project_maxdepth;
3054 our $projectroot;
3055 # skip project-list toplevel, if we get it.
3056 return if (m!^[/.]$!);
3057 # only directories can be git repositories
3058 return unless (-d $_);
3059 # don't traverse too deep (Find is super slow on os x)
3060 # $project_maxdepth excludes depth of $projectroot
3061 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3062 $File::Find::prune = 1;
3063 return;
3066 my $path = substr($File::Find::name, $pfxlen + 1);
3067 # paranoidly only filter here
3068 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3069 next;
3071 # we check related file in $projectroot
3072 if (check_export_ok("$projectroot/$path")) {
3073 push @list, { path => $path };
3074 $File::Find::prune = 1;
3077 }, "$dir");
3079 } elsif (-f $projects_list) {
3080 # read from file(url-encoded):
3081 # 'git%2Fgit.git Linus+Torvalds'
3082 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3083 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3084 open my $fd, '<', $projects_list or return;
3085 PROJECT:
3086 while (my $line = <$fd>) {
3087 chomp $line;
3088 my ($path, $owner) = split ' ', $line;
3089 $path = unescape($path);
3090 $owner = unescape($owner);
3091 if (!defined $path) {
3092 next;
3094 # if $filter is rpovided, check if $path begins with $filter
3095 if ($filter && $path !~ m!^\Q$filter\E/!) {
3096 next;
3098 if (check_export_ok("$projectroot/$path")) {
3099 my $pr = {
3100 path => $path
3102 if ($owner) {
3103 $pr->{'owner'} = to_utf8($owner);
3105 push @list, $pr;
3108 close $fd;
3110 return @list;
3113 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3114 # as side effects it sets 'forks' field to list of forks for forked projects
3115 sub filter_forks_from_projects_list {
3116 my $projects = shift;
3118 my %trie; # prefix tree of directories (path components)
3119 # generate trie out of those directories that might contain forks
3120 foreach my $pr (@$projects) {
3121 my $path = $pr->{'path'};
3122 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3123 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3124 next unless ($path); # skip '.git' repository: tests, git-instaweb
3125 next unless (-d "$projectroot/$path"); # containing directory exists
3126 $pr->{'forks'} = []; # there can be 0 or more forks of project
3128 # add to trie
3129 my @dirs = split('/', $path);
3130 # walk the trie, until either runs out of components or out of trie
3131 my $ref = \%trie;
3132 while (scalar @dirs &&
3133 exists($ref->{$dirs[0]})) {
3134 $ref = $ref->{shift @dirs};
3136 # create rest of trie structure from rest of components
3137 foreach my $dir (@dirs) {
3138 $ref = $ref->{$dir} = {};
3140 # create end marker, store $pr as a data
3141 $ref->{''} = $pr if (!exists $ref->{''});
3144 # filter out forks, by finding shortest prefix match for paths
3145 my @filtered;
3146 PROJECT:
3147 foreach my $pr (@$projects) {
3148 # trie lookup
3149 my $ref = \%trie;
3150 DIR:
3151 foreach my $dir (split('/', $pr->{'path'})) {
3152 if (exists $ref->{''}) {
3153 # found [shortest] prefix, is a fork - skip it
3154 push @{$ref->{''}{'forks'}}, $pr;
3155 next PROJECT;
3157 if (!exists $ref->{$dir}) {
3158 # not in trie, cannot have prefix, not a fork
3159 push @filtered, $pr;
3160 next PROJECT;
3162 # If the dir is there, we just walk one step down the trie.
3163 $ref = $ref->{$dir};
3165 # we ran out of trie
3166 # (shouldn't happen: it's either no match, or end marker)
3167 push @filtered, $pr;
3170 return @filtered;
3173 # note: fill_project_list_info must be run first,
3174 # for 'descr_long' and 'ctags' to be filled
3175 sub search_projects_list {
3176 my ($projlist, %opts) = @_;
3177 my $tagfilter = $opts{'tagfilter'};
3178 my $search_re = $opts{'search_regexp'};
3180 return @$projlist
3181 unless ($tagfilter || $search_re);
3183 # searching projects require filling to be run before it;
3184 fill_project_list_info($projlist,
3185 $tagfilter ? 'ctags' : (),
3186 $search_re ? ('path', 'descr') : ());
3187 my @projects;
3188 PROJECT:
3189 foreach my $pr (@$projlist) {
3191 if ($tagfilter) {
3192 next unless ref($pr->{'ctags'}) eq 'HASH';
3193 next unless
3194 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3197 if ($search_re) {
3198 next unless
3199 $pr->{'path'} =~ /$search_re/ ||
3200 $pr->{'descr_long'} =~ /$search_re/;
3203 push @projects, $pr;
3206 return @projects;
3209 our $gitweb_project_owner = undef;
3210 sub git_get_project_list_from_file {
3212 return if (defined $gitweb_project_owner);
3214 $gitweb_project_owner = {};
3215 # read from file (url-encoded):
3216 # 'git%2Fgit.git Linus+Torvalds'
3217 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3218 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3219 if (-f $projects_list) {
3220 open(my $fd, '<', $projects_list);
3221 while (my $line = <$fd>) {
3222 chomp $line;
3223 my ($pr, $ow) = split ' ', $line;
3224 $pr = unescape($pr);
3225 $ow = unescape($ow);
3226 $gitweb_project_owner->{$pr} = to_utf8($ow);
3228 close $fd;
3232 sub git_get_project_owner {
3233 my $project = shift;
3234 my $owner;
3236 return undef unless $project;
3237 $git_dir = "$projectroot/$project";
3239 if (!defined $gitweb_project_owner) {
3240 git_get_project_list_from_file();
3243 if (exists $gitweb_project_owner->{$project}) {
3244 $owner = $gitweb_project_owner->{$project};
3246 if (!defined $owner){
3247 $owner = git_get_project_config('owner');
3249 if (!defined $owner) {
3250 $owner = get_file_owner("$git_dir");
3253 return $owner;
3256 sub git_get_last_activity {
3257 my ($path) = @_;
3258 my $fd;
3260 $git_dir = "$projectroot/$path";
3261 open($fd, "-|", git_cmd(), 'for-each-ref',
3262 '--format=%(committer)',
3263 '--sort=-committerdate',
3264 '--count=1',
3265 map { "refs/$_" } get_branch_refs ()) or return;
3266 my $most_recent = <$fd>;
3267 close $fd or return;
3268 if (defined $most_recent &&
3269 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3270 my $timestamp = $1;
3271 my $age = time - $timestamp;
3272 return ($age, age_string($age));
3274 return (undef, undef);
3277 # Implementation note: when a single remote is wanted, we cannot use 'git
3278 # remote show -n' because that command always work (assuming it's a remote URL
3279 # if it's not defined), and we cannot use 'git remote show' because that would
3280 # try to make a network roundtrip. So the only way to find if that particular
3281 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3282 # and when we find what we want.
3283 sub git_get_remotes_list {
3284 my $wanted = shift;
3285 my %remotes = ();
3287 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3288 return unless $fd;
3289 while (my $remote = <$fd>) {
3290 chomp $remote;
3291 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3292 next if $wanted and not $remote eq $wanted;
3293 my ($url, $key) = ($1, $2);
3295 $remotes{$remote} ||= { 'heads' => () };
3296 $remotes{$remote}{$key} = $url;
3298 close $fd or return;
3299 return wantarray ? %remotes : \%remotes;
3302 # Takes a hash of remotes as first parameter and fills it by adding the
3303 # available remote heads for each of the indicated remotes.
3304 sub fill_remote_heads {
3305 my $remotes = shift;
3306 my @heads = map { "remotes/$_" } keys %$remotes;
3307 my @remoteheads = git_get_heads_list(undef, @heads);
3308 foreach my $remote (keys %$remotes) {
3309 $remotes->{$remote}{'heads'} = [ grep {
3310 $_->{'name'} =~ s!^$remote/!!
3311 } @remoteheads ];
3315 sub git_get_references {
3316 my $type = shift || "";
3317 my %refs;
3318 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3319 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3320 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3321 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3322 or return;
3324 while (my $line = <$fd>) {
3325 chomp $line;
3326 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3327 if (defined $refs{$1}) {
3328 push @{$refs{$1}}, $2;
3329 } else {
3330 $refs{$1} = [ $2 ];
3334 close $fd or return;
3335 return \%refs;
3338 sub git_get_rev_name_tags {
3339 my $hash = shift || return undef;
3341 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3342 or return;
3343 my $name_rev = <$fd>;
3344 close $fd;
3346 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3347 return $1;
3348 } else {
3349 # catches also '$hash undefined' output
3350 return undef;
3354 ## ----------------------------------------------------------------------
3355 ## parse to hash functions
3357 sub parse_date {
3358 my $epoch = shift;
3359 my $tz = shift || "-0000";
3361 my %date;
3362 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3363 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3364 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3365 $date{'hour'} = $hour;
3366 $date{'minute'} = $min;
3367 $date{'mday'} = $mday;
3368 $date{'day'} = $days[$wday];
3369 $date{'month'} = $months[$mon];
3370 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3371 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3372 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3373 $mday, $months[$mon], $hour ,$min;
3374 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3375 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3377 my ($tz_sign, $tz_hour, $tz_min) =
3378 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3379 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3380 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3381 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3382 $date{'hour_local'} = $hour;
3383 $date{'minute_local'} = $min;
3384 $date{'tz_local'} = $tz;
3385 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3386 1900+$year, $mon+1, $mday,
3387 $hour, $min, $sec, $tz);
3388 return %date;
3391 sub parse_tag {
3392 my $tag_id = shift;
3393 my %tag;
3394 my @comment;
3396 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3397 $tag{'id'} = $tag_id;
3398 while (my $line = <$fd>) {
3399 chomp $line;
3400 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3401 $tag{'object'} = $1;
3402 } elsif ($line =~ m/^type (.+)$/) {
3403 $tag{'type'} = $1;
3404 } elsif ($line =~ m/^tag (.+)$/) {
3405 $tag{'name'} = $1;
3406 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3407 $tag{'author'} = $1;
3408 $tag{'author_epoch'} = $2;
3409 $tag{'author_tz'} = $3;
3410 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3411 $tag{'author_name'} = $1;
3412 $tag{'author_email'} = $2;
3413 } else {
3414 $tag{'author_name'} = $tag{'author'};
3416 } elsif ($line =~ m/--BEGIN/) {
3417 push @comment, $line;
3418 last;
3419 } elsif ($line eq "") {
3420 last;
3423 push @comment, <$fd>;
3424 $tag{'comment'} = \@comment;
3425 close $fd or return;
3426 if (!defined $tag{'name'}) {
3427 return
3429 return %tag
3432 sub parse_commit_text {
3433 my ($commit_text, $withparents) = @_;
3434 my @commit_lines = split '\n', $commit_text;
3435 my %co;
3437 pop @commit_lines; # Remove '\0'
3439 if (! @commit_lines) {
3440 return;
3443 my $header = shift @commit_lines;
3444 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3445 return;
3447 ($co{'id'}, my @parents) = split ' ', $header;
3448 while (my $line = shift @commit_lines) {
3449 last if $line eq "\n";
3450 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3451 $co{'tree'} = $1;
3452 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3453 push @parents, $1;
3454 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3455 $co{'author'} = to_utf8($1);
3456 $co{'author_epoch'} = $2;
3457 $co{'author_tz'} = $3;
3458 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3459 $co{'author_name'} = $1;
3460 $co{'author_email'} = $2;
3461 } else {
3462 $co{'author_name'} = $co{'author'};
3464 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3465 $co{'committer'} = to_utf8($1);
3466 $co{'committer_epoch'} = $2;
3467 $co{'committer_tz'} = $3;
3468 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3469 $co{'committer_name'} = $1;
3470 $co{'committer_email'} = $2;
3471 } else {
3472 $co{'committer_name'} = $co{'committer'};
3476 if (!defined $co{'tree'}) {
3477 return;
3479 $co{'parents'} = \@parents;
3480 $co{'parent'} = $parents[0];
3482 foreach my $title (@commit_lines) {
3483 $title =~ s/^ //;
3484 if ($title ne "") {
3485 $co{'title'} = chop_str($title, 80, 5);
3486 # remove leading stuff of merges to make the interesting part visible
3487 if (length($title) > 50) {
3488 $title =~ s/^Automatic //;
3489 $title =~ s/^merge (of|with) /Merge ... /i;
3490 if (length($title) > 50) {
3491 $title =~ s/(http|rsync):\/\///;
3493 if (length($title) > 50) {
3494 $title =~ s/(master|www|rsync)\.//;
3496 if (length($title) > 50) {
3497 $title =~ s/kernel.org:?//;
3499 if (length($title) > 50) {
3500 $title =~ s/\/pub\/scm//;
3503 $co{'title_short'} = chop_str($title, 50, 5);
3504 last;
3507 if (! defined $co{'title'} || $co{'title'} eq "") {
3508 $co{'title'} = $co{'title_short'} = '(no commit message)';
3510 # remove added spaces
3511 foreach my $line (@commit_lines) {
3512 $line =~ s/^ //;
3514 $co{'comment'} = \@commit_lines;
3516 my $age = time - $co{'committer_epoch'};
3517 $co{'age'} = $age;
3518 $co{'age_string'} = age_string($age);
3519 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3520 if ($age > 60*60*24*7*2) {
3521 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3522 $co{'age_string_age'} = $co{'age_string'};
3523 } else {
3524 $co{'age_string_date'} = $co{'age_string'};
3525 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3527 return %co;
3530 sub parse_commit {
3531 my ($commit_id) = @_;
3532 my %co;
3534 local $/ = "\0";
3536 open my $fd, "-|", git_cmd(), "rev-list",
3537 "--parents",
3538 "--header",
3539 "--max-count=1",
3540 $commit_id,
3541 "--",
3542 or die_error(500, "Open git-rev-list failed");
3543 %co = parse_commit_text(<$fd>, 1);
3544 close $fd;
3546 return %co;
3549 sub parse_commits {
3550 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3551 my @cos;
3553 $maxcount ||= 1;
3554 $skip ||= 0;
3556 local $/ = "\0";
3558 open my $fd, "-|", git_cmd(), "rev-list",
3559 "--header",
3560 @args,
3561 ("--max-count=" . $maxcount),
3562 ("--skip=" . $skip),
3563 @extra_options,
3564 $commit_id,
3565 "--",
3566 ($filename ? ($filename) : ())
3567 or die_error(500, "Open git-rev-list failed");
3568 while (my $line = <$fd>) {
3569 my %co = parse_commit_text($line);
3570 push @cos, \%co;
3572 close $fd;
3574 return wantarray ? @cos : \@cos;
3577 # parse line of git-diff-tree "raw" output
3578 sub parse_difftree_raw_line {
3579 my $line = shift;
3580 my %res;
3582 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3583 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3584 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3585 $res{'from_mode'} = $1;
3586 $res{'to_mode'} = $2;
3587 $res{'from_id'} = $3;
3588 $res{'to_id'} = $4;
3589 $res{'status'} = $5;
3590 $res{'similarity'} = $6;
3591 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3592 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3593 } else {
3594 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3597 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3598 # combined diff (for merge commit)
3599 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3600 $res{'nparents'} = length($1);
3601 $res{'from_mode'} = [ split(' ', $2) ];
3602 $res{'to_mode'} = pop @{$res{'from_mode'}};
3603 $res{'from_id'} = [ split(' ', $3) ];
3604 $res{'to_id'} = pop @{$res{'from_id'}};
3605 $res{'status'} = [ split('', $4) ];
3606 $res{'to_file'} = unquote($5);
3608 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3609 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3610 $res{'commit'} = $1;
3613 return wantarray ? %res : \%res;
3616 # wrapper: return parsed line of git-diff-tree "raw" output
3617 # (the argument might be raw line, or parsed info)
3618 sub parsed_difftree_line {
3619 my $line_or_ref = shift;
3621 if (ref($line_or_ref) eq "HASH") {
3622 # pre-parsed (or generated by hand)
3623 return $line_or_ref;
3624 } else {
3625 return parse_difftree_raw_line($line_or_ref);
3629 # parse line of git-ls-tree output
3630 sub parse_ls_tree_line {
3631 my $line = shift;
3632 my %opts = @_;
3633 my %res;
3635 if ($opts{'-l'}) {
3636 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3637 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3639 $res{'mode'} = $1;
3640 $res{'type'} = $2;
3641 $res{'hash'} = $3;
3642 $res{'size'} = $4;
3643 if ($opts{'-z'}) {
3644 $res{'name'} = $5;
3645 } else {
3646 $res{'name'} = unquote($5);
3648 } else {
3649 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3650 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3652 $res{'mode'} = $1;
3653 $res{'type'} = $2;
3654 $res{'hash'} = $3;
3655 if ($opts{'-z'}) {
3656 $res{'name'} = $4;
3657 } else {
3658 $res{'name'} = unquote($4);
3662 return wantarray ? %res : \%res;
3665 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3666 sub parse_from_to_diffinfo {
3667 my ($diffinfo, $from, $to, @parents) = @_;
3669 if ($diffinfo->{'nparents'}) {
3670 # combined diff
3671 $from->{'file'} = [];
3672 $from->{'href'} = [];
3673 fill_from_file_info($diffinfo, @parents)
3674 unless exists $diffinfo->{'from_file'};
3675 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3676 $from->{'file'}[$i] =
3677 defined $diffinfo->{'from_file'}[$i] ?
3678 $diffinfo->{'from_file'}[$i] :
3679 $diffinfo->{'to_file'};
3680 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3681 $from->{'href'}[$i] = href(action=>"blob",
3682 hash_base=>$parents[$i],
3683 hash=>$diffinfo->{'from_id'}[$i],
3684 file_name=>$from->{'file'}[$i]);
3685 } else {
3686 $from->{'href'}[$i] = undef;
3689 } else {
3690 # ordinary (not combined) diff
3691 $from->{'file'} = $diffinfo->{'from_file'};
3692 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3693 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3694 hash=>$diffinfo->{'from_id'},
3695 file_name=>$from->{'file'});
3696 } else {
3697 delete $from->{'href'};
3701 $to->{'file'} = $diffinfo->{'to_file'};
3702 if (!is_deleted($diffinfo)) { # file exists in result
3703 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3704 hash=>$diffinfo->{'to_id'},
3705 file_name=>$to->{'file'});
3706 } else {
3707 delete $to->{'href'};
3711 ## ......................................................................
3712 ## parse to array of hashes functions
3714 sub git_get_heads_list {
3715 my ($limit, @classes) = @_;
3716 @classes = get_branch_refs() unless @classes;
3717 my @patterns = map { "refs/$_" } @classes;
3718 my @headslist;
3720 open my $fd, '-|', git_cmd(), 'for-each-ref',
3721 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3722 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3723 @patterns
3724 or return;
3725 while (my $line = <$fd>) {
3726 my %ref_item;
3728 chomp $line;
3729 my ($refinfo, $committerinfo) = split(/\0/, $line);
3730 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3731 my ($committer, $epoch, $tz) =
3732 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3733 $ref_item{'fullname'} = $name;
3734 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3735 $name =~ s!^refs/($strip_refs|remotes)/!!;
3736 $ref_item{'name'} = $name;
3737 # for refs neither in 'heads' nor 'remotes' we want to
3738 # show their ref dir
3739 my $ref_dir = (defined $1) ? $1 : '';
3740 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3741 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3744 $ref_item{'id'} = $hash;
3745 $ref_item{'title'} = $title || '(no commit message)';
3746 $ref_item{'epoch'} = $epoch;
3747 if ($epoch) {
3748 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3749 } else {
3750 $ref_item{'age'} = "unknown";
3753 push @headslist, \%ref_item;
3755 close $fd;
3757 return wantarray ? @headslist : \@headslist;
3760 sub git_get_tags_list {
3761 my $limit = shift;
3762 my @tagslist;
3764 open my $fd, '-|', git_cmd(), 'for-each-ref',
3765 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3766 '--format=%(objectname) %(objecttype) %(refname) '.
3767 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3768 'refs/tags'
3769 or return;
3770 while (my $line = <$fd>) {
3771 my %ref_item;
3773 chomp $line;
3774 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3775 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3776 my ($creator, $epoch, $tz) =
3777 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3778 $ref_item{'fullname'} = $name;
3779 $name =~ s!^refs/tags/!!;
3781 $ref_item{'type'} = $type;
3782 $ref_item{'id'} = $id;
3783 $ref_item{'name'} = $name;
3784 if ($type eq "tag") {
3785 $ref_item{'subject'} = $title;
3786 $ref_item{'reftype'} = $reftype;
3787 $ref_item{'refid'} = $refid;
3788 } else {
3789 $ref_item{'reftype'} = $type;
3790 $ref_item{'refid'} = $id;
3793 if ($type eq "tag" || $type eq "commit") {
3794 $ref_item{'epoch'} = $epoch;
3795 if ($epoch) {
3796 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3797 } else {
3798 $ref_item{'age'} = "unknown";
3802 push @tagslist, \%ref_item;
3804 close $fd;
3806 return wantarray ? @tagslist : \@tagslist;
3809 ## ----------------------------------------------------------------------
3810 ## filesystem-related functions
3812 sub get_file_owner {
3813 my $path = shift;
3815 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3816 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3817 if (!defined $gcos) {
3818 return undef;
3820 my $owner = $gcos;
3821 $owner =~ s/[,;].*$//;
3822 return to_utf8($owner);
3825 # assume that file exists
3826 sub insert_file {
3827 my $filename = shift;
3829 open my $fd, '<', $filename;
3830 print map { to_utf8($_) } <$fd>;
3831 close $fd;
3834 ## ......................................................................
3835 ## mimetype related functions
3837 sub mimetype_guess_file {
3838 my $filename = shift;
3839 my $mimemap = shift;
3840 -r $mimemap or return undef;
3842 my %mimemap;
3843 open(my $mh, '<', $mimemap) or return undef;
3844 while (<$mh>) {
3845 next if m/^#/; # skip comments
3846 my ($mimetype, @exts) = split(/\s+/);
3847 foreach my $ext (@exts) {
3848 $mimemap{$ext} = $mimetype;
3851 close($mh);
3853 $filename =~ /\.([^.]*)$/;
3854 return $mimemap{$1};
3857 sub mimetype_guess {
3858 my $filename = shift;
3859 my $mime;
3860 $filename =~ /\./ or return undef;
3862 if ($mimetypes_file) {
3863 my $file = $mimetypes_file;
3864 if ($file !~ m!^/!) { # if it is relative path
3865 # it is relative to project
3866 $file = "$projectroot/$project/$file";
3868 $mime = mimetype_guess_file($filename, $file);
3870 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3871 return $mime;
3874 sub blob_mimetype {
3875 my $fd = shift;
3876 my $filename = shift;
3878 if ($filename) {
3879 my $mime = mimetype_guess($filename);
3880 $mime and return $mime;
3883 # just in case
3884 return $default_blob_plain_mimetype unless $fd;
3886 if (-T $fd) {
3887 return 'text/plain';
3888 } elsif (! $filename) {
3889 return 'application/octet-stream';
3890 } elsif ($filename =~ m/\.png$/i) {
3891 return 'image/png';
3892 } elsif ($filename =~ m/\.gif$/i) {
3893 return 'image/gif';
3894 } elsif ($filename =~ m/\.jpe?g$/i) {
3895 return 'image/jpeg';
3896 } else {
3897 return 'application/octet-stream';
3901 sub blob_contenttype {
3902 my ($fd, $file_name, $type) = @_;
3904 $type ||= blob_mimetype($fd, $file_name);
3905 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3906 $type .= "; charset=$default_text_plain_charset";
3909 return $type;
3912 # guess file syntax for syntax highlighting; return undef if no highlighting
3913 # the name of syntax can (in the future) depend on syntax highlighter used
3914 sub guess_file_syntax {
3915 my ($highlight, $mimetype, $file_name) = @_;
3916 return undef unless ($highlight && defined $file_name);
3917 my $basename = basename($file_name, '.in');
3918 return $highlight_basename{$basename}
3919 if exists $highlight_basename{$basename};
3921 $basename =~ /\.([^.]*)$/;
3922 my $ext = $1 or return undef;
3923 return $highlight_ext{$ext}
3924 if exists $highlight_ext{$ext};
3926 return undef;
3929 # run highlighter and return FD of its output,
3930 # or return original FD if no highlighting
3931 sub run_highlighter {
3932 my ($fd, $highlight, $syntax) = @_;
3933 return $fd unless ($highlight && defined $syntax);
3935 close $fd;
3936 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3937 quote_command($highlight_bin).
3938 " --replace-tabs=8 --fragment --syntax $syntax |"
3939 or die_error(500, "Couldn't open file or run syntax highlighter");
3940 return $fd;
3943 ## ======================================================================
3944 ## functions printing HTML: header, footer, error page
3946 sub get_page_title {
3947 my $title = to_utf8($site_name);
3949 unless (defined $project) {
3950 if (defined $project_filter) {
3951 $title .= " - projects in '" . esc_path($project_filter) . "'";
3953 return $title;
3955 $title .= " - " . to_utf8($project);
3957 return $title unless (defined $action);
3958 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3960 return $title unless (defined $file_name);
3961 $title .= " - " . esc_path($file_name);
3962 if ($action eq "tree" && $file_name !~ m|/$|) {
3963 $title .= "/";
3966 return $title;
3969 sub get_content_type_html {
3970 # require explicit support from the UA if we are to send the page as
3971 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3972 # we have to do this because MSIE sometimes globs '*/*', pretending to
3973 # support xhtml+xml but choking when it gets what it asked for.
3974 if (defined $cgi->http('HTTP_ACCEPT') &&
3975 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3976 $cgi->Accept('application/xhtml+xml') != 0) {
3977 return 'application/xhtml+xml';
3978 } else {
3979 return 'text/html';
3983 sub print_feed_meta {
3984 if (defined $project) {
3985 my %href_params = get_feed_info();
3986 if (!exists $href_params{'-title'}) {
3987 $href_params{'-title'} = 'log';
3990 foreach my $format (qw(RSS Atom)) {
3991 my $type = lc($format);
3992 my %link_attr = (
3993 '-rel' => 'alternate',
3994 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
3995 '-type' => "application/$type+xml"
3998 $href_params{'extra_options'} = undef;
3999 $href_params{'action'} = $type;
4000 $link_attr{'-href'} = href(%href_params);
4001 print "<link ".
4002 "rel=\"$link_attr{'-rel'}\" ".
4003 "title=\"$link_attr{'-title'}\" ".
4004 "href=\"$link_attr{'-href'}\" ".
4005 "type=\"$link_attr{'-type'}\" ".
4006 "/>\n";
4008 $href_params{'extra_options'} = '--no-merges';
4009 $link_attr{'-href'} = href(%href_params);
4010 $link_attr{'-title'} .= ' (no merges)';
4011 print "<link ".
4012 "rel=\"$link_attr{'-rel'}\" ".
4013 "title=\"$link_attr{'-title'}\" ".
4014 "href=\"$link_attr{'-href'}\" ".
4015 "type=\"$link_attr{'-type'}\" ".
4016 "/>\n";
4019 } else {
4020 printf('<link rel="alternate" title="%s projects list" '.
4021 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4022 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4023 printf('<link rel="alternate" title="%s projects feeds" '.
4024 'href="%s" type="text/x-opml" />'."\n",
4025 esc_attr($site_name), href(project=>undef, action=>"opml"));
4029 sub print_header_links {
4030 my $status = shift;
4032 # print out each stylesheet that exist, providing backwards capability
4033 # for those people who defined $stylesheet in a config file
4034 if (defined $stylesheet) {
4035 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4036 } else {
4037 foreach my $stylesheet (@stylesheets) {
4038 next unless $stylesheet;
4039 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4042 print_feed_meta()
4043 if ($status eq '200 OK');
4044 if (defined $favicon) {
4045 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4049 sub print_nav_breadcrumbs_path {
4050 my $dirprefix = undef;
4051 while (my $part = shift) {
4052 $dirprefix .= "/" if defined $dirprefix;
4053 $dirprefix .= $part;
4054 print $cgi->a({-href => href(project => undef,
4055 project_filter => $dirprefix,
4056 action => "project_list")},
4057 esc_html($part)) . " / ";
4061 sub print_nav_breadcrumbs {
4062 my %opts = @_;
4064 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4065 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4067 if (defined $project) {
4068 my @dirname = split '/', $project;
4069 my $projectbasename = pop @dirname;
4070 print_nav_breadcrumbs_path(@dirname);
4071 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4072 if (defined $action) {
4073 my $action_print = $action ;
4074 if (defined $opts{-action_extra}) {
4075 $action_print = $cgi->a({-href => href(action=>$action)},
4076 $action);
4078 print " / $action_print";
4080 if (defined $opts{-action_extra}) {
4081 print " / $opts{-action_extra}";
4083 print "\n";
4084 } elsif (defined $project_filter) {
4085 print_nav_breadcrumbs_path(split '/', $project_filter);
4089 sub print_search_form {
4090 if (!defined $searchtext) {
4091 $searchtext = "";
4093 my $search_hash;
4094 if (defined $hash_base) {
4095 $search_hash = $hash_base;
4096 } elsif (defined $hash) {
4097 $search_hash = $hash;
4098 } else {
4099 $search_hash = "HEAD";
4101 my $action = $my_uri;
4102 my $use_pathinfo = gitweb_check_feature('pathinfo');
4103 if ($use_pathinfo) {
4104 $action .= "/".esc_url($project);
4106 print $cgi->start_form(-method => "get", -action => $action) .
4107 "<div class=\"search\">\n" .
4108 (!$use_pathinfo &&
4109 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4110 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4111 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4112 $cgi->popup_menu(-name => 'st', -default => 'commit',
4113 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4114 " " . $cgi->a({-href => href(action=>"search_help"),
4115 -title => "search help" }, "?") . " search:\n",
4116 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4117 "<span title=\"Extended regular expression\">" .
4118 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4119 -checked => $search_use_regexp) .
4120 "</span>" .
4121 "</div>" .
4122 $cgi->end_form() . "\n";
4125 sub git_header_html {
4126 my $status = shift || "200 OK";
4127 my $expires = shift;
4128 my %opts = @_;
4130 my $title = get_page_title();
4131 my $content_type = get_content_type_html();
4132 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4133 -status=> $status, -expires => $expires)
4134 unless ($opts{'-no_http_header'});
4135 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4136 print <<EOF;
4137 <?xml version="1.0" encoding="utf-8"?>
4138 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4139 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4140 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4141 <!-- git core binaries version $git_version -->
4142 <head>
4143 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4144 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4145 <meta name="robots" content="index, nofollow"/>
4146 <title>$title</title>
4148 # the stylesheet, favicon etc urls won't work correctly with path_info
4149 # unless we set the appropriate base URL
4150 if ($ENV{'PATH_INFO'}) {
4151 print "<base href=\"".esc_url($base_url)."\" />\n";
4153 print_header_links($status);
4155 if (defined $site_html_head_string) {
4156 print to_utf8($site_html_head_string);
4159 print "</head>\n" .
4160 "<body>\n";
4162 if (defined $site_header && -f $site_header) {
4163 insert_file($site_header);
4166 print "<div class=\"page_header\">\n";
4167 if (defined $logo) {
4168 print $cgi->a({-href => esc_url($logo_url),
4169 -title => $logo_label},
4170 $cgi->img({-src => esc_url($logo),
4171 -width => 72, -height => 27,
4172 -alt => "git",
4173 -class => "logo"}));
4175 print_nav_breadcrumbs(%opts);
4176 print "</div>\n";
4178 my $have_search = gitweb_check_feature('search');
4179 if (defined $project && $have_search) {
4180 print_search_form();
4184 sub git_footer_html {
4185 my $feed_class = 'rss_logo';
4187 print "<div class=\"page_footer\">\n";
4188 if (defined $project) {
4189 my $descr = git_get_project_description($project);
4190 if (defined $descr) {
4191 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4194 my %href_params = get_feed_info();
4195 if (!%href_params) {
4196 $feed_class .= ' generic';
4198 $href_params{'-title'} ||= 'log';
4200 foreach my $format (qw(RSS Atom)) {
4201 $href_params{'action'} = lc($format);
4202 print $cgi->a({-href => href(%href_params),
4203 -title => "$href_params{'-title'} $format feed",
4204 -class => $feed_class}, $format)."\n";
4207 } else {
4208 print $cgi->a({-href => href(project=>undef, action=>"opml",
4209 project_filter => $project_filter),
4210 -class => $feed_class}, "OPML") . " ";
4211 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4212 project_filter => $project_filter),
4213 -class => $feed_class}, "TXT") . "\n";
4215 print "</div>\n"; # class="page_footer"
4217 if (defined $t0 && gitweb_check_feature('timed')) {
4218 print "<div id=\"generating_info\">\n";
4219 print 'This page took '.
4220 '<span id="generating_time" class="time_span">'.
4221 tv_interval($t0, [ gettimeofday() ]).
4222 ' seconds </span>'.
4223 ' and '.
4224 '<span id="generating_cmd">'.
4225 $number_of_git_cmds.
4226 '</span> git commands '.
4227 " to generate.\n";
4228 print "</div>\n"; # class="page_footer"
4231 if (defined $site_footer && -f $site_footer) {
4232 insert_file($site_footer);
4235 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4236 if (defined $action &&
4237 $action eq 'blame_incremental') {
4238 print qq!<script type="text/javascript">\n!.
4239 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4240 qq! "!. href() .qq!");\n!.
4241 qq!</script>\n!;
4242 } else {
4243 my ($jstimezone, $tz_cookie, $datetime_class) =
4244 gitweb_get_feature('javascript-timezone');
4246 print qq!<script type="text/javascript">\n!.
4247 qq!window.onload = function () {\n!;
4248 if (gitweb_check_feature('javascript-actions')) {
4249 print qq! fixLinks();\n!;
4251 if ($jstimezone && $tz_cookie && $datetime_class) {
4252 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4253 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4255 print qq!};\n!.
4256 qq!</script>\n!;
4259 print "</body>\n" .
4260 "</html>";
4263 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4264 # Example: die_error(404, 'Hash not found')
4265 # By convention, use the following status codes (as defined in RFC 2616):
4266 # 400: Invalid or missing CGI parameters, or
4267 # requested object exists but has wrong type.
4268 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4269 # this server or project.
4270 # 404: Requested object/revision/project doesn't exist.
4271 # 500: The server isn't configured properly, or
4272 # an internal error occurred (e.g. failed assertions caused by bugs), or
4273 # an unknown error occurred (e.g. the git binary died unexpectedly).
4274 # 503: The server is currently unavailable (because it is overloaded,
4275 # or down for maintenance). Generally, this is a temporary state.
4276 sub die_error {
4277 my $status = shift || 500;
4278 my $error = esc_html(shift) || "Internal Server Error";
4279 my $extra = shift;
4280 my %opts = @_;
4282 my %http_responses = (
4283 400 => '400 Bad Request',
4284 403 => '403 Forbidden',
4285 404 => '404 Not Found',
4286 500 => '500 Internal Server Error',
4287 503 => '503 Service Unavailable',
4289 git_header_html($http_responses{$status}, undef, %opts);
4290 print <<EOF;
4291 <div class="page_body">
4292 <br /><br />
4293 $status - $error
4294 <br />
4296 if (defined $extra) {
4297 print "<hr />\n" .
4298 "$extra\n";
4300 print "</div>\n";
4302 git_footer_html();
4303 CORE::die
4304 unless ($opts{'-error_handler'});
4307 ## ----------------------------------------------------------------------
4308 ## functions printing or outputting HTML: navigation
4310 sub git_print_page_nav {
4311 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4312 $extra = '' if !defined $extra; # pager or formats
4314 my @navs = qw(summary shortlog log commit commitdiff tree);
4315 if ($suppress) {
4316 @navs = grep { $_ ne $suppress } @navs;
4319 my %arg = map { $_ => {action=>$_} } @navs;
4320 if (defined $head) {
4321 for (qw(commit commitdiff)) {
4322 $arg{$_}{'hash'} = $head;
4324 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4325 for (qw(shortlog log)) {
4326 $arg{$_}{'hash'} = $head;
4331 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4332 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4334 my @actions = gitweb_get_feature('actions');
4335 my %repl = (
4336 '%' => '%',
4337 'n' => $project, # project name
4338 'f' => $git_dir, # project path within filesystem
4339 'h' => $treehead || '', # current hash ('h' parameter)
4340 'b' => $treebase || '', # hash base ('hb' parameter)
4342 while (@actions) {
4343 my ($label, $link, $pos) = splice(@actions,0,3);
4344 # insert
4345 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4346 # munch munch
4347 $link =~ s/%([%nfhb])/$repl{$1}/g;
4348 $arg{$label}{'_href'} = $link;
4351 print "<div class=\"page_nav\">\n" .
4352 (join " | ",
4353 map { $_ eq $current ?
4354 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4355 } @navs);
4356 print "<br/>\n$extra<br/>\n" .
4357 "</div>\n";
4360 # returns a submenu for the nagivation of the refs views (tags, heads,
4361 # remotes) with the current view disabled and the remotes view only
4362 # available if the feature is enabled
4363 sub format_ref_views {
4364 my ($current) = @_;
4365 my @ref_views = qw{tags heads};
4366 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4367 return join " | ", map {
4368 $_ eq $current ? $_ :
4369 $cgi->a({-href => href(action=>$_)}, $_)
4370 } @ref_views
4373 sub format_paging_nav {
4374 my ($action, $page, $has_next_link) = @_;
4375 my $paging_nav;
4378 if ($page > 0) {
4379 $paging_nav .=
4380 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4381 " &sdot; " .
4382 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4383 -accesskey => "p", -title => "Alt-p"}, "prev");
4384 } else {
4385 $paging_nav .= "first &sdot; prev";
4388 if ($has_next_link) {
4389 $paging_nav .= " &sdot; " .
4390 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4391 -accesskey => "n", -title => "Alt-n"}, "next");
4392 } else {
4393 $paging_nav .= " &sdot; next";
4396 return $paging_nav;
4399 ## ......................................................................
4400 ## functions printing or outputting HTML: div
4402 sub git_print_header_div {
4403 my ($action, $title, $hash, $hash_base) = @_;
4404 my %args = ();
4406 $args{'action'} = $action;
4407 $args{'hash'} = $hash if $hash;
4408 $args{'hash_base'} = $hash_base if $hash_base;
4410 print "<div class=\"header\">\n" .
4411 $cgi->a({-href => href(%args), -class => "title"},
4412 $title ? $title : $action) .
4413 "\n</div>\n";
4416 sub format_repo_url {
4417 my ($name, $url) = @_;
4418 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4421 # Group output by placing it in a DIV element and adding a header.
4422 # Options for start_div() can be provided by passing a hash reference as the
4423 # first parameter to the function.
4424 # Options to git_print_header_div() can be provided by passing an array
4425 # reference. This must follow the options to start_div if they are present.
4426 # The content can be a scalar, which is output as-is, a scalar reference, which
4427 # is output after html escaping, an IO handle passed either as *handle or
4428 # *handle{IO}, or a function reference. In the latter case all following
4429 # parameters will be taken as argument to the content function call.
4430 sub git_print_section {
4431 my ($div_args, $header_args, $content);
4432 my $arg = shift;
4433 if (ref($arg) eq 'HASH') {
4434 $div_args = $arg;
4435 $arg = shift;
4437 if (ref($arg) eq 'ARRAY') {
4438 $header_args = $arg;
4439 $arg = shift;
4441 $content = $arg;
4443 print $cgi->start_div($div_args);
4444 git_print_header_div(@$header_args);
4446 if (ref($content) eq 'CODE') {
4447 $content->(@_);
4448 } elsif (ref($content) eq 'SCALAR') {
4449 print esc_html($$content);
4450 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4451 print <$content>;
4452 } elsif (!ref($content) && defined($content)) {
4453 print $content;
4456 print $cgi->end_div;
4459 sub format_timestamp_html {
4460 my $date = shift;
4461 my $strtime = $date->{'rfc2822'};
4463 my (undef, undef, $datetime_class) =
4464 gitweb_get_feature('javascript-timezone');
4465 if ($datetime_class) {
4466 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4469 my $localtime_format = '(%02d:%02d %s)';
4470 if ($date->{'hour_local'} < 6) {
4471 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4473 $strtime .= ' ' .
4474 sprintf($localtime_format,
4475 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4477 return $strtime;
4480 # Outputs the author name and date in long form
4481 sub git_print_authorship {
4482 my $co = shift;
4483 my %opts = @_;
4484 my $tag = $opts{-tag} || 'div';
4485 my $author = $co->{'author_name'};
4487 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4488 print "<$tag class=\"author_date\">" .
4489 format_search_author($author, "author", esc_html($author)) .
4490 " [".format_timestamp_html(\%ad)."]".
4491 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4492 "</$tag>\n";
4495 # Outputs table rows containing the full author or committer information,
4496 # in the format expected for 'commit' view (& similar).
4497 # Parameters are a commit hash reference, followed by the list of people
4498 # to output information for. If the list is empty it defaults to both
4499 # author and committer.
4500 sub git_print_authorship_rows {
4501 my $co = shift;
4502 # too bad we can't use @people = @_ || ('author', 'committer')
4503 my @people = @_;
4504 @people = ('author', 'committer') unless @people;
4505 foreach my $who (@people) {
4506 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4507 print "<tr><td>$who</td><td>" .
4508 format_search_author($co->{"${who}_name"}, $who,
4509 esc_html($co->{"${who}_name"})) . " " .
4510 format_search_author($co->{"${who}_email"}, $who,
4511 esc_html("<" . $co->{"${who}_email"} . ">")) .
4512 "</td><td rowspan=\"2\">" .
4513 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4514 "</td></tr>\n" .
4515 "<tr>" .
4516 "<td></td><td>" .
4517 format_timestamp_html(\%wd) .
4518 "</td>" .
4519 "</tr>\n";
4523 sub git_print_page_path {
4524 my $name = shift;
4525 my $type = shift;
4526 my $hb = shift;
4529 print "<div class=\"page_path\">";
4530 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4531 -title => 'tree root'}, to_utf8("[$project]"));
4532 print " / ";
4533 if (defined $name) {
4534 my @dirname = split '/', $name;
4535 my $basename = pop @dirname;
4536 my $fullname = '';
4538 foreach my $dir (@dirname) {
4539 $fullname .= ($fullname ? '/' : '') . $dir;
4540 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4541 hash_base=>$hb),
4542 -title => $fullname}, esc_path($dir));
4543 print " / ";
4545 if (defined $type && $type eq 'blob') {
4546 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4547 hash_base=>$hb),
4548 -title => $name}, esc_path($basename));
4549 } elsif (defined $type && $type eq 'tree') {
4550 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4551 hash_base=>$hb),
4552 -title => $name}, esc_path($basename));
4553 print " / ";
4554 } else {
4555 print esc_path($basename);
4558 print "<br/></div>\n";
4561 sub git_print_log {
4562 my $log = shift;
4563 my %opts = @_;
4565 if ($opts{'-remove_title'}) {
4566 # remove title, i.e. first line of log
4567 shift @$log;
4569 # remove leading empty lines
4570 while (defined $log->[0] && $log->[0] eq "") {
4571 shift @$log;
4574 # print log
4575 my $skip_blank_line = 0;
4576 foreach my $line (@$log) {
4577 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4578 if (! $opts{'-remove_signoff'}) {
4579 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4580 $skip_blank_line = 1;
4582 next;
4585 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4586 if (! $opts{'-remove_signoff'}) {
4587 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4588 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4589 "</span><br/>\n";
4590 $skip_blank_line = 1;
4592 next;
4595 # print only one empty line
4596 # do not print empty line after signoff
4597 if ($line eq "") {
4598 next if ($skip_blank_line);
4599 $skip_blank_line = 1;
4600 } else {
4601 $skip_blank_line = 0;
4604 print format_log_line_html($line) . "<br/>\n";
4607 if ($opts{'-final_empty_line'}) {
4608 # end with single empty line
4609 print "<br/>\n" unless $skip_blank_line;
4613 # return link target (what link points to)
4614 sub git_get_link_target {
4615 my $hash = shift;
4616 my $link_target;
4618 # read link
4619 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4620 or return;
4622 local $/ = undef;
4623 $link_target = <$fd>;
4625 close $fd
4626 or return;
4628 return $link_target;
4631 # given link target, and the directory (basedir) the link is in,
4632 # return target of link relative to top directory (top tree);
4633 # return undef if it is not possible (including absolute links).
4634 sub normalize_link_target {
4635 my ($link_target, $basedir) = @_;
4637 # absolute symlinks (beginning with '/') cannot be normalized
4638 return if (substr($link_target, 0, 1) eq '/');
4640 # normalize link target to path from top (root) tree (dir)
4641 my $path;
4642 if ($basedir) {
4643 $path = $basedir . '/' . $link_target;
4644 } else {
4645 # we are in top (root) tree (dir)
4646 $path = $link_target;
4649 # remove //, /./, and /../
4650 my @path_parts;
4651 foreach my $part (split('/', $path)) {
4652 # discard '.' and ''
4653 next if (!$part || $part eq '.');
4654 # handle '..'
4655 if ($part eq '..') {
4656 if (@path_parts) {
4657 pop @path_parts;
4658 } else {
4659 # link leads outside repository (outside top dir)
4660 return;
4662 } else {
4663 push @path_parts, $part;
4666 $path = join('/', @path_parts);
4668 return $path;
4671 # print tree entry (row of git_tree), but without encompassing <tr> element
4672 sub git_print_tree_entry {
4673 my ($t, $basedir, $hash_base, $have_blame) = @_;
4675 my %base_key = ();
4676 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4678 # The format of a table row is: mode list link. Where mode is
4679 # the mode of the entry, list is the name of the entry, an href,
4680 # and link is the action links of the entry.
4682 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4683 if (exists $t->{'size'}) {
4684 print "<td class=\"size\">$t->{'size'}</td>\n";
4686 if ($t->{'type'} eq "blob") {
4687 print "<td class=\"list\">" .
4688 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4689 file_name=>"$basedir$t->{'name'}", %base_key),
4690 -class => "list"}, esc_path($t->{'name'}));
4691 if (S_ISLNK(oct $t->{'mode'})) {
4692 my $link_target = git_get_link_target($t->{'hash'});
4693 if ($link_target) {
4694 my $norm_target = normalize_link_target($link_target, $basedir);
4695 if (defined $norm_target) {
4696 print " -> " .
4697 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4698 file_name=>$norm_target),
4699 -title => $norm_target}, esc_path($link_target));
4700 } else {
4701 print " -> " . esc_path($link_target);
4705 print "</td>\n";
4706 print "<td class=\"link\">";
4707 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4708 file_name=>"$basedir$t->{'name'}", %base_key)},
4709 "blob");
4710 if ($have_blame) {
4711 print " | " .
4712 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4713 file_name=>"$basedir$t->{'name'}", %base_key)},
4714 "blame");
4716 if (defined $hash_base) {
4717 print " | " .
4718 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4719 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4720 "history");
4722 print " | " .
4723 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4724 file_name=>"$basedir$t->{'name'}")},
4725 "raw");
4726 print "</td>\n";
4728 } elsif ($t->{'type'} eq "tree") {
4729 print "<td class=\"list\">";
4730 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4731 file_name=>"$basedir$t->{'name'}",
4732 %base_key)},
4733 esc_path($t->{'name'}));
4734 print "</td>\n";
4735 print "<td class=\"link\">";
4736 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4737 file_name=>"$basedir$t->{'name'}",
4738 %base_key)},
4739 "tree");
4740 if (defined $hash_base) {
4741 print " | " .
4742 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4743 file_name=>"$basedir$t->{'name'}")},
4744 "history");
4746 print "</td>\n";
4747 } else {
4748 # unknown object: we can only present history for it
4749 # (this includes 'commit' object, i.e. submodule support)
4750 print "<td class=\"list\">" .
4751 esc_path($t->{'name'}) .
4752 "</td>\n";
4753 print "<td class=\"link\">";
4754 if (defined $hash_base) {
4755 print $cgi->a({-href => href(action=>"history",
4756 hash_base=>$hash_base,
4757 file_name=>"$basedir$t->{'name'}")},
4758 "history");
4760 print "</td>\n";
4764 ## ......................................................................
4765 ## functions printing large fragments of HTML
4767 # get pre-image filenames for merge (combined) diff
4768 sub fill_from_file_info {
4769 my ($diff, @parents) = @_;
4771 $diff->{'from_file'} = [ ];
4772 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4773 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4774 if ($diff->{'status'}[$i] eq 'R' ||
4775 $diff->{'status'}[$i] eq 'C') {
4776 $diff->{'from_file'}[$i] =
4777 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4781 return $diff;
4784 # is current raw difftree line of file deletion
4785 sub is_deleted {
4786 my $diffinfo = shift;
4788 return $diffinfo->{'to_id'} eq ('0' x 40);
4791 # does patch correspond to [previous] difftree raw line
4792 # $diffinfo - hashref of parsed raw diff format
4793 # $patchinfo - hashref of parsed patch diff format
4794 # (the same keys as in $diffinfo)
4795 sub is_patch_split {
4796 my ($diffinfo, $patchinfo) = @_;
4798 return defined $diffinfo && defined $patchinfo
4799 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4803 sub git_difftree_body {
4804 my ($difftree, $hash, @parents) = @_;
4805 my ($parent) = $parents[0];
4806 my $have_blame = gitweb_check_feature('blame');
4807 print "<div class=\"list_head\">\n";
4808 if ($#{$difftree} > 10) {
4809 print(($#{$difftree} + 1) . " files changed:\n");
4811 print "</div>\n";
4813 print "<table class=\"" .
4814 (@parents > 1 ? "combined " : "") .
4815 "diff_tree\">\n";
4817 # header only for combined diff in 'commitdiff' view
4818 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4819 if ($has_header) {
4820 # table header
4821 print "<thead><tr>\n" .
4822 "<th></th><th></th>\n"; # filename, patchN link
4823 for (my $i = 0; $i < @parents; $i++) {
4824 my $par = $parents[$i];
4825 print "<th>" .
4826 $cgi->a({-href => href(action=>"commitdiff",
4827 hash=>$hash, hash_parent=>$par),
4828 -title => 'commitdiff to parent number ' .
4829 ($i+1) . ': ' . substr($par,0,7)},
4830 $i+1) .
4831 "&nbsp;</th>\n";
4833 print "</tr></thead>\n<tbody>\n";
4836 my $alternate = 1;
4837 my $patchno = 0;
4838 foreach my $line (@{$difftree}) {
4839 my $diff = parsed_difftree_line($line);
4841 if ($alternate) {
4842 print "<tr class=\"dark\">\n";
4843 } else {
4844 print "<tr class=\"light\">\n";
4846 $alternate ^= 1;
4848 if (exists $diff->{'nparents'}) { # combined diff
4850 fill_from_file_info($diff, @parents)
4851 unless exists $diff->{'from_file'};
4853 if (!is_deleted($diff)) {
4854 # file exists in the result (child) commit
4855 print "<td>" .
4856 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4857 file_name=>$diff->{'to_file'},
4858 hash_base=>$hash),
4859 -class => "list"}, esc_path($diff->{'to_file'})) .
4860 "</td>\n";
4861 } else {
4862 print "<td>" .
4863 esc_path($diff->{'to_file'}) .
4864 "</td>\n";
4867 if ($action eq 'commitdiff') {
4868 # link to patch
4869 $patchno++;
4870 print "<td class=\"link\">" .
4871 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4872 "patch") .
4873 " | " .
4874 "</td>\n";
4877 my $has_history = 0;
4878 my $not_deleted = 0;
4879 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4880 my $hash_parent = $parents[$i];
4881 my $from_hash = $diff->{'from_id'}[$i];
4882 my $from_path = $diff->{'from_file'}[$i];
4883 my $status = $diff->{'status'}[$i];
4885 $has_history ||= ($status ne 'A');
4886 $not_deleted ||= ($status ne 'D');
4888 if ($status eq 'A') {
4889 print "<td class=\"link\" align=\"right\"> | </td>\n";
4890 } elsif ($status eq 'D') {
4891 print "<td class=\"link\">" .
4892 $cgi->a({-href => href(action=>"blob",
4893 hash_base=>$hash,
4894 hash=>$from_hash,
4895 file_name=>$from_path)},
4896 "blob" . ($i+1)) .
4897 " | </td>\n";
4898 } else {
4899 if ($diff->{'to_id'} eq $from_hash) {
4900 print "<td class=\"link nochange\">";
4901 } else {
4902 print "<td class=\"link\">";
4904 print $cgi->a({-href => href(action=>"blobdiff",
4905 hash=>$diff->{'to_id'},
4906 hash_parent=>$from_hash,
4907 hash_base=>$hash,
4908 hash_parent_base=>$hash_parent,
4909 file_name=>$diff->{'to_file'},
4910 file_parent=>$from_path)},
4911 "diff" . ($i+1)) .
4912 " | </td>\n";
4916 print "<td class=\"link\">";
4917 if ($not_deleted) {
4918 print $cgi->a({-href => href(action=>"blob",
4919 hash=>$diff->{'to_id'},
4920 file_name=>$diff->{'to_file'},
4921 hash_base=>$hash)},
4922 "blob");
4923 print " | " if ($has_history);
4925 if ($has_history) {
4926 print $cgi->a({-href => href(action=>"history",
4927 file_name=>$diff->{'to_file'},
4928 hash_base=>$hash)},
4929 "history");
4931 print "</td>\n";
4933 print "</tr>\n";
4934 next; # instead of 'else' clause, to avoid extra indent
4936 # else ordinary diff
4938 my ($to_mode_oct, $to_mode_str, $to_file_type);
4939 my ($from_mode_oct, $from_mode_str, $from_file_type);
4940 if ($diff->{'to_mode'} ne ('0' x 6)) {
4941 $to_mode_oct = oct $diff->{'to_mode'};
4942 if (S_ISREG($to_mode_oct)) { # only for regular file
4943 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4945 $to_file_type = file_type($diff->{'to_mode'});
4947 if ($diff->{'from_mode'} ne ('0' x 6)) {
4948 $from_mode_oct = oct $diff->{'from_mode'};
4949 if (S_ISREG($from_mode_oct)) { # only for regular file
4950 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4952 $from_file_type = file_type($diff->{'from_mode'});
4955 if ($diff->{'status'} eq "A") { # created
4956 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4957 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4958 $mode_chng .= "]</span>";
4959 print "<td>";
4960 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4961 hash_base=>$hash, file_name=>$diff->{'file'}),
4962 -class => "list"}, esc_path($diff->{'file'}));
4963 print "</td>\n";
4964 print "<td>$mode_chng</td>\n";
4965 print "<td class=\"link\">";
4966 if ($action eq 'commitdiff') {
4967 # link to patch
4968 $patchno++;
4969 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4970 "patch") .
4971 " | ";
4973 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4974 hash_base=>$hash, file_name=>$diff->{'file'})},
4975 "blob");
4976 print "</td>\n";
4978 } elsif ($diff->{'status'} eq "D") { # deleted
4979 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4980 print "<td>";
4981 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4982 hash_base=>$parent, file_name=>$diff->{'file'}),
4983 -class => "list"}, esc_path($diff->{'file'}));
4984 print "</td>\n";
4985 print "<td>$mode_chng</td>\n";
4986 print "<td class=\"link\">";
4987 if ($action eq 'commitdiff') {
4988 # link to patch
4989 $patchno++;
4990 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4991 "patch") .
4992 " | ";
4994 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4995 hash_base=>$parent, file_name=>$diff->{'file'})},
4996 "blob") . " | ";
4997 if ($have_blame) {
4998 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4999 file_name=>$diff->{'file'})},
5000 "blame") . " | ";
5002 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5003 file_name=>$diff->{'file'})},
5004 "history");
5005 print "</td>\n";
5007 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5008 my $mode_chnge = "";
5009 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5010 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5011 if ($from_file_type ne $to_file_type) {
5012 $mode_chnge .= " from $from_file_type to $to_file_type";
5014 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5015 if ($from_mode_str && $to_mode_str) {
5016 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5017 } elsif ($to_mode_str) {
5018 $mode_chnge .= " mode: $to_mode_str";
5021 $mode_chnge .= "]</span>\n";
5023 print "<td>";
5024 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5025 hash_base=>$hash, file_name=>$diff->{'file'}),
5026 -class => "list"}, esc_path($diff->{'file'}));
5027 print "</td>\n";
5028 print "<td>$mode_chnge</td>\n";
5029 print "<td class=\"link\">";
5030 if ($action eq 'commitdiff') {
5031 # link to patch
5032 $patchno++;
5033 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5034 "patch") .
5035 " | ";
5036 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5037 # "commit" view and modified file (not onlu mode changed)
5038 print $cgi->a({-href => href(action=>"blobdiff",
5039 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5040 hash_base=>$hash, hash_parent_base=>$parent,
5041 file_name=>$diff->{'file'})},
5042 "diff") .
5043 " | ";
5045 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5046 hash_base=>$hash, file_name=>$diff->{'file'})},
5047 "blob") . " | ";
5048 if ($have_blame) {
5049 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5050 file_name=>$diff->{'file'})},
5051 "blame") . " | ";
5053 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5054 file_name=>$diff->{'file'})},
5055 "history");
5056 print "</td>\n";
5058 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5059 my %status_name = ('R' => 'moved', 'C' => 'copied');
5060 my $nstatus = $status_name{$diff->{'status'}};
5061 my $mode_chng = "";
5062 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5063 # mode also for directories, so we cannot use $to_mode_str
5064 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5066 print "<td>" .
5067 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5068 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5069 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5070 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5071 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5072 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5073 -class => "list"}, esc_path($diff->{'from_file'})) .
5074 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5075 "<td class=\"link\">";
5076 if ($action eq 'commitdiff') {
5077 # link to patch
5078 $patchno++;
5079 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5080 "patch") .
5081 " | ";
5082 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5083 # "commit" view and modified file (not only pure rename or copy)
5084 print $cgi->a({-href => href(action=>"blobdiff",
5085 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5086 hash_base=>$hash, hash_parent_base=>$parent,
5087 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5088 "diff") .
5089 " | ";
5091 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5092 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5093 "blob") . " | ";
5094 if ($have_blame) {
5095 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5096 file_name=>$diff->{'to_file'})},
5097 "blame") . " | ";
5099 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5100 file_name=>$diff->{'to_file'})},
5101 "history");
5102 print "</td>\n";
5104 } # we should not encounter Unmerged (U) or Unknown (X) status
5105 print "</tr>\n";
5107 print "</tbody>" if $has_header;
5108 print "</table>\n";
5111 # Print context lines and then rem/add lines in a side-by-side manner.
5112 sub print_sidebyside_diff_lines {
5113 my ($ctx, $rem, $add) = @_;
5115 # print context block before add/rem block
5116 if (@$ctx) {
5117 print join '',
5118 '<div class="chunk_block ctx">',
5119 '<div class="old">',
5120 @$ctx,
5121 '</div>',
5122 '<div class="new">',
5123 @$ctx,
5124 '</div>',
5125 '</div>';
5128 if (!@$add) {
5129 # pure removal
5130 print join '',
5131 '<div class="chunk_block rem">',
5132 '<div class="old">',
5133 @$rem,
5134 '</div>',
5135 '</div>';
5136 } elsif (!@$rem) {
5137 # pure addition
5138 print join '',
5139 '<div class="chunk_block add">',
5140 '<div class="new">',
5141 @$add,
5142 '</div>',
5143 '</div>';
5144 } else {
5145 print join '',
5146 '<div class="chunk_block chg">',
5147 '<div class="old">',
5148 @$rem,
5149 '</div>',
5150 '<div class="new">',
5151 @$add,
5152 '</div>',
5153 '</div>';
5157 # Print context lines and then rem/add lines in inline manner.
5158 sub print_inline_diff_lines {
5159 my ($ctx, $rem, $add) = @_;
5161 print @$ctx, @$rem, @$add;
5164 # Format removed and added line, mark changed part and HTML-format them.
5165 # Implementation is based on contrib/diff-highlight
5166 sub format_rem_add_lines_pair {
5167 my ($rem, $add, $num_parents) = @_;
5169 # We need to untabify lines before split()'ing them;
5170 # otherwise offsets would be invalid.
5171 chomp $rem;
5172 chomp $add;
5173 $rem = untabify($rem);
5174 $add = untabify($add);
5176 my @rem = split(//, $rem);
5177 my @add = split(//, $add);
5178 my ($esc_rem, $esc_add);
5179 # Ignore leading +/- characters for each parent.
5180 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5181 my ($prefix_has_nonspace, $suffix_has_nonspace);
5183 my $shorter = (@rem < @add) ? @rem : @add;
5184 while ($prefix_len < $shorter) {
5185 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5187 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5188 $prefix_len++;
5191 while ($prefix_len + $suffix_len < $shorter) {
5192 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5194 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5195 $suffix_len++;
5198 # Mark lines that are different from each other, but have some common
5199 # part that isn't whitespace. If lines are completely different, don't
5200 # mark them because that would make output unreadable, especially if
5201 # diff consists of multiple lines.
5202 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5203 $esc_rem = esc_html_hl_regions($rem, 'marked',
5204 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5205 $esc_add = esc_html_hl_regions($add, 'marked',
5206 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5207 } else {
5208 $esc_rem = esc_html($rem, -nbsp=>1);
5209 $esc_add = esc_html($add, -nbsp=>1);
5212 return format_diff_line(\$esc_rem, 'rem'),
5213 format_diff_line(\$esc_add, 'add');
5216 # HTML-format diff context, removed and added lines.
5217 sub format_ctx_rem_add_lines {
5218 my ($ctx, $rem, $add, $num_parents) = @_;
5219 my (@new_ctx, @new_rem, @new_add);
5220 my $can_highlight = 0;
5221 my $is_combined = ($num_parents > 1);
5223 # Highlight if every removed line has a corresponding added line.
5224 if (@$add > 0 && @$add == @$rem) {
5225 $can_highlight = 1;
5227 # Highlight lines in combined diff only if the chunk contains
5228 # diff between the same version, e.g.
5230 # - a
5231 # - b
5232 # + c
5233 # + d
5235 # Otherwise the highlightling would be confusing.
5236 if ($is_combined) {
5237 for (my $i = 0; $i < @$add; $i++) {
5238 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5239 my $prefix_add = substr($add->[$i], 0, $num_parents);
5241 $prefix_rem =~ s/-/+/g;
5243 if ($prefix_rem ne $prefix_add) {
5244 $can_highlight = 0;
5245 last;
5251 if ($can_highlight) {
5252 for (my $i = 0; $i < @$add; $i++) {
5253 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5254 $rem->[$i], $add->[$i], $num_parents);
5255 push @new_rem, $line_rem;
5256 push @new_add, $line_add;
5258 } else {
5259 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5260 @new_add = map { format_diff_line($_, 'add') } @$add;
5263 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5265 return (\@new_ctx, \@new_rem, \@new_add);
5268 # Print context lines and then rem/add lines.
5269 sub print_diff_lines {
5270 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5271 my $is_combined = $num_parents > 1;
5273 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5274 $num_parents);
5276 if ($diff_style eq 'sidebyside' && !$is_combined) {
5277 print_sidebyside_diff_lines($ctx, $rem, $add);
5278 } else {
5279 # default 'inline' style and unknown styles
5280 print_inline_diff_lines($ctx, $rem, $add);
5284 sub print_diff_chunk {
5285 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5286 my (@ctx, @rem, @add);
5288 # The class of the previous line.
5289 my $prev_class = '';
5291 return unless @chunk;
5293 # incomplete last line might be among removed or added lines,
5294 # or both, or among context lines: find which
5295 for (my $i = 1; $i < @chunk; $i++) {
5296 if ($chunk[$i][0] eq 'incomplete') {
5297 $chunk[$i][0] = $chunk[$i-1][0];
5301 # guardian
5302 push @chunk, ["", ""];
5304 foreach my $line_info (@chunk) {
5305 my ($class, $line) = @$line_info;
5307 # print chunk headers
5308 if ($class && $class eq 'chunk_header') {
5309 print format_diff_line($line, $class, $from, $to);
5310 next;
5313 ## print from accumulator when have some add/rem lines or end
5314 # of chunk (flush context lines), or when have add and rem
5315 # lines and new block is reached (otherwise add/rem lines could
5316 # be reordered)
5317 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5318 (@rem && @add && $class ne $prev_class)) {
5319 print_diff_lines(\@ctx, \@rem, \@add,
5320 $diff_style, $num_parents);
5321 @ctx = @rem = @add = ();
5324 ## adding lines to accumulator
5325 # guardian value
5326 last unless $line;
5327 # rem, add or change
5328 if ($class eq 'rem') {
5329 push @rem, $line;
5330 } elsif ($class eq 'add') {
5331 push @add, $line;
5333 # context line
5334 if ($class eq 'ctx') {
5335 push @ctx, $line;
5338 $prev_class = $class;
5342 sub git_patchset_body {
5343 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5344 my ($hash_parent) = $hash_parents[0];
5346 my $is_combined = (@hash_parents > 1);
5347 my $patch_idx = 0;
5348 my $patch_number = 0;
5349 my $patch_line;
5350 my $diffinfo;
5351 my $to_name;
5352 my (%from, %to);
5353 my @chunk; # for side-by-side diff
5355 print "<div class=\"patchset\">\n";
5357 # skip to first patch
5358 while ($patch_line = <$fd>) {
5359 chomp $patch_line;
5361 last if ($patch_line =~ m/^diff /);
5364 PATCH:
5365 while ($patch_line) {
5367 # parse "git diff" header line
5368 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5369 # $1 is from_name, which we do not use
5370 $to_name = unquote($2);
5371 $to_name =~ s!^b/!!;
5372 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5373 # $1 is 'cc' or 'combined', which we do not use
5374 $to_name = unquote($2);
5375 } else {
5376 $to_name = undef;
5379 # check if current patch belong to current raw line
5380 # and parse raw git-diff line if needed
5381 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5382 # this is continuation of a split patch
5383 print "<div class=\"patch cont\">\n";
5384 } else {
5385 # advance raw git-diff output if needed
5386 $patch_idx++ if defined $diffinfo;
5388 # read and prepare patch information
5389 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5391 # compact combined diff output can have some patches skipped
5392 # find which patch (using pathname of result) we are at now;
5393 if ($is_combined) {
5394 while ($to_name ne $diffinfo->{'to_file'}) {
5395 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5396 format_diff_cc_simplified($diffinfo, @hash_parents) .
5397 "</div>\n"; # class="patch"
5399 $patch_idx++;
5400 $patch_number++;
5402 last if $patch_idx > $#$difftree;
5403 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5407 # modifies %from, %to hashes
5408 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5410 # this is first patch for raw difftree line with $patch_idx index
5411 # we index @$difftree array from 0, but number patches from 1
5412 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5415 # git diff header
5416 #assert($patch_line =~ m/^diff /) if DEBUG;
5417 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5418 $patch_number++;
5419 # print "git diff" header
5420 print format_git_diff_header_line($patch_line, $diffinfo,
5421 \%from, \%to);
5423 # print extended diff header
5424 print "<div class=\"diff extended_header\">\n";
5425 EXTENDED_HEADER:
5426 while ($patch_line = <$fd>) {
5427 chomp $patch_line;
5429 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5431 print format_extended_diff_header_line($patch_line, $diffinfo,
5432 \%from, \%to);
5434 print "</div>\n"; # class="diff extended_header"
5436 # from-file/to-file diff header
5437 if (! $patch_line) {
5438 print "</div>\n"; # class="patch"
5439 last PATCH;
5441 next PATCH if ($patch_line =~ m/^diff /);
5442 #assert($patch_line =~ m/^---/) if DEBUG;
5444 my $last_patch_line = $patch_line;
5445 $patch_line = <$fd>;
5446 chomp $patch_line;
5447 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5449 print format_diff_from_to_header($last_patch_line, $patch_line,
5450 $diffinfo, \%from, \%to,
5451 @hash_parents);
5453 # the patch itself
5454 LINE:
5455 while ($patch_line = <$fd>) {
5456 chomp $patch_line;
5458 next PATCH if ($patch_line =~ m/^diff /);
5460 my $class = diff_line_class($patch_line, \%from, \%to);
5462 if ($class eq 'chunk_header') {
5463 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5464 @chunk = ();
5467 push @chunk, [ $class, $patch_line ];
5470 } continue {
5471 if (@chunk) {
5472 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5473 @chunk = ();
5475 print "</div>\n"; # class="patch"
5478 # for compact combined (--cc) format, with chunk and patch simplification
5479 # the patchset might be empty, but there might be unprocessed raw lines
5480 for (++$patch_idx if $patch_number > 0;
5481 $patch_idx < @$difftree;
5482 ++$patch_idx) {
5483 # read and prepare patch information
5484 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5486 # generate anchor for "patch" links in difftree / whatchanged part
5487 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5488 format_diff_cc_simplified($diffinfo, @hash_parents) .
5489 "</div>\n"; # class="patch"
5491 $patch_number++;
5494 if ($patch_number == 0) {
5495 if (@hash_parents > 1) {
5496 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5497 } else {
5498 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5502 print "</div>\n"; # class="patchset"
5505 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5507 sub git_project_search_form {
5508 my ($searchtext, $search_use_regexp) = @_;
5510 my $limit = '';
5511 if ($project_filter) {
5512 $limit = " in '$project_filter/'";
5515 print "<div class=\"projsearch\">\n";
5516 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5517 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5518 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5519 if (defined $project_filter);
5520 print $cgi->textfield(-name => 's', -value => $searchtext,
5521 -title => "Search project by name and description$limit",
5522 -size => 60) . "\n" .
5523 "<span title=\"Extended regular expression\">" .
5524 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5525 -checked => $search_use_regexp) .
5526 "</span>\n" .
5527 $cgi->submit(-name => 'btnS', -value => 'Search') .
5528 $cgi->end_form() . "\n" .
5529 $cgi->a({-href => href(project => undef, searchtext => undef,
5530 project_filter => $project_filter)},
5531 esc_html("List all projects$limit")) . "<br />\n";
5532 print "</div>\n";
5535 # entry for given @keys needs filling if at least one of keys in list
5536 # is not present in %$project_info
5537 sub project_info_needs_filling {
5538 my ($project_info, @keys) = @_;
5540 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5541 foreach my $key (@keys) {
5542 if (!exists $project_info->{$key}) {
5543 return 1;
5546 return;
5549 # fills project list info (age, description, owner, category, forks, etc.)
5550 # for each project in the list, removing invalid projects from
5551 # returned list, or fill only specified info.
5553 # Invalid projects are removed from the returned list if and only if you
5554 # ask 'age' or 'age_string' to be filled, because they are the only fields
5555 # that run unconditionally git command that requires repository, and
5556 # therefore do always check if project repository is invalid.
5558 # USAGE:
5559 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5560 # ensures that 'descr_long' and 'ctags' fields are filled
5561 # * @project_list = fill_project_list_info(\@project_list)
5562 # ensures that all fields are filled (and invalid projects removed)
5564 # NOTE: modifies $projlist, but does not remove entries from it
5565 sub fill_project_list_info {
5566 my ($projlist, @wanted_keys) = @_;
5567 my @projects;
5568 my $filter_set = sub { return @_; };
5569 if (@wanted_keys) {
5570 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5571 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5574 my $show_ctags = gitweb_check_feature('ctags');
5575 PROJECT:
5576 foreach my $pr (@$projlist) {
5577 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5578 my (@activity) = git_get_last_activity($pr->{'path'});
5579 unless (@activity) {
5580 next PROJECT;
5582 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5584 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5585 my $descr = git_get_project_description($pr->{'path'}) || "";
5586 $descr = to_utf8($descr);
5587 $pr->{'descr_long'} = $descr;
5588 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5590 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5591 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5593 if ($show_ctags &&
5594 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5595 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5597 if ($projects_list_group_categories &&
5598 project_info_needs_filling($pr, $filter_set->('category'))) {
5599 my $cat = git_get_project_category($pr->{'path'}) ||
5600 $project_list_default_category;
5601 $pr->{'category'} = to_utf8($cat);
5604 push @projects, $pr;
5607 return @projects;
5610 sub sort_projects_list {
5611 my ($projlist, $order) = @_;
5613 sub order_str {
5614 my $key = shift;
5615 return sub { $a->{$key} cmp $b->{$key} };
5618 sub order_num_then_undef {
5619 my $key = shift;
5620 return sub {
5621 defined $a->{$key} ?
5622 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5623 (defined $b->{$key} ? 1 : 0)
5627 my %orderings = (
5628 project => order_str('path'),
5629 descr => order_str('descr_long'),
5630 owner => order_str('owner'),
5631 age => order_num_then_undef('age'),
5634 my $ordering = $orderings{$order};
5635 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5638 # returns a hash of categories, containing the list of project
5639 # belonging to each category
5640 sub build_projlist_by_category {
5641 my ($projlist, $from, $to) = @_;
5642 my %categories;
5644 $from = 0 unless defined $from;
5645 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5647 for (my $i = $from; $i <= $to; $i++) {
5648 my $pr = $projlist->[$i];
5649 push @{$categories{ $pr->{'category'} }}, $pr;
5652 return wantarray ? %categories : \%categories;
5655 # print 'sort by' <th> element, generating 'sort by $name' replay link
5656 # if that order is not selected
5657 sub print_sort_th {
5658 print format_sort_th(@_);
5661 sub format_sort_th {
5662 my ($name, $order, $header) = @_;
5663 my $sort_th = "";
5664 $header ||= ucfirst($name);
5666 if ($order eq $name) {
5667 $sort_th .= "<th>$header</th>\n";
5668 } else {
5669 $sort_th .= "<th>" .
5670 $cgi->a({-href => href(-replay=>1, order=>$name),
5671 -class => "header"}, $header) .
5672 "</th>\n";
5675 return $sort_th;
5678 sub git_project_list_rows {
5679 my ($projlist, $from, $to, $check_forks) = @_;
5681 $from = 0 unless defined $from;
5682 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5684 my $alternate = 1;
5685 for (my $i = $from; $i <= $to; $i++) {
5686 my $pr = $projlist->[$i];
5688 if ($alternate) {
5689 print "<tr class=\"dark\">\n";
5690 } else {
5691 print "<tr class=\"light\">\n";
5693 $alternate ^= 1;
5695 if ($check_forks) {
5696 print "<td>";
5697 if ($pr->{'forks'}) {
5698 my $nforks = scalar @{$pr->{'forks'}};
5699 if ($nforks > 0) {
5700 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5701 -title => "$nforks forks"}, "+");
5702 } else {
5703 print $cgi->span({-title => "$nforks forks"}, "+");
5706 print "</td>\n";
5708 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5709 -class => "list"},
5710 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5711 "</td>\n" .
5712 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5713 -class => "list",
5714 -title => $pr->{'descr_long'}},
5715 $search_regexp
5716 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5717 $pr->{'descr'}, $search_regexp)
5718 : esc_html($pr->{'descr'})) .
5719 "</td>\n";
5720 unless ($omit_owner) {
5721 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5723 unless ($omit_age_column) {
5724 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5725 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5727 print"<td class=\"link\">" .
5728 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5729 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5730 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5731 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5732 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5733 "</td>\n" .
5734 "</tr>\n";
5738 sub git_project_list_body {
5739 # actually uses global variable $project
5740 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5741 my @projects = @$projlist;
5743 my $check_forks = gitweb_check_feature('forks');
5744 my $show_ctags = gitweb_check_feature('ctags');
5745 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5746 $check_forks = undef
5747 if ($tagfilter || $search_regexp);
5749 # filtering out forks before filling info allows to do less work
5750 @projects = filter_forks_from_projects_list(\@projects)
5751 if ($check_forks);
5752 # search_projects_list pre-fills required info
5753 @projects = search_projects_list(\@projects,
5754 'search_regexp' => $search_regexp,
5755 'tagfilter' => $tagfilter)
5756 if ($tagfilter || $search_regexp);
5757 # fill the rest
5758 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5759 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5760 push @all_fields, 'owner' unless($omit_owner);
5761 @projects = fill_project_list_info(\@projects, @all_fields);
5763 $order ||= $default_projects_order;
5764 $from = 0 unless defined $from;
5765 $to = $#projects if (!defined $to || $#projects < $to);
5767 # short circuit
5768 if ($from > $to) {
5769 print "<center>\n".
5770 "<b>No such projects found</b><br />\n".
5771 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5772 "</center>\n<br />\n";
5773 return;
5776 @projects = sort_projects_list(\@projects, $order);
5778 if ($show_ctags) {
5779 my $ctags = git_gather_all_ctags(\@projects);
5780 my $cloud = git_populate_project_tagcloud($ctags);
5781 print git_show_project_tagcloud($cloud, 64);
5784 print "<table class=\"project_list\">\n";
5785 unless ($no_header) {
5786 print "<tr>\n";
5787 if ($check_forks) {
5788 print "<th></th>\n";
5790 print_sort_th('project', $order, 'Project');
5791 print_sort_th('descr', $order, 'Description');
5792 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5793 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5794 print "<th></th>\n" . # for links
5795 "</tr>\n";
5798 if ($projects_list_group_categories) {
5799 # only display categories with projects in the $from-$to window
5800 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5801 my %categories = build_projlist_by_category(\@projects, $from, $to);
5802 foreach my $cat (sort keys %categories) {
5803 unless ($cat eq "") {
5804 print "<tr>\n";
5805 if ($check_forks) {
5806 print "<td></td>\n";
5808 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5809 print "</tr>\n";
5812 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5814 } else {
5815 git_project_list_rows(\@projects, $from, $to, $check_forks);
5818 if (defined $extra) {
5819 print "<tr>\n";
5820 if ($check_forks) {
5821 print "<td></td>\n";
5823 print "<td colspan=\"5\">$extra</td>\n" .
5824 "</tr>\n";
5826 print "</table>\n";
5829 sub git_log_body {
5830 # uses global variable $project
5831 my ($commitlist, $from, $to, $refs, $extra) = @_;
5833 $from = 0 unless defined $from;
5834 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5836 for (my $i = 0; $i <= $to; $i++) {
5837 my %co = %{$commitlist->[$i]};
5838 next if !%co;
5839 my $commit = $co{'id'};
5840 my $ref = format_ref_marker($refs, $commit);
5841 git_print_header_div('commit',
5842 "<span class=\"age\">$co{'age_string'}</span>" .
5843 esc_html($co{'title'}) . $ref,
5844 $commit);
5845 print "<div class=\"title_text\">\n" .
5846 "<div class=\"log_link\">\n" .
5847 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5848 " | " .
5849 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5850 " | " .
5851 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5852 "<br/>\n" .
5853 "</div>\n";
5854 git_print_authorship(\%co, -tag => 'span');
5855 print "<br/>\n</div>\n";
5857 print "<div class=\"log_body\">\n";
5858 git_print_log($co{'comment'}, -final_empty_line=> 1);
5859 print "</div>\n";
5861 if ($extra) {
5862 print "<div class=\"page_nav\">\n";
5863 print "$extra\n";
5864 print "</div>\n";
5868 sub git_shortlog_body {
5869 # uses global variable $project
5870 my ($commitlist, $from, $to, $refs, $extra) = @_;
5872 $from = 0 unless defined $from;
5873 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5875 print "<table class=\"shortlog\">\n";
5876 my $alternate = 1;
5877 for (my $i = $from; $i <= $to; $i++) {
5878 my %co = %{$commitlist->[$i]};
5879 my $commit = $co{'id'};
5880 my $ref = format_ref_marker($refs, $commit);
5881 if ($alternate) {
5882 print "<tr class=\"dark\">\n";
5883 } else {
5884 print "<tr class=\"light\">\n";
5886 $alternate ^= 1;
5887 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5888 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5889 format_author_html('td', \%co, 10) . "<td>";
5890 print format_subject_html($co{'title'}, $co{'title_short'},
5891 href(action=>"commit", hash=>$commit), $ref);
5892 print "</td>\n" .
5893 "<td class=\"link\">" .
5894 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5895 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5896 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5897 my $snapshot_links = format_snapshot_links($commit);
5898 if (defined $snapshot_links) {
5899 print " | " . $snapshot_links;
5901 print "</td>\n" .
5902 "</tr>\n";
5904 if (defined $extra) {
5905 print "<tr>\n" .
5906 "<td colspan=\"4\">$extra</td>\n" .
5907 "</tr>\n";
5909 print "</table>\n";
5912 sub git_history_body {
5913 # Warning: assumes constant type (blob or tree) during history
5914 my ($commitlist, $from, $to, $refs, $extra,
5915 $file_name, $file_hash, $ftype) = @_;
5917 $from = 0 unless defined $from;
5918 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5920 print "<table class=\"history\">\n";
5921 my $alternate = 1;
5922 for (my $i = $from; $i <= $to; $i++) {
5923 my %co = %{$commitlist->[$i]};
5924 if (!%co) {
5925 next;
5927 my $commit = $co{'id'};
5929 my $ref = format_ref_marker($refs, $commit);
5931 if ($alternate) {
5932 print "<tr class=\"dark\">\n";
5933 } else {
5934 print "<tr class=\"light\">\n";
5936 $alternate ^= 1;
5937 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5938 # shortlog: format_author_html('td', \%co, 10)
5939 format_author_html('td', \%co, 15, 3) . "<td>";
5940 # originally git_history used chop_str($co{'title'}, 50)
5941 print format_subject_html($co{'title'}, $co{'title_short'},
5942 href(action=>"commit", hash=>$commit), $ref);
5943 print "</td>\n" .
5944 "<td class=\"link\">" .
5945 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5946 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5948 if ($ftype eq 'blob') {
5949 my $blob_current = $file_hash;
5950 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5951 if (defined $blob_current && defined $blob_parent &&
5952 $blob_current ne $blob_parent) {
5953 print " | " .
5954 $cgi->a({-href => href(action=>"blobdiff",
5955 hash=>$blob_current, hash_parent=>$blob_parent,
5956 hash_base=>$hash_base, hash_parent_base=>$commit,
5957 file_name=>$file_name)},
5958 "diff to current");
5961 print "</td>\n" .
5962 "</tr>\n";
5964 if (defined $extra) {
5965 print "<tr>\n" .
5966 "<td colspan=\"4\">$extra</td>\n" .
5967 "</tr>\n";
5969 print "</table>\n";
5972 sub git_tags_body {
5973 # uses global variable $project
5974 my ($taglist, $from, $to, $extra) = @_;
5975 $from = 0 unless defined $from;
5976 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5978 print "<table class=\"tags\">\n";
5979 my $alternate = 1;
5980 for (my $i = $from; $i <= $to; $i++) {
5981 my $entry = $taglist->[$i];
5982 my %tag = %$entry;
5983 my $comment = $tag{'subject'};
5984 my $comment_short;
5985 if (defined $comment) {
5986 $comment_short = chop_str($comment, 30, 5);
5988 if ($alternate) {
5989 print "<tr class=\"dark\">\n";
5990 } else {
5991 print "<tr class=\"light\">\n";
5993 $alternate ^= 1;
5994 if (defined $tag{'age'}) {
5995 print "<td><i>$tag{'age'}</i></td>\n";
5996 } else {
5997 print "<td></td>\n";
5999 print "<td>" .
6000 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6001 -class => "list name"}, esc_html($tag{'name'})) .
6002 "</td>\n" .
6003 "<td>";
6004 if (defined $comment) {
6005 print format_subject_html($comment, $comment_short,
6006 href(action=>"tag", hash=>$tag{'id'}));
6008 print "</td>\n" .
6009 "<td class=\"selflink\">";
6010 if ($tag{'type'} eq "tag") {
6011 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6012 } else {
6013 print "&nbsp;";
6015 print "</td>\n" .
6016 "<td class=\"link\">" . " | " .
6017 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6018 if ($tag{'reftype'} eq "commit") {
6019 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6020 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6021 } elsif ($tag{'reftype'} eq "blob") {
6022 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6024 print "</td>\n" .
6025 "</tr>";
6027 if (defined $extra) {
6028 print "<tr>\n" .
6029 "<td colspan=\"5\">$extra</td>\n" .
6030 "</tr>\n";
6032 print "</table>\n";
6035 sub git_heads_body {
6036 # uses global variable $project
6037 my ($headlist, $head_at, $from, $to, $extra) = @_;
6038 $from = 0 unless defined $from;
6039 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6041 print "<table class=\"heads\">\n";
6042 my $alternate = 1;
6043 for (my $i = $from; $i <= $to; $i++) {
6044 my $entry = $headlist->[$i];
6045 my %ref = %$entry;
6046 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6047 if ($alternate) {
6048 print "<tr class=\"dark\">\n";
6049 } else {
6050 print "<tr class=\"light\">\n";
6052 $alternate ^= 1;
6053 print "<td><i>$ref{'age'}</i></td>\n" .
6054 ($curr ? "<td class=\"current_head\">" : "<td>") .
6055 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6056 -class => "list name"},esc_html($ref{'name'})) .
6057 "</td>\n" .
6058 "<td class=\"link\">" .
6059 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6060 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6061 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6062 "</td>\n" .
6063 "</tr>";
6065 if (defined $extra) {
6066 print "<tr>\n" .
6067 "<td colspan=\"3\">$extra</td>\n" .
6068 "</tr>\n";
6070 print "</table>\n";
6073 # Display a single remote block
6074 sub git_remote_block {
6075 my ($remote, $rdata, $limit, $head) = @_;
6077 my $heads = $rdata->{'heads'};
6078 my $fetch = $rdata->{'fetch'};
6079 my $push = $rdata->{'push'};
6081 my $urls_table = "<table class=\"projects_list\">\n" ;
6083 if (defined $fetch) {
6084 if ($fetch eq $push) {
6085 $urls_table .= format_repo_url("URL", $fetch);
6086 } else {
6087 $urls_table .= format_repo_url("Fetch URL", $fetch);
6088 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6090 } elsif (defined $push) {
6091 $urls_table .= format_repo_url("Push URL", $push);
6092 } else {
6093 $urls_table .= format_repo_url("", "No remote URL");
6096 $urls_table .= "</table>\n";
6098 my $dots;
6099 if (defined $limit && $limit < @$heads) {
6100 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6103 print $urls_table;
6104 git_heads_body($heads, $head, 0, $limit, $dots);
6107 # Display a list of remote names with the respective fetch and push URLs
6108 sub git_remotes_list {
6109 my ($remotedata, $limit) = @_;
6110 print "<table class=\"heads\">\n";
6111 my $alternate = 1;
6112 my @remotes = sort keys %$remotedata;
6114 my $limited = $limit && $limit < @remotes;
6116 $#remotes = $limit - 1 if $limited;
6118 while (my $remote = shift @remotes) {
6119 my $rdata = $remotedata->{$remote};
6120 my $fetch = $rdata->{'fetch'};
6121 my $push = $rdata->{'push'};
6122 if ($alternate) {
6123 print "<tr class=\"dark\">\n";
6124 } else {
6125 print "<tr class=\"light\">\n";
6127 $alternate ^= 1;
6128 print "<td>" .
6129 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6130 -class=> "list name"},esc_html($remote)) .
6131 "</td>";
6132 print "<td class=\"link\">" .
6133 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6134 " | " .
6135 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6136 "</td>";
6138 print "</tr>\n";
6141 if ($limited) {
6142 print "<tr>\n" .
6143 "<td colspan=\"3\">" .
6144 $cgi->a({-href => href(action=>"remotes")}, "...") .
6145 "</td>\n" . "</tr>\n";
6148 print "</table>";
6151 # Display remote heads grouped by remote, unless there are too many
6152 # remotes, in which case we only display the remote names
6153 sub git_remotes_body {
6154 my ($remotedata, $limit, $head) = @_;
6155 if ($limit and $limit < keys %$remotedata) {
6156 git_remotes_list($remotedata, $limit);
6157 } else {
6158 fill_remote_heads($remotedata);
6159 while (my ($remote, $rdata) = each %$remotedata) {
6160 git_print_section({-class=>"remote", -id=>$remote},
6161 ["remotes", $remote, $remote], sub {
6162 git_remote_block($remote, $rdata, $limit, $head);
6168 sub git_search_message {
6169 my %co = @_;
6171 my $greptype;
6172 if ($searchtype eq 'commit') {
6173 $greptype = "--grep=";
6174 } elsif ($searchtype eq 'author') {
6175 $greptype = "--author=";
6176 } elsif ($searchtype eq 'committer') {
6177 $greptype = "--committer=";
6179 $greptype .= $searchtext;
6180 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6181 $greptype, '--regexp-ignore-case',
6182 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6184 my $paging_nav = '';
6185 if ($page > 0) {
6186 $paging_nav .=
6187 $cgi->a({-href => href(-replay=>1, page=>undef)},
6188 "first") .
6189 " &sdot; " .
6190 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6191 -accesskey => "p", -title => "Alt-p"}, "prev");
6192 } else {
6193 $paging_nav .= "first &sdot; prev";
6195 my $next_link = '';
6196 if ($#commitlist >= 100) {
6197 $next_link =
6198 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6199 -accesskey => "n", -title => "Alt-n"}, "next");
6200 $paging_nav .= " &sdot; $next_link";
6201 } else {
6202 $paging_nav .= " &sdot; next";
6205 git_header_html();
6207 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6208 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6209 if ($page == 0 && !@commitlist) {
6210 print "<p>No match.</p>\n";
6211 } else {
6212 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6215 git_footer_html();
6218 sub git_search_changes {
6219 my %co = @_;
6221 local $/ = "\n";
6222 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6223 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6224 ($search_use_regexp ? '--pickaxe-regex' : ())
6225 or die_error(500, "Open git-log failed");
6227 git_header_html();
6229 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6230 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6232 print "<table class=\"pickaxe search\">\n";
6233 my $alternate = 1;
6234 undef %co;
6235 my @files;
6236 while (my $line = <$fd>) {
6237 chomp $line;
6238 next unless $line;
6240 my %set = parse_difftree_raw_line($line);
6241 if (defined $set{'commit'}) {
6242 # finish previous commit
6243 if (%co) {
6244 print "</td>\n" .
6245 "<td class=\"link\">" .
6246 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6247 "commit") .
6248 " | " .
6249 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6250 hash_base=>$co{'id'})},
6251 "tree") .
6252 "</td>\n" .
6253 "</tr>\n";
6256 if ($alternate) {
6257 print "<tr class=\"dark\">\n";
6258 } else {
6259 print "<tr class=\"light\">\n";
6261 $alternate ^= 1;
6262 %co = parse_commit($set{'commit'});
6263 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6264 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6265 "<td><i>$author</i></td>\n" .
6266 "<td>" .
6267 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6268 -class => "list subject"},
6269 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6270 } elsif (defined $set{'to_id'}) {
6271 next if ($set{'to_id'} =~ m/^0{40}$/);
6273 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6274 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6275 -class => "list"},
6276 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6277 "<br/>\n";
6280 close $fd;
6282 # finish last commit (warning: repetition!)
6283 if (%co) {
6284 print "</td>\n" .
6285 "<td class=\"link\">" .
6286 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6287 "commit") .
6288 " | " .
6289 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6290 hash_base=>$co{'id'})},
6291 "tree") .
6292 "</td>\n" .
6293 "</tr>\n";
6296 print "</table>\n";
6298 git_footer_html();
6301 sub git_search_files {
6302 my %co = @_;
6304 local $/ = "\n";
6305 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6306 $search_use_regexp ? ('-E', '-i') : '-F',
6307 $searchtext, $co{'tree'}
6308 or die_error(500, "Open git-grep failed");
6310 git_header_html();
6312 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6313 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6315 print "<table class=\"grep_search\">\n";
6316 my $alternate = 1;
6317 my $matches = 0;
6318 my $lastfile = '';
6319 my $file_href;
6320 while (my $line = <$fd>) {
6321 chomp $line;
6322 my ($file, $lno, $ltext, $binary);
6323 last if ($matches++ > 1000);
6324 if ($line =~ /^Binary file (.+) matches$/) {
6325 $file = $1;
6326 $binary = 1;
6327 } else {
6328 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6329 $file =~ s/^$co{'tree'}://;
6331 if ($file ne $lastfile) {
6332 $lastfile and print "</td></tr>\n";
6333 if ($alternate++) {
6334 print "<tr class=\"dark\">\n";
6335 } else {
6336 print "<tr class=\"light\">\n";
6338 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6339 file_name=>$file);
6340 print "<td class=\"list\">".
6341 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6342 print "</td><td>\n";
6343 $lastfile = $file;
6345 if ($binary) {
6346 print "<div class=\"binary\">Binary file</div>\n";
6347 } else {
6348 $ltext = untabify($ltext);
6349 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6350 $ltext = esc_html($1, -nbsp=>1);
6351 $ltext .= '<span class="match">';
6352 $ltext .= esc_html($2, -nbsp=>1);
6353 $ltext .= '</span>';
6354 $ltext .= esc_html($3, -nbsp=>1);
6355 } else {
6356 $ltext = esc_html($ltext, -nbsp=>1);
6358 print "<div class=\"pre\">" .
6359 $cgi->a({-href => $file_href.'#l'.$lno,
6360 -class => "linenr"}, sprintf('%4i', $lno)) .
6361 ' ' . $ltext . "</div>\n";
6364 if ($lastfile) {
6365 print "</td></tr>\n";
6366 if ($matches > 1000) {
6367 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6369 } else {
6370 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6372 close $fd;
6374 print "</table>\n";
6376 git_footer_html();
6379 sub git_search_grep_body {
6380 my ($commitlist, $from, $to, $extra) = @_;
6381 $from = 0 unless defined $from;
6382 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6384 print "<table class=\"commit_search\">\n";
6385 my $alternate = 1;
6386 for (my $i = $from; $i <= $to; $i++) {
6387 my %co = %{$commitlist->[$i]};
6388 if (!%co) {
6389 next;
6391 my $commit = $co{'id'};
6392 if ($alternate) {
6393 print "<tr class=\"dark\">\n";
6394 } else {
6395 print "<tr class=\"light\">\n";
6397 $alternate ^= 1;
6398 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6399 format_author_html('td', \%co, 15, 5) .
6400 "<td>" .
6401 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6402 -class => "list subject"},
6403 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6404 my $comment = $co{'comment'};
6405 foreach my $line (@$comment) {
6406 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6407 my ($lead, $match, $trail) = ($1, $2, $3);
6408 $match = chop_str($match, 70, 5, 'center');
6409 my $contextlen = int((80 - length($match))/2);
6410 $contextlen = 30 if ($contextlen > 30);
6411 $lead = chop_str($lead, $contextlen, 10, 'left');
6412 $trail = chop_str($trail, $contextlen, 10, 'right');
6414 $lead = esc_html($lead);
6415 $match = esc_html($match);
6416 $trail = esc_html($trail);
6418 print "$lead<span class=\"match\">$match</span>$trail<br />";
6421 print "</td>\n" .
6422 "<td class=\"link\">" .
6423 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6424 " | " .
6425 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6426 " | " .
6427 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6428 print "</td>\n" .
6429 "</tr>\n";
6431 if (defined $extra) {
6432 print "<tr>\n" .
6433 "<td colspan=\"3\">$extra</td>\n" .
6434 "</tr>\n";
6436 print "</table>\n";
6439 ## ======================================================================
6440 ## ======================================================================
6441 ## actions
6443 sub git_project_list {
6444 my $order = $input_params{'order'};
6445 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6446 die_error(400, "Unknown order parameter");
6449 my @list = git_get_projects_list($project_filter, $strict_export);
6450 if (!@list) {
6451 die_error(404, "No projects found");
6454 git_header_html();
6455 if (defined $home_text && -f $home_text) {
6456 print "<div class=\"index_include\">\n";
6457 insert_file($home_text);
6458 print "</div>\n";
6461 git_project_search_form($searchtext, $search_use_regexp);
6462 git_project_list_body(\@list, $order);
6463 git_footer_html();
6466 sub git_forks {
6467 my $order = $input_params{'order'};
6468 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6469 die_error(400, "Unknown order parameter");
6472 my $filter = $project;
6473 $filter =~ s/\.git$//;
6474 my @list = git_get_projects_list($filter);
6475 if (!@list) {
6476 die_error(404, "No forks found");
6479 git_header_html();
6480 git_print_page_nav('','');
6481 git_print_header_div('summary', "$project forks");
6482 git_project_list_body(\@list, $order);
6483 git_footer_html();
6486 sub git_project_index {
6487 my @projects = git_get_projects_list($project_filter, $strict_export);
6488 if (!@projects) {
6489 die_error(404, "No projects found");
6492 print $cgi->header(
6493 -type => 'text/plain',
6494 -charset => 'utf-8',
6495 -content_disposition => 'inline; filename="index.aux"');
6497 foreach my $pr (@projects) {
6498 if (!exists $pr->{'owner'}) {
6499 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6502 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6503 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6504 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6505 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6506 $path =~ s/ /\+/g;
6507 $owner =~ s/ /\+/g;
6509 print "$path $owner\n";
6513 sub git_summary {
6514 my $descr = git_get_project_description($project) || "none";
6515 my %co = parse_commit("HEAD");
6516 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6517 my $head = $co{'id'};
6518 my $remote_heads = gitweb_check_feature('remote_heads');
6520 my $owner = git_get_project_owner($project);
6522 my $refs = git_get_references();
6523 # These get_*_list functions return one more to allow us to see if
6524 # there are more ...
6525 my @taglist = git_get_tags_list(16);
6526 my @headlist = git_get_heads_list(16);
6527 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6528 my @forklist;
6529 my $check_forks = gitweb_check_feature('forks');
6531 if ($check_forks) {
6532 # find forks of a project
6533 my $filter = $project;
6534 $filter =~ s/\.git$//;
6535 @forklist = git_get_projects_list($filter);
6536 # filter out forks of forks
6537 @forklist = filter_forks_from_projects_list(\@forklist)
6538 if (@forklist);
6541 git_header_html();
6542 git_print_page_nav('summary','', $head);
6544 print "<div class=\"title\">&nbsp;</div>\n";
6545 print "<table class=\"projects_list\">\n" .
6546 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6547 if ($owner and not $omit_owner) {
6548 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6550 if (defined $cd{'rfc2822'}) {
6551 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6552 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6555 # use per project git URL list in $projectroot/$project/cloneurl
6556 # or make project git URL from git base URL and project name
6557 my $url_tag = "URL";
6558 my @url_list = git_get_project_url_list($project);
6559 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6560 foreach my $git_url (@url_list) {
6561 next unless $git_url;
6562 print format_repo_url($url_tag, $git_url);
6563 $url_tag = "";
6566 # Tag cloud
6567 my $show_ctags = gitweb_check_feature('ctags');
6568 if ($show_ctags) {
6569 my $ctags = git_get_project_ctags($project);
6570 if (%$ctags) {
6571 # without ability to add tags, don't show if there are none
6572 my $cloud = git_populate_project_tagcloud($ctags);
6573 print "<tr id=\"metadata_ctags\">" .
6574 "<td>content tags</td>" .
6575 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6576 "</tr>\n";
6580 print "</table>\n";
6582 # If XSS prevention is on, we don't include README.html.
6583 # TODO: Allow a readme in some safe format.
6584 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6585 print "<div class=\"title\">readme</div>\n" .
6586 "<div class=\"readme\">\n";
6587 insert_file("$projectroot/$project/README.html");
6588 print "\n</div>\n"; # class="readme"
6591 # we need to request one more than 16 (0..15) to check if
6592 # those 16 are all
6593 my @commitlist = $head ? parse_commits($head, 17) : ();
6594 if (@commitlist) {
6595 git_print_header_div('shortlog');
6596 git_shortlog_body(\@commitlist, 0, 15, $refs,
6597 $#commitlist <= 15 ? undef :
6598 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6601 if (@taglist) {
6602 git_print_header_div('tags');
6603 git_tags_body(\@taglist, 0, 15,
6604 $#taglist <= 15 ? undef :
6605 $cgi->a({-href => href(action=>"tags")}, "..."));
6608 if (@headlist) {
6609 git_print_header_div('heads');
6610 git_heads_body(\@headlist, $head, 0, 15,
6611 $#headlist <= 15 ? undef :
6612 $cgi->a({-href => href(action=>"heads")}, "..."));
6615 if (%remotedata) {
6616 git_print_header_div('remotes');
6617 git_remotes_body(\%remotedata, 15, $head);
6620 if (@forklist) {
6621 git_print_header_div('forks');
6622 git_project_list_body(\@forklist, 'age', 0, 15,
6623 $#forklist <= 15 ? undef :
6624 $cgi->a({-href => href(action=>"forks")}, "..."),
6625 'no_header');
6628 git_footer_html();
6631 sub git_tag {
6632 my %tag = parse_tag($hash);
6634 if (! %tag) {
6635 die_error(404, "Unknown tag object");
6638 my $head = git_get_head_hash($project);
6639 git_header_html();
6640 git_print_page_nav('','', $head,undef,$head);
6641 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6642 print "<div class=\"title_text\">\n" .
6643 "<table class=\"object_header\">\n" .
6644 "<tr>\n" .
6645 "<td>object</td>\n" .
6646 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6647 $tag{'object'}) . "</td>\n" .
6648 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6649 $tag{'type'}) . "</td>\n" .
6650 "</tr>\n";
6651 if (defined($tag{'author'})) {
6652 git_print_authorship_rows(\%tag, 'author');
6654 print "</table>\n\n" .
6655 "</div>\n";
6656 print "<div class=\"page_body\">";
6657 my $comment = $tag{'comment'};
6658 foreach my $line (@$comment) {
6659 chomp $line;
6660 print esc_html($line, -nbsp=>1) . "<br/>\n";
6662 print "</div>\n";
6663 git_footer_html();
6666 sub git_blame_common {
6667 my $format = shift || 'porcelain';
6668 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6669 $format = 'incremental';
6670 $action = 'blame_incremental'; # for page title etc
6673 # permissions
6674 gitweb_check_feature('blame')
6675 or die_error(403, "Blame view not allowed");
6677 # error checking
6678 die_error(400, "No file name given") unless $file_name;
6679 $hash_base ||= git_get_head_hash($project);
6680 die_error(404, "Couldn't find base commit") unless $hash_base;
6681 my %co = parse_commit($hash_base)
6682 or die_error(404, "Commit not found");
6683 my $ftype = "blob";
6684 if (!defined $hash) {
6685 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6686 or die_error(404, "Error looking up file");
6687 } else {
6688 $ftype = git_get_type($hash);
6689 if ($ftype !~ "blob") {
6690 die_error(400, "Object is not a blob");
6694 my $fd;
6695 if ($format eq 'incremental') {
6696 # get file contents (as base)
6697 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6698 or die_error(500, "Open git-cat-file failed");
6699 } elsif ($format eq 'data') {
6700 # run git-blame --incremental
6701 open $fd, "-|", git_cmd(), "blame", "--incremental",
6702 $hash_base, "--", $file_name
6703 or die_error(500, "Open git-blame --incremental failed");
6704 } else {
6705 # run git-blame --porcelain
6706 open $fd, "-|", git_cmd(), "blame", '-p',
6707 $hash_base, '--', $file_name
6708 or die_error(500, "Open git-blame --porcelain failed");
6710 binmode $fd, ':utf8';
6712 # incremental blame data returns early
6713 if ($format eq 'data') {
6714 print $cgi->header(
6715 -type=>"text/plain", -charset => "utf-8",
6716 -status=> "200 OK");
6717 local $| = 1; # output autoflush
6718 while (my $line = <$fd>) {
6719 print to_utf8($line);
6721 close $fd
6722 or print "ERROR $!\n";
6724 print 'END';
6725 if (defined $t0 && gitweb_check_feature('timed')) {
6726 print ' '.
6727 tv_interval($t0, [ gettimeofday() ]).
6728 ' '.$number_of_git_cmds;
6730 print "\n";
6732 return;
6735 # page header
6736 git_header_html();
6737 my $formats_nav =
6738 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6739 "blob") .
6740 " | ";
6741 if ($format eq 'incremental') {
6742 $formats_nav .=
6743 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6744 "blame") . " (non-incremental)";
6745 } else {
6746 $formats_nav .=
6747 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6748 "blame") . " (incremental)";
6750 $formats_nav .=
6751 " | " .
6752 $cgi->a({-href => href(action=>"history", -replay=>1)},
6753 "history") .
6754 " | " .
6755 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6756 "HEAD");
6757 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6758 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6759 git_print_page_path($file_name, $ftype, $hash_base);
6761 # page body
6762 if ($format eq 'incremental') {
6763 print "<noscript>\n<div class=\"error\"><center><b>\n".
6764 "This page requires JavaScript to run.\n Use ".
6765 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6766 'this page').
6767 " instead.\n".
6768 "</b></center></div>\n</noscript>\n";
6770 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6773 print qq!<div class="page_body">\n!;
6774 print qq!<div id="progress_info">... / ...</div>\n!
6775 if ($format eq 'incremental');
6776 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6777 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6778 qq!<thead>\n!.
6779 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6780 qq!</thead>\n!.
6781 qq!<tbody>\n!;
6783 my @rev_color = qw(light dark);
6784 my $num_colors = scalar(@rev_color);
6785 my $current_color = 0;
6787 if ($format eq 'incremental') {
6788 my $color_class = $rev_color[$current_color];
6790 #contents of a file
6791 my $linenr = 0;
6792 LINE:
6793 while (my $line = <$fd>) {
6794 chomp $line;
6795 $linenr++;
6797 print qq!<tr id="l$linenr" class="$color_class">!.
6798 qq!<td class="sha1"><a href=""> </a></td>!.
6799 qq!<td class="linenr">!.
6800 qq!<a class="linenr" href="">$linenr</a></td>!;
6801 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6802 print qq!</tr>\n!;
6805 } else { # porcelain, i.e. ordinary blame
6806 my %metainfo = (); # saves information about commits
6808 # blame data
6809 LINE:
6810 while (my $line = <$fd>) {
6811 chomp $line;
6812 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6813 # no <lines in group> for subsequent lines in group of lines
6814 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6815 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6816 if (!exists $metainfo{$full_rev}) {
6817 $metainfo{$full_rev} = { 'nprevious' => 0 };
6819 my $meta = $metainfo{$full_rev};
6820 my $data;
6821 while ($data = <$fd>) {
6822 chomp $data;
6823 last if ($data =~ s/^\t//); # contents of line
6824 if ($data =~ /^(\S+)(?: (.*))?$/) {
6825 $meta->{$1} = $2 unless exists $meta->{$1};
6827 if ($data =~ /^previous /) {
6828 $meta->{'nprevious'}++;
6831 my $short_rev = substr($full_rev, 0, 8);
6832 my $author = $meta->{'author'};
6833 my %date =
6834 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6835 my $date = $date{'iso-tz'};
6836 if ($group_size) {
6837 $current_color = ($current_color + 1) % $num_colors;
6839 my $tr_class = $rev_color[$current_color];
6840 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6841 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6842 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6843 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6844 if ($group_size) {
6845 print "<td class=\"sha1\"";
6846 print " title=\"". esc_html($author) . ", $date\"";
6847 print " rowspan=\"$group_size\"" if ($group_size > 1);
6848 print ">";
6849 print $cgi->a({-href => href(action=>"commit",
6850 hash=>$full_rev,
6851 file_name=>$file_name)},
6852 esc_html($short_rev));
6853 if ($group_size >= 2) {
6854 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6855 if (@author_initials) {
6856 print "<br />" .
6857 esc_html(join('', @author_initials));
6858 # or join('.', ...)
6861 print "</td>\n";
6863 # 'previous' <sha1 of parent commit> <filename at commit>
6864 if (exists $meta->{'previous'} &&
6865 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6866 $meta->{'parent'} = $1;
6867 $meta->{'file_parent'} = unquote($2);
6869 my $linenr_commit =
6870 exists($meta->{'parent'}) ?
6871 $meta->{'parent'} : $full_rev;
6872 my $linenr_filename =
6873 exists($meta->{'file_parent'}) ?
6874 $meta->{'file_parent'} : unquote($meta->{'filename'});
6875 my $blamed = href(action => 'blame',
6876 file_name => $linenr_filename,
6877 hash_base => $linenr_commit);
6878 print "<td class=\"linenr\">";
6879 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6880 -class => "linenr" },
6881 esc_html($lineno));
6882 print "</td>";
6883 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6884 print "</tr>\n";
6885 } # end while
6889 # footer
6890 print "</tbody>\n".
6891 "</table>\n"; # class="blame"
6892 print "</div>\n"; # class="blame_body"
6893 close $fd
6894 or print "Reading blob failed\n";
6896 git_footer_html();
6899 sub git_blame {
6900 git_blame_common();
6903 sub git_blame_incremental {
6904 git_blame_common('incremental');
6907 sub git_blame_data {
6908 git_blame_common('data');
6911 sub git_tags {
6912 my $head = git_get_head_hash($project);
6913 git_header_html();
6914 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6915 git_print_header_div('summary', $project);
6917 my @tagslist = git_get_tags_list();
6918 if (@tagslist) {
6919 git_tags_body(\@tagslist);
6921 git_footer_html();
6924 sub git_heads {
6925 my $head = git_get_head_hash($project);
6926 git_header_html();
6927 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6928 git_print_header_div('summary', $project);
6930 my @headslist = git_get_heads_list();
6931 if (@headslist) {
6932 git_heads_body(\@headslist, $head);
6934 git_footer_html();
6937 # used both for single remote view and for list of all the remotes
6938 sub git_remotes {
6939 gitweb_check_feature('remote_heads')
6940 or die_error(403, "Remote heads view is disabled");
6942 my $head = git_get_head_hash($project);
6943 my $remote = $input_params{'hash'};
6945 my $remotedata = git_get_remotes_list($remote);
6946 die_error(500, "Unable to get remote information") unless defined $remotedata;
6948 unless (%$remotedata) {
6949 die_error(404, defined $remote ?
6950 "Remote $remote not found" :
6951 "No remotes found");
6954 git_header_html(undef, undef, -action_extra => $remote);
6955 git_print_page_nav('', '', $head, undef, $head,
6956 format_ref_views($remote ? '' : 'remotes'));
6958 fill_remote_heads($remotedata);
6959 if (defined $remote) {
6960 git_print_header_div('remotes', "$remote remote for $project");
6961 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6962 } else {
6963 git_print_header_div('summary', "$project remotes");
6964 git_remotes_body($remotedata, undef, $head);
6967 git_footer_html();
6970 sub git_blob_plain {
6971 my $type = shift;
6972 my $expires;
6974 if (!defined $hash) {
6975 if (defined $file_name) {
6976 my $base = $hash_base || git_get_head_hash($project);
6977 $hash = git_get_hash_by_path($base, $file_name, "blob")
6978 or die_error(404, "Cannot find file");
6979 } else {
6980 die_error(400, "No file name defined");
6982 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6983 # blobs defined by non-textual hash id's can be cached
6984 $expires = "+1d";
6987 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6988 or die_error(500, "Open git-cat-file blob '$hash' failed");
6990 # content-type (can include charset)
6991 $type = blob_contenttype($fd, $file_name, $type);
6993 # "save as" filename, even when no $file_name is given
6994 my $save_as = "$hash";
6995 if (defined $file_name) {
6996 $save_as = $file_name;
6997 } elsif ($type =~ m/^text\//) {
6998 $save_as .= '.txt';
7001 # With XSS prevention on, blobs of all types except a few known safe
7002 # ones are served with "Content-Disposition: attachment" to make sure
7003 # they don't run in our security domain. For certain image types,
7004 # blob view writes an <img> tag referring to blob_plain view, and we
7005 # want to be sure not to break that by serving the image as an
7006 # attachment (though Firefox 3 doesn't seem to care).
7007 my $sandbox = $prevent_xss &&
7008 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7010 # serve text/* as text/plain
7011 if ($prevent_xss &&
7012 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7013 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7014 my $rest = $1;
7015 $rest = defined $rest ? $rest : '';
7016 $type = "text/plain$rest";
7019 print $cgi->header(
7020 -type => $type,
7021 -expires => $expires,
7022 -content_disposition =>
7023 ($sandbox ? 'attachment' : 'inline')
7024 . '; filename="' . $save_as . '"');
7025 local $/ = undef;
7026 binmode STDOUT, ':raw';
7027 print <$fd>;
7028 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7029 close $fd;
7032 sub git_blob {
7033 my $expires;
7035 if (!defined $hash) {
7036 if (defined $file_name) {
7037 my $base = $hash_base || git_get_head_hash($project);
7038 $hash = git_get_hash_by_path($base, $file_name, "blob")
7039 or die_error(404, "Cannot find file");
7040 } else {
7041 die_error(400, "No file name defined");
7043 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7044 # blobs defined by non-textual hash id's can be cached
7045 $expires = "+1d";
7048 my $have_blame = gitweb_check_feature('blame');
7049 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7050 or die_error(500, "Couldn't cat $file_name, $hash");
7051 my $mimetype = blob_mimetype($fd, $file_name);
7052 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7053 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7054 close $fd;
7055 return git_blob_plain($mimetype);
7057 # we can have blame only for text/* mimetype
7058 $have_blame &&= ($mimetype =~ m!^text/!);
7060 my $highlight = gitweb_check_feature('highlight');
7061 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7062 $fd = run_highlighter($fd, $highlight, $syntax)
7063 if $syntax;
7065 git_header_html(undef, $expires);
7066 my $formats_nav = '';
7067 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7068 if (defined $file_name) {
7069 if ($have_blame) {
7070 $formats_nav .=
7071 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7072 "blame") .
7073 " | ";
7075 $formats_nav .=
7076 $cgi->a({-href => href(action=>"history", -replay=>1)},
7077 "history") .
7078 " | " .
7079 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7080 "raw") .
7081 " | " .
7082 $cgi->a({-href => href(action=>"blob",
7083 hash_base=>"HEAD", file_name=>$file_name)},
7084 "HEAD");
7085 } else {
7086 $formats_nav .=
7087 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7088 "raw");
7090 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7091 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7092 } else {
7093 print "<div class=\"page_nav\">\n" .
7094 "<br/><br/></div>\n" .
7095 "<div class=\"title\">".esc_html($hash)."</div>\n";
7097 git_print_page_path($file_name, "blob", $hash_base);
7098 print "<div class=\"page_body\">\n";
7099 if ($mimetype =~ m!^image/!) {
7100 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7101 if ($file_name) {
7102 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7104 print qq! src="! .
7105 href(action=>"blob_plain", hash=>$hash,
7106 hash_base=>$hash_base, file_name=>$file_name) .
7107 qq!" />\n!;
7108 } else {
7109 my $nr;
7110 while (my $line = <$fd>) {
7111 chomp $line;
7112 $nr++;
7113 $line = untabify($line);
7114 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7115 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7116 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7119 close $fd
7120 or print "Reading blob failed.\n";
7121 print "</div>";
7122 git_footer_html();
7125 sub git_tree {
7126 if (!defined $hash_base) {
7127 $hash_base = "HEAD";
7129 if (!defined $hash) {
7130 if (defined $file_name) {
7131 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7132 } else {
7133 $hash = $hash_base;
7136 die_error(404, "No such tree") unless defined($hash);
7138 my $show_sizes = gitweb_check_feature('show-sizes');
7139 my $have_blame = gitweb_check_feature('blame');
7141 my @entries = ();
7143 local $/ = "\0";
7144 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7145 ($show_sizes ? '-l' : ()), @extra_options, $hash
7146 or die_error(500, "Open git-ls-tree failed");
7147 @entries = map { chomp; $_ } <$fd>;
7148 close $fd
7149 or die_error(404, "Reading tree failed");
7152 my $refs = git_get_references();
7153 my $ref = format_ref_marker($refs, $hash_base);
7154 git_header_html();
7155 my $basedir = '';
7156 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7157 my @views_nav = ();
7158 if (defined $file_name) {
7159 push @views_nav,
7160 $cgi->a({-href => href(action=>"history", -replay=>1)},
7161 "history"),
7162 $cgi->a({-href => href(action=>"tree",
7163 hash_base=>"HEAD", file_name=>$file_name)},
7164 "HEAD"),
7166 my $snapshot_links = format_snapshot_links($hash);
7167 if (defined $snapshot_links) {
7168 # FIXME: Should be available when we have no hash base as well.
7169 push @views_nav, $snapshot_links;
7171 git_print_page_nav('tree','', $hash_base, undef, undef,
7172 join(' | ', @views_nav));
7173 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7174 } else {
7175 undef $hash_base;
7176 print "<div class=\"page_nav\">\n";
7177 print "<br/><br/></div>\n";
7178 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7180 if (defined $file_name) {
7181 $basedir = $file_name;
7182 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7183 $basedir .= '/';
7185 git_print_page_path($file_name, 'tree', $hash_base);
7187 print "<div class=\"page_body\">\n";
7188 print "<table class=\"tree\">\n";
7189 my $alternate = 1;
7190 # '..' (top directory) link if possible
7191 if (defined $hash_base &&
7192 defined $file_name && $file_name =~ m![^/]+$!) {
7193 if ($alternate) {
7194 print "<tr class=\"dark\">\n";
7195 } else {
7196 print "<tr class=\"light\">\n";
7198 $alternate ^= 1;
7200 my $up = $file_name;
7201 $up =~ s!/?[^/]+$!!;
7202 undef $up unless $up;
7203 # based on git_print_tree_entry
7204 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7205 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7206 print '<td class="list">';
7207 print $cgi->a({-href => href(action=>"tree",
7208 hash_base=>$hash_base,
7209 file_name=>$up)},
7210 "..");
7211 print "</td>\n";
7212 print "<td class=\"link\"></td>\n";
7214 print "</tr>\n";
7216 foreach my $line (@entries) {
7217 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7219 if ($alternate) {
7220 print "<tr class=\"dark\">\n";
7221 } else {
7222 print "<tr class=\"light\">\n";
7224 $alternate ^= 1;
7226 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7228 print "</tr>\n";
7230 print "</table>\n" .
7231 "</div>";
7232 git_footer_html();
7235 sub sanitize_for_filename {
7236 my $name = shift;
7238 $name =~ s!/!-!g;
7239 $name =~ s/[^[:alnum:]_.-]//g;
7241 return $name;
7244 sub snapshot_name {
7245 my ($project, $hash) = @_;
7247 # path/to/project.git -> project
7248 # path/to/project/.git -> project
7249 my $name = to_utf8($project);
7250 $name =~ s,([^/])/*\.git$,$1,;
7251 $name = sanitize_for_filename(basename($name));
7253 my $ver = $hash;
7254 if ($hash =~ /^[0-9a-fA-F]+$/) {
7255 # shorten SHA-1 hash
7256 my $full_hash = git_get_full_hash($project, $hash);
7257 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7258 $ver = git_get_short_hash($project, $hash);
7260 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7261 # tags don't need shortened SHA-1 hash
7262 $ver = $1;
7263 } else {
7264 # branches and other need shortened SHA-1 hash
7265 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7266 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7267 my $ref_dir = (defined $1) ? $1 : '';
7268 $ver = $2;
7270 $ref_dir = sanitize_for_filename($ref_dir);
7271 # for refs neither in heads nor remotes we want to
7272 # add a ref dir to archive name
7273 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7274 $ver = $ref_dir . '-' . $ver;
7277 $ver .= '-' . git_get_short_hash($project, $hash);
7279 # special case of sanitization for filename - we change
7280 # slashes to dots instead of dashes
7281 # in case of hierarchical branch names
7282 $ver =~ s!/!.!g;
7283 $ver =~ s/[^[:alnum:]_.-]//g;
7285 # name = project-version_string
7286 $name = "$name-$ver";
7288 return wantarray ? ($name, $name) : $name;
7291 sub exit_if_unmodified_since {
7292 my ($latest_epoch) = @_;
7293 our $cgi;
7295 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7296 if (defined $if_modified) {
7297 my $since;
7298 if (eval { require HTTP::Date; 1; }) {
7299 $since = HTTP::Date::str2time($if_modified);
7300 } elsif (eval { require Time::ParseDate; 1; }) {
7301 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7303 if (defined $since && $latest_epoch <= $since) {
7304 my %latest_date = parse_date($latest_epoch);
7305 print $cgi->header(
7306 -last_modified => $latest_date{'rfc2822'},
7307 -status => '304 Not Modified');
7308 CORE::die;
7313 sub git_snapshot {
7314 my $format = $input_params{'snapshot_format'};
7315 if (!@snapshot_fmts) {
7316 die_error(403, "Snapshots not allowed");
7318 # default to first supported snapshot format
7319 $format ||= $snapshot_fmts[0];
7320 if ($format !~ m/^[a-z0-9]+$/) {
7321 die_error(400, "Invalid snapshot format parameter");
7322 } elsif (!exists($known_snapshot_formats{$format})) {
7323 die_error(400, "Unknown snapshot format");
7324 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7325 die_error(403, "Snapshot format not allowed");
7326 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7327 die_error(403, "Unsupported snapshot format");
7330 my $type = git_get_type("$hash^{}");
7331 if (!$type) {
7332 die_error(404, 'Object does not exist');
7333 } elsif ($type eq 'blob') {
7334 die_error(400, 'Object is not a tree-ish');
7337 my ($name, $prefix) = snapshot_name($project, $hash);
7338 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7340 my %co = parse_commit($hash);
7341 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7343 my $cmd = quote_command(
7344 git_cmd(), 'archive',
7345 "--format=$known_snapshot_formats{$format}{'format'}",
7346 "--prefix=$prefix/", $hash);
7347 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7348 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7351 $filename =~ s/(["\\])/\\$1/g;
7352 my %latest_date;
7353 if (%co) {
7354 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7357 print $cgi->header(
7358 -type => $known_snapshot_formats{$format}{'type'},
7359 -content_disposition => 'inline; filename="' . $filename . '"',
7360 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7361 -status => '200 OK');
7363 open my $fd, "-|", $cmd
7364 or die_error(500, "Execute git-archive failed");
7365 binmode STDOUT, ':raw';
7366 print <$fd>;
7367 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7368 close $fd;
7371 sub git_log_generic {
7372 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7374 my $head = git_get_head_hash($project);
7375 if (!defined $base) {
7376 $base = $head;
7378 if (!defined $page) {
7379 $page = 0;
7381 my $refs = git_get_references();
7383 my $commit_hash = $base;
7384 if (defined $parent) {
7385 $commit_hash = "$parent..$base";
7387 my @commitlist =
7388 parse_commits($commit_hash, 101, (100 * $page),
7389 defined $file_name ? ($file_name, "--full-history") : ());
7391 my $ftype;
7392 if (!defined $file_hash && defined $file_name) {
7393 # some commits could have deleted file in question,
7394 # and not have it in tree, but one of them has to have it
7395 for (my $i = 0; $i < @commitlist; $i++) {
7396 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7397 last if defined $file_hash;
7400 if (defined $file_hash) {
7401 $ftype = git_get_type($file_hash);
7403 if (defined $file_name && !defined $ftype) {
7404 die_error(500, "Unknown type of object");
7406 my %co;
7407 if (defined $file_name) {
7408 %co = parse_commit($base)
7409 or die_error(404, "Unknown commit object");
7413 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7414 my $next_link = '';
7415 if ($#commitlist >= 100) {
7416 $next_link =
7417 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7418 -accesskey => "n", -title => "Alt-n"}, "next");
7420 my $patch_max = gitweb_get_feature('patches');
7421 if ($patch_max && !defined $file_name) {
7422 if ($patch_max < 0 || @commitlist <= $patch_max) {
7423 $paging_nav .= " &sdot; " .
7424 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7425 "patches");
7429 git_header_html();
7430 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7431 if (defined $file_name) {
7432 git_print_header_div('commit', esc_html($co{'title'}), $base);
7433 } else {
7434 git_print_header_div('summary', $project)
7436 git_print_page_path($file_name, $ftype, $hash_base)
7437 if (defined $file_name);
7439 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7440 $file_name, $file_hash, $ftype);
7442 git_footer_html();
7445 sub git_log {
7446 git_log_generic('log', \&git_log_body,
7447 $hash, $hash_parent);
7450 sub git_commit {
7451 $hash ||= $hash_base || "HEAD";
7452 my %co = parse_commit($hash)
7453 or die_error(404, "Unknown commit object");
7455 my $parent = $co{'parent'};
7456 my $parents = $co{'parents'}; # listref
7458 # we need to prepare $formats_nav before any parameter munging
7459 my $formats_nav;
7460 if (!defined $parent) {
7461 # --root commitdiff
7462 $formats_nav .= '(initial)';
7463 } elsif (@$parents == 1) {
7464 # single parent commit
7465 $formats_nav .=
7466 '(parent: ' .
7467 $cgi->a({-href => href(action=>"commit",
7468 hash=>$parent)},
7469 esc_html(substr($parent, 0, 7))) .
7470 ')';
7471 } else {
7472 # merge commit
7473 $formats_nav .=
7474 '(merge: ' .
7475 join(' ', map {
7476 $cgi->a({-href => href(action=>"commit",
7477 hash=>$_)},
7478 esc_html(substr($_, 0, 7)));
7479 } @$parents ) .
7480 ')';
7482 if (gitweb_check_feature('patches') && @$parents <= 1) {
7483 $formats_nav .= " | " .
7484 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7485 "patch");
7488 if (!defined $parent) {
7489 $parent = "--root";
7491 my @difftree;
7492 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7493 @diff_opts,
7494 (@$parents <= 1 ? $parent : '-c'),
7495 $hash, "--"
7496 or die_error(500, "Open git-diff-tree failed");
7497 @difftree = map { chomp; $_ } <$fd>;
7498 close $fd or die_error(404, "Reading git-diff-tree failed");
7500 # non-textual hash id's can be cached
7501 my $expires;
7502 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7503 $expires = "+1d";
7505 my $refs = git_get_references();
7506 my $ref = format_ref_marker($refs, $co{'id'});
7508 git_header_html(undef, $expires);
7509 git_print_page_nav('commit', '',
7510 $hash, $co{'tree'}, $hash,
7511 $formats_nav);
7513 if (defined $co{'parent'}) {
7514 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7515 } else {
7516 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7518 print "<div class=\"title_text\">\n" .
7519 "<table class=\"object_header\">\n";
7520 git_print_authorship_rows(\%co);
7521 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7522 print "<tr>" .
7523 "<td>tree</td>" .
7524 "<td class=\"sha1\">" .
7525 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7526 class => "list"}, $co{'tree'}) .
7527 "</td>" .
7528 "<td class=\"link\">" .
7529 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7530 "tree");
7531 my $snapshot_links = format_snapshot_links($hash);
7532 if (defined $snapshot_links) {
7533 print " | " . $snapshot_links;
7535 print "</td>" .
7536 "</tr>\n";
7538 foreach my $par (@$parents) {
7539 print "<tr>" .
7540 "<td>parent</td>" .
7541 "<td class=\"sha1\">" .
7542 $cgi->a({-href => href(action=>"commit", hash=>$par),
7543 class => "list"}, $par) .
7544 "</td>" .
7545 "<td class=\"link\">" .
7546 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7547 " | " .
7548 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7549 "</td>" .
7550 "</tr>\n";
7552 print "</table>".
7553 "</div>\n";
7555 print "<div class=\"page_body\">\n";
7556 git_print_log($co{'comment'});
7557 print "</div>\n";
7559 git_difftree_body(\@difftree, $hash, @$parents);
7561 git_footer_html();
7564 sub git_object {
7565 # object is defined by:
7566 # - hash or hash_base alone
7567 # - hash_base and file_name
7568 my $type;
7570 # - hash or hash_base alone
7571 if ($hash || ($hash_base && !defined $file_name)) {
7572 my $object_id = $hash || $hash_base;
7574 open my $fd, "-|", quote_command(
7575 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7576 or die_error(404, "Object does not exist");
7577 $type = <$fd>;
7578 chomp $type;
7579 close $fd
7580 or die_error(404, "Object does not exist");
7582 # - hash_base and file_name
7583 } elsif ($hash_base && defined $file_name) {
7584 $file_name =~ s,/+$,,;
7586 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7587 or die_error(404, "Base object does not exist");
7589 # here errors should not happen
7590 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7591 or die_error(500, "Open git-ls-tree failed");
7592 my $line = <$fd>;
7593 close $fd;
7595 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7596 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7597 die_error(404, "File or directory for given base does not exist");
7599 $type = $2;
7600 $hash = $3;
7601 } else {
7602 die_error(400, "Not enough information to find object");
7605 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7606 hash=>$hash, hash_base=>$hash_base,
7607 file_name=>$file_name),
7608 -status => '302 Found');
7611 sub git_blobdiff {
7612 my $format = shift || 'html';
7613 my $diff_style = $input_params{'diff_style'} || 'inline';
7615 my $fd;
7616 my @difftree;
7617 my %diffinfo;
7618 my $expires;
7620 # preparing $fd and %diffinfo for git_patchset_body
7621 # new style URI
7622 if (defined $hash_base && defined $hash_parent_base) {
7623 if (defined $file_name) {
7624 # read raw output
7625 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7626 $hash_parent_base, $hash_base,
7627 "--", (defined $file_parent ? $file_parent : ()), $file_name
7628 or die_error(500, "Open git-diff-tree failed");
7629 @difftree = map { chomp; $_ } <$fd>;
7630 close $fd
7631 or die_error(404, "Reading git-diff-tree failed");
7632 @difftree
7633 or die_error(404, "Blob diff not found");
7635 } elsif (defined $hash &&
7636 $hash =~ /[0-9a-fA-F]{40}/) {
7637 # try to find filename from $hash
7639 # read filtered raw output
7640 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7641 $hash_parent_base, $hash_base, "--"
7642 or die_error(500, "Open git-diff-tree failed");
7643 @difftree =
7644 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7645 # $hash == to_id
7646 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7647 map { chomp; $_ } <$fd>;
7648 close $fd
7649 or die_error(404, "Reading git-diff-tree failed");
7650 @difftree
7651 or die_error(404, "Blob diff not found");
7653 } else {
7654 die_error(400, "Missing one of the blob diff parameters");
7657 if (@difftree > 1) {
7658 die_error(400, "Ambiguous blob diff specification");
7661 %diffinfo = parse_difftree_raw_line($difftree[0]);
7662 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7663 $file_name ||= $diffinfo{'to_file'};
7665 $hash_parent ||= $diffinfo{'from_id'};
7666 $hash ||= $diffinfo{'to_id'};
7668 # non-textual hash id's can be cached
7669 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7670 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7671 $expires = '+1d';
7674 # open patch output
7675 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7676 '-p', ($format eq 'html' ? "--full-index" : ()),
7677 $hash_parent_base, $hash_base,
7678 "--", (defined $file_parent ? $file_parent : ()), $file_name
7679 or die_error(500, "Open git-diff-tree failed");
7682 # old/legacy style URI -- not generated anymore since 1.4.3.
7683 if (!%diffinfo) {
7684 die_error('404 Not Found', "Missing one of the blob diff parameters")
7687 # header
7688 if ($format eq 'html') {
7689 my $formats_nav =
7690 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7691 "raw");
7692 $formats_nav .= diff_style_nav($diff_style);
7693 git_header_html(undef, $expires);
7694 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7695 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7696 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7697 } else {
7698 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7699 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7701 if (defined $file_name) {
7702 git_print_page_path($file_name, "blob", $hash_base);
7703 } else {
7704 print "<div class=\"page_path\"></div>\n";
7707 } elsif ($format eq 'plain') {
7708 print $cgi->header(
7709 -type => 'text/plain',
7710 -charset => 'utf-8',
7711 -expires => $expires,
7712 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7714 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7716 } else {
7717 die_error(400, "Unknown blobdiff format");
7720 # patch
7721 if ($format eq 'html') {
7722 print "<div class=\"page_body\">\n";
7724 git_patchset_body($fd, $diff_style,
7725 [ \%diffinfo ], $hash_base, $hash_parent_base);
7726 close $fd;
7728 print "</div>\n"; # class="page_body"
7729 git_footer_html();
7731 } else {
7732 while (my $line = <$fd>) {
7733 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7734 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7736 print $line;
7738 last if $line =~ m!^\+\+\+!;
7740 local $/ = undef;
7741 print <$fd>;
7742 close $fd;
7746 sub git_blobdiff_plain {
7747 git_blobdiff('plain');
7750 # assumes that it is added as later part of already existing navigation,
7751 # so it returns "| foo | bar" rather than just "foo | bar"
7752 sub diff_style_nav {
7753 my ($diff_style, $is_combined) = @_;
7754 $diff_style ||= 'inline';
7756 return "" if ($is_combined);
7758 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7759 my %styles = @styles;
7760 @styles =
7761 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7763 return join '',
7764 map { " | ".$_ }
7765 map {
7766 $_ eq $diff_style ? $styles{$_} :
7767 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7768 } @styles;
7771 sub git_commitdiff {
7772 my %params = @_;
7773 my $format = $params{-format} || 'html';
7774 my $diff_style = $input_params{'diff_style'} || 'inline';
7776 my ($patch_max) = gitweb_get_feature('patches');
7777 if ($format eq 'patch') {
7778 die_error(403, "Patch view not allowed") unless $patch_max;
7781 $hash ||= $hash_base || "HEAD";
7782 my %co = parse_commit($hash)
7783 or die_error(404, "Unknown commit object");
7785 # choose format for commitdiff for merge
7786 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7787 $hash_parent = '--cc';
7789 # we need to prepare $formats_nav before almost any parameter munging
7790 my $formats_nav;
7791 if ($format eq 'html') {
7792 $formats_nav =
7793 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7794 "raw");
7795 if ($patch_max && @{$co{'parents'}} <= 1) {
7796 $formats_nav .= " | " .
7797 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7798 "patch");
7800 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7802 if (defined $hash_parent &&
7803 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7804 # commitdiff with two commits given
7805 my $hash_parent_short = $hash_parent;
7806 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7807 $hash_parent_short = substr($hash_parent, 0, 7);
7809 $formats_nav .=
7810 ' (from';
7811 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7812 if ($co{'parents'}[$i] eq $hash_parent) {
7813 $formats_nav .= ' parent ' . ($i+1);
7814 last;
7817 $formats_nav .= ': ' .
7818 $cgi->a({-href => href(-replay=>1,
7819 hash=>$hash_parent, hash_base=>undef)},
7820 esc_html($hash_parent_short)) .
7821 ')';
7822 } elsif (!$co{'parent'}) {
7823 # --root commitdiff
7824 $formats_nav .= ' (initial)';
7825 } elsif (scalar @{$co{'parents'}} == 1) {
7826 # single parent commit
7827 $formats_nav .=
7828 ' (parent: ' .
7829 $cgi->a({-href => href(-replay=>1,
7830 hash=>$co{'parent'}, hash_base=>undef)},
7831 esc_html(substr($co{'parent'}, 0, 7))) .
7832 ')';
7833 } else {
7834 # merge commit
7835 if ($hash_parent eq '--cc') {
7836 $formats_nav .= ' | ' .
7837 $cgi->a({-href => href(-replay=>1,
7838 hash=>$hash, hash_parent=>'-c')},
7839 'combined');
7840 } else { # $hash_parent eq '-c'
7841 $formats_nav .= ' | ' .
7842 $cgi->a({-href => href(-replay=>1,
7843 hash=>$hash, hash_parent=>'--cc')},
7844 'compact');
7846 $formats_nav .=
7847 ' (merge: ' .
7848 join(' ', map {
7849 $cgi->a({-href => href(-replay=>1,
7850 hash=>$_, hash_base=>undef)},
7851 esc_html(substr($_, 0, 7)));
7852 } @{$co{'parents'}} ) .
7853 ')';
7857 my $hash_parent_param = $hash_parent;
7858 if (!defined $hash_parent_param) {
7859 # --cc for multiple parents, --root for parentless
7860 $hash_parent_param =
7861 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7864 # read commitdiff
7865 my $fd;
7866 my @difftree;
7867 if ($format eq 'html') {
7868 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7869 "--no-commit-id", "--patch-with-raw", "--full-index",
7870 $hash_parent_param, $hash, "--"
7871 or die_error(500, "Open git-diff-tree failed");
7873 while (my $line = <$fd>) {
7874 chomp $line;
7875 # empty line ends raw part of diff-tree output
7876 last unless $line;
7877 push @difftree, scalar parse_difftree_raw_line($line);
7880 } elsif ($format eq 'plain') {
7881 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7882 '-p', $hash_parent_param, $hash, "--"
7883 or die_error(500, "Open git-diff-tree failed");
7884 } elsif ($format eq 'patch') {
7885 # For commit ranges, we limit the output to the number of
7886 # patches specified in the 'patches' feature.
7887 # For single commits, we limit the output to a single patch,
7888 # diverging from the git-format-patch default.
7889 my @commit_spec = ();
7890 if ($hash_parent) {
7891 if ($patch_max > 0) {
7892 push @commit_spec, "-$patch_max";
7894 push @commit_spec, '-n', "$hash_parent..$hash";
7895 } else {
7896 if ($params{-single}) {
7897 push @commit_spec, '-1';
7898 } else {
7899 if ($patch_max > 0) {
7900 push @commit_spec, "-$patch_max";
7902 push @commit_spec, "-n";
7904 push @commit_spec, '--root', $hash;
7906 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7907 '--encoding=utf8', '--stdout', @commit_spec
7908 or die_error(500, "Open git-format-patch failed");
7909 } else {
7910 die_error(400, "Unknown commitdiff format");
7913 # non-textual hash id's can be cached
7914 my $expires;
7915 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7916 $expires = "+1d";
7919 # write commit message
7920 if ($format eq 'html') {
7921 my $refs = git_get_references();
7922 my $ref = format_ref_marker($refs, $co{'id'});
7924 git_header_html(undef, $expires);
7925 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7926 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7927 print "<div class=\"title_text\">\n" .
7928 "<table class=\"object_header\">\n";
7929 git_print_authorship_rows(\%co);
7930 print "</table>".
7931 "</div>\n";
7932 print "<div class=\"page_body\">\n";
7933 if (@{$co{'comment'}} > 1) {
7934 print "<div class=\"log\">\n";
7935 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7936 print "</div>\n"; # class="log"
7939 } elsif ($format eq 'plain') {
7940 my $refs = git_get_references("tags");
7941 my $tagname = git_get_rev_name_tags($hash);
7942 my $filename = basename($project) . "-$hash.patch";
7944 print $cgi->header(
7945 -type => 'text/plain',
7946 -charset => 'utf-8',
7947 -expires => $expires,
7948 -content_disposition => 'inline; filename="' . "$filename" . '"');
7949 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7950 print "From: " . to_utf8($co{'author'}) . "\n";
7951 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7952 print "Subject: " . to_utf8($co{'title'}) . "\n";
7954 print "X-Git-Tag: $tagname\n" if $tagname;
7955 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7957 foreach my $line (@{$co{'comment'}}) {
7958 print to_utf8($line) . "\n";
7960 print "---\n\n";
7961 } elsif ($format eq 'patch') {
7962 my $filename = basename($project) . "-$hash.patch";
7964 print $cgi->header(
7965 -type => 'text/plain',
7966 -charset => 'utf-8',
7967 -expires => $expires,
7968 -content_disposition => 'inline; filename="' . "$filename" . '"');
7971 # write patch
7972 if ($format eq 'html') {
7973 my $use_parents = !defined $hash_parent ||
7974 $hash_parent eq '-c' || $hash_parent eq '--cc';
7975 git_difftree_body(\@difftree, $hash,
7976 $use_parents ? @{$co{'parents'}} : $hash_parent);
7977 print "<br/>\n";
7979 git_patchset_body($fd, $diff_style,
7980 \@difftree, $hash,
7981 $use_parents ? @{$co{'parents'}} : $hash_parent);
7982 close $fd;
7983 print "</div>\n"; # class="page_body"
7984 git_footer_html();
7986 } elsif ($format eq 'plain') {
7987 local $/ = undef;
7988 print <$fd>;
7989 close $fd
7990 or print "Reading git-diff-tree failed\n";
7991 } elsif ($format eq 'patch') {
7992 local $/ = undef;
7993 print <$fd>;
7994 close $fd
7995 or print "Reading git-format-patch failed\n";
7999 sub git_commitdiff_plain {
8000 git_commitdiff(-format => 'plain');
8003 # format-patch-style patches
8004 sub git_patch {
8005 git_commitdiff(-format => 'patch', -single => 1);
8008 sub git_patches {
8009 git_commitdiff(-format => 'patch');
8012 sub git_history {
8013 git_log_generic('history', \&git_history_body,
8014 $hash_base, $hash_parent_base,
8015 $file_name, $hash);
8018 sub git_search {
8019 $searchtype ||= 'commit';
8021 # check if appropriate features are enabled
8022 gitweb_check_feature('search')
8023 or die_error(403, "Search is disabled");
8024 if ($searchtype eq 'pickaxe') {
8025 # pickaxe may take all resources of your box and run for several minutes
8026 # with every query - so decide by yourself how public you make this feature
8027 gitweb_check_feature('pickaxe')
8028 or die_error(403, "Pickaxe search is disabled");
8030 if ($searchtype eq 'grep') {
8031 # grep search might be potentially CPU-intensive, too
8032 gitweb_check_feature('grep')
8033 or die_error(403, "Grep search is disabled");
8036 if (!defined $searchtext) {
8037 die_error(400, "Text field is empty");
8039 if (!defined $hash) {
8040 $hash = git_get_head_hash($project);
8042 my %co = parse_commit($hash);
8043 if (!%co) {
8044 die_error(404, "Unknown commit object");
8046 if (!defined $page) {
8047 $page = 0;
8050 if ($searchtype eq 'commit' ||
8051 $searchtype eq 'author' ||
8052 $searchtype eq 'committer') {
8053 git_search_message(%co);
8054 } elsif ($searchtype eq 'pickaxe') {
8055 git_search_changes(%co);
8056 } elsif ($searchtype eq 'grep') {
8057 git_search_files(%co);
8058 } else {
8059 die_error(400, "Unknown search type");
8063 sub git_search_help {
8064 git_header_html();
8065 git_print_page_nav('','', $hash,$hash,$hash);
8066 print <<EOT;
8067 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8068 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8069 the pattern entered is recognized as the POSIX extended
8070 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8071 insensitive).</p>
8072 <dl>
8073 <dt><b>commit</b></dt>
8074 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8076 my $have_grep = gitweb_check_feature('grep');
8077 if ($have_grep) {
8078 print <<EOT;
8079 <dt><b>grep</b></dt>
8080 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8081 a different one) are searched for the given pattern. On large trees, this search can take
8082 a while and put some strain on the server, so please use it with some consideration. Note that
8083 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8084 case-sensitive.</dd>
8087 print <<EOT;
8088 <dt><b>author</b></dt>
8089 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8090 <dt><b>committer</b></dt>
8091 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8093 my $have_pickaxe = gitweb_check_feature('pickaxe');
8094 if ($have_pickaxe) {
8095 print <<EOT;
8096 <dt><b>pickaxe</b></dt>
8097 <dd>All commits that caused the string to appear or disappear from any file (changes that
8098 added, removed or "modified" the string) will be listed. This search can take a while and
8099 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8100 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8103 print "</dl>\n";
8104 git_footer_html();
8107 sub git_shortlog {
8108 git_log_generic('shortlog', \&git_shortlog_body,
8109 $hash, $hash_parent);
8112 ## ......................................................................
8113 ## feeds (RSS, Atom; OPML)
8115 sub git_feed {
8116 my $format = shift || 'atom';
8117 my $have_blame = gitweb_check_feature('blame');
8119 # Atom: http://www.atomenabled.org/developers/syndication/
8120 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8121 if ($format ne 'rss' && $format ne 'atom') {
8122 die_error(400, "Unknown web feed format");
8125 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8126 my $head = $hash || 'HEAD';
8127 my @commitlist = parse_commits($head, 150, 0, $file_name);
8129 my %latest_commit;
8130 my %latest_date;
8131 my $content_type = "application/$format+xml";
8132 if (defined $cgi->http('HTTP_ACCEPT') &&
8133 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8134 # browser (feed reader) prefers text/xml
8135 $content_type = 'text/xml';
8137 if (defined($commitlist[0])) {
8138 %latest_commit = %{$commitlist[0]};
8139 my $latest_epoch = $latest_commit{'committer_epoch'};
8140 exit_if_unmodified_since($latest_epoch);
8141 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8143 print $cgi->header(
8144 -type => $content_type,
8145 -charset => 'utf-8',
8146 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8147 -status => '200 OK');
8149 # Optimization: skip generating the body if client asks only
8150 # for Last-Modified date.
8151 return if ($cgi->request_method() eq 'HEAD');
8153 # header variables
8154 my $title = "$site_name - $project/$action";
8155 my $feed_type = 'log';
8156 if (defined $hash) {
8157 $title .= " - '$hash'";
8158 $feed_type = 'branch log';
8159 if (defined $file_name) {
8160 $title .= " :: $file_name";
8161 $feed_type = 'history';
8163 } elsif (defined $file_name) {
8164 $title .= " - $file_name";
8165 $feed_type = 'history';
8167 $title .= " $feed_type";
8168 $title = esc_html($title);
8169 my $descr = git_get_project_description($project);
8170 if (defined $descr) {
8171 $descr = esc_html($descr);
8172 } else {
8173 $descr = "$project " .
8174 ($format eq 'rss' ? 'RSS' : 'Atom') .
8175 " feed";
8177 my $owner = git_get_project_owner($project);
8178 $owner = esc_html($owner);
8180 #header
8181 my $alt_url;
8182 if (defined $file_name) {
8183 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8184 } elsif (defined $hash) {
8185 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8186 } else {
8187 $alt_url = href(-full=>1, action=>"summary");
8189 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8190 if ($format eq 'rss') {
8191 print <<XML;
8192 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8193 <channel>
8195 print "<title>$title</title>\n" .
8196 "<link>$alt_url</link>\n" .
8197 "<description>$descr</description>\n" .
8198 "<language>en</language>\n" .
8199 # project owner is responsible for 'editorial' content
8200 "<managingEditor>$owner</managingEditor>\n";
8201 if (defined $logo || defined $favicon) {
8202 # prefer the logo to the favicon, since RSS
8203 # doesn't allow both
8204 my $img = esc_url($logo || $favicon);
8205 print "<image>\n" .
8206 "<url>$img</url>\n" .
8207 "<title>$title</title>\n" .
8208 "<link>$alt_url</link>\n" .
8209 "</image>\n";
8211 if (%latest_date) {
8212 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8213 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8215 print "<generator>gitweb v.$version/$git_version</generator>\n";
8216 } elsif ($format eq 'atom') {
8217 print <<XML;
8218 <feed xmlns="http://www.w3.org/2005/Atom">
8220 print "<title>$title</title>\n" .
8221 "<subtitle>$descr</subtitle>\n" .
8222 '<link rel="alternate" type="text/html" href="' .
8223 $alt_url . '" />' . "\n" .
8224 '<link rel="self" type="' . $content_type . '" href="' .
8225 $cgi->self_url() . '" />' . "\n" .
8226 "<id>" . href(-full=>1) . "</id>\n" .
8227 # use project owner for feed author
8228 "<author><name>$owner</name></author>\n";
8229 if (defined $favicon) {
8230 print "<icon>" . esc_url($favicon) . "</icon>\n";
8232 if (defined $logo) {
8233 # not twice as wide as tall: 72 x 27 pixels
8234 print "<logo>" . esc_url($logo) . "</logo>\n";
8236 if (! %latest_date) {
8237 # dummy date to keep the feed valid until commits trickle in:
8238 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8239 } else {
8240 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8242 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8245 # contents
8246 for (my $i = 0; $i <= $#commitlist; $i++) {
8247 my %co = %{$commitlist[$i]};
8248 my $commit = $co{'id'};
8249 # we read 150, we always show 30 and the ones more recent than 48 hours
8250 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8251 last;
8253 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8255 # get list of changed files
8256 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8257 $co{'parent'} || "--root",
8258 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8259 or next;
8260 my @difftree = map { chomp; $_ } <$fd>;
8261 close $fd
8262 or next;
8264 # print element (entry, item)
8265 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8266 if ($format eq 'rss') {
8267 print "<item>\n" .
8268 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8269 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8270 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8271 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8272 "<link>$co_url</link>\n" .
8273 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8274 "<content:encoded>" .
8275 "<![CDATA[\n";
8276 } elsif ($format eq 'atom') {
8277 print "<entry>\n" .
8278 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8279 "<updated>$cd{'iso-8601'}</updated>\n" .
8280 "<author>\n" .
8281 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8282 if ($co{'author_email'}) {
8283 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8285 print "</author>\n" .
8286 # use committer for contributor
8287 "<contributor>\n" .
8288 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8289 if ($co{'committer_email'}) {
8290 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8292 print "</contributor>\n" .
8293 "<published>$cd{'iso-8601'}</published>\n" .
8294 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8295 "<id>$co_url</id>\n" .
8296 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8297 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8299 my $comment = $co{'comment'};
8300 print "<pre>\n";
8301 foreach my $line (@$comment) {
8302 $line = esc_html($line);
8303 print "$line\n";
8305 print "</pre><ul>\n";
8306 foreach my $difftree_line (@difftree) {
8307 my %difftree = parse_difftree_raw_line($difftree_line);
8308 next if !$difftree{'from_id'};
8310 my $file = $difftree{'file'} || $difftree{'to_file'};
8312 print "<li>" .
8313 "[" .
8314 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8315 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8316 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8317 file_name=>$file, file_parent=>$difftree{'from_file'}),
8318 -title => "diff"}, 'D');
8319 if ($have_blame) {
8320 print $cgi->a({-href => href(-full=>1, action=>"blame",
8321 file_name=>$file, hash_base=>$commit),
8322 -title => "blame"}, 'B');
8324 # if this is not a feed of a file history
8325 if (!defined $file_name || $file_name ne $file) {
8326 print $cgi->a({-href => href(-full=>1, action=>"history",
8327 file_name=>$file, hash=>$commit),
8328 -title => "history"}, 'H');
8330 $file = esc_path($file);
8331 print "] ".
8332 "$file</li>\n";
8334 if ($format eq 'rss') {
8335 print "</ul>]]>\n" .
8336 "</content:encoded>\n" .
8337 "</item>\n";
8338 } elsif ($format eq 'atom') {
8339 print "</ul>\n</div>\n" .
8340 "</content>\n" .
8341 "</entry>\n";
8345 # end of feed
8346 if ($format eq 'rss') {
8347 print "</channel>\n</rss>\n";
8348 } elsif ($format eq 'atom') {
8349 print "</feed>\n";
8353 sub git_rss {
8354 git_feed('rss');
8357 sub git_atom {
8358 git_feed('atom');
8361 sub git_opml {
8362 my @list = git_get_projects_list($project_filter, $strict_export);
8363 if (!@list) {
8364 die_error(404, "No projects found");
8367 print $cgi->header(
8368 -type => 'text/xml',
8369 -charset => 'utf-8',
8370 -content_disposition => 'inline; filename="opml.xml"');
8372 my $title = esc_html($site_name);
8373 my $filter = " within subdirectory ";
8374 if (defined $project_filter) {
8375 $filter .= esc_html($project_filter);
8376 } else {
8377 $filter = "";
8379 print <<XML;
8380 <?xml version="1.0" encoding="utf-8"?>
8381 <opml version="1.0">
8382 <head>
8383 <title>$title OPML Export$filter</title>
8384 </head>
8385 <body>
8386 <outline text="git RSS feeds">
8389 foreach my $pr (@list) {
8390 my %proj = %$pr;
8391 my $head = git_get_head_hash($proj{'path'});
8392 if (!defined $head) {
8393 next;
8395 $git_dir = "$projectroot/$proj{'path'}";
8396 my %co = parse_commit($head);
8397 if (!%co) {
8398 next;
8401 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8402 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8403 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8404 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8406 print <<XML;
8407 </outline>
8408 </body>
8409 </opml>