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