Merge commit 'refs/top-bases/t/config/auto-fcgi' into t/config/auto-fcgi
[git/gitweb.git] / gitweb / gitweb.perl
bloba7159af59ae5ae62766ae4f64561c9c5e266150b
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use 5.008;
11 use strict;
12 use warnings;
13 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
16 use Encode;
17 use Fcntl ':mode';
18 use File::Find qw();
19 use File::Basename qw(basename);
20 use Time::HiRes qw(gettimeofday tv_interval);
21 binmode STDOUT, ':utf8';
23 if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
24 eval 'sub CGI::multi_param { CGI::param(@_) }'
27 our $t0 = [ gettimeofday() ];
28 our $number_of_git_cmds = 0;
30 BEGIN {
31 CGI->compile() if $ENV{'MOD_PERL'};
34 our $version = "++GIT_VERSION++";
36 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
37 sub evaluate_uri {
38 our $cgi;
40 our $my_url = $cgi->url();
41 our $my_uri = $cgi->url(-absolute => 1);
43 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
44 # needed and used only for URLs with nonempty PATH_INFO
45 our $base_url = $my_url;
47 # When the script is used as DirectoryIndex, the URL does not contain the name
48 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
49 # have to do it ourselves. We make $path_info global because it's also used
50 # later on.
52 # Another issue with the script being the DirectoryIndex is that the resulting
53 # $my_url data is not the full script URL: this is good, because we want
54 # generated links to keep implying the script name if it wasn't explicitly
55 # indicated in the URL we're handling, but it means that $my_url cannot be used
56 # as base URL.
57 # Therefore, if we needed to strip PATH_INFO, then we know that we have
58 # to build the base URL ourselves:
59 our $path_info = decode_utf8($ENV{"PATH_INFO"});
60 if ($path_info) {
61 # $path_info has already been URL-decoded by the web server, but
62 # $my_url and $my_uri have not. URL-decode them so we can properly
63 # strip $path_info.
64 $my_url = unescape($my_url);
65 $my_uri = unescape($my_uri);
66 if ($my_url =~ s,\Q$path_info\E$,, &&
67 $my_uri =~ s,\Q$path_info\E$,, &&
68 defined $ENV{'SCRIPT_NAME'}) {
69 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
73 # target of the home link on top of all pages
74 our $home_link = $my_uri || "/";
77 # core git executable to use
78 # this can just be "git" if your webserver has a sensible PATH
79 our $GIT = "++GIT_BINDIR++/git";
81 # absolute fs-path which will be prepended to the project path
82 #our $projectroot = "/pub/scm";
83 our $projectroot = "++GITWEB_PROJECTROOT++";
85 # fs traversing limit for getting project list
86 # the number is relative to the projectroot
87 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
89 # string of the home link on top of all pages
90 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
92 # extra breadcrumbs preceding the home link
93 our @extra_breadcrumbs = ();
95 # name of your site or organization to appear in page titles
96 # replace this with something more descriptive for clearer bookmarks
97 our $site_name = "++GITWEB_SITENAME++"
98 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
100 # html snippet to include in the <head> section of each page
101 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
102 # filename of html text to include at top of each page
103 our $site_header = "++GITWEB_SITE_HEADER++";
104 # html text to include at home page
105 our $home_text = "++GITWEB_HOMETEXT++";
106 # filename of html text to include at bottom of each page
107 our $site_footer = "++GITWEB_SITE_FOOTER++";
109 # URI of stylesheets
110 our @stylesheets = ("++GITWEB_CSS++");
111 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
112 our $stylesheet = undef;
113 # URI of GIT logo (72x27 size)
114 our $logo = "++GITWEB_LOGO++";
115 # URI of GIT favicon, assumed to be image/png type
116 our $favicon = "++GITWEB_FAVICON++";
117 # URI of gitweb.js (JavaScript code for gitweb)
118 our $javascript = "++GITWEB_JS++";
120 # URI and label (title) of GIT logo link
121 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
122 #our $logo_label = "git documentation";
123 our $logo_url = "http://git-scm.com/";
124 our $logo_label = "git homepage";
126 # source of projects list
127 our $projects_list = "++GITWEB_LIST++";
129 # the width (in characters) of the projects list "Description" column
130 our $projects_list_description_width = 25;
132 # group projects by category on the projects list
133 # (enabled if this variable evaluates to true)
134 our $projects_list_group_categories = 0;
136 # default category if none specified
137 # (leave the empty string for no category)
138 our $project_list_default_category = "";
140 # default order of projects list
141 # valid values are none, project, descr, owner, and age
142 our $default_projects_order = "project";
144 # show repository only if this file exists
145 # (only effective if this variable evaluates to true)
146 our $export_ok = "++GITWEB_EXPORT_OK++";
148 # don't generate age column on the projects list page
149 our $omit_age_column = 0;
151 # don't generate information about owners of repositories
152 our $omit_owner=0;
154 # show repository only if this subroutine returns true
155 # when given the path to the project, for example:
156 # sub { return -e "$_[0]/git-daemon-export-ok"; }
157 our $export_auth_hook = undef;
159 # only allow viewing of repositories also shown on the overview page
160 our $strict_export = "++GITWEB_STRICT_EXPORT++";
162 # list of git base URLs used for URL to where fetch project from,
163 # i.e. full URL is "$git_base_url/$project"
164 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
166 # default blob_plain mimetype and default charset for text/plain blob
167 our $default_blob_plain_mimetype = 'text/plain';
168 our $default_text_plain_charset = undef;
170 # file to use for guessing MIME types before trying /etc/mime.types
171 # (relative to the current git repository)
172 our $mimetypes_file = undef;
174 # assume this charset if line contains non-UTF-8 characters;
175 # it should be valid encoding (see Encoding::Supported(3pm) for list),
176 # for which encoding all byte sequences are valid, for example
177 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
178 # could be even 'utf-8' for the old behavior)
179 our $fallback_encoding = 'latin1';
181 # rename detection options for git-diff and git-diff-tree
182 # - default is '-M', with the cost proportional to
183 # (number of removed files) * (number of new files).
184 # - more costly is '-C' (which implies '-M'), with the cost proportional to
185 # (number of changed files + number of removed files) * (number of new files)
186 # - even more costly is '-C', '--find-copies-harder' with cost
187 # (number of files in the original tree) * (number of new files)
188 # - one might want to include '-B' option, e.g. '-B', '-M'
189 our @diff_opts = ('-M'); # taken from git_commit
191 # Disables features that would allow repository owners to inject script into
192 # the gitweb domain.
193 our $prevent_xss = 0;
195 # Path to the highlight executable to use (must be the one from
196 # http://www.andre-simon.de due to assumptions about parameters and output).
197 # Useful if highlight is not installed on your webserver's PATH.
198 # [Default: highlight]
199 our $highlight_bin = "++HIGHLIGHT_BIN++";
201 # information about snapshot formats that gitweb is capable of serving
202 our %known_snapshot_formats = (
203 # name => {
204 # 'display' => display name,
205 # 'type' => mime type,
206 # 'suffix' => filename suffix,
207 # 'format' => --format for git-archive,
208 # 'compressor' => [compressor command and arguments]
209 # (array reference, optional)
210 # 'disabled' => boolean (optional)}
212 'tgz' => {
213 'display' => 'tar.gz',
214 'type' => 'application/x-gzip',
215 'suffix' => '.tar.gz',
216 'format' => 'tar',
217 'compressor' => ['gzip', '-n']},
219 'tbz2' => {
220 'display' => 'tar.bz2',
221 'type' => 'application/x-bzip2',
222 'suffix' => '.tar.bz2',
223 'format' => 'tar',
224 'compressor' => ['bzip2']},
226 'txz' => {
227 'display' => 'tar.xz',
228 'type' => 'application/x-xz',
229 'suffix' => '.tar.xz',
230 'format' => 'tar',
231 'compressor' => ['xz'],
232 'disabled' => 1},
234 'zip' => {
235 'display' => 'zip',
236 'type' => 'application/x-zip',
237 'suffix' => '.zip',
238 'format' => 'zip'},
241 # Aliases so we understand old gitweb.snapshot values in repository
242 # configuration.
243 our %known_snapshot_format_aliases = (
244 'gzip' => 'tgz',
245 'bzip2' => 'tbz2',
246 'xz' => 'txz',
248 # backward compatibility: legacy gitweb config support
249 'x-gzip' => undef, 'gz' => undef,
250 'x-bzip2' => undef, 'bz2' => undef,
251 'x-zip' => undef, '' => undef,
254 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
255 # are changed, it may be appropriate to change these values too via
256 # $GITWEB_CONFIG.
257 our %avatar_size = (
258 'default' => 16,
259 'double' => 32
262 # Used to set the maximum load that we will still respond to gitweb queries.
263 # If server load exceed this value then return "503 server busy" error.
264 # If gitweb cannot determined server load, it is taken to be 0.
265 # Leave it undefined (or set to 'undef') to turn off load checking.
266 our $maxload = 300;
268 # configuration for 'highlight' (http://www.andre-simon.de/)
269 # match by basename
270 our %highlight_basename = (
271 #'Program' => 'py',
272 #'Library' => 'py',
273 'SConstruct' => 'py', # SCons equivalent of Makefile
274 'Makefile' => 'make',
276 # match by extension
277 our %highlight_ext = (
278 # main extensions, defining name of syntax;
279 # see files in /usr/share/highlight/langDefs/ directory
280 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
281 # alternate extensions, see /etc/highlight/filetypes.conf
282 (map { $_ => 'c' } qw(c h)),
283 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
284 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
285 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
286 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
287 (map { $_ => 'make'} qw(make mak mk)),
288 (map { $_ => 'xml' } qw(xml xhtml html htm)),
291 # You define site-wide feature defaults here; override them with
292 # $GITWEB_CONFIG as necessary.
293 our %feature = (
294 # feature => {
295 # 'sub' => feature-sub (subroutine),
296 # 'override' => allow-override (boolean),
297 # 'default' => [ default options...] (array reference)}
299 # if feature is overridable (it means that allow-override has true value),
300 # then feature-sub will be called with default options as parameters;
301 # return value of feature-sub indicates if to enable specified feature
303 # if there is no 'sub' key (no feature-sub), then feature cannot be
304 # overridden
306 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
307 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
308 # is enabled
310 # Enable the 'blame' blob view, showing the last commit that modified
311 # each line in the file. This can be very CPU-intensive.
313 # To enable system wide have in $GITWEB_CONFIG
314 # $feature{'blame'}{'default'} = [1];
315 # To have project specific config enable override in $GITWEB_CONFIG
316 # $feature{'blame'}{'override'} = 1;
317 # and in project config gitweb.blame = 0|1;
318 'blame' => {
319 'sub' => sub { feature_bool('blame', @_) },
320 'override' => 0,
321 'default' => [0]},
323 # Enable the 'snapshot' link, providing a compressed archive of any
324 # tree. This can potentially generate high traffic if you have large
325 # project.
327 # Value is a list of formats defined in %known_snapshot_formats that
328 # you wish to offer.
329 # To disable system wide have in $GITWEB_CONFIG
330 # $feature{'snapshot'}{'default'} = [];
331 # To have project specific config enable override in $GITWEB_CONFIG
332 # $feature{'snapshot'}{'override'} = 1;
333 # and in project config, a comma-separated list of formats or "none"
334 # to disable. Example: gitweb.snapshot = tbz2,zip;
335 'snapshot' => {
336 'sub' => \&feature_snapshot,
337 'override' => 0,
338 'default' => ['tgz']},
340 # Enable text search, which will list the commits which match author,
341 # committer or commit text to a given string. Enabled by default.
342 # Project specific override is not supported.
344 # Note that this controls all search features, which means that if
345 # it is disabled, then 'grep' and 'pickaxe' search would also be
346 # disabled.
347 'search' => {
348 'override' => 0,
349 'default' => [1]},
351 # Enable grep search, which will list the files in currently selected
352 # tree containing the given string. Enabled by default. This can be
353 # potentially CPU-intensive, of course.
354 # Note that you need to have 'search' feature enabled too.
356 # To enable system wide have in $GITWEB_CONFIG
357 # $feature{'grep'}{'default'} = [1];
358 # To have project specific config enable override in $GITWEB_CONFIG
359 # $feature{'grep'}{'override'} = 1;
360 # and in project config gitweb.grep = 0|1;
361 'grep' => {
362 'sub' => sub { feature_bool('grep', @_) },
363 'override' => 0,
364 'default' => [1]},
366 # Enable the pickaxe search, which will list the commits that modified
367 # a given string in a file. This can be practical and quite faster
368 # alternative to 'blame', but still potentially CPU-intensive.
369 # Note that you need to have 'search' feature enabled too.
371 # To enable system wide have in $GITWEB_CONFIG
372 # $feature{'pickaxe'}{'default'} = [1];
373 # To have project specific config enable override in $GITWEB_CONFIG
374 # $feature{'pickaxe'}{'override'} = 1;
375 # and in project config gitweb.pickaxe = 0|1;
376 'pickaxe' => {
377 'sub' => sub { feature_bool('pickaxe', @_) },
378 'override' => 0,
379 'default' => [1]},
381 # Enable showing size of blobs in a 'tree' view, in a separate
382 # column, similar to what 'ls -l' does. This cost a bit of IO.
384 # To disable system wide have in $GITWEB_CONFIG
385 # $feature{'show-sizes'}{'default'} = [0];
386 # To have project specific config enable override in $GITWEB_CONFIG
387 # $feature{'show-sizes'}{'override'} = 1;
388 # and in project config gitweb.showsizes = 0|1;
389 'show-sizes' => {
390 'sub' => sub { feature_bool('showsizes', @_) },
391 'override' => 0,
392 'default' => [1]},
394 # Make gitweb use an alternative format of the URLs which can be
395 # more readable and natural-looking: project name is embedded
396 # directly in the path and the query string contains other
397 # auxiliary information. All gitweb installations recognize
398 # URL in either format; this configures in which formats gitweb
399 # generates links.
401 # To enable system wide have in $GITWEB_CONFIG
402 # $feature{'pathinfo'}{'default'} = [1];
403 # Project specific override is not supported.
405 # Note that you will need to change the default location of CSS,
406 # favicon, logo and possibly other files to an absolute URL. Also,
407 # if gitweb.cgi serves as your indexfile, you will need to force
408 # $my_uri to contain the script name in your $GITWEB_CONFIG.
410 # For FCGI use, note that $my_uri and $home_link are recomputed at the
411 # beginning of every request. If they need to be forced for pathinfo
412 # mode to work properly (likely) then $per_request_config must not be
413 # false (it defaults to true). To avoid the overhead of running the
414 # config on every FCGI request, set $per_request_config to a CODE ref
415 # that forces the needed values.
416 'pathinfo' => {
417 'override' => 0,
418 'default' => [0]},
420 # Make gitweb consider projects in project root subdirectories
421 # to be forks of existing projects. Given project $projname.git,
422 # projects matching $projname/*.git will not be shown in the main
423 # projects list, instead a '+' mark will be added to $projname
424 # there and a 'forks' view will be enabled for the project, listing
425 # all the forks. If project list is taken from a file, forks have
426 # to be listed after the main project.
428 # To enable system wide have in $GITWEB_CONFIG
429 # $feature{'forks'}{'default'} = [1];
430 # Project specific override is not supported.
431 'forks' => {
432 'override' => 0,
433 'default' => [0]},
435 # Insert custom links to the action bar of all project pages.
436 # This enables you mainly to link to third-party scripts integrating
437 # into gitweb; e.g. git-browser for graphical history representation
438 # or custom web-based repository administration interface.
440 # The 'default' value consists of a list of triplets in the form
441 # (label, link, position) where position is the label after which
442 # to insert the link and link is a format string where %n expands
443 # to the project name, %f to the project path within the filesystem,
444 # %h to the current hash (h gitweb parameter) and %b to the current
445 # hash base (hb gitweb parameter); %% expands to %.
447 # To enable system wide have in $GITWEB_CONFIG e.g.
448 # $feature{'actions'}{'default'} = [('graphiclog',
449 # '/git-browser/by-commit.html?r=%n', 'summary')];
450 # Project specific override is not supported.
451 'actions' => {
452 'override' => 0,
453 'default' => []},
455 # Allow gitweb scan project content tags of project repository,
456 # and display the popular Web 2.0-ish "tag cloud" near the projects
457 # list. Note that this is something COMPLETELY different from the
458 # normal Git tags.
460 # gitweb by itself can show existing tags, but it does not handle
461 # tagging itself; you need to do it externally, outside gitweb.
462 # The format is described in git_get_project_ctags() subroutine.
463 # You may want to install the HTML::TagCloud Perl module to get
464 # a pretty tag cloud instead of just a list of tags.
466 # To enable system wide have in $GITWEB_CONFIG
467 # $feature{'ctags'}{'default'} = [1];
468 # Project specific override is not supported.
470 # In the future whether ctags editing is enabled might depend
471 # on the value, but using 1 should always mean no editing of ctags.
472 'ctags' => {
473 'override' => 0,
474 'default' => [0]},
476 # The maximum number of patches in a patchset generated in patch
477 # view. Set this to 0 or undef to disable patch view, or to a
478 # negative number to remove any limit.
480 # To disable system wide have in $GITWEB_CONFIG
481 # $feature{'patches'}{'default'} = [0];
482 # To have project specific config enable override in $GITWEB_CONFIG
483 # $feature{'patches'}{'override'} = 1;
484 # and in project config gitweb.patches = 0|n;
485 # where n is the maximum number of patches allowed in a patchset.
486 'patches' => {
487 'sub' => \&feature_patches,
488 'override' => 0,
489 'default' => [16]},
491 # Avatar support. When this feature is enabled, views such as
492 # shortlog or commit will display an avatar associated with
493 # the email of the committer(s) and/or author(s).
495 # Currently available providers are gravatar and picon.
496 # If an unknown provider is specified, the feature is disabled.
498 # Gravatar depends on Digest::MD5.
499 # Picon currently relies on the indiana.edu database.
501 # To enable system wide have in $GITWEB_CONFIG
502 # $feature{'avatar'}{'default'} = ['<provider>'];
503 # where <provider> is either gravatar or picon.
504 # To have project specific config enable override in $GITWEB_CONFIG
505 # $feature{'avatar'}{'override'} = 1;
506 # and in project config gitweb.avatar = <provider>;
507 'avatar' => {
508 'sub' => \&feature_avatar,
509 'override' => 0,
510 'default' => ['']},
512 # Enable displaying how much time and how many git commands
513 # it took to generate and display page. Disabled by default.
514 # Project specific override is not supported.
515 'timed' => {
516 'override' => 0,
517 'default' => [0]},
519 # Enable turning some links into links to actions which require
520 # JavaScript to run (like 'blame_incremental'). Not enabled by
521 # default. Project specific override is currently not supported.
522 'javascript-actions' => {
523 'override' => 0,
524 'default' => [0]},
526 # Enable and configure ability to change common timezone for dates
527 # in gitweb output via JavaScript. Enabled by default.
528 # Project specific override is not supported.
529 'javascript-timezone' => {
530 'override' => 0,
531 'default' => [
532 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
533 # or undef to turn off this feature
534 'gitweb_tz', # name of cookie where to store selected timezone
535 'datetime', # CSS class used to mark up dates for manipulation
538 # Syntax highlighting support. This is based on Daniel Svensson's
539 # and Sham Chukoury's work in gitweb-xmms2.git.
540 # It requires the 'highlight' program present in $PATH,
541 # and therefore is disabled by default.
543 # To enable system wide have in $GITWEB_CONFIG
544 # $feature{'highlight'}{'default'} = [1];
546 'highlight' => {
547 'sub' => sub { feature_bool('highlight', @_) },
548 'override' => 0,
549 'default' => [0]},
551 # Enable displaying of remote heads in the heads list
553 # To enable system wide have in $GITWEB_CONFIG
554 # $feature{'remote_heads'}{'default'} = [1];
555 # To have project specific config enable override in $GITWEB_CONFIG
556 # $feature{'remote_heads'}{'override'} = 1;
557 # and in project config gitweb.remoteheads = 0|1;
558 'remote_heads' => {
559 'sub' => sub { feature_bool('remote_heads', @_) },
560 'override' => 0,
561 'default' => [0]},
563 # Enable showing branches under other refs in addition to heads
565 # To set system wide extra branch refs have in $GITWEB_CONFIG
566 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
567 # To have project specific config enable override in $GITWEB_CONFIG
568 # $feature{'extra-branch-refs'}{'override'} = 1;
569 # and in project config gitweb.extrabranchrefs = dirs of choice
570 # Every directory is separated with whitespace.
572 'extra-branch-refs' => {
573 'sub' => \&feature_extra_branch_refs,
574 'override' => 0,
575 'default' => []},
578 sub gitweb_get_feature {
579 my ($name) = @_;
580 return unless exists $feature{$name};
581 my ($sub, $override, @defaults) = (
582 $feature{$name}{'sub'},
583 $feature{$name}{'override'},
584 @{$feature{$name}{'default'}});
585 # project specific override is possible only if we have project
586 our $git_dir; # global variable, declared later
587 if (!$override || !defined $git_dir) {
588 return @defaults;
590 if (!defined $sub) {
591 warn "feature $name is not overridable";
592 return @defaults;
594 return $sub->(@defaults);
597 # A wrapper to check if a given feature is enabled.
598 # With this, you can say
600 # my $bool_feat = gitweb_check_feature('bool_feat');
601 # gitweb_check_feature('bool_feat') or somecode;
603 # instead of
605 # my ($bool_feat) = gitweb_get_feature('bool_feat');
606 # (gitweb_get_feature('bool_feat'))[0] or somecode;
608 sub gitweb_check_feature {
609 return (gitweb_get_feature(@_))[0];
613 sub feature_bool {
614 my $key = shift;
615 my ($val) = git_get_project_config($key, '--bool');
617 if (!defined $val) {
618 return ($_[0]);
619 } elsif ($val eq 'true') {
620 return (1);
621 } elsif ($val eq 'false') {
622 return (0);
626 sub feature_snapshot {
627 my (@fmts) = @_;
629 my ($val) = git_get_project_config('snapshot');
631 if ($val) {
632 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
635 return @fmts;
638 sub feature_patches {
639 my @val = (git_get_project_config('patches', '--int'));
641 if (@val) {
642 return @val;
645 return ($_[0]);
648 sub feature_avatar {
649 my @val = (git_get_project_config('avatar'));
651 return @val ? @val : @_;
654 sub feature_extra_branch_refs {
655 my (@branch_refs) = @_;
656 my $values = git_get_project_config('extrabranchrefs');
658 if ($values) {
659 $values = config_to_multi ($values);
660 @branch_refs = ();
661 foreach my $value (@{$values}) {
662 push @branch_refs, split /\s+/, $value;
666 return @branch_refs;
669 # checking HEAD file with -e is fragile if the repository was
670 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
671 # and then pruned.
672 sub check_head_link {
673 my ($dir) = @_;
674 my $headfile = "$dir/HEAD";
675 return ((-e $headfile) ||
676 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
679 sub check_export_ok {
680 my ($dir) = @_;
681 return (check_head_link($dir) &&
682 (!$export_ok || -e "$dir/$export_ok") &&
683 (!$export_auth_hook || $export_auth_hook->($dir)));
686 # process alternate names for backward compatibility
687 # filter out unsupported (unknown) snapshot formats
688 sub filter_snapshot_fmts {
689 my @fmts = @_;
691 @fmts = map {
692 exists $known_snapshot_format_aliases{$_} ?
693 $known_snapshot_format_aliases{$_} : $_} @fmts;
694 @fmts = grep {
695 exists $known_snapshot_formats{$_} &&
696 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
699 sub filter_and_validate_refs {
700 my @refs = @_;
701 my %unique_refs = ();
703 foreach my $ref (@refs) {
704 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
705 # 'heads' are added implicitly in get_branch_refs().
706 $unique_refs{$ref} = 1 if ($ref ne 'heads');
708 return sort keys %unique_refs;
711 # If it is set to code reference, it is code that it is to be run once per
712 # request, allowing updating configurations that change with each request,
713 # while running other code in config file only once.
715 # Otherwise, if it is false then gitweb would process config file only once;
716 # if it is true then gitweb config would be run for each request.
717 our $per_request_config = 1;
719 # If true and fileno STDIN is 0 and getsockname succeeds, then FCGI mode will
720 # be activated automatically as though the --fcgi option was given.
721 our $auto_fcgi = 0;
723 # read and parse gitweb config file given by its parameter.
724 # returns true on success, false on recoverable error, allowing
725 # to chain this subroutine, using first file that exists.
726 # dies on errors during parsing config file, as it is unrecoverable.
727 sub read_config_file {
728 my $filename = shift;
729 return unless defined $filename;
730 # die if there are errors parsing config file
731 if (-e $filename) {
732 do $filename;
733 die $@ if $@;
734 return 1;
736 return;
739 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
740 sub evaluate_gitweb_config {
741 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
742 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
743 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
745 # Protect against duplications of file names, to not read config twice.
746 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
747 # there possibility of duplication of filename there doesn't matter.
748 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
749 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
751 # Common system-wide settings for convenience.
752 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
753 read_config_file($GITWEB_CONFIG_COMMON);
755 # Use first config file that exists. This means use the per-instance
756 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
757 read_config_file($GITWEB_CONFIG) and return;
758 read_config_file($GITWEB_CONFIG_SYSTEM);
761 # Get loadavg of system, to compare against $maxload.
762 # Currently it requires '/proc/loadavg' present to get loadavg;
763 # if it is not present it returns 0, which means no load checking.
764 sub get_loadavg {
765 if( -e '/proc/loadavg' ){
766 open my $fd, '<', '/proc/loadavg'
767 or return 0;
768 my @load = split(/\s+/, scalar <$fd>);
769 close $fd;
771 # The first three columns measure CPU and IO utilization of the last one,
772 # five, and 10 minute periods. The fourth column shows the number of
773 # currently running processes and the total number of processes in the m/n
774 # format. The last column displays the last process ID used.
775 return $load[0] || 0;
777 # additional checks for load average should go here for things that don't export
778 # /proc/loadavg
780 return 0;
783 # version of the core git binary
784 our $git_version;
785 sub evaluate_git_version {
786 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
787 $number_of_git_cmds++;
790 sub check_loadavg {
791 if (defined $maxload && get_loadavg() > $maxload) {
792 die_error(503, "The load average on the server is too high");
796 # ======================================================================
797 # input validation and dispatch
799 # input parameters can be collected from a variety of sources (presently, CGI
800 # and PATH_INFO), so we define an %input_params hash that collects them all
801 # together during validation: this allows subsequent uses (e.g. href()) to be
802 # agnostic of the parameter origin
804 our %input_params = ();
806 # input parameters are stored with the long parameter name as key. This will
807 # also be used in the href subroutine to convert parameters to their CGI
808 # equivalent, and since the href() usage is the most frequent one, we store
809 # the name -> CGI key mapping here, instead of the reverse.
811 # XXX: Warning: If you touch this, check the search form for updating,
812 # too.
814 our @cgi_param_mapping = (
815 project => "p",
816 action => "a",
817 file_name => "f",
818 file_parent => "fp",
819 hash => "h",
820 hash_parent => "hp",
821 hash_base => "hb",
822 hash_parent_base => "hpb",
823 page => "pg",
824 order => "o",
825 searchtext => "s",
826 searchtype => "st",
827 snapshot_format => "sf",
828 extra_options => "opt",
829 search_use_regexp => "sr",
830 ctag => "by_tag",
831 diff_style => "ds",
832 project_filter => "pf",
833 # this must be last entry (for manipulation from JavaScript)
834 javascript => "js"
836 our %cgi_param_mapping = @cgi_param_mapping;
838 # we will also need to know the possible actions, for validation
839 our %actions = (
840 "blame" => \&git_blame,
841 "blame_incremental" => \&git_blame_incremental,
842 "blame_data" => \&git_blame_data,
843 "blobdiff" => \&git_blobdiff,
844 "blobdiff_plain" => \&git_blobdiff_plain,
845 "blob" => \&git_blob,
846 "blob_plain" => \&git_blob_plain,
847 "commitdiff" => \&git_commitdiff,
848 "commitdiff_plain" => \&git_commitdiff_plain,
849 "commit" => \&git_commit,
850 "forks" => \&git_forks,
851 "heads" => \&git_heads,
852 "history" => \&git_history,
853 "log" => \&git_log,
854 "patch" => \&git_patch,
855 "patches" => \&git_patches,
856 "remotes" => \&git_remotes,
857 "rss" => \&git_rss,
858 "atom" => \&git_atom,
859 "search" => \&git_search,
860 "search_help" => \&git_search_help,
861 "shortlog" => \&git_shortlog,
862 "summary" => \&git_summary,
863 "tag" => \&git_tag,
864 "tags" => \&git_tags,
865 "tree" => \&git_tree,
866 "snapshot" => \&git_snapshot,
867 "object" => \&git_object,
868 # those below don't need $project
869 "opml" => \&git_opml,
870 "project_list" => \&git_project_list,
871 "project_index" => \&git_project_index,
874 # finally, we have the hash of allowed extra_options for the commands that
875 # allow them
876 our %allowed_options = (
877 "--no-merges" => [ qw(rss atom log shortlog history) ],
880 # fill %input_params with the CGI parameters. All values except for 'opt'
881 # should be single values, but opt can be an array. We should probably
882 # build an array of parameters that can be multi-valued, but since for the time
883 # being it's only this one, we just single it out
884 sub evaluate_query_params {
885 our $cgi;
887 while (my ($name, $symbol) = each %cgi_param_mapping) {
888 if ($symbol eq 'opt') {
889 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
890 } else {
891 $input_params{$name} = decode_utf8($cgi->param($symbol));
896 # now read PATH_INFO and update the parameter list for missing parameters
897 sub evaluate_path_info {
898 return if defined $input_params{'project'};
899 return if !$path_info;
900 $path_info =~ s,^/+,,;
901 return if !$path_info;
903 # find which part of PATH_INFO is project
904 my $project = $path_info;
905 $project =~ s,/+$,,;
906 while ($project && !check_head_link("$projectroot/$project")) {
907 $project =~ s,/*[^/]*$,,;
909 return unless $project;
910 $input_params{'project'} = $project;
912 # do not change any parameters if an action is given using the query string
913 return if $input_params{'action'};
914 $path_info =~ s,^\Q$project\E/*,,;
916 # next, check if we have an action
917 my $action = $path_info;
918 $action =~ s,/.*$,,;
919 if (exists $actions{$action}) {
920 $path_info =~ s,^$action/*,,;
921 $input_params{'action'} = $action;
924 # list of actions that want hash_base instead of hash, but can have no
925 # pathname (f) parameter
926 my @wants_base = (
927 'tree',
928 'history',
931 # we want to catch, among others
932 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
933 my ($parentrefname, $parentpathname, $refname, $pathname) =
934 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
936 # first, analyze the 'current' part
937 if (defined $pathname) {
938 # we got "branch:filename" or "branch:dir/"
939 # we could use git_get_type(branch:pathname), but:
940 # - it needs $git_dir
941 # - it does a git() call
942 # - the convention of terminating directories with a slash
943 # makes it superfluous
944 # - embedding the action in the PATH_INFO would make it even
945 # more superfluous
946 $pathname =~ s,^/+,,;
947 if (!$pathname || substr($pathname, -1) eq "/") {
948 $input_params{'action'} ||= "tree";
949 $pathname =~ s,/$,,;
950 } else {
951 # the default action depends on whether we had parent info
952 # or not
953 if ($parentrefname) {
954 $input_params{'action'} ||= "blobdiff_plain";
955 } else {
956 $input_params{'action'} ||= "blob_plain";
959 $input_params{'hash_base'} ||= $refname;
960 $input_params{'file_name'} ||= $pathname;
961 } elsif (defined $refname) {
962 # we got "branch". In this case we have to choose if we have to
963 # set hash or hash_base.
965 # Most of the actions without a pathname only want hash to be
966 # set, except for the ones specified in @wants_base that want
967 # hash_base instead. It should also be noted that hand-crafted
968 # links having 'history' as an action and no pathname or hash
969 # set will fail, but that happens regardless of PATH_INFO.
970 if (defined $parentrefname) {
971 # if there is parent let the default be 'shortlog' action
972 # (for http://git.example.com/repo.git/A..B links); if there
973 # is no parent, dispatch will detect type of object and set
974 # action appropriately if required (if action is not set)
975 $input_params{'action'} ||= "shortlog";
977 if ($input_params{'action'} &&
978 grep { $_ eq $input_params{'action'} } @wants_base) {
979 $input_params{'hash_base'} ||= $refname;
980 } else {
981 $input_params{'hash'} ||= $refname;
985 # next, handle the 'parent' part, if present
986 if (defined $parentrefname) {
987 # a missing pathspec defaults to the 'current' filename, allowing e.g.
988 # someproject/blobdiff/oldrev..newrev:/filename
989 if ($parentpathname) {
990 $parentpathname =~ s,^/+,,;
991 $parentpathname =~ s,/$,,;
992 $input_params{'file_parent'} ||= $parentpathname;
993 } else {
994 $input_params{'file_parent'} ||= $input_params{'file_name'};
996 # we assume that hash_parent_base is wanted if a path was specified,
997 # or if the action wants hash_base instead of hash
998 if (defined $input_params{'file_parent'} ||
999 grep { $_ eq $input_params{'action'} } @wants_base) {
1000 $input_params{'hash_parent_base'} ||= $parentrefname;
1001 } else {
1002 $input_params{'hash_parent'} ||= $parentrefname;
1006 # for the snapshot action, we allow URLs in the form
1007 # $project/snapshot/$hash.ext
1008 # where .ext determines the snapshot and gets removed from the
1009 # passed $refname to provide the $hash.
1011 # To be able to tell that $refname includes the format extension, we
1012 # require the following two conditions to be satisfied:
1013 # - the hash input parameter MUST have been set from the $refname part
1014 # of the URL (i.e. they must be equal)
1015 # - the snapshot format MUST NOT have been defined already (e.g. from
1016 # CGI parameter sf)
1017 # It's also useless to try any matching unless $refname has a dot,
1018 # so we check for that too
1019 if (defined $input_params{'action'} &&
1020 $input_params{'action'} eq 'snapshot' &&
1021 defined $refname && index($refname, '.') != -1 &&
1022 $refname eq $input_params{'hash'} &&
1023 !defined $input_params{'snapshot_format'}) {
1024 # We loop over the known snapshot formats, checking for
1025 # extensions. Allowed extensions are both the defined suffix
1026 # (which includes the initial dot already) and the snapshot
1027 # format key itself, with a prepended dot
1028 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1029 my $hash = $refname;
1030 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1031 next;
1033 my $sfx = $1;
1034 # a valid suffix was found, so set the snapshot format
1035 # and reset the hash parameter
1036 $input_params{'snapshot_format'} = $fmt;
1037 $input_params{'hash'} = $hash;
1038 # we also set the format suffix to the one requested
1039 # in the URL: this way a request for e.g. .tgz returns
1040 # a .tgz instead of a .tar.gz
1041 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1042 last;
1047 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1048 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1049 $searchtext, $search_regexp, $project_filter);
1050 sub evaluate_and_validate_params {
1051 our $action = $input_params{'action'};
1052 if (defined $action) {
1053 if (!is_valid_action($action)) {
1054 die_error(400, "Invalid action parameter");
1058 # parameters which are pathnames
1059 our $project = $input_params{'project'};
1060 if (defined $project) {
1061 if (!is_valid_project($project)) {
1062 undef $project;
1063 die_error(404, "No such project");
1067 our $project_filter = $input_params{'project_filter'};
1068 if (defined $project_filter) {
1069 if (!is_valid_pathname($project_filter)) {
1070 die_error(404, "Invalid project_filter parameter");
1074 our $file_name = $input_params{'file_name'};
1075 if (defined $file_name) {
1076 if (!is_valid_pathname($file_name)) {
1077 die_error(400, "Invalid file parameter");
1081 our $file_parent = $input_params{'file_parent'};
1082 if (defined $file_parent) {
1083 if (!is_valid_pathname($file_parent)) {
1084 die_error(400, "Invalid file parent parameter");
1088 # parameters which are refnames
1089 our $hash = $input_params{'hash'};
1090 if (defined $hash) {
1091 if (!is_valid_refname($hash)) {
1092 die_error(400, "Invalid hash parameter");
1096 our $hash_parent = $input_params{'hash_parent'};
1097 if (defined $hash_parent) {
1098 if (!is_valid_refname($hash_parent)) {
1099 die_error(400, "Invalid hash parent parameter");
1103 our $hash_base = $input_params{'hash_base'};
1104 if (defined $hash_base) {
1105 if (!is_valid_refname($hash_base)) {
1106 die_error(400, "Invalid hash base parameter");
1110 our @extra_options = @{$input_params{'extra_options'}};
1111 # @extra_options is always defined, since it can only be (currently) set from
1112 # CGI, and $cgi->param() returns the empty array in array context if the param
1113 # is not set
1114 foreach my $opt (@extra_options) {
1115 if (not exists $allowed_options{$opt}) {
1116 die_error(400, "Invalid option parameter");
1118 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1119 die_error(400, "Invalid option parameter for this action");
1123 our $hash_parent_base = $input_params{'hash_parent_base'};
1124 if (defined $hash_parent_base) {
1125 if (!is_valid_refname($hash_parent_base)) {
1126 die_error(400, "Invalid hash parent base parameter");
1130 # other parameters
1131 our $page = $input_params{'page'};
1132 if (defined $page) {
1133 if ($page =~ m/[^0-9]/) {
1134 die_error(400, "Invalid page parameter");
1138 our $searchtype = $input_params{'searchtype'};
1139 if (defined $searchtype) {
1140 if ($searchtype =~ m/[^a-z]/) {
1141 die_error(400, "Invalid searchtype parameter");
1145 our $search_use_regexp = $input_params{'search_use_regexp'};
1147 our $searchtext = $input_params{'searchtext'};
1148 our $search_regexp = undef;
1149 if (defined $searchtext) {
1150 if (length($searchtext) < 2) {
1151 die_error(403, "At least two characters are required for search parameter");
1153 if ($search_use_regexp) {
1154 $search_regexp = $searchtext;
1155 if (!eval { qr/$search_regexp/; 1; }) {
1156 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1157 die_error(400, "Invalid search regexp '$search_regexp'",
1158 esc_html($error));
1160 } else {
1161 $search_regexp = quotemeta $searchtext;
1166 # path to the current git repository
1167 our $git_dir;
1168 sub evaluate_git_dir {
1169 our $git_dir = "$projectroot/$project" if $project;
1172 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1173 sub configure_gitweb_features {
1174 # list of supported snapshot formats
1175 our @snapshot_fmts = gitweb_get_feature('snapshot');
1176 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1178 # check that the avatar feature is set to a known provider name,
1179 # and for each provider check if the dependencies are satisfied.
1180 # if the provider name is invalid or the dependencies are not met,
1181 # reset $git_avatar to the empty string.
1182 our ($git_avatar) = gitweb_get_feature('avatar');
1183 if ($git_avatar eq 'gravatar') {
1184 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1185 } elsif ($git_avatar eq 'picon') {
1186 # no dependencies
1187 } else {
1188 $git_avatar = '';
1191 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1192 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1195 sub get_branch_refs {
1196 return ('heads', @extra_branch_refs);
1199 # custom error handler: 'die <message>' is Internal Server Error
1200 sub handle_errors_html {
1201 my $msg = shift; # it is already HTML escaped
1203 # to avoid infinite loop where error occurs in die_error,
1204 # change handler to default handler, disabling handle_errors_html
1205 set_message("Error occurred when inside die_error:\n$msg");
1207 # you cannot jump out of die_error when called as error handler;
1208 # the subroutine set via CGI::Carp::set_message is called _after_
1209 # HTTP headers are already written, so it cannot write them itself
1210 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1212 set_message(\&handle_errors_html);
1214 # dispatch
1215 sub dispatch {
1216 if (!defined $action) {
1217 if (defined $hash) {
1218 $action = git_get_type($hash);
1219 $action or die_error(404, "Object does not exist");
1220 } elsif (defined $hash_base && defined $file_name) {
1221 $action = git_get_type("$hash_base:$file_name");
1222 $action or die_error(404, "File or directory does not exist");
1223 } elsif (defined $project) {
1224 $action = 'summary';
1225 } else {
1226 $action = 'project_list';
1229 if (!defined($actions{$action})) {
1230 die_error(400, "Unknown action");
1232 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1233 !$project) {
1234 die_error(400, "Project needed");
1236 $actions{$action}->();
1239 sub reset_timer {
1240 our $t0 = [ gettimeofday() ]
1241 if defined $t0;
1242 our $number_of_git_cmds = 0;
1245 our $first_request = 1;
1246 sub run_request {
1247 my ($old_uri, $old_hl);
1248 reset_timer();
1250 # Only allow GET and HEAD methods
1251 if (!$ENV{'REQUEST_METHOD'} || ($ENV{'REQUEST_METHOD'} ne 'GET' && $ENV{'REQUEST_METHOD'} ne 'HEAD')) {
1252 print <<EOT;
1253 Status: 405 Method Not Allowed
1254 Content-Type: text/plain
1255 Allow: GET,HEAD
1257 405 Method Not Allowed
1259 return;
1262 ($old_uri, $old_hl) = ($my_uri, $home_link) if $first_request;
1263 evaluate_uri();
1264 if ($first_request) {
1265 $my_uri = $old_uri if defined $old_uri && $old_uri ne '';
1266 $home_link = $old_hl if defined $old_hl && $old_hl ne '';
1268 if ($per_request_config) {
1269 if (ref($per_request_config) eq 'CODE') {
1270 $per_request_config->();
1271 } elsif (!$first_request) {
1272 evaluate_gitweb_config();
1275 check_loadavg();
1277 # $projectroot and $projects_list might be set in gitweb config file
1278 $projects_list ||= $projectroot;
1280 evaluate_query_params();
1281 evaluate_path_info();
1282 evaluate_and_validate_params();
1283 evaluate_git_dir();
1285 configure_gitweb_features();
1287 dispatch();
1290 our $is_last_request = sub { 1 };
1291 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1292 our $CGI = 'CGI';
1293 our $cgi;
1294 our $fcgi_mode = 0;
1295 sub configure_as_fcgi {
1296 return if $fcgi_mode;
1298 require CGI::Fast;
1299 our $CGI = 'CGI::Fast';
1301 $fcgi_mode = 1;
1302 $first_request = 0;
1303 my $request_number = 0;
1304 # let each child service 100 requests
1305 our $is_last_request = sub { ++$request_number > 100 };
1307 sub evaluate_argv {
1308 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1309 configure_as_fcgi()
1310 if $script_name =~ /\.fcgi$/
1311 or $auto_fcgi && defined fileno STDIN && fileno STDIN == 0 && getsockname(STDIN);
1313 return unless (@ARGV);
1315 require Getopt::Long;
1316 Getopt::Long::GetOptions(
1317 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1318 'nproc|n=i' => sub {
1319 my ($arg, $val) = @_;
1320 return unless eval { require FCGI::ProcManager; 1; };
1321 my $proc_manager = FCGI::ProcManager->new({
1322 n_processes => $val,
1324 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1325 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1326 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1331 sub run {
1332 evaluate_gitweb_config();
1333 evaluate_git_version();
1335 $first_request = 1;
1336 evaluate_argv();
1338 $pre_listen_hook->()
1339 if $pre_listen_hook;
1341 REQUEST:
1342 while ($cgi = $CGI->new()) {
1343 $pre_dispatch_hook->()
1344 if $pre_dispatch_hook;
1346 run_request();
1348 $post_dispatch_hook->()
1349 if $post_dispatch_hook;
1350 $first_request = 0;
1352 last REQUEST if ($is_last_request->());
1355 DONE_GITWEB:
1359 run();
1361 if (defined caller) {
1362 # wrapped in a subroutine processing requests,
1363 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1364 return;
1365 } else {
1366 # pure CGI script, serving single request
1367 exit;
1370 ## ======================================================================
1371 ## action links
1373 # possible values of extra options
1374 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1375 # -replay => 1 - start from a current view (replay with modifications)
1376 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1377 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1378 sub href {
1379 my %params = @_;
1380 # default is to use -absolute url() i.e. $my_uri
1381 my $href = $params{-full} ? $my_url : $my_uri;
1383 # implicit -replay, must be first of implicit params
1384 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1386 $params{'project'} = $project unless exists $params{'project'};
1388 if ($params{-replay}) {
1389 while (my ($name, $symbol) = each %cgi_param_mapping) {
1390 if (!exists $params{$name}) {
1391 $params{$name} = $input_params{$name};
1396 my $use_pathinfo = gitweb_check_feature('pathinfo');
1397 if (defined $params{'project'} &&
1398 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1399 # try to put as many parameters as possible in PATH_INFO:
1400 # - project name
1401 # - action
1402 # - hash_parent or hash_parent_base:/file_parent
1403 # - hash or hash_base:/filename
1404 # - the snapshot_format as an appropriate suffix
1406 # When the script is the root DirectoryIndex for the domain,
1407 # $href here would be something like http://gitweb.example.com/
1408 # Thus, we strip any trailing / from $href, to spare us double
1409 # slashes in the final URL
1410 $href =~ s,/$,,;
1412 # Then add the project name, if present
1413 $href .= "/".esc_path_info($params{'project'});
1414 delete $params{'project'};
1416 # since we destructively absorb parameters, we keep this
1417 # boolean that remembers if we're handling a snapshot
1418 my $is_snapshot = $params{'action'} eq 'snapshot';
1420 # Summary just uses the project path URL, any other action is
1421 # added to the URL
1422 if (defined $params{'action'}) {
1423 $href .= "/".esc_path_info($params{'action'})
1424 unless $params{'action'} eq 'summary';
1425 delete $params{'action'};
1428 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1429 # stripping nonexistent or useless pieces
1430 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1431 || $params{'hash_parent'} || $params{'hash'});
1432 if (defined $params{'hash_base'}) {
1433 if (defined $params{'hash_parent_base'}) {
1434 $href .= esc_path_info($params{'hash_parent_base'});
1435 # skip the file_parent if it's the same as the file_name
1436 if (defined $params{'file_parent'}) {
1437 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1438 delete $params{'file_parent'};
1439 } elsif ($params{'file_parent'} !~ /\.\./) {
1440 $href .= ":/".esc_path_info($params{'file_parent'});
1441 delete $params{'file_parent'};
1444 $href .= "..";
1445 delete $params{'hash_parent'};
1446 delete $params{'hash_parent_base'};
1447 } elsif (defined $params{'hash_parent'}) {
1448 $href .= esc_path_info($params{'hash_parent'}). "..";
1449 delete $params{'hash_parent'};
1452 $href .= esc_path_info($params{'hash_base'});
1453 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1454 $href .= ":/".esc_path_info($params{'file_name'});
1455 delete $params{'file_name'};
1457 delete $params{'hash'};
1458 delete $params{'hash_base'};
1459 } elsif (defined $params{'hash'}) {
1460 $href .= esc_path_info($params{'hash'});
1461 delete $params{'hash'};
1464 # If the action was a snapshot, we can absorb the
1465 # snapshot_format parameter too
1466 if ($is_snapshot) {
1467 my $fmt = $params{'snapshot_format'};
1468 # snapshot_format should always be defined when href()
1469 # is called, but just in case some code forgets, we
1470 # fall back to the default
1471 $fmt ||= $snapshot_fmts[0];
1472 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1473 delete $params{'snapshot_format'};
1477 # now encode the parameters explicitly
1478 my @result = ();
1479 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1480 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1481 if (defined $params{$name}) {
1482 if (ref($params{$name}) eq "ARRAY") {
1483 foreach my $par (@{$params{$name}}) {
1484 push @result, $symbol . "=" . esc_param($par);
1486 } else {
1487 push @result, $symbol . "=" . esc_param($params{$name});
1491 $href .= "?" . join(';', @result) if scalar @result;
1493 # final transformation: trailing spaces must be escaped (URI-encoded)
1494 $href =~ s/(\s+)$/CGI::escape($1)/e;
1496 if ($params{-anchor}) {
1497 $href .= "#".esc_param($params{-anchor});
1500 return $href;
1504 ## ======================================================================
1505 ## validation, quoting/unquoting and escaping
1507 sub is_valid_action {
1508 my $input = shift;
1509 return undef unless exists $actions{$input};
1510 return 1;
1513 sub is_valid_project {
1514 my $input = shift;
1516 return unless defined $input;
1517 if (!is_valid_pathname($input) ||
1518 !(-d "$projectroot/$input") ||
1519 !check_export_ok("$projectroot/$input") ||
1520 ($strict_export && !project_in_list($input))) {
1521 return undef;
1522 } else {
1523 return 1;
1527 sub is_valid_pathname {
1528 my $input = shift;
1530 return undef unless defined $input;
1531 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1532 # at the beginning, at the end, and between slashes.
1533 # also this catches doubled slashes
1534 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1535 return undef;
1537 # no null characters
1538 if ($input =~ m!\0!) {
1539 return undef;
1541 return 1;
1544 sub is_valid_ref_format {
1545 my $input = shift;
1547 return undef unless defined $input;
1548 # restrictions on ref name according to git-check-ref-format
1549 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1550 return undef;
1552 return 1;
1555 sub is_valid_refname {
1556 my $input = shift;
1558 return undef unless defined $input;
1559 # textual hashes are O.K.
1560 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1561 return 1;
1563 # it must be correct pathname
1564 is_valid_pathname($input) or return undef;
1565 # check git-check-ref-format restrictions
1566 is_valid_ref_format($input) or return undef;
1567 return 1;
1570 # decode sequences of octets in utf8 into Perl's internal form,
1571 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1572 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1573 sub to_utf8 {
1574 my $str = shift;
1575 return undef unless defined $str;
1577 if (utf8::is_utf8($str) || utf8::decode($str)) {
1578 return $str;
1579 } else {
1580 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1584 # quote unsafe chars, but keep the slash, even when it's not
1585 # correct, but quoted slashes look too horrible in bookmarks
1586 sub esc_param {
1587 my $str = shift;
1588 return undef unless defined $str;
1589 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1590 $str =~ s/ /\+/g;
1591 return $str;
1594 # the quoting rules for path_info fragment are slightly different
1595 sub esc_path_info {
1596 my $str = shift;
1597 return undef unless defined $str;
1599 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1600 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1602 return $str;
1605 # quote unsafe chars in whole URL, so some characters cannot be quoted
1606 sub esc_url {
1607 my $str = shift;
1608 return undef unless defined $str;
1609 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1610 $str =~ s/ /\+/g;
1611 return $str;
1614 # quote unsafe characters in HTML attributes
1615 sub esc_attr {
1617 # for XHTML conformance escaping '"' to '&quot;' is not enough
1618 return esc_html(@_);
1621 # replace invalid utf8 character with SUBSTITUTION sequence
1622 sub esc_html {
1623 my $str = shift;
1624 my %opts = @_;
1626 return undef unless defined $str;
1628 $str = to_utf8($str);
1629 $str = $cgi->escapeHTML($str);
1630 if ($opts{'-nbsp'}) {
1631 $str =~ s/ /&nbsp;/g;
1633 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1634 return $str;
1637 # quote control characters and escape filename to HTML
1638 sub esc_path {
1639 my $str = shift;
1640 my %opts = @_;
1642 return undef unless defined $str;
1644 $str = to_utf8($str);
1645 $str = $cgi->escapeHTML($str);
1646 if ($opts{'-nbsp'}) {
1647 $str =~ s/ /&nbsp;/g;
1649 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1650 return $str;
1653 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1654 sub sanitize {
1655 my $str = shift;
1657 return undef unless defined $str;
1659 $str = to_utf8($str);
1660 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1661 return $str;
1664 # Make control characters "printable", using character escape codes (CEC)
1665 sub quot_cec {
1666 my $cntrl = shift;
1667 my %opts = @_;
1668 my %es = ( # character escape codes, aka escape sequences
1669 "\t" => '\t', # tab (HT)
1670 "\n" => '\n', # line feed (LF)
1671 "\r" => '\r', # carrige return (CR)
1672 "\f" => '\f', # form feed (FF)
1673 "\b" => '\b', # backspace (BS)
1674 "\a" => '\a', # alarm (bell) (BEL)
1675 "\e" => '\e', # escape (ESC)
1676 "\013" => '\v', # vertical tab (VT)
1677 "\000" => '\0', # nul character (NUL)
1679 my $chr = ( (exists $es{$cntrl})
1680 ? $es{$cntrl}
1681 : sprintf('\%2x', ord($cntrl)) );
1682 if ($opts{-nohtml}) {
1683 return $chr;
1684 } else {
1685 return "<span class=\"cntrl\">$chr</span>";
1689 # Alternatively use unicode control pictures codepoints,
1690 # Unicode "printable representation" (PR)
1691 sub quot_upr {
1692 my $cntrl = shift;
1693 my %opts = @_;
1695 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1696 if ($opts{-nohtml}) {
1697 return $chr;
1698 } else {
1699 return "<span class=\"cntrl\">$chr</span>";
1703 # git may return quoted and escaped filenames
1704 sub unquote {
1705 my $str = shift;
1707 sub unq {
1708 my $seq = shift;
1709 my %es = ( # character escape codes, aka escape sequences
1710 't' => "\t", # tab (HT, TAB)
1711 'n' => "\n", # newline (NL)
1712 'r' => "\r", # return (CR)
1713 'f' => "\f", # form feed (FF)
1714 'b' => "\b", # backspace (BS)
1715 'a' => "\a", # alarm (bell) (BEL)
1716 'e' => "\e", # escape (ESC)
1717 'v' => "\013", # vertical tab (VT)
1720 if ($seq =~ m/^[0-7]{1,3}$/) {
1721 # octal char sequence
1722 return chr(oct($seq));
1723 } elsif (exists $es{$seq}) {
1724 # C escape sequence, aka character escape code
1725 return $es{$seq};
1727 # quoted ordinary character
1728 return $seq;
1731 if ($str =~ m/^"(.*)"$/) {
1732 # needs unquoting
1733 $str = $1;
1734 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1736 return $str;
1739 # escape tabs (convert tabs to spaces)
1740 sub untabify {
1741 my $line = shift;
1743 while ((my $pos = index($line, "\t")) != -1) {
1744 if (my $count = (8 - ($pos % 8))) {
1745 my $spaces = ' ' x $count;
1746 $line =~ s/\t/$spaces/;
1750 return $line;
1753 sub project_in_list {
1754 my $project = shift;
1755 my @list = git_get_projects_list();
1756 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1759 ## ----------------------------------------------------------------------
1760 ## HTML aware string manipulation
1762 # Try to chop given string on a word boundary between position
1763 # $len and $len+$add_len. If there is no word boundary there,
1764 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1765 # (marking chopped part) would be longer than given string.
1766 sub chop_str {
1767 my $str = shift;
1768 my $len = shift;
1769 my $add_len = shift || 10;
1770 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1772 # Make sure perl knows it is utf8 encoded so we don't
1773 # cut in the middle of a utf8 multibyte char.
1774 $str = to_utf8($str);
1776 # allow only $len chars, but don't cut a word if it would fit in $add_len
1777 # if it doesn't fit, cut it if it's still longer than the dots we would add
1778 # remove chopped character entities entirely
1780 # when chopping in the middle, distribute $len into left and right part
1781 # return early if chopping wouldn't make string shorter
1782 if ($where eq 'center') {
1783 return $str if ($len + 5 >= length($str)); # filler is length 5
1784 $len = int($len/2);
1785 } else {
1786 return $str if ($len + 4 >= length($str)); # filler is length 4
1789 # regexps: ending and beginning with word part up to $add_len
1790 my $endre = qr/.{$len}\w{0,$add_len}/;
1791 my $begre = qr/\w{0,$add_len}.{$len}/;
1793 if ($where eq 'left') {
1794 $str =~ m/^(.*?)($begre)$/;
1795 my ($lead, $body) = ($1, $2);
1796 if (length($lead) > 4) {
1797 $lead = " ...";
1799 return "$lead$body";
1801 } elsif ($where eq 'center') {
1802 $str =~ m/^($endre)(.*)$/;
1803 my ($left, $str) = ($1, $2);
1804 $str =~ m/^(.*?)($begre)$/;
1805 my ($mid, $right) = ($1, $2);
1806 if (length($mid) > 5) {
1807 $mid = " ... ";
1809 return "$left$mid$right";
1811 } else {
1812 $str =~ m/^($endre)(.*)$/;
1813 my $body = $1;
1814 my $tail = $2;
1815 if (length($tail) > 4) {
1816 $tail = "... ";
1818 return "$body$tail";
1822 # takes the same arguments as chop_str, but also wraps a <span> around the
1823 # result with a title attribute if it does get chopped. Additionally, the
1824 # string is HTML-escaped.
1825 sub chop_and_escape_str {
1826 my ($str) = @_;
1828 my $chopped = chop_str(@_);
1829 $str = to_utf8($str);
1830 if ($chopped eq $str) {
1831 return esc_html($chopped);
1832 } else {
1833 $str =~ s/[[:cntrl:]]/?/g;
1834 return $cgi->span({-title=>$str}, esc_html($chopped));
1838 # Highlight selected fragments of string, using given CSS class,
1839 # and escape HTML. It is assumed that fragments do not overlap.
1840 # Regions are passed as list of pairs (array references).
1842 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1843 # '<span class="mark">foo</span>bar'
1844 sub esc_html_hl_regions {
1845 my ($str, $css_class, @sel) = @_;
1846 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1847 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1848 return esc_html($str, %opts) unless @sel;
1850 my $out = '';
1851 my $pos = 0;
1853 for my $s (@sel) {
1854 my ($begin, $end) = @$s;
1856 # Don't create empty <span> elements.
1857 next if $end <= $begin;
1859 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1860 %opts);
1862 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1863 if ($begin - $pos > 0);
1864 $out .= $cgi->span({-class => $css_class}, $escaped);
1866 $pos = $end;
1868 $out .= esc_html(substr($str, $pos), %opts)
1869 if ($pos < length($str));
1871 return $out;
1874 # return positions of beginning and end of each match
1875 sub matchpos_list {
1876 my ($str, $regexp) = @_;
1877 return unless (defined $str && defined $regexp);
1879 my @matches;
1880 while ($str =~ /$regexp/g) {
1881 push @matches, [$-[0], $+[0]];
1883 return @matches;
1886 # highlight match (if any), and escape HTML
1887 sub esc_html_match_hl {
1888 my ($str, $regexp) = @_;
1889 return esc_html($str) unless defined $regexp;
1891 my @matches = matchpos_list($str, $regexp);
1892 return esc_html($str) unless @matches;
1894 return esc_html_hl_regions($str, 'match', @matches);
1898 # highlight match (if any) of shortened string, and escape HTML
1899 sub esc_html_match_hl_chopped {
1900 my ($str, $chopped, $regexp) = @_;
1901 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1903 my @matches = matchpos_list($str, $regexp);
1904 return esc_html($chopped) unless @matches;
1906 # filter matches so that we mark chopped string
1907 my $tail = "... "; # see chop_str
1908 unless ($chopped =~ s/\Q$tail\E$//) {
1909 $tail = '';
1911 my $chop_len = length($chopped);
1912 my $tail_len = length($tail);
1913 my @filtered;
1915 for my $m (@matches) {
1916 if ($m->[0] > $chop_len) {
1917 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1918 last;
1919 } elsif ($m->[1] > $chop_len) {
1920 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1921 last;
1923 push @filtered, $m;
1926 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1929 ## ----------------------------------------------------------------------
1930 ## functions returning short strings
1932 # CSS class for given age value (in seconds)
1933 sub age_class {
1934 my $age = shift;
1936 if (!defined $age) {
1937 return "noage";
1938 } elsif ($age < 60*60*2) {
1939 return "age0";
1940 } elsif ($age < 60*60*24*2) {
1941 return "age1";
1942 } else {
1943 return "age2";
1947 # convert age in seconds to "nn units ago" string
1948 sub age_string {
1949 my $age = shift;
1950 my $age_str;
1952 if ($age > 60*60*24*365*2) {
1953 $age_str = (int $age/60/60/24/365);
1954 $age_str .= " years ago";
1955 } elsif ($age > 60*60*24*(365/12)*2) {
1956 $age_str = int $age/60/60/24/(365/12);
1957 $age_str .= " months ago";
1958 } elsif ($age > 60*60*24*7*2) {
1959 $age_str = int $age/60/60/24/7;
1960 $age_str .= " weeks ago";
1961 } elsif ($age > 60*60*24*2) {
1962 $age_str = int $age/60/60/24;
1963 $age_str .= " days ago";
1964 } elsif ($age > 60*60*2) {
1965 $age_str = int $age/60/60;
1966 $age_str .= " hours ago";
1967 } elsif ($age > 60*2) {
1968 $age_str = int $age/60;
1969 $age_str .= " min ago";
1970 } elsif ($age > 2) {
1971 $age_str = int $age;
1972 $age_str .= " sec ago";
1973 } else {
1974 $age_str .= " right now";
1976 return $age_str;
1979 use constant {
1980 S_IFINVALID => 0030000,
1981 S_IFGITLINK => 0160000,
1984 # submodule/subproject, a commit object reference
1985 sub S_ISGITLINK {
1986 my $mode = shift;
1988 return (($mode & S_IFMT) == S_IFGITLINK)
1991 # convert file mode in octal to symbolic file mode string
1992 sub mode_str {
1993 my $mode = oct shift;
1995 if (S_ISGITLINK($mode)) {
1996 return 'm---------';
1997 } elsif (S_ISDIR($mode & S_IFMT)) {
1998 return 'drwxr-xr-x';
1999 } elsif (S_ISLNK($mode)) {
2000 return 'lrwxrwxrwx';
2001 } elsif (S_ISREG($mode)) {
2002 # git cares only about the executable bit
2003 if ($mode & S_IXUSR) {
2004 return '-rwxr-xr-x';
2005 } else {
2006 return '-rw-r--r--';
2008 } else {
2009 return '----------';
2013 # convert file mode in octal to file type string
2014 sub file_type {
2015 my $mode = shift;
2017 if ($mode !~ m/^[0-7]+$/) {
2018 return $mode;
2019 } else {
2020 $mode = oct $mode;
2023 if (S_ISGITLINK($mode)) {
2024 return "submodule";
2025 } elsif (S_ISDIR($mode & S_IFMT)) {
2026 return "directory";
2027 } elsif (S_ISLNK($mode)) {
2028 return "symlink";
2029 } elsif (S_ISREG($mode)) {
2030 return "file";
2031 } else {
2032 return "unknown";
2036 # convert file mode in octal to file type description string
2037 sub file_type_long {
2038 my $mode = shift;
2040 if ($mode !~ m/^[0-7]+$/) {
2041 return $mode;
2042 } else {
2043 $mode = oct $mode;
2046 if (S_ISGITLINK($mode)) {
2047 return "submodule";
2048 } elsif (S_ISDIR($mode & S_IFMT)) {
2049 return "directory";
2050 } elsif (S_ISLNK($mode)) {
2051 return "symlink";
2052 } elsif (S_ISREG($mode)) {
2053 if ($mode & S_IXUSR) {
2054 return "executable";
2055 } else {
2056 return "file";
2058 } else {
2059 return "unknown";
2064 ## ----------------------------------------------------------------------
2065 ## functions returning short HTML fragments, or transforming HTML fragments
2066 ## which don't belong to other sections
2068 # format line of commit message.
2069 sub format_log_line_html {
2070 my $line = shift;
2072 $line = esc_html($line, -nbsp=>1);
2073 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2074 $cgi->a({-href => href(action=>"object", hash=>$1),
2075 -class => "text"}, $1);
2076 }eg;
2078 return $line;
2081 # format marker of refs pointing to given object
2083 # the destination action is chosen based on object type and current context:
2084 # - for annotated tags, we choose the tag view unless it's the current view
2085 # already, in which case we go to shortlog view
2086 # - for other refs, we keep the current view if we're in history, shortlog or
2087 # log view, and select shortlog otherwise
2088 sub format_ref_marker {
2089 my ($refs, $id) = @_;
2090 my $markers = '';
2092 if (defined $refs->{$id}) {
2093 foreach my $ref (@{$refs->{$id}}) {
2094 # this code exploits the fact that non-lightweight tags are the
2095 # only indirect objects, and that they are the only objects for which
2096 # we want to use tag instead of shortlog as action
2097 my ($type, $name) = qw();
2098 my $indirect = ($ref =~ s/\^\{\}$//);
2099 # e.g. tags/v2.6.11 or heads/next
2100 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2101 $type = $1;
2102 $name = $2;
2103 } else {
2104 $type = "ref";
2105 $name = $ref;
2108 my $class = $type;
2109 $class .= " indirect" if $indirect;
2111 my $dest_action = "shortlog";
2113 if ($indirect) {
2114 $dest_action = "tag" unless $action eq "tag";
2115 } elsif ($action =~ /^(history|(short)?log)$/) {
2116 $dest_action = $action;
2119 my $dest = "";
2120 $dest .= "refs/" unless $ref =~ m!^refs/!;
2121 $dest .= $ref;
2123 my $link = $cgi->a({
2124 -href => href(
2125 action=>$dest_action,
2126 hash=>$dest
2127 )}, $name);
2129 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2130 $link . "</span>";
2134 if ($markers) {
2135 return ' <span class="refs">'. $markers . '</span>';
2136 } else {
2137 return "";
2141 # format, perhaps shortened and with markers, title line
2142 sub format_subject_html {
2143 my ($long, $short, $href, $extra) = @_;
2144 $extra = '' unless defined($extra);
2146 if (length($short) < length($long)) {
2147 $long =~ s/[[:cntrl:]]/?/g;
2148 return $cgi->a({-href => $href, -class => "list subject",
2149 -title => to_utf8($long)},
2150 esc_html($short)) . $extra;
2151 } else {
2152 return $cgi->a({-href => $href, -class => "list subject"},
2153 esc_html($long)) . $extra;
2157 # Rather than recomputing the url for an email multiple times, we cache it
2158 # after the first hit. This gives a visible benefit in views where the avatar
2159 # for the same email is used repeatedly (e.g. shortlog).
2160 # The cache is shared by all avatar engines (currently gravatar only), which
2161 # are free to use it as preferred. Since only one avatar engine is used for any
2162 # given page, there's no risk for cache conflicts.
2163 our %avatar_cache = ();
2165 # Compute the picon url for a given email, by using the picon search service over at
2166 # http://www.cs.indiana.edu/picons/search.html
2167 sub picon_url {
2168 my $email = lc shift;
2169 if (!$avatar_cache{$email}) {
2170 my ($user, $domain) = split('@', $email);
2171 $avatar_cache{$email} =
2172 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2173 "$domain/$user/" .
2174 "users+domains+unknown/up/single";
2176 return $avatar_cache{$email};
2179 # Compute the gravatar url for a given email, if it's not in the cache already.
2180 # Gravatar stores only the part of the URL before the size, since that's the
2181 # one computationally more expensive. This also allows reuse of the cache for
2182 # different sizes (for this particular engine).
2183 sub gravatar_url {
2184 my $email = lc shift;
2185 my $size = shift;
2186 $avatar_cache{$email} ||=
2187 "//www.gravatar.com/avatar/" .
2188 Digest::MD5::md5_hex($email) . "?s=";
2189 return $avatar_cache{$email} . $size;
2192 # Insert an avatar for the given $email at the given $size if the feature
2193 # is enabled.
2194 sub git_get_avatar {
2195 my ($email, %opts) = @_;
2196 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2197 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2198 $opts{-size} ||= 'default';
2199 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2200 my $url = "";
2201 if ($git_avatar eq 'gravatar') {
2202 $url = gravatar_url($email, $size);
2203 } elsif ($git_avatar eq 'picon') {
2204 $url = picon_url($email);
2206 # Other providers can be added by extending the if chain, defining $url
2207 # as needed. If no variant puts something in $url, we assume avatars
2208 # are completely disabled/unavailable.
2209 if ($url) {
2210 return $pre_white .
2211 "<img width=\"$size\" " .
2212 "class=\"avatar\" " .
2213 "src=\"".esc_url($url)."\" " .
2214 "alt=\"\" " .
2215 "/>" . $post_white;
2216 } else {
2217 return "";
2221 sub format_search_author {
2222 my ($author, $searchtype, $displaytext) = @_;
2223 my $have_search = gitweb_check_feature('search');
2225 if ($have_search) {
2226 my $performed = "";
2227 if ($searchtype eq 'author') {
2228 $performed = "authored";
2229 } elsif ($searchtype eq 'committer') {
2230 $performed = "committed";
2233 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2234 searchtext=>$author,
2235 searchtype=>$searchtype), class=>"list",
2236 title=>"Search for commits $performed by $author"},
2237 $displaytext);
2239 } else {
2240 return $displaytext;
2244 # format the author name of the given commit with the given tag
2245 # the author name is chopped and escaped according to the other
2246 # optional parameters (see chop_str).
2247 sub format_author_html {
2248 my $tag = shift;
2249 my $co = shift;
2250 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2251 return "<$tag class=\"author\">" .
2252 format_search_author($co->{'author_name'}, "author",
2253 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2254 $author) .
2255 "</$tag>";
2258 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2259 sub format_git_diff_header_line {
2260 my $line = shift;
2261 my $diffinfo = shift;
2262 my ($from, $to) = @_;
2264 if ($diffinfo->{'nparents'}) {
2265 # combined diff
2266 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2267 if ($to->{'href'}) {
2268 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2269 esc_path($to->{'file'}));
2270 } else { # file was deleted (no href)
2271 $line .= esc_path($to->{'file'});
2273 } else {
2274 # "ordinary" diff
2275 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2276 if ($from->{'href'}) {
2277 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2278 'a/' . esc_path($from->{'file'}));
2279 } else { # file was added (no href)
2280 $line .= 'a/' . esc_path($from->{'file'});
2282 $line .= ' ';
2283 if ($to->{'href'}) {
2284 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2285 'b/' . esc_path($to->{'file'}));
2286 } else { # file was deleted
2287 $line .= 'b/' . esc_path($to->{'file'});
2291 return "<div class=\"diff header\">$line</div>\n";
2294 # format extended diff header line, before patch itself
2295 sub format_extended_diff_header_line {
2296 my $line = shift;
2297 my $diffinfo = shift;
2298 my ($from, $to) = @_;
2300 # match <path>
2301 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2302 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2303 esc_path($from->{'file'}));
2305 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2306 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2307 esc_path($to->{'file'}));
2309 # match single <mode>
2310 if ($line =~ m/\s(\d{6})$/) {
2311 $line .= '<span class="info"> (' .
2312 file_type_long($1) .
2313 ')</span>';
2315 # match <hash>
2316 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2317 # can match only for combined diff
2318 $line = 'index ';
2319 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2320 if ($from->{'href'}[$i]) {
2321 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2322 -class=>"hash"},
2323 substr($diffinfo->{'from_id'}[$i],0,7));
2324 } else {
2325 $line .= '0' x 7;
2327 # separator
2328 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2330 $line .= '..';
2331 if ($to->{'href'}) {
2332 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2333 substr($diffinfo->{'to_id'},0,7));
2334 } else {
2335 $line .= '0' x 7;
2338 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2339 # can match only for ordinary diff
2340 my ($from_link, $to_link);
2341 if ($from->{'href'}) {
2342 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2343 substr($diffinfo->{'from_id'},0,7));
2344 } else {
2345 $from_link = '0' x 7;
2347 if ($to->{'href'}) {
2348 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2349 substr($diffinfo->{'to_id'},0,7));
2350 } else {
2351 $to_link = '0' x 7;
2353 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2354 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2357 return $line . "<br/>\n";
2360 # format from-file/to-file diff header
2361 sub format_diff_from_to_header {
2362 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2363 my $line;
2364 my $result = '';
2366 $line = $from_line;
2367 #assert($line =~ m/^---/) if DEBUG;
2368 # no extra formatting for "^--- /dev/null"
2369 if (! $diffinfo->{'nparents'}) {
2370 # ordinary (single parent) diff
2371 if ($line =~ m!^--- "?a/!) {
2372 if ($from->{'href'}) {
2373 $line = '--- a/' .
2374 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2375 esc_path($from->{'file'}));
2376 } else {
2377 $line = '--- a/' .
2378 esc_path($from->{'file'});
2381 $result .= qq!<div class="diff from_file">$line</div>\n!;
2383 } else {
2384 # combined diff (merge commit)
2385 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2386 if ($from->{'href'}[$i]) {
2387 $line = '--- ' .
2388 $cgi->a({-href=>href(action=>"blobdiff",
2389 hash_parent=>$diffinfo->{'from_id'}[$i],
2390 hash_parent_base=>$parents[$i],
2391 file_parent=>$from->{'file'}[$i],
2392 hash=>$diffinfo->{'to_id'},
2393 hash_base=>$hash,
2394 file_name=>$to->{'file'}),
2395 -class=>"path",
2396 -title=>"diff" . ($i+1)},
2397 $i+1) .
2398 '/' .
2399 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2400 esc_path($from->{'file'}[$i]));
2401 } else {
2402 $line = '--- /dev/null';
2404 $result .= qq!<div class="diff from_file">$line</div>\n!;
2408 $line = $to_line;
2409 #assert($line =~ m/^\+\+\+/) if DEBUG;
2410 # no extra formatting for "^+++ /dev/null"
2411 if ($line =~ m!^\+\+\+ "?b/!) {
2412 if ($to->{'href'}) {
2413 $line = '+++ b/' .
2414 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2415 esc_path($to->{'file'}));
2416 } else {
2417 $line = '+++ b/' .
2418 esc_path($to->{'file'});
2421 $result .= qq!<div class="diff to_file">$line</div>\n!;
2423 return $result;
2426 # create note for patch simplified by combined diff
2427 sub format_diff_cc_simplified {
2428 my ($diffinfo, @parents) = @_;
2429 my $result = '';
2431 $result .= "<div class=\"diff header\">" .
2432 "diff --cc ";
2433 if (!is_deleted($diffinfo)) {
2434 $result .= $cgi->a({-href => href(action=>"blob",
2435 hash_base=>$hash,
2436 hash=>$diffinfo->{'to_id'},
2437 file_name=>$diffinfo->{'to_file'}),
2438 -class => "path"},
2439 esc_path($diffinfo->{'to_file'}));
2440 } else {
2441 $result .= esc_path($diffinfo->{'to_file'});
2443 $result .= "</div>\n" . # class="diff header"
2444 "<div class=\"diff nodifferences\">" .
2445 "Simple merge" .
2446 "</div>\n"; # class="diff nodifferences"
2448 return $result;
2451 sub diff_line_class {
2452 my ($line, $from, $to) = @_;
2454 # ordinary diff
2455 my $num_sign = 1;
2456 # combined diff
2457 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2458 $num_sign = scalar @{$from->{'href'}};
2461 my @diff_line_classifier = (
2462 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2463 { regexp => qr/^\\/, class => "incomplete" },
2464 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2465 # classifier for context must come before classifier add/rem,
2466 # or we would have to use more complicated regexp, for example
2467 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2468 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2469 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2471 for my $clsfy (@diff_line_classifier) {
2472 return $clsfy->{'class'}
2473 if ($line =~ $clsfy->{'regexp'});
2476 # fallback
2477 return "";
2480 # assumes that $from and $to are defined and correctly filled,
2481 # and that $line holds a line of chunk header for unified diff
2482 sub format_unidiff_chunk_header {
2483 my ($line, $from, $to) = @_;
2485 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2486 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2488 $from_lines = 0 unless defined $from_lines;
2489 $to_lines = 0 unless defined $to_lines;
2491 if ($from->{'href'}) {
2492 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2493 -class=>"list"}, $from_text);
2495 if ($to->{'href'}) {
2496 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2497 -class=>"list"}, $to_text);
2499 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2500 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2501 return $line;
2504 # assumes that $from and $to are defined and correctly filled,
2505 # and that $line holds a line of chunk header for combined diff
2506 sub format_cc_diff_chunk_header {
2507 my ($line, $from, $to) = @_;
2509 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2510 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2512 @from_text = split(' ', $ranges);
2513 for (my $i = 0; $i < @from_text; ++$i) {
2514 ($from_start[$i], $from_nlines[$i]) =
2515 (split(',', substr($from_text[$i], 1)), 0);
2518 $to_text = pop @from_text;
2519 $to_start = pop @from_start;
2520 $to_nlines = pop @from_nlines;
2522 $line = "<span class=\"chunk_info\">$prefix ";
2523 for (my $i = 0; $i < @from_text; ++$i) {
2524 if ($from->{'href'}[$i]) {
2525 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2526 -class=>"list"}, $from_text[$i]);
2527 } else {
2528 $line .= $from_text[$i];
2530 $line .= " ";
2532 if ($to->{'href'}) {
2533 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2534 -class=>"list"}, $to_text);
2535 } else {
2536 $line .= $to_text;
2538 $line .= " $prefix</span>" .
2539 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2540 return $line;
2543 # process patch (diff) line (not to be used for diff headers),
2544 # returning HTML-formatted (but not wrapped) line.
2545 # If the line is passed as a reference, it is treated as HTML and not
2546 # esc_html()'ed.
2547 sub format_diff_line {
2548 my ($line, $diff_class, $from, $to) = @_;
2550 if (ref($line)) {
2551 $line = $$line;
2552 } else {
2553 chomp $line;
2554 $line = untabify($line);
2556 if ($from && $to && $line =~ m/^\@{2} /) {
2557 $line = format_unidiff_chunk_header($line, $from, $to);
2558 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2559 $line = format_cc_diff_chunk_header($line, $from, $to);
2560 } else {
2561 $line = esc_html($line, -nbsp=>1);
2565 my $diff_classes = "diff";
2566 $diff_classes .= " $diff_class" if ($diff_class);
2567 $line = "<div class=\"$diff_classes\">$line</div>\n";
2569 return $line;
2572 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2573 # linked. Pass the hash of the tree/commit to snapshot.
2574 sub format_snapshot_links {
2575 my ($hash) = @_;
2576 my $num_fmts = @snapshot_fmts;
2577 if ($num_fmts > 1) {
2578 # A parenthesized list of links bearing format names.
2579 # e.g. "snapshot (_tar.gz_ _zip_)"
2580 return "snapshot (" . join(' ', map
2581 $cgi->a({
2582 -href => href(
2583 action=>"snapshot",
2584 hash=>$hash,
2585 snapshot_format=>$_
2587 }, $known_snapshot_formats{$_}{'display'})
2588 , @snapshot_fmts) . ")";
2589 } elsif ($num_fmts == 1) {
2590 # A single "snapshot" link whose tooltip bears the format name.
2591 # i.e. "_snapshot_"
2592 my ($fmt) = @snapshot_fmts;
2593 return
2594 $cgi->a({
2595 -href => href(
2596 action=>"snapshot",
2597 hash=>$hash,
2598 snapshot_format=>$fmt
2600 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2601 }, "snapshot");
2602 } else { # $num_fmts == 0
2603 return undef;
2607 ## ......................................................................
2608 ## functions returning values to be passed, perhaps after some
2609 ## transformation, to other functions; e.g. returning arguments to href()
2611 # returns hash to be passed to href to generate gitweb URL
2612 # in -title key it returns description of link
2613 sub get_feed_info {
2614 my $format = shift || 'Atom';
2615 my %res = (action => lc($format));
2616 my $matched_ref = 0;
2618 # feed links are possible only for project views
2619 return unless (defined $project);
2620 # some views should link to OPML, or to generic project feed,
2621 # or don't have specific feed yet (so they should use generic)
2622 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2624 my $branch = undef;
2625 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2626 # (fullname) to differentiate from tag links; this also makes
2627 # possible to detect branch links
2628 for my $ref (get_branch_refs()) {
2629 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2630 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2631 $branch = $1;
2632 $matched_ref = $ref;
2633 last;
2636 # find log type for feed description (title)
2637 my $type = 'log';
2638 if (defined $file_name) {
2639 $type = "history of $file_name";
2640 $type .= "/" if ($action eq 'tree');
2641 $type .= " on '$branch'" if (defined $branch);
2642 } else {
2643 $type = "log of $branch" if (defined $branch);
2646 $res{-title} = $type;
2647 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2648 $res{'file_name'} = $file_name;
2650 return %res;
2653 ## ----------------------------------------------------------------------
2654 ## git utility subroutines, invoking git commands
2656 # returns path to the core git executable and the --git-dir parameter as list
2657 sub git_cmd {
2658 $number_of_git_cmds++;
2659 return $GIT, '--git-dir='.$git_dir;
2662 # quote the given arguments for passing them to the shell
2663 # quote_command("command", "arg 1", "arg with ' and ! characters")
2664 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2665 # Try to avoid using this function wherever possible.
2666 sub quote_command {
2667 return join(' ',
2668 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2671 # get HEAD ref of given project as hash
2672 sub git_get_head_hash {
2673 return git_get_full_hash(shift, 'HEAD');
2676 sub git_get_full_hash {
2677 return git_get_hash(@_);
2680 sub git_get_short_hash {
2681 return git_get_hash(@_, '--short=7');
2684 sub git_get_hash {
2685 my ($project, $hash, @options) = @_;
2686 my $o_git_dir = $git_dir;
2687 my $retval = undef;
2688 $git_dir = "$projectroot/$project";
2689 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2690 '--verify', '-q', @options, $hash) {
2691 $retval = <$fd>;
2692 chomp $retval if defined $retval;
2693 close $fd;
2695 if (defined $o_git_dir) {
2696 $git_dir = $o_git_dir;
2698 return $retval;
2701 # get type of given object
2702 sub git_get_type {
2703 my $hash = shift;
2705 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2706 my $type = <$fd>;
2707 close $fd or return;
2708 chomp $type;
2709 return $type;
2712 # repository configuration
2713 our $config_file = '';
2714 our %config;
2716 # store multiple values for single key as anonymous array reference
2717 # single values stored directly in the hash, not as [ <value> ]
2718 sub hash_set_multi {
2719 my ($hash, $key, $value) = @_;
2721 if (!exists $hash->{$key}) {
2722 $hash->{$key} = $value;
2723 } elsif (!ref $hash->{$key}) {
2724 $hash->{$key} = [ $hash->{$key}, $value ];
2725 } else {
2726 push @{$hash->{$key}}, $value;
2730 # return hash of git project configuration
2731 # optionally limited to some section, e.g. 'gitweb'
2732 sub git_parse_project_config {
2733 my $section_regexp = shift;
2734 my %config;
2736 local $/ = "\0";
2738 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2739 or return;
2741 while (my $keyval = <$fh>) {
2742 chomp $keyval;
2743 my ($key, $value) = split(/\n/, $keyval, 2);
2745 hash_set_multi(\%config, $key, $value)
2746 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2748 close $fh;
2750 return %config;
2753 # convert config value to boolean: 'true' or 'false'
2754 # no value, number > 0, 'true' and 'yes' values are true
2755 # rest of values are treated as false (never as error)
2756 sub config_to_bool {
2757 my $val = shift;
2759 return 1 if !defined $val; # section.key
2761 # strip leading and trailing whitespace
2762 $val =~ s/^\s+//;
2763 $val =~ s/\s+$//;
2765 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2766 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2769 # convert config value to simple decimal number
2770 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2771 # to be multiplied by 1024, 1048576, or 1073741824
2772 sub config_to_int {
2773 my $val = shift;
2775 # strip leading and trailing whitespace
2776 $val =~ s/^\s+//;
2777 $val =~ s/\s+$//;
2779 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2780 $unit = lc($unit);
2781 # unknown unit is treated as 1
2782 return $num * ($unit eq 'g' ? 1073741824 :
2783 $unit eq 'm' ? 1048576 :
2784 $unit eq 'k' ? 1024 : 1);
2786 return $val;
2789 # convert config value to array reference, if needed
2790 sub config_to_multi {
2791 my $val = shift;
2793 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2796 sub git_get_project_config {
2797 my ($key, $type) = @_;
2799 return unless defined $git_dir;
2801 # key sanity check
2802 return unless ($key);
2803 # only subsection, if exists, is case sensitive,
2804 # and not lowercased by 'git config -z -l'
2805 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2806 $lo =~ s/_//g;
2807 $key = join(".", lc($hi), $mi, lc($lo));
2808 return if ($lo =~ /\W/ || $hi =~ /\W/);
2809 } else {
2810 $key = lc($key);
2811 $key =~ s/_//g;
2812 return if ($key =~ /\W/);
2814 $key =~ s/^gitweb\.//;
2816 # type sanity check
2817 if (defined $type) {
2818 $type =~ s/^--//;
2819 $type = undef
2820 unless ($type eq 'bool' || $type eq 'int');
2823 # get config
2824 if (!defined $config_file ||
2825 $config_file ne "$git_dir/config") {
2826 %config = git_parse_project_config('gitweb');
2827 $config_file = "$git_dir/config";
2830 # check if config variable (key) exists
2831 return unless exists $config{"gitweb.$key"};
2833 # ensure given type
2834 if (!defined $type) {
2835 return $config{"gitweb.$key"};
2836 } elsif ($type eq 'bool') {
2837 # backward compatibility: 'git config --bool' returns true/false
2838 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2839 } elsif ($type eq 'int') {
2840 return config_to_int($config{"gitweb.$key"});
2842 return $config{"gitweb.$key"};
2845 # get hash of given path at given ref
2846 sub git_get_hash_by_path {
2847 my $base = shift;
2848 my $path = shift || return undef;
2849 my $type = shift;
2851 $path =~ s,/+$,,;
2853 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2854 or die_error(500, "Open git-ls-tree failed");
2855 my $line = <$fd>;
2856 close $fd or return undef;
2858 if (!defined $line) {
2859 # there is no tree or hash given by $path at $base
2860 return undef;
2863 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2864 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2865 if (defined $type && $type ne $2) {
2866 # type doesn't match
2867 return undef;
2869 return $3;
2872 # get path of entry with given hash at given tree-ish (ref)
2873 # used to get 'from' filename for combined diff (merge commit) for renames
2874 sub git_get_path_by_hash {
2875 my $base = shift || return;
2876 my $hash = shift || return;
2878 local $/ = "\0";
2880 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2881 or return undef;
2882 while (my $line = <$fd>) {
2883 chomp $line;
2885 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2886 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2887 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2888 close $fd;
2889 return $1;
2892 close $fd;
2893 return undef;
2896 ## ......................................................................
2897 ## git utility functions, directly accessing git repository
2899 # get the value of config variable either from file named as the variable
2900 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2901 # configuration variable in the repository config file.
2902 sub git_get_file_or_project_config {
2903 my ($path, $name) = @_;
2905 $git_dir = "$projectroot/$path";
2906 open my $fd, '<', "$git_dir/$name"
2907 or return git_get_project_config($name);
2908 my $conf = <$fd>;
2909 close $fd;
2910 if (defined $conf) {
2911 chomp $conf;
2913 return $conf;
2916 sub git_get_project_description {
2917 my $path = shift;
2918 return git_get_file_or_project_config($path, 'description');
2921 sub git_get_project_category {
2922 my $path = shift;
2923 return git_get_file_or_project_config($path, 'category');
2927 # supported formats:
2928 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2929 # - if its contents is a number, use it as tag weight,
2930 # - otherwise add a tag with weight 1
2931 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2932 # the same value multiple times increases tag weight
2933 # * `gitweb.ctag' multi-valued repo config variable
2934 sub git_get_project_ctags {
2935 my $project = shift;
2936 my $ctags = {};
2938 $git_dir = "$projectroot/$project";
2939 if (opendir my $dh, "$git_dir/ctags") {
2940 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2941 foreach my $tagfile (@files) {
2942 open my $ct, '<', $tagfile
2943 or next;
2944 my $val = <$ct>;
2945 chomp $val if $val;
2946 close $ct;
2948 (my $ctag = $tagfile) =~ s#.*/##;
2949 if ($val =~ /^\d+$/) {
2950 $ctags->{$ctag} = $val;
2951 } else {
2952 $ctags->{$ctag} = 1;
2955 closedir $dh;
2957 } elsif (open my $fh, '<', "$git_dir/ctags") {
2958 while (my $line = <$fh>) {
2959 chomp $line;
2960 $ctags->{$line}++ if $line;
2962 close $fh;
2964 } else {
2965 my $taglist = config_to_multi(git_get_project_config('ctag'));
2966 foreach my $tag (@$taglist) {
2967 $ctags->{$tag}++;
2971 return $ctags;
2974 # return hash, where keys are content tags ('ctags'),
2975 # and values are sum of weights of given tag in every project
2976 sub git_gather_all_ctags {
2977 my $projects = shift;
2978 my $ctags = {};
2980 foreach my $p (@$projects) {
2981 foreach my $ct (keys %{$p->{'ctags'}}) {
2982 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2986 return $ctags;
2989 sub git_populate_project_tagcloud {
2990 my $ctags = shift;
2992 # First, merge different-cased tags; tags vote on casing
2993 my %ctags_lc;
2994 foreach (keys %$ctags) {
2995 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2996 if (not $ctags_lc{lc $_}->{topcount}
2997 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2998 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2999 $ctags_lc{lc $_}->{topname} = $_;
3003 my $cloud;
3004 my $matched = $input_params{'ctag'};
3005 if (eval { require HTML::TagCloud; 1; }) {
3006 $cloud = HTML::TagCloud->new;
3007 foreach my $ctag (sort keys %ctags_lc) {
3008 # Pad the title with spaces so that the cloud looks
3009 # less crammed.
3010 my $title = esc_html($ctags_lc{$ctag}->{topname});
3011 $title =~ s/ /&nbsp;/g;
3012 $title =~ s/^/&nbsp;/g;
3013 $title =~ s/$/&nbsp;/g;
3014 if (defined $matched && $matched eq $ctag) {
3015 $title = qq(<span class="match">$title</span>);
3017 $cloud->add($title, href(project=>undef, ctag=>$ctag),
3018 $ctags_lc{$ctag}->{count});
3020 } else {
3021 $cloud = {};
3022 foreach my $ctag (keys %ctags_lc) {
3023 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3024 if (defined $matched && $matched eq $ctag) {
3025 $title = qq(<span class="match">$title</span>);
3027 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3028 $cloud->{$ctag}{ctag} =
3029 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3032 return $cloud;
3035 sub git_show_project_tagcloud {
3036 my ($cloud, $count) = @_;
3037 if (ref $cloud eq 'HTML::TagCloud') {
3038 return $cloud->html_and_css($count);
3039 } else {
3040 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3041 return
3042 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3043 join (', ', map {
3044 $cloud->{$_}->{'ctag'}
3045 } splice(@tags, 0, $count)) .
3046 '</div>';
3050 sub git_get_project_url_list {
3051 my $path = shift;
3053 $git_dir = "$projectroot/$path";
3054 open my $fd, '<', "$git_dir/cloneurl"
3055 or return wantarray ?
3056 @{ config_to_multi(git_get_project_config('url')) } :
3057 config_to_multi(git_get_project_config('url'));
3058 my @git_project_url_list = map { chomp; $_ } <$fd>;
3059 close $fd;
3061 return wantarray ? @git_project_url_list : \@git_project_url_list;
3064 sub git_get_projects_list {
3065 my $filter = shift || '';
3066 my $paranoid = shift;
3067 my @list;
3069 if (-d $projects_list) {
3070 # search in directory
3071 my $dir = $projects_list;
3072 # remove the trailing "/"
3073 $dir =~ s!/+$!!;
3074 my $pfxlen = length("$dir");
3075 my $pfxdepth = ($dir =~ tr!/!!);
3076 # when filtering, search only given subdirectory
3077 if ($filter && !$paranoid) {
3078 $dir .= "/$filter";
3079 $dir =~ s!/+$!!;
3082 File::Find::find({
3083 follow_fast => 1, # follow symbolic links
3084 follow_skip => 2, # ignore duplicates
3085 dangling_symlinks => 0, # ignore dangling symlinks, silently
3086 wanted => sub {
3087 # global variables
3088 our $project_maxdepth;
3089 our $projectroot;
3090 # skip project-list toplevel, if we get it.
3091 return if (m!^[/.]$!);
3092 # only directories can be git repositories
3093 return unless (-d $_);
3094 # don't traverse too deep (Find is super slow on os x)
3095 # $project_maxdepth excludes depth of $projectroot
3096 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3097 $File::Find::prune = 1;
3098 return;
3101 my $path = substr($File::Find::name, $pfxlen + 1);
3102 # paranoidly only filter here
3103 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3104 next;
3106 # we check related file in $projectroot
3107 if (check_export_ok("$projectroot/$path")) {
3108 push @list, { path => $path };
3109 $File::Find::prune = 1;
3112 }, "$dir");
3114 } elsif (-f $projects_list) {
3115 # read from file(url-encoded):
3116 # 'git%2Fgit.git Linus+Torvalds'
3117 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3118 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3119 open my $fd, '<', $projects_list or return;
3120 PROJECT:
3121 while (my $line = <$fd>) {
3122 chomp $line;
3123 my ($path, $owner) = split ' ', $line;
3124 $path = unescape($path);
3125 $owner = unescape($owner);
3126 if (!defined $path) {
3127 next;
3129 # if $filter is rpovided, check if $path begins with $filter
3130 if ($filter && $path !~ m!^\Q$filter\E/!) {
3131 next;
3133 if (check_export_ok("$projectroot/$path")) {
3134 my $pr = {
3135 path => $path
3137 if ($owner) {
3138 $pr->{'owner'} = to_utf8($owner);
3140 push @list, $pr;
3143 close $fd;
3145 return @list;
3148 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3149 # as side effects it sets 'forks' field to list of forks for forked projects
3150 sub filter_forks_from_projects_list {
3151 my $projects = shift;
3153 my %trie; # prefix tree of directories (path components)
3154 # generate trie out of those directories that might contain forks
3155 foreach my $pr (@$projects) {
3156 my $path = $pr->{'path'};
3157 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3158 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3159 next unless ($path); # skip '.git' repository: tests, git-instaweb
3160 next unless (-d "$projectroot/$path"); # containing directory exists
3161 $pr->{'forks'} = []; # there can be 0 or more forks of project
3163 # add to trie
3164 my @dirs = split('/', $path);
3165 # walk the trie, until either runs out of components or out of trie
3166 my $ref = \%trie;
3167 while (scalar @dirs &&
3168 exists($ref->{$dirs[0]})) {
3169 $ref = $ref->{shift @dirs};
3171 # create rest of trie structure from rest of components
3172 foreach my $dir (@dirs) {
3173 $ref = $ref->{$dir} = {};
3175 # create end marker, store $pr as a data
3176 $ref->{''} = $pr if (!exists $ref->{''});
3179 # filter out forks, by finding shortest prefix match for paths
3180 my @filtered;
3181 PROJECT:
3182 foreach my $pr (@$projects) {
3183 # trie lookup
3184 my $ref = \%trie;
3185 DIR:
3186 foreach my $dir (split('/', $pr->{'path'})) {
3187 if (exists $ref->{''}) {
3188 # found [shortest] prefix, is a fork - skip it
3189 push @{$ref->{''}{'forks'}}, $pr;
3190 next PROJECT;
3192 if (!exists $ref->{$dir}) {
3193 # not in trie, cannot have prefix, not a fork
3194 push @filtered, $pr;
3195 next PROJECT;
3197 # If the dir is there, we just walk one step down the trie.
3198 $ref = $ref->{$dir};
3200 # we ran out of trie
3201 # (shouldn't happen: it's either no match, or end marker)
3202 push @filtered, $pr;
3205 return @filtered;
3208 # note: fill_project_list_info must be run first,
3209 # for 'descr_long' and 'ctags' to be filled
3210 sub search_projects_list {
3211 my ($projlist, %opts) = @_;
3212 my $tagfilter = $opts{'tagfilter'};
3213 my $search_re = $opts{'search_regexp'};
3215 return @$projlist
3216 unless ($tagfilter || $search_re);
3218 # searching projects require filling to be run before it;
3219 fill_project_list_info($projlist,
3220 $tagfilter ? 'ctags' : (),
3221 $search_re ? ('path', 'descr') : ());
3222 my @projects;
3223 PROJECT:
3224 foreach my $pr (@$projlist) {
3226 if ($tagfilter) {
3227 next unless ref($pr->{'ctags'}) eq 'HASH';
3228 next unless
3229 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3232 if ($search_re) {
3233 next unless
3234 $pr->{'path'} =~ /$search_re/ ||
3235 $pr->{'descr_long'} =~ /$search_re/;
3238 push @projects, $pr;
3241 return @projects;
3244 our $gitweb_project_owner = undef;
3245 sub git_get_project_list_from_file {
3247 return if (defined $gitweb_project_owner);
3249 $gitweb_project_owner = {};
3250 # read from file (url-encoded):
3251 # 'git%2Fgit.git Linus+Torvalds'
3252 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3253 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3254 if (-f $projects_list) {
3255 open(my $fd, '<', $projects_list);
3256 while (my $line = <$fd>) {
3257 chomp $line;
3258 my ($pr, $ow) = split ' ', $line;
3259 $pr = unescape($pr);
3260 $ow = unescape($ow);
3261 $gitweb_project_owner->{$pr} = to_utf8($ow);
3263 close $fd;
3267 sub git_get_project_owner {
3268 my $project = shift;
3269 my $owner;
3271 return undef unless $project;
3272 $git_dir = "$projectroot/$project";
3274 if (!defined $gitweb_project_owner) {
3275 git_get_project_list_from_file();
3278 if (exists $gitweb_project_owner->{$project}) {
3279 $owner = $gitweb_project_owner->{$project};
3281 if (!defined $owner){
3282 $owner = git_get_project_config('owner');
3284 if (!defined $owner) {
3285 $owner = get_file_owner("$git_dir");
3288 return $owner;
3291 sub git_get_last_activity {
3292 my ($path) = @_;
3293 my $fd;
3295 $git_dir = "$projectroot/$path";
3296 open($fd, "-|", git_cmd(), 'for-each-ref',
3297 '--format=%(committer)',
3298 '--sort=-committerdate',
3299 '--count=1',
3300 map { "refs/$_" } get_branch_refs ()) or return;
3301 my $most_recent = <$fd>;
3302 close $fd or return;
3303 if (defined $most_recent &&
3304 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3305 my $timestamp = $1;
3306 my $age = time - $timestamp;
3307 return ($age, age_string($age));
3309 return (undef, undef);
3312 # Implementation note: when a single remote is wanted, we cannot use 'git
3313 # remote show -n' because that command always work (assuming it's a remote URL
3314 # if it's not defined), and we cannot use 'git remote show' because that would
3315 # try to make a network roundtrip. So the only way to find if that particular
3316 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3317 # and when we find what we want.
3318 sub git_get_remotes_list {
3319 my $wanted = shift;
3320 my %remotes = ();
3322 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3323 return unless $fd;
3324 while (my $remote = <$fd>) {
3325 chomp $remote;
3326 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3327 next if $wanted and not $remote eq $wanted;
3328 my ($url, $key) = ($1, $2);
3330 $remotes{$remote} ||= { 'heads' => () };
3331 $remotes{$remote}{$key} = $url;
3333 close $fd or return;
3334 return wantarray ? %remotes : \%remotes;
3337 # Takes a hash of remotes as first parameter and fills it by adding the
3338 # available remote heads for each of the indicated remotes.
3339 sub fill_remote_heads {
3340 my $remotes = shift;
3341 my @heads = map { "remotes/$_" } keys %$remotes;
3342 my @remoteheads = git_get_heads_list(undef, @heads);
3343 foreach my $remote (keys %$remotes) {
3344 $remotes->{$remote}{'heads'} = [ grep {
3345 $_->{'name'} =~ s!^$remote/!!
3346 } @remoteheads ];
3350 sub git_get_references {
3351 my $type = shift || "";
3352 my %refs;
3353 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3354 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3355 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3356 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3357 or return;
3359 while (my $line = <$fd>) {
3360 chomp $line;
3361 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3362 if (defined $refs{$1}) {
3363 push @{$refs{$1}}, $2;
3364 } else {
3365 $refs{$1} = [ $2 ];
3369 close $fd or return;
3370 return \%refs;
3373 sub git_get_rev_name_tags {
3374 my $hash = shift || return undef;
3376 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3377 or return;
3378 my $name_rev = <$fd>;
3379 close $fd;
3381 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3382 return $1;
3383 } else {
3384 # catches also '$hash undefined' output
3385 return undef;
3389 ## ----------------------------------------------------------------------
3390 ## parse to hash functions
3392 sub parse_date {
3393 my $epoch = shift;
3394 my $tz = shift || "-0000";
3396 my %date;
3397 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3398 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3399 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3400 $date{'hour'} = $hour;
3401 $date{'minute'} = $min;
3402 $date{'mday'} = $mday;
3403 $date{'day'} = $days[$wday];
3404 $date{'month'} = $months[$mon];
3405 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3406 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3407 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3408 $mday, $months[$mon], $hour ,$min;
3409 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3410 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3412 my ($tz_sign, $tz_hour, $tz_min) =
3413 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3414 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3415 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3416 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3417 $date{'hour_local'} = $hour;
3418 $date{'minute_local'} = $min;
3419 $date{'tz_local'} = $tz;
3420 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3421 1900+$year, $mon+1, $mday,
3422 $hour, $min, $sec, $tz);
3423 return %date;
3426 sub parse_tag {
3427 my $tag_id = shift;
3428 my %tag;
3429 my @comment;
3431 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3432 $tag{'id'} = $tag_id;
3433 while (my $line = <$fd>) {
3434 chomp $line;
3435 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3436 $tag{'object'} = $1;
3437 } elsif ($line =~ m/^type (.+)$/) {
3438 $tag{'type'} = $1;
3439 } elsif ($line =~ m/^tag (.+)$/) {
3440 $tag{'name'} = $1;
3441 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3442 $tag{'author'} = $1;
3443 $tag{'author_epoch'} = $2;
3444 $tag{'author_tz'} = $3;
3445 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3446 $tag{'author_name'} = $1;
3447 $tag{'author_email'} = $2;
3448 } else {
3449 $tag{'author_name'} = $tag{'author'};
3451 } elsif ($line =~ m/--BEGIN/) {
3452 push @comment, $line;
3453 last;
3454 } elsif ($line eq "") {
3455 last;
3458 push @comment, <$fd>;
3459 $tag{'comment'} = \@comment;
3460 close $fd or return;
3461 if (!defined $tag{'name'}) {
3462 return
3464 return %tag
3467 sub parse_commit_text {
3468 my ($commit_text, $withparents) = @_;
3469 my @commit_lines = split '\n', $commit_text;
3470 my %co;
3472 pop @commit_lines; # Remove '\0'
3474 if (! @commit_lines) {
3475 return;
3478 my $header = shift @commit_lines;
3479 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3480 return;
3482 ($co{'id'}, my @parents) = split ' ', $header;
3483 while (my $line = shift @commit_lines) {
3484 last if $line eq "\n";
3485 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3486 $co{'tree'} = $1;
3487 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3488 push @parents, $1;
3489 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3490 $co{'author'} = to_utf8($1);
3491 $co{'author_epoch'} = $2;
3492 $co{'author_tz'} = $3;
3493 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3494 $co{'author_name'} = $1;
3495 $co{'author_email'} = $2;
3496 } else {
3497 $co{'author_name'} = $co{'author'};
3499 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3500 $co{'committer'} = to_utf8($1);
3501 $co{'committer_epoch'} = $2;
3502 $co{'committer_tz'} = $3;
3503 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3504 $co{'committer_name'} = $1;
3505 $co{'committer_email'} = $2;
3506 } else {
3507 $co{'committer_name'} = $co{'committer'};
3511 if (!defined $co{'tree'}) {
3512 return;
3514 $co{'parents'} = \@parents;
3515 $co{'parent'} = $parents[0];
3517 foreach my $title (@commit_lines) {
3518 $title =~ s/^ //;
3519 if ($title ne "") {
3520 $co{'title'} = chop_str($title, 80, 5);
3521 # remove leading stuff of merges to make the interesting part visible
3522 if (length($title) > 50) {
3523 $title =~ s/^Automatic //;
3524 $title =~ s/^merge (of|with) /Merge ... /i;
3525 if (length($title) > 50) {
3526 $title =~ s/(http|rsync):\/\///;
3528 if (length($title) > 50) {
3529 $title =~ s/(master|www|rsync)\.//;
3531 if (length($title) > 50) {
3532 $title =~ s/kernel.org:?//;
3534 if (length($title) > 50) {
3535 $title =~ s/\/pub\/scm//;
3538 $co{'title_short'} = chop_str($title, 50, 5);
3539 last;
3542 if (! defined $co{'title'} || $co{'title'} eq "") {
3543 $co{'title'} = $co{'title_short'} = '(no commit message)';
3545 # remove added spaces
3546 foreach my $line (@commit_lines) {
3547 $line =~ s/^ //;
3549 $co{'comment'} = \@commit_lines;
3551 my $age = time - $co{'committer_epoch'};
3552 $co{'age'} = $age;
3553 $co{'age_string'} = age_string($age);
3554 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3555 if ($age > 60*60*24*7*2) {
3556 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3557 $co{'age_string_age'} = $co{'age_string'};
3558 } else {
3559 $co{'age_string_date'} = $co{'age_string'};
3560 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3562 return %co;
3565 sub parse_commit {
3566 my ($commit_id) = @_;
3567 my %co;
3569 local $/ = "\0";
3571 open my $fd, "-|", git_cmd(), "rev-list",
3572 "--parents",
3573 "--header",
3574 "--max-count=1",
3575 $commit_id,
3576 "--",
3577 or die_error(500, "Open git-rev-list failed");
3578 %co = parse_commit_text(<$fd>, 1);
3579 close $fd;
3581 return %co;
3584 sub parse_commits {
3585 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3586 my @cos;
3588 $maxcount ||= 1;
3589 $skip ||= 0;
3591 local $/ = "\0";
3593 open my $fd, "-|", git_cmd(), "rev-list",
3594 "--header",
3595 @args,
3596 ("--max-count=" . $maxcount),
3597 ("--skip=" . $skip),
3598 @extra_options,
3599 $commit_id,
3600 "--",
3601 ($filename ? ($filename) : ())
3602 or die_error(500, "Open git-rev-list failed");
3603 while (my $line = <$fd>) {
3604 my %co = parse_commit_text($line);
3605 push @cos, \%co;
3607 close $fd;
3609 return wantarray ? @cos : \@cos;
3612 # parse line of git-diff-tree "raw" output
3613 sub parse_difftree_raw_line {
3614 my $line = shift;
3615 my %res;
3617 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3618 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3619 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3620 $res{'from_mode'} = $1;
3621 $res{'to_mode'} = $2;
3622 $res{'from_id'} = $3;
3623 $res{'to_id'} = $4;
3624 $res{'status'} = $5;
3625 $res{'similarity'} = $6;
3626 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3627 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3628 } else {
3629 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3632 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3633 # combined diff (for merge commit)
3634 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3635 $res{'nparents'} = length($1);
3636 $res{'from_mode'} = [ split(' ', $2) ];
3637 $res{'to_mode'} = pop @{$res{'from_mode'}};
3638 $res{'from_id'} = [ split(' ', $3) ];
3639 $res{'to_id'} = pop @{$res{'from_id'}};
3640 $res{'status'} = [ split('', $4) ];
3641 $res{'to_file'} = unquote($5);
3643 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3644 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3645 $res{'commit'} = $1;
3648 return wantarray ? %res : \%res;
3651 # wrapper: return parsed line of git-diff-tree "raw" output
3652 # (the argument might be raw line, or parsed info)
3653 sub parsed_difftree_line {
3654 my $line_or_ref = shift;
3656 if (ref($line_or_ref) eq "HASH") {
3657 # pre-parsed (or generated by hand)
3658 return $line_or_ref;
3659 } else {
3660 return parse_difftree_raw_line($line_or_ref);
3664 # parse line of git-ls-tree output
3665 sub parse_ls_tree_line {
3666 my $line = shift;
3667 my %opts = @_;
3668 my %res;
3670 if ($opts{'-l'}) {
3671 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3672 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3674 $res{'mode'} = $1;
3675 $res{'type'} = $2;
3676 $res{'hash'} = $3;
3677 $res{'size'} = $4;
3678 if ($opts{'-z'}) {
3679 $res{'name'} = $5;
3680 } else {
3681 $res{'name'} = unquote($5);
3683 } else {
3684 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3685 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3687 $res{'mode'} = $1;
3688 $res{'type'} = $2;
3689 $res{'hash'} = $3;
3690 if ($opts{'-z'}) {
3691 $res{'name'} = $4;
3692 } else {
3693 $res{'name'} = unquote($4);
3697 return wantarray ? %res : \%res;
3700 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3701 sub parse_from_to_diffinfo {
3702 my ($diffinfo, $from, $to, @parents) = @_;
3704 if ($diffinfo->{'nparents'}) {
3705 # combined diff
3706 $from->{'file'} = [];
3707 $from->{'href'} = [];
3708 fill_from_file_info($diffinfo, @parents)
3709 unless exists $diffinfo->{'from_file'};
3710 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3711 $from->{'file'}[$i] =
3712 defined $diffinfo->{'from_file'}[$i] ?
3713 $diffinfo->{'from_file'}[$i] :
3714 $diffinfo->{'to_file'};
3715 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3716 $from->{'href'}[$i] = href(action=>"blob",
3717 hash_base=>$parents[$i],
3718 hash=>$diffinfo->{'from_id'}[$i],
3719 file_name=>$from->{'file'}[$i]);
3720 } else {
3721 $from->{'href'}[$i] = undef;
3724 } else {
3725 # ordinary (not combined) diff
3726 $from->{'file'} = $diffinfo->{'from_file'};
3727 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3728 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3729 hash=>$diffinfo->{'from_id'},
3730 file_name=>$from->{'file'});
3731 } else {
3732 delete $from->{'href'};
3736 $to->{'file'} = $diffinfo->{'to_file'};
3737 if (!is_deleted($diffinfo)) { # file exists in result
3738 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3739 hash=>$diffinfo->{'to_id'},
3740 file_name=>$to->{'file'});
3741 } else {
3742 delete $to->{'href'};
3746 ## ......................................................................
3747 ## parse to array of hashes functions
3749 sub git_get_heads_list {
3750 my ($limit, @classes) = @_;
3751 @classes = get_branch_refs() unless @classes;
3752 my @patterns = map { "refs/$_" } @classes;
3753 my @headslist;
3755 open my $fd, '-|', git_cmd(), 'for-each-ref',
3756 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3757 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3758 @patterns
3759 or return;
3760 while (my $line = <$fd>) {
3761 my %ref_item;
3763 chomp $line;
3764 my ($refinfo, $committerinfo) = split(/\0/, $line);
3765 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3766 my ($committer, $epoch, $tz) =
3767 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3768 $ref_item{'fullname'} = $name;
3769 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3770 $name =~ s!^refs/($strip_refs|remotes)/!!;
3771 $ref_item{'name'} = $name;
3772 # for refs neither in 'heads' nor 'remotes' we want to
3773 # show their ref dir
3774 my $ref_dir = (defined $1) ? $1 : '';
3775 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3776 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3779 $ref_item{'id'} = $hash;
3780 $ref_item{'title'} = $title || '(no commit message)';
3781 $ref_item{'epoch'} = $epoch;
3782 if ($epoch) {
3783 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3784 } else {
3785 $ref_item{'age'} = "unknown";
3788 push @headslist, \%ref_item;
3790 close $fd;
3792 return wantarray ? @headslist : \@headslist;
3795 sub git_get_tags_list {
3796 my $limit = shift;
3797 my @tagslist;
3799 open my $fd, '-|', git_cmd(), 'for-each-ref',
3800 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3801 '--format=%(objectname) %(objecttype) %(refname) '.
3802 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3803 'refs/tags'
3804 or return;
3805 while (my $line = <$fd>) {
3806 my %ref_item;
3808 chomp $line;
3809 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3810 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3811 my ($creator, $epoch, $tz) =
3812 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3813 $ref_item{'fullname'} = $name;
3814 $name =~ s!^refs/tags/!!;
3816 $ref_item{'type'} = $type;
3817 $ref_item{'id'} = $id;
3818 $ref_item{'name'} = $name;
3819 if ($type eq "tag") {
3820 $ref_item{'subject'} = $title;
3821 $ref_item{'reftype'} = $reftype;
3822 $ref_item{'refid'} = $refid;
3823 } else {
3824 $ref_item{'reftype'} = $type;
3825 $ref_item{'refid'} = $id;
3828 if ($type eq "tag" || $type eq "commit") {
3829 $ref_item{'epoch'} = $epoch;
3830 if ($epoch) {
3831 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3832 } else {
3833 $ref_item{'age'} = "unknown";
3837 push @tagslist, \%ref_item;
3839 close $fd;
3841 return wantarray ? @tagslist : \@tagslist;
3844 ## ----------------------------------------------------------------------
3845 ## filesystem-related functions
3847 sub get_file_owner {
3848 my $path = shift;
3850 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3851 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3852 if (!defined $gcos) {
3853 return undef;
3855 my $owner = $gcos;
3856 $owner =~ s/[,;].*$//;
3857 return to_utf8($owner);
3860 # assume that file exists
3861 sub insert_file {
3862 my $filename = shift;
3864 open my $fd, '<', $filename;
3865 print map { to_utf8($_) } <$fd>;
3866 close $fd;
3869 ## ......................................................................
3870 ## mimetype related functions
3872 sub mimetype_guess_file {
3873 my $filename = shift;
3874 my $mimemap = shift;
3875 -r $mimemap or return undef;
3877 my %mimemap;
3878 open(my $mh, '<', $mimemap) or return undef;
3879 while (<$mh>) {
3880 next if m/^#/; # skip comments
3881 my ($mimetype, @exts) = split(/\s+/);
3882 foreach my $ext (@exts) {
3883 $mimemap{$ext} = $mimetype;
3886 close($mh);
3888 $filename =~ /\.([^.]*)$/;
3889 return $mimemap{$1};
3892 sub mimetype_guess {
3893 my $filename = shift;
3894 my $mime;
3895 $filename =~ /\./ or return undef;
3897 if ($mimetypes_file) {
3898 my $file = $mimetypes_file;
3899 if ($file !~ m!^/!) { # if it is relative path
3900 # it is relative to project
3901 $file = "$projectroot/$project/$file";
3903 $mime = mimetype_guess_file($filename, $file);
3905 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3906 return $mime;
3909 sub blob_mimetype {
3910 my $fd = shift;
3911 my $filename = shift;
3913 if ($filename) {
3914 my $mime = mimetype_guess($filename);
3915 $mime and return $mime;
3918 # just in case
3919 return $default_blob_plain_mimetype unless $fd;
3921 if (-T $fd) {
3922 return 'text/plain';
3923 } elsif (! $filename) {
3924 return 'application/octet-stream';
3925 } elsif ($filename =~ m/\.png$/i) {
3926 return 'image/png';
3927 } elsif ($filename =~ m/\.gif$/i) {
3928 return 'image/gif';
3929 } elsif ($filename =~ m/\.jpe?g$/i) {
3930 return 'image/jpeg';
3931 } else {
3932 return 'application/octet-stream';
3936 sub blob_contenttype {
3937 my ($fd, $file_name, $type) = @_;
3939 $type ||= blob_mimetype($fd, $file_name);
3940 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3941 $type .= "; charset=$default_text_plain_charset";
3944 return $type;
3947 # guess file syntax for syntax highlighting; return undef if no highlighting
3948 # the name of syntax can (in the future) depend on syntax highlighter used
3949 sub guess_file_syntax {
3950 my ($highlight, $mimetype, $file_name) = @_;
3951 return undef unless ($highlight && defined $file_name);
3952 my $basename = basename($file_name, '.in');
3953 return $highlight_basename{$basename}
3954 if exists $highlight_basename{$basename};
3956 $basename =~ /\.([^.]*)$/;
3957 my $ext = $1 or return undef;
3958 return $highlight_ext{$ext}
3959 if exists $highlight_ext{$ext};
3961 return undef;
3964 # run highlighter and return FD of its output,
3965 # or return original FD if no highlighting
3966 sub run_highlighter {
3967 my ($fd, $highlight, $syntax) = @_;
3968 return $fd unless ($highlight && defined $syntax);
3970 close $fd;
3971 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3972 quote_command($highlight_bin).
3973 " --replace-tabs=8 --fragment --syntax $syntax |"
3974 or die_error(500, "Couldn't open file or run syntax highlighter");
3975 return $fd;
3978 ## ======================================================================
3979 ## functions printing HTML: header, footer, error page
3981 sub get_page_title {
3982 my $title = to_utf8($site_name);
3984 unless (defined $project) {
3985 if (defined $project_filter) {
3986 $title .= " - projects in '" . esc_path($project_filter) . "'";
3988 return $title;
3990 $title .= " - " . to_utf8($project);
3992 return $title unless (defined $action);
3993 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3995 return $title unless (defined $file_name);
3996 $title .= " - " . esc_path($file_name);
3997 if ($action eq "tree" && $file_name !~ m|/$|) {
3998 $title .= "/";
4001 return $title;
4004 sub get_content_type_html {
4005 # require explicit support from the UA if we are to send the page as
4006 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4007 # we have to do this because MSIE sometimes globs '*/*', pretending to
4008 # support xhtml+xml but choking when it gets what it asked for.
4009 if (defined $cgi->http('HTTP_ACCEPT') &&
4010 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
4011 $cgi->Accept('application/xhtml+xml') != 0) {
4012 return 'application/xhtml+xml';
4013 } else {
4014 return 'text/html';
4018 sub print_feed_meta {
4019 if (defined $project) {
4020 my %href_params = get_feed_info();
4021 if (!exists $href_params{'-title'}) {
4022 $href_params{'-title'} = 'log';
4025 foreach my $format (qw(RSS Atom)) {
4026 my $type = lc($format);
4027 my %link_attr = (
4028 '-rel' => 'alternate',
4029 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4030 '-type' => "application/$type+xml"
4033 $href_params{'extra_options'} = undef;
4034 $href_params{'action'} = $type;
4035 $link_attr{'-href'} = href(%href_params);
4036 print "<link ".
4037 "rel=\"$link_attr{'-rel'}\" ".
4038 "title=\"$link_attr{'-title'}\" ".
4039 "href=\"$link_attr{'-href'}\" ".
4040 "type=\"$link_attr{'-type'}\" ".
4041 "/>\n";
4043 $href_params{'extra_options'} = '--no-merges';
4044 $link_attr{'-href'} = href(%href_params);
4045 $link_attr{'-title'} .= ' (no merges)';
4046 print "<link ".
4047 "rel=\"$link_attr{'-rel'}\" ".
4048 "title=\"$link_attr{'-title'}\" ".
4049 "href=\"$link_attr{'-href'}\" ".
4050 "type=\"$link_attr{'-type'}\" ".
4051 "/>\n";
4054 } else {
4055 printf('<link rel="alternate" title="%s projects list" '.
4056 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4057 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4058 printf('<link rel="alternate" title="%s projects feeds" '.
4059 'href="%s" type="text/x-opml" />'."\n",
4060 esc_attr($site_name), href(project=>undef, action=>"opml"));
4064 sub print_header_links {
4065 my $status = shift;
4067 # print out each stylesheet that exist, providing backwards capability
4068 # for those people who defined $stylesheet in a config file
4069 if (defined $stylesheet) {
4070 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4071 } else {
4072 foreach my $stylesheet (@stylesheets) {
4073 next unless $stylesheet;
4074 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4077 print_feed_meta()
4078 if ($status eq '200 OK');
4079 if (defined $favicon) {
4080 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4084 sub print_nav_breadcrumbs_path {
4085 my $dirprefix = undef;
4086 while (my $part = shift) {
4087 $dirprefix .= "/" if defined $dirprefix;
4088 $dirprefix .= $part;
4089 print $cgi->a({-href => href(project => undef,
4090 project_filter => $dirprefix,
4091 action => "project_list")},
4092 esc_html($part)) . " / ";
4096 sub print_nav_breadcrumbs {
4097 my %opts = @_;
4099 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4100 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4102 if (defined $project) {
4103 my @dirname = split '/', $project;
4104 my $projectbasename = pop @dirname;
4105 print_nav_breadcrumbs_path(@dirname);
4106 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4107 if (defined $action) {
4108 my $action_print = $action ;
4109 if (defined $opts{-action_extra}) {
4110 $action_print = $cgi->a({-href => href(action=>$action)},
4111 $action);
4113 print " / $action_print";
4115 if (defined $opts{-action_extra}) {
4116 print " / $opts{-action_extra}";
4118 print "\n";
4119 } elsif (defined $project_filter) {
4120 print_nav_breadcrumbs_path(split '/', $project_filter);
4124 sub print_search_form {
4125 if (!defined $searchtext) {
4126 $searchtext = "";
4128 my $search_hash;
4129 if (defined $hash_base) {
4130 $search_hash = $hash_base;
4131 } elsif (defined $hash) {
4132 $search_hash = $hash;
4133 } else {
4134 $search_hash = "HEAD";
4136 my $action = $my_uri;
4137 my $use_pathinfo = gitweb_check_feature('pathinfo');
4138 if ($use_pathinfo) {
4139 $action .= "/".esc_url($project);
4141 print $cgi->start_form(-method => "get", -action => $action) .
4142 "<div class=\"search\">\n" .
4143 (!$use_pathinfo &&
4144 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4145 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4146 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4147 $cgi->popup_menu(-name => 'st', -default => 'commit',
4148 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4149 " " . $cgi->a({-href => href(action=>"search_help"),
4150 -title => "search help" }, "?") . " search:\n",
4151 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4152 "<span title=\"Extended regular expression\">" .
4153 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4154 -checked => $search_use_regexp) .
4155 "</span>" .
4156 "</div>" .
4157 $cgi->end_form() . "\n";
4160 sub git_header_html {
4161 my $status = shift || "200 OK";
4162 my $expires = shift;
4163 my %opts = @_;
4165 my $title = get_page_title();
4166 my $content_type = get_content_type_html();
4167 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4168 -status=> $status, -expires => $expires)
4169 unless ($opts{'-no_http_header'});
4170 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4171 print <<EOF;
4172 <?xml version="1.0" encoding="utf-8"?>
4173 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4174 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4175 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4176 <!-- git core binaries version $git_version -->
4177 <head>
4178 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4179 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4180 <meta name="robots" content="index, nofollow"/>
4181 <title>$title</title>
4183 # the stylesheet, favicon etc urls won't work correctly with path_info
4184 # unless we set the appropriate base URL
4185 if ($ENV{'PATH_INFO'}) {
4186 print "<base href=\"".esc_url($base_url)."\" />\n";
4188 print_header_links($status);
4190 if (defined $site_html_head_string) {
4191 print to_utf8($site_html_head_string);
4194 print "</head>\n" .
4195 "<body>\n";
4197 if (defined $site_header && -f $site_header) {
4198 insert_file($site_header);
4201 print "<div class=\"page_header\">\n";
4202 if (defined $logo) {
4203 print $cgi->a({-href => esc_url($logo_url),
4204 -title => $logo_label},
4205 $cgi->img({-src => esc_url($logo),
4206 -width => 72, -height => 27,
4207 -alt => "git",
4208 -class => "logo"}));
4210 print_nav_breadcrumbs(%opts);
4211 print "</div>\n";
4213 my $have_search = gitweb_check_feature('search');
4214 if (defined $project && $have_search) {
4215 print_search_form();
4219 sub git_footer_html {
4220 my $feed_class = 'rss_logo';
4222 print "<div class=\"page_footer\">\n";
4223 if (defined $project) {
4224 my $descr = git_get_project_description($project);
4225 if (defined $descr) {
4226 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4229 my %href_params = get_feed_info();
4230 if (!%href_params) {
4231 $feed_class .= ' generic';
4233 $href_params{'-title'} ||= 'log';
4235 foreach my $format (qw(RSS Atom)) {
4236 $href_params{'action'} = lc($format);
4237 print $cgi->a({-href => href(%href_params),
4238 -title => "$href_params{'-title'} $format feed",
4239 -class => $feed_class}, $format)."\n";
4242 } else {
4243 print $cgi->a({-href => href(project=>undef, action=>"opml",
4244 project_filter => $project_filter),
4245 -class => $feed_class}, "OPML") . " ";
4246 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4247 project_filter => $project_filter),
4248 -class => $feed_class}, "TXT") . "\n";
4250 print "</div>\n"; # class="page_footer"
4252 if (defined $t0 && gitweb_check_feature('timed')) {
4253 print "<div id=\"generating_info\">\n";
4254 print 'This page took '.
4255 '<span id="generating_time" class="time_span">'.
4256 tv_interval($t0, [ gettimeofday() ]).
4257 ' seconds </span>'.
4258 ' and '.
4259 '<span id="generating_cmd">'.
4260 $number_of_git_cmds.
4261 '</span> git commands '.
4262 " to generate.\n";
4263 print "</div>\n"; # class="page_footer"
4266 if (defined $site_footer && -f $site_footer) {
4267 insert_file($site_footer);
4270 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4271 if (defined $action &&
4272 $action eq 'blame_incremental') {
4273 print qq!<script type="text/javascript">\n!.
4274 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4275 qq! "!. href() .qq!");\n!.
4276 qq!</script>\n!;
4277 } else {
4278 my ($jstimezone, $tz_cookie, $datetime_class) =
4279 gitweb_get_feature('javascript-timezone');
4281 print qq!<script type="text/javascript">\n!.
4282 qq!window.onload = function () {\n!;
4283 if (gitweb_check_feature('javascript-actions')) {
4284 print qq! fixLinks();\n!;
4286 if ($jstimezone && $tz_cookie && $datetime_class) {
4287 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4288 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4290 print qq!};\n!.
4291 qq!</script>\n!;
4294 print "</body>\n" .
4295 "</html>";
4298 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4299 # Example: die_error(404, 'Hash not found')
4300 # By convention, use the following status codes (as defined in RFC 2616):
4301 # 400: Invalid or missing CGI parameters, or
4302 # requested object exists but has wrong type.
4303 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4304 # this server or project.
4305 # 404: Requested object/revision/project doesn't exist.
4306 # 500: The server isn't configured properly, or
4307 # an internal error occurred (e.g. failed assertions caused by bugs), or
4308 # an unknown error occurred (e.g. the git binary died unexpectedly).
4309 # 503: The server is currently unavailable (because it is overloaded,
4310 # or down for maintenance). Generally, this is a temporary state.
4311 sub die_error {
4312 my $status = shift || 500;
4313 my $error = esc_html(shift) || "Internal Server Error";
4314 my $extra = shift;
4315 my %opts = @_;
4317 my %http_responses = (
4318 400 => '400 Bad Request',
4319 403 => '403 Forbidden',
4320 404 => '404 Not Found',
4321 500 => '500 Internal Server Error',
4322 503 => '503 Service Unavailable',
4324 git_header_html($http_responses{$status}, undef, %opts);
4325 print <<EOF;
4326 <div class="page_body">
4327 <br /><br />
4328 $status - $error
4329 <br />
4331 if (defined $extra) {
4332 print "<hr />\n" .
4333 "$extra\n";
4335 print "</div>\n";
4337 git_footer_html();
4338 goto DONE_GITWEB
4339 unless ($opts{'-error_handler'});
4342 ## ----------------------------------------------------------------------
4343 ## functions printing or outputting HTML: navigation
4345 sub git_print_page_nav {
4346 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4347 $extra = '' if !defined $extra; # pager or formats
4349 my @navs = qw(summary shortlog log commit commitdiff tree);
4350 if ($suppress) {
4351 @navs = grep { $_ ne $suppress } @navs;
4354 my %arg = map { $_ => {action=>$_} } @navs;
4355 if (defined $head) {
4356 for (qw(commit commitdiff)) {
4357 $arg{$_}{'hash'} = $head;
4359 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4360 for (qw(shortlog log)) {
4361 $arg{$_}{'hash'} = $head;
4366 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4367 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4369 my @actions = gitweb_get_feature('actions');
4370 my %repl = (
4371 '%' => '%',
4372 'n' => $project, # project name
4373 'f' => $git_dir, # project path within filesystem
4374 'h' => $treehead || '', # current hash ('h' parameter)
4375 'b' => $treebase || '', # hash base ('hb' parameter)
4377 while (@actions) {
4378 my ($label, $link, $pos) = splice(@actions,0,3);
4379 # insert
4380 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4381 # munch munch
4382 $link =~ s/%([%nfhb])/$repl{$1}/g;
4383 $arg{$label}{'_href'} = $link;
4386 print "<div class=\"page_nav\">\n" .
4387 (join " | ",
4388 map { $_ eq $current ?
4389 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4390 } @navs);
4391 print "<br/>\n$extra<br/>\n" .
4392 "</div>\n";
4395 # returns a submenu for the nagivation of the refs views (tags, heads,
4396 # remotes) with the current view disabled and the remotes view only
4397 # available if the feature is enabled
4398 sub format_ref_views {
4399 my ($current) = @_;
4400 my @ref_views = qw{tags heads};
4401 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4402 return join " | ", map {
4403 $_ eq $current ? $_ :
4404 $cgi->a({-href => href(action=>$_)}, $_)
4405 } @ref_views
4408 sub format_paging_nav {
4409 my ($action, $page, $has_next_link) = @_;
4410 my $paging_nav;
4413 if ($page > 0) {
4414 $paging_nav .=
4415 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4416 " &sdot; " .
4417 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4418 -accesskey => "p", -title => "Alt-p"}, "prev");
4419 } else {
4420 $paging_nav .= "first &sdot; prev";
4423 if ($has_next_link) {
4424 $paging_nav .= " &sdot; " .
4425 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4426 -accesskey => "n", -title => "Alt-n"}, "next");
4427 } else {
4428 $paging_nav .= " &sdot; next";
4431 return $paging_nav;
4434 ## ......................................................................
4435 ## functions printing or outputting HTML: div
4437 sub git_print_header_div {
4438 my ($action, $title, $hash, $hash_base) = @_;
4439 my %args = ();
4441 $args{'action'} = $action;
4442 $args{'hash'} = $hash if $hash;
4443 $args{'hash_base'} = $hash_base if $hash_base;
4445 print "<div class=\"header\">\n" .
4446 $cgi->a({-href => href(%args), -class => "title"},
4447 $title ? $title : $action) .
4448 "\n</div>\n";
4451 sub format_repo_url {
4452 my ($name, $url) = @_;
4453 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4456 # Group output by placing it in a DIV element and adding a header.
4457 # Options for start_div() can be provided by passing a hash reference as the
4458 # first parameter to the function.
4459 # Options to git_print_header_div() can be provided by passing an array
4460 # reference. This must follow the options to start_div if they are present.
4461 # The content can be a scalar, which is output as-is, a scalar reference, which
4462 # is output after html escaping, an IO handle passed either as *handle or
4463 # *handle{IO}, or a function reference. In the latter case all following
4464 # parameters will be taken as argument to the content function call.
4465 sub git_print_section {
4466 my ($div_args, $header_args, $content);
4467 my $arg = shift;
4468 if (ref($arg) eq 'HASH') {
4469 $div_args = $arg;
4470 $arg = shift;
4472 if (ref($arg) eq 'ARRAY') {
4473 $header_args = $arg;
4474 $arg = shift;
4476 $content = $arg;
4478 print $cgi->start_div($div_args);
4479 git_print_header_div(@$header_args);
4481 if (ref($content) eq 'CODE') {
4482 $content->(@_);
4483 } elsif (ref($content) eq 'SCALAR') {
4484 print esc_html($$content);
4485 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4486 print <$content>;
4487 } elsif (!ref($content) && defined($content)) {
4488 print $content;
4491 print $cgi->end_div;
4494 sub format_timestamp_html {
4495 my $date = shift;
4496 my $strtime = $date->{'rfc2822'};
4498 my (undef, undef, $datetime_class) =
4499 gitweb_get_feature('javascript-timezone');
4500 if ($datetime_class) {
4501 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4504 my $localtime_format = '(%02d:%02d %s)';
4505 if ($date->{'hour_local'} < 6) {
4506 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4508 $strtime .= ' ' .
4509 sprintf($localtime_format,
4510 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4512 return $strtime;
4515 # Outputs the author name and date in long form
4516 sub git_print_authorship {
4517 my $co = shift;
4518 my %opts = @_;
4519 my $tag = $opts{-tag} || 'div';
4520 my $author = $co->{'author_name'};
4522 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4523 print "<$tag class=\"author_date\">" .
4524 format_search_author($author, "author", esc_html($author)) .
4525 " [".format_timestamp_html(\%ad)."]".
4526 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4527 "</$tag>\n";
4530 # Outputs table rows containing the full author or committer information,
4531 # in the format expected for 'commit' view (& similar).
4532 # Parameters are a commit hash reference, followed by the list of people
4533 # to output information for. If the list is empty it defaults to both
4534 # author and committer.
4535 sub git_print_authorship_rows {
4536 my $co = shift;
4537 # too bad we can't use @people = @_ || ('author', 'committer')
4538 my @people = @_;
4539 @people = ('author', 'committer') unless @people;
4540 foreach my $who (@people) {
4541 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4542 print "<tr><td>$who</td><td>" .
4543 format_search_author($co->{"${who}_name"}, $who,
4544 esc_html($co->{"${who}_name"})) . " " .
4545 format_search_author($co->{"${who}_email"}, $who,
4546 esc_html("<" . $co->{"${who}_email"} . ">")) .
4547 "</td><td rowspan=\"2\">" .
4548 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4549 "</td></tr>\n" .
4550 "<tr>" .
4551 "<td></td><td>" .
4552 format_timestamp_html(\%wd) .
4553 "</td>" .
4554 "</tr>\n";
4558 sub git_print_page_path {
4559 my $name = shift;
4560 my $type = shift;
4561 my $hb = shift;
4564 print "<div class=\"page_path\">";
4565 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4566 -title => 'tree root'}, to_utf8("[$project]"));
4567 print " / ";
4568 if (defined $name) {
4569 my @dirname = split '/', $name;
4570 my $basename = pop @dirname;
4571 my $fullname = '';
4573 foreach my $dir (@dirname) {
4574 $fullname .= ($fullname ? '/' : '') . $dir;
4575 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4576 hash_base=>$hb),
4577 -title => $fullname}, esc_path($dir));
4578 print " / ";
4580 if (defined $type && $type eq 'blob') {
4581 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4582 hash_base=>$hb),
4583 -title => $name}, esc_path($basename));
4584 } elsif (defined $type && $type eq 'tree') {
4585 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4586 hash_base=>$hb),
4587 -title => $name}, esc_path($basename));
4588 print " / ";
4589 } else {
4590 print esc_path($basename);
4593 print "<br/></div>\n";
4596 sub git_print_log {
4597 my $log = shift;
4598 my %opts = @_;
4600 if ($opts{'-remove_title'}) {
4601 # remove title, i.e. first line of log
4602 shift @$log;
4604 # remove leading empty lines
4605 while (defined $log->[0] && $log->[0] eq "") {
4606 shift @$log;
4609 # print log
4610 my $skip_blank_line = 0;
4611 foreach my $line (@$log) {
4612 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4613 if (! $opts{'-remove_signoff'}) {
4614 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4615 $skip_blank_line = 1;
4617 next;
4620 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4621 if (! $opts{'-remove_signoff'}) {
4622 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4623 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4624 "</span><br/>\n";
4625 $skip_blank_line = 1;
4627 next;
4630 # print only one empty line
4631 # do not print empty line after signoff
4632 if ($line eq "") {
4633 next if ($skip_blank_line);
4634 $skip_blank_line = 1;
4635 } else {
4636 $skip_blank_line = 0;
4639 print format_log_line_html($line) . "<br/>\n";
4642 if ($opts{'-final_empty_line'}) {
4643 # end with single empty line
4644 print "<br/>\n" unless $skip_blank_line;
4648 # return link target (what link points to)
4649 sub git_get_link_target {
4650 my $hash = shift;
4651 my $link_target;
4653 # read link
4654 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4655 or return;
4657 local $/ = undef;
4658 $link_target = <$fd>;
4660 close $fd
4661 or return;
4663 return $link_target;
4666 # given link target, and the directory (basedir) the link is in,
4667 # return target of link relative to top directory (top tree);
4668 # return undef if it is not possible (including absolute links).
4669 sub normalize_link_target {
4670 my ($link_target, $basedir) = @_;
4672 # absolute symlinks (beginning with '/') cannot be normalized
4673 return if (substr($link_target, 0, 1) eq '/');
4675 # normalize link target to path from top (root) tree (dir)
4676 my $path;
4677 if ($basedir) {
4678 $path = $basedir . '/' . $link_target;
4679 } else {
4680 # we are in top (root) tree (dir)
4681 $path = $link_target;
4684 # remove //, /./, and /../
4685 my @path_parts;
4686 foreach my $part (split('/', $path)) {
4687 # discard '.' and ''
4688 next if (!$part || $part eq '.');
4689 # handle '..'
4690 if ($part eq '..') {
4691 if (@path_parts) {
4692 pop @path_parts;
4693 } else {
4694 # link leads outside repository (outside top dir)
4695 return;
4697 } else {
4698 push @path_parts, $part;
4701 $path = join('/', @path_parts);
4703 return $path;
4706 # print tree entry (row of git_tree), but without encompassing <tr> element
4707 sub git_print_tree_entry {
4708 my ($t, $basedir, $hash_base, $have_blame) = @_;
4710 my %base_key = ();
4711 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4713 # The format of a table row is: mode list link. Where mode is
4714 # the mode of the entry, list is the name of the entry, an href,
4715 # and link is the action links of the entry.
4717 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4718 if (exists $t->{'size'}) {
4719 print "<td class=\"size\">$t->{'size'}</td>\n";
4721 if ($t->{'type'} eq "blob") {
4722 print "<td class=\"list\">" .
4723 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4724 file_name=>"$basedir$t->{'name'}", %base_key),
4725 -class => "list"}, esc_path($t->{'name'}));
4726 if (S_ISLNK(oct $t->{'mode'})) {
4727 my $link_target = git_get_link_target($t->{'hash'});
4728 if ($link_target) {
4729 my $norm_target = normalize_link_target($link_target, $basedir);
4730 if (defined $norm_target) {
4731 print " -> " .
4732 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4733 file_name=>$norm_target),
4734 -title => $norm_target}, esc_path($link_target));
4735 } else {
4736 print " -> " . esc_path($link_target);
4740 print "</td>\n";
4741 print "<td class=\"link\">";
4742 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4743 file_name=>"$basedir$t->{'name'}", %base_key)},
4744 "blob");
4745 if ($have_blame) {
4746 print " | " .
4747 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4748 file_name=>"$basedir$t->{'name'}", %base_key)},
4749 "blame");
4751 if (defined $hash_base) {
4752 print " | " .
4753 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4754 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4755 "history");
4757 print " | " .
4758 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4759 file_name=>"$basedir$t->{'name'}")},
4760 "raw");
4761 print "</td>\n";
4763 } elsif ($t->{'type'} eq "tree") {
4764 print "<td class=\"list\">";
4765 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4766 file_name=>"$basedir$t->{'name'}",
4767 %base_key)},
4768 esc_path($t->{'name'}));
4769 print "</td>\n";
4770 print "<td class=\"link\">";
4771 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4772 file_name=>"$basedir$t->{'name'}",
4773 %base_key)},
4774 "tree");
4775 if (defined $hash_base) {
4776 print " | " .
4777 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4778 file_name=>"$basedir$t->{'name'}")},
4779 "history");
4781 print "</td>\n";
4782 } else {
4783 # unknown object: we can only present history for it
4784 # (this includes 'commit' object, i.e. submodule support)
4785 print "<td class=\"list\">" .
4786 esc_path($t->{'name'}) .
4787 "</td>\n";
4788 print "<td class=\"link\">";
4789 if (defined $hash_base) {
4790 print $cgi->a({-href => href(action=>"history",
4791 hash_base=>$hash_base,
4792 file_name=>"$basedir$t->{'name'}")},
4793 "history");
4795 print "</td>\n";
4799 ## ......................................................................
4800 ## functions printing large fragments of HTML
4802 # get pre-image filenames for merge (combined) diff
4803 sub fill_from_file_info {
4804 my ($diff, @parents) = @_;
4806 $diff->{'from_file'} = [ ];
4807 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4808 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4809 if ($diff->{'status'}[$i] eq 'R' ||
4810 $diff->{'status'}[$i] eq 'C') {
4811 $diff->{'from_file'}[$i] =
4812 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4816 return $diff;
4819 # is current raw difftree line of file deletion
4820 sub is_deleted {
4821 my $diffinfo = shift;
4823 return $diffinfo->{'to_id'} eq ('0' x 40);
4826 # does patch correspond to [previous] difftree raw line
4827 # $diffinfo - hashref of parsed raw diff format
4828 # $patchinfo - hashref of parsed patch diff format
4829 # (the same keys as in $diffinfo)
4830 sub is_patch_split {
4831 my ($diffinfo, $patchinfo) = @_;
4833 return defined $diffinfo && defined $patchinfo
4834 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4838 sub git_difftree_body {
4839 my ($difftree, $hash, @parents) = @_;
4840 my ($parent) = $parents[0];
4841 my $have_blame = gitweb_check_feature('blame');
4842 print "<div class=\"list_head\">\n";
4843 if ($#{$difftree} > 10) {
4844 print(($#{$difftree} + 1) . " files changed:\n");
4846 print "</div>\n";
4848 print "<table class=\"" .
4849 (@parents > 1 ? "combined " : "") .
4850 "diff_tree\">\n";
4852 # header only for combined diff in 'commitdiff' view
4853 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4854 if ($has_header) {
4855 # table header
4856 print "<thead><tr>\n" .
4857 "<th></th><th></th>\n"; # filename, patchN link
4858 for (my $i = 0; $i < @parents; $i++) {
4859 my $par = $parents[$i];
4860 print "<th>" .
4861 $cgi->a({-href => href(action=>"commitdiff",
4862 hash=>$hash, hash_parent=>$par),
4863 -title => 'commitdiff to parent number ' .
4864 ($i+1) . ': ' . substr($par,0,7)},
4865 $i+1) .
4866 "&nbsp;</th>\n";
4868 print "</tr></thead>\n<tbody>\n";
4871 my $alternate = 1;
4872 my $patchno = 0;
4873 foreach my $line (@{$difftree}) {
4874 my $diff = parsed_difftree_line($line);
4876 if ($alternate) {
4877 print "<tr class=\"dark\">\n";
4878 } else {
4879 print "<tr class=\"light\">\n";
4881 $alternate ^= 1;
4883 if (exists $diff->{'nparents'}) { # combined diff
4885 fill_from_file_info($diff, @parents)
4886 unless exists $diff->{'from_file'};
4888 if (!is_deleted($diff)) {
4889 # file exists in the result (child) commit
4890 print "<td>" .
4891 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4892 file_name=>$diff->{'to_file'},
4893 hash_base=>$hash),
4894 -class => "list"}, esc_path($diff->{'to_file'})) .
4895 "</td>\n";
4896 } else {
4897 print "<td>" .
4898 esc_path($diff->{'to_file'}) .
4899 "</td>\n";
4902 if ($action eq 'commitdiff') {
4903 # link to patch
4904 $patchno++;
4905 print "<td class=\"link\">" .
4906 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4907 "patch") .
4908 " | " .
4909 "</td>\n";
4912 my $has_history = 0;
4913 my $not_deleted = 0;
4914 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4915 my $hash_parent = $parents[$i];
4916 my $from_hash = $diff->{'from_id'}[$i];
4917 my $from_path = $diff->{'from_file'}[$i];
4918 my $status = $diff->{'status'}[$i];
4920 $has_history ||= ($status ne 'A');
4921 $not_deleted ||= ($status ne 'D');
4923 if ($status eq 'A') {
4924 print "<td class=\"link\" align=\"right\"> | </td>\n";
4925 } elsif ($status eq 'D') {
4926 print "<td class=\"link\">" .
4927 $cgi->a({-href => href(action=>"blob",
4928 hash_base=>$hash,
4929 hash=>$from_hash,
4930 file_name=>$from_path)},
4931 "blob" . ($i+1)) .
4932 " | </td>\n";
4933 } else {
4934 if ($diff->{'to_id'} eq $from_hash) {
4935 print "<td class=\"link nochange\">";
4936 } else {
4937 print "<td class=\"link\">";
4939 print $cgi->a({-href => href(action=>"blobdiff",
4940 hash=>$diff->{'to_id'},
4941 hash_parent=>$from_hash,
4942 hash_base=>$hash,
4943 hash_parent_base=>$hash_parent,
4944 file_name=>$diff->{'to_file'},
4945 file_parent=>$from_path)},
4946 "diff" . ($i+1)) .
4947 " | </td>\n";
4951 print "<td class=\"link\">";
4952 if ($not_deleted) {
4953 print $cgi->a({-href => href(action=>"blob",
4954 hash=>$diff->{'to_id'},
4955 file_name=>$diff->{'to_file'},
4956 hash_base=>$hash)},
4957 "blob");
4958 print " | " if ($has_history);
4960 if ($has_history) {
4961 print $cgi->a({-href => href(action=>"history",
4962 file_name=>$diff->{'to_file'},
4963 hash_base=>$hash)},
4964 "history");
4966 print "</td>\n";
4968 print "</tr>\n";
4969 next; # instead of 'else' clause, to avoid extra indent
4971 # else ordinary diff
4973 my ($to_mode_oct, $to_mode_str, $to_file_type);
4974 my ($from_mode_oct, $from_mode_str, $from_file_type);
4975 if ($diff->{'to_mode'} ne ('0' x 6)) {
4976 $to_mode_oct = oct $diff->{'to_mode'};
4977 if (S_ISREG($to_mode_oct)) { # only for regular file
4978 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4980 $to_file_type = file_type($diff->{'to_mode'});
4982 if ($diff->{'from_mode'} ne ('0' x 6)) {
4983 $from_mode_oct = oct $diff->{'from_mode'};
4984 if (S_ISREG($from_mode_oct)) { # only for regular file
4985 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4987 $from_file_type = file_type($diff->{'from_mode'});
4990 if ($diff->{'status'} eq "A") { # created
4991 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4992 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4993 $mode_chng .= "]</span>";
4994 print "<td>";
4995 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4996 hash_base=>$hash, file_name=>$diff->{'file'}),
4997 -class => "list"}, esc_path($diff->{'file'}));
4998 print "</td>\n";
4999 print "<td>$mode_chng</td>\n";
5000 print "<td class=\"link\">";
5001 if ($action eq 'commitdiff') {
5002 # link to patch
5003 $patchno++;
5004 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5005 "patch") .
5006 " | ";
5008 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5009 hash_base=>$hash, file_name=>$diff->{'file'})},
5010 "blob");
5011 print "</td>\n";
5013 } elsif ($diff->{'status'} eq "D") { # deleted
5014 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5015 print "<td>";
5016 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5017 hash_base=>$parent, file_name=>$diff->{'file'}),
5018 -class => "list"}, esc_path($diff->{'file'}));
5019 print "</td>\n";
5020 print "<td>$mode_chng</td>\n";
5021 print "<td class=\"link\">";
5022 if ($action eq 'commitdiff') {
5023 # link to patch
5024 $patchno++;
5025 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5026 "patch") .
5027 " | ";
5029 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5030 hash_base=>$parent, file_name=>$diff->{'file'})},
5031 "blob") . " | ";
5032 if ($have_blame) {
5033 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5034 file_name=>$diff->{'file'})},
5035 "blame") . " | ";
5037 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5038 file_name=>$diff->{'file'})},
5039 "history");
5040 print "</td>\n";
5042 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5043 my $mode_chnge = "";
5044 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5045 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5046 if ($from_file_type ne $to_file_type) {
5047 $mode_chnge .= " from $from_file_type to $to_file_type";
5049 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5050 if ($from_mode_str && $to_mode_str) {
5051 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5052 } elsif ($to_mode_str) {
5053 $mode_chnge .= " mode: $to_mode_str";
5056 $mode_chnge .= "]</span>\n";
5058 print "<td>";
5059 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5060 hash_base=>$hash, file_name=>$diff->{'file'}),
5061 -class => "list"}, esc_path($diff->{'file'}));
5062 print "</td>\n";
5063 print "<td>$mode_chnge</td>\n";
5064 print "<td class=\"link\">";
5065 if ($action eq 'commitdiff') {
5066 # link to patch
5067 $patchno++;
5068 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5069 "patch") .
5070 " | ";
5071 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5072 # "commit" view and modified file (not onlu mode changed)
5073 print $cgi->a({-href => href(action=>"blobdiff",
5074 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5075 hash_base=>$hash, hash_parent_base=>$parent,
5076 file_name=>$diff->{'file'})},
5077 "diff") .
5078 " | ";
5080 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5081 hash_base=>$hash, file_name=>$diff->{'file'})},
5082 "blob") . " | ";
5083 if ($have_blame) {
5084 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5085 file_name=>$diff->{'file'})},
5086 "blame") . " | ";
5088 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5089 file_name=>$diff->{'file'})},
5090 "history");
5091 print "</td>\n";
5093 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5094 my %status_name = ('R' => 'moved', 'C' => 'copied');
5095 my $nstatus = $status_name{$diff->{'status'}};
5096 my $mode_chng = "";
5097 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5098 # mode also for directories, so we cannot use $to_mode_str
5099 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5101 print "<td>" .
5102 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5103 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5104 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5105 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5106 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5107 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5108 -class => "list"}, esc_path($diff->{'from_file'})) .
5109 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5110 "<td class=\"link\">";
5111 if ($action eq 'commitdiff') {
5112 # link to patch
5113 $patchno++;
5114 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5115 "patch") .
5116 " | ";
5117 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5118 # "commit" view and modified file (not only pure rename or copy)
5119 print $cgi->a({-href => href(action=>"blobdiff",
5120 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5121 hash_base=>$hash, hash_parent_base=>$parent,
5122 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5123 "diff") .
5124 " | ";
5126 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5127 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5128 "blob") . " | ";
5129 if ($have_blame) {
5130 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5131 file_name=>$diff->{'to_file'})},
5132 "blame") . " | ";
5134 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5135 file_name=>$diff->{'to_file'})},
5136 "history");
5137 print "</td>\n";
5139 } # we should not encounter Unmerged (U) or Unknown (X) status
5140 print "</tr>\n";
5142 print "</tbody>" if $has_header;
5143 print "</table>\n";
5146 # Print context lines and then rem/add lines in a side-by-side manner.
5147 sub print_sidebyside_diff_lines {
5148 my ($ctx, $rem, $add) = @_;
5150 # print context block before add/rem block
5151 if (@$ctx) {
5152 print join '',
5153 '<div class="chunk_block ctx">',
5154 '<div class="old">',
5155 @$ctx,
5156 '</div>',
5157 '<div class="new">',
5158 @$ctx,
5159 '</div>',
5160 '</div>';
5163 if (!@$add) {
5164 # pure removal
5165 print join '',
5166 '<div class="chunk_block rem">',
5167 '<div class="old">',
5168 @$rem,
5169 '</div>',
5170 '</div>';
5171 } elsif (!@$rem) {
5172 # pure addition
5173 print join '',
5174 '<div class="chunk_block add">',
5175 '<div class="new">',
5176 @$add,
5177 '</div>',
5178 '</div>';
5179 } else {
5180 print join '',
5181 '<div class="chunk_block chg">',
5182 '<div class="old">',
5183 @$rem,
5184 '</div>',
5185 '<div class="new">',
5186 @$add,
5187 '</div>',
5188 '</div>';
5192 # Print context lines and then rem/add lines in inline manner.
5193 sub print_inline_diff_lines {
5194 my ($ctx, $rem, $add) = @_;
5196 print @$ctx, @$rem, @$add;
5199 # Format removed and added line, mark changed part and HTML-format them.
5200 # Implementation is based on contrib/diff-highlight
5201 sub format_rem_add_lines_pair {
5202 my ($rem, $add, $num_parents) = @_;
5204 # We need to untabify lines before split()'ing them;
5205 # otherwise offsets would be invalid.
5206 chomp $rem;
5207 chomp $add;
5208 $rem = untabify($rem);
5209 $add = untabify($add);
5211 my @rem = split(//, $rem);
5212 my @add = split(//, $add);
5213 my ($esc_rem, $esc_add);
5214 # Ignore leading +/- characters for each parent.
5215 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5216 my ($prefix_has_nonspace, $suffix_has_nonspace);
5218 my $shorter = (@rem < @add) ? @rem : @add;
5219 while ($prefix_len < $shorter) {
5220 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5222 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5223 $prefix_len++;
5226 while ($prefix_len + $suffix_len < $shorter) {
5227 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5229 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5230 $suffix_len++;
5233 # Mark lines that are different from each other, but have some common
5234 # part that isn't whitespace. If lines are completely different, don't
5235 # mark them because that would make output unreadable, especially if
5236 # diff consists of multiple lines.
5237 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5238 $esc_rem = esc_html_hl_regions($rem, 'marked',
5239 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5240 $esc_add = esc_html_hl_regions($add, 'marked',
5241 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5242 } else {
5243 $esc_rem = esc_html($rem, -nbsp=>1);
5244 $esc_add = esc_html($add, -nbsp=>1);
5247 return format_diff_line(\$esc_rem, 'rem'),
5248 format_diff_line(\$esc_add, 'add');
5251 # HTML-format diff context, removed and added lines.
5252 sub format_ctx_rem_add_lines {
5253 my ($ctx, $rem, $add, $num_parents) = @_;
5254 my (@new_ctx, @new_rem, @new_add);
5255 my $can_highlight = 0;
5256 my $is_combined = ($num_parents > 1);
5258 # Highlight if every removed line has a corresponding added line.
5259 if (@$add > 0 && @$add == @$rem) {
5260 $can_highlight = 1;
5262 # Highlight lines in combined diff only if the chunk contains
5263 # diff between the same version, e.g.
5265 # - a
5266 # - b
5267 # + c
5268 # + d
5270 # Otherwise the highlightling would be confusing.
5271 if ($is_combined) {
5272 for (my $i = 0; $i < @$add; $i++) {
5273 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5274 my $prefix_add = substr($add->[$i], 0, $num_parents);
5276 $prefix_rem =~ s/-/+/g;
5278 if ($prefix_rem ne $prefix_add) {
5279 $can_highlight = 0;
5280 last;
5286 if ($can_highlight) {
5287 for (my $i = 0; $i < @$add; $i++) {
5288 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5289 $rem->[$i], $add->[$i], $num_parents);
5290 push @new_rem, $line_rem;
5291 push @new_add, $line_add;
5293 } else {
5294 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5295 @new_add = map { format_diff_line($_, 'add') } @$add;
5298 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5300 return (\@new_ctx, \@new_rem, \@new_add);
5303 # Print context lines and then rem/add lines.
5304 sub print_diff_lines {
5305 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5306 my $is_combined = $num_parents > 1;
5308 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5309 $num_parents);
5311 if ($diff_style eq 'sidebyside' && !$is_combined) {
5312 print_sidebyside_diff_lines($ctx, $rem, $add);
5313 } else {
5314 # default 'inline' style and unknown styles
5315 print_inline_diff_lines($ctx, $rem, $add);
5319 sub print_diff_chunk {
5320 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5321 my (@ctx, @rem, @add);
5323 # The class of the previous line.
5324 my $prev_class = '';
5326 return unless @chunk;
5328 # incomplete last line might be among removed or added lines,
5329 # or both, or among context lines: find which
5330 for (my $i = 1; $i < @chunk; $i++) {
5331 if ($chunk[$i][0] eq 'incomplete') {
5332 $chunk[$i][0] = $chunk[$i-1][0];
5336 # guardian
5337 push @chunk, ["", ""];
5339 foreach my $line_info (@chunk) {
5340 my ($class, $line) = @$line_info;
5342 # print chunk headers
5343 if ($class && $class eq 'chunk_header') {
5344 print format_diff_line($line, $class, $from, $to);
5345 next;
5348 ## print from accumulator when have some add/rem lines or end
5349 # of chunk (flush context lines), or when have add and rem
5350 # lines and new block is reached (otherwise add/rem lines could
5351 # be reordered)
5352 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5353 (@rem && @add && $class ne $prev_class)) {
5354 print_diff_lines(\@ctx, \@rem, \@add,
5355 $diff_style, $num_parents);
5356 @ctx = @rem = @add = ();
5359 ## adding lines to accumulator
5360 # guardian value
5361 last unless $line;
5362 # rem, add or change
5363 if ($class eq 'rem') {
5364 push @rem, $line;
5365 } elsif ($class eq 'add') {
5366 push @add, $line;
5368 # context line
5369 if ($class eq 'ctx') {
5370 push @ctx, $line;
5373 $prev_class = $class;
5377 sub git_patchset_body {
5378 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5379 my ($hash_parent) = $hash_parents[0];
5381 my $is_combined = (@hash_parents > 1);
5382 my $patch_idx = 0;
5383 my $patch_number = 0;
5384 my $patch_line;
5385 my $diffinfo;
5386 my $to_name;
5387 my (%from, %to);
5388 my @chunk; # for side-by-side diff
5390 print "<div class=\"patchset\">\n";
5392 # skip to first patch
5393 while ($patch_line = <$fd>) {
5394 chomp $patch_line;
5396 last if ($patch_line =~ m/^diff /);
5399 PATCH:
5400 while ($patch_line) {
5402 # parse "git diff" header line
5403 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5404 # $1 is from_name, which we do not use
5405 $to_name = unquote($2);
5406 $to_name =~ s!^b/!!;
5407 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5408 # $1 is 'cc' or 'combined', which we do not use
5409 $to_name = unquote($2);
5410 } else {
5411 $to_name = undef;
5414 # check if current patch belong to current raw line
5415 # and parse raw git-diff line if needed
5416 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5417 # this is continuation of a split patch
5418 print "<div class=\"patch cont\">\n";
5419 } else {
5420 # advance raw git-diff output if needed
5421 $patch_idx++ if defined $diffinfo;
5423 # read and prepare patch information
5424 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5426 # compact combined diff output can have some patches skipped
5427 # find which patch (using pathname of result) we are at now;
5428 if ($is_combined) {
5429 while ($to_name ne $diffinfo->{'to_file'}) {
5430 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5431 format_diff_cc_simplified($diffinfo, @hash_parents) .
5432 "</div>\n"; # class="patch"
5434 $patch_idx++;
5435 $patch_number++;
5437 last if $patch_idx > $#$difftree;
5438 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5442 # modifies %from, %to hashes
5443 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5445 # this is first patch for raw difftree line with $patch_idx index
5446 # we index @$difftree array from 0, but number patches from 1
5447 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5450 # git diff header
5451 #assert($patch_line =~ m/^diff /) if DEBUG;
5452 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5453 $patch_number++;
5454 # print "git diff" header
5455 print format_git_diff_header_line($patch_line, $diffinfo,
5456 \%from, \%to);
5458 # print extended diff header
5459 print "<div class=\"diff extended_header\">\n";
5460 EXTENDED_HEADER:
5461 while ($patch_line = <$fd>) {
5462 chomp $patch_line;
5464 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5466 print format_extended_diff_header_line($patch_line, $diffinfo,
5467 \%from, \%to);
5469 print "</div>\n"; # class="diff extended_header"
5471 # from-file/to-file diff header
5472 if (! $patch_line) {
5473 print "</div>\n"; # class="patch"
5474 last PATCH;
5476 next PATCH if ($patch_line =~ m/^diff /);
5477 #assert($patch_line =~ m/^---/) if DEBUG;
5479 my $last_patch_line = $patch_line;
5480 $patch_line = <$fd>;
5481 chomp $patch_line;
5482 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5484 print format_diff_from_to_header($last_patch_line, $patch_line,
5485 $diffinfo, \%from, \%to,
5486 @hash_parents);
5488 # the patch itself
5489 LINE:
5490 while ($patch_line = <$fd>) {
5491 chomp $patch_line;
5493 next PATCH if ($patch_line =~ m/^diff /);
5495 my $class = diff_line_class($patch_line, \%from, \%to);
5497 if ($class eq 'chunk_header') {
5498 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5499 @chunk = ();
5502 push @chunk, [ $class, $patch_line ];
5505 } continue {
5506 if (@chunk) {
5507 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5508 @chunk = ();
5510 print "</div>\n"; # class="patch"
5513 # for compact combined (--cc) format, with chunk and patch simplification
5514 # the patchset might be empty, but there might be unprocessed raw lines
5515 for (++$patch_idx if $patch_number > 0;
5516 $patch_idx < @$difftree;
5517 ++$patch_idx) {
5518 # read and prepare patch information
5519 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5521 # generate anchor for "patch" links in difftree / whatchanged part
5522 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5523 format_diff_cc_simplified($diffinfo, @hash_parents) .
5524 "</div>\n"; # class="patch"
5526 $patch_number++;
5529 if ($patch_number == 0) {
5530 if (@hash_parents > 1) {
5531 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5532 } else {
5533 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5537 print "</div>\n"; # class="patchset"
5540 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5542 sub git_project_search_form {
5543 my ($searchtext, $search_use_regexp) = @_;
5545 my $limit = '';
5546 if ($project_filter) {
5547 $limit = " in '$project_filter/'";
5550 print "<div class=\"projsearch\">\n";
5551 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5552 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5553 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5554 if (defined $project_filter);
5555 print $cgi->textfield(-name => 's', -value => $searchtext,
5556 -title => "Search project by name and description$limit",
5557 -size => 60) . "\n" .
5558 "<span title=\"Extended regular expression\">" .
5559 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5560 -checked => $search_use_regexp) .
5561 "</span>\n" .
5562 $cgi->submit(-name => 'btnS', -value => 'Search') .
5563 $cgi->end_form() . "\n" .
5564 $cgi->a({-href => href(project => undef, searchtext => undef,
5565 project_filter => $project_filter)},
5566 esc_html("List all projects$limit")) . "<br />\n";
5567 print "</div>\n";
5570 # entry for given @keys needs filling if at least one of keys in list
5571 # is not present in %$project_info
5572 sub project_info_needs_filling {
5573 my ($project_info, @keys) = @_;
5575 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5576 foreach my $key (@keys) {
5577 if (!exists $project_info->{$key}) {
5578 return 1;
5581 return;
5584 # fills project list info (age, description, owner, category, forks, etc.)
5585 # for each project in the list, removing invalid projects from
5586 # returned list, or fill only specified info.
5588 # Invalid projects are removed from the returned list if and only if you
5589 # ask 'age' or 'age_string' to be filled, because they are the only fields
5590 # that run unconditionally git command that requires repository, and
5591 # therefore do always check if project repository is invalid.
5593 # USAGE:
5594 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5595 # ensures that 'descr_long' and 'ctags' fields are filled
5596 # * @project_list = fill_project_list_info(\@project_list)
5597 # ensures that all fields are filled (and invalid projects removed)
5599 # NOTE: modifies $projlist, but does not remove entries from it
5600 sub fill_project_list_info {
5601 my ($projlist, @wanted_keys) = @_;
5602 my @projects;
5603 my $filter_set = sub { return @_; };
5604 if (@wanted_keys) {
5605 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5606 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5609 my $show_ctags = gitweb_check_feature('ctags');
5610 PROJECT:
5611 foreach my $pr (@$projlist) {
5612 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5613 my (@activity) = git_get_last_activity($pr->{'path'});
5614 unless (@activity) {
5615 next PROJECT;
5617 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5619 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5620 my $descr = git_get_project_description($pr->{'path'}) || "";
5621 $descr = to_utf8($descr);
5622 $pr->{'descr_long'} = $descr;
5623 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5625 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5626 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5628 if ($show_ctags &&
5629 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5630 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5632 if ($projects_list_group_categories &&
5633 project_info_needs_filling($pr, $filter_set->('category'))) {
5634 my $cat = git_get_project_category($pr->{'path'}) ||
5635 $project_list_default_category;
5636 $pr->{'category'} = to_utf8($cat);
5639 push @projects, $pr;
5642 return @projects;
5645 sub sort_projects_list {
5646 my ($projlist, $order) = @_;
5648 sub order_str {
5649 my $key = shift;
5650 return sub { $a->{$key} cmp $b->{$key} };
5653 sub order_num_then_undef {
5654 my $key = shift;
5655 return sub {
5656 defined $a->{$key} ?
5657 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5658 (defined $b->{$key} ? 1 : 0)
5662 my %orderings = (
5663 project => order_str('path'),
5664 descr => order_str('descr_long'),
5665 owner => order_str('owner'),
5666 age => order_num_then_undef('age'),
5669 my $ordering = $orderings{$order};
5670 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5673 # returns a hash of categories, containing the list of project
5674 # belonging to each category
5675 sub build_projlist_by_category {
5676 my ($projlist, $from, $to) = @_;
5677 my %categories;
5679 $from = 0 unless defined $from;
5680 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5682 for (my $i = $from; $i <= $to; $i++) {
5683 my $pr = $projlist->[$i];
5684 push @{$categories{ $pr->{'category'} }}, $pr;
5687 return wantarray ? %categories : \%categories;
5690 # print 'sort by' <th> element, generating 'sort by $name' replay link
5691 # if that order is not selected
5692 sub print_sort_th {
5693 print format_sort_th(@_);
5696 sub format_sort_th {
5697 my ($name, $order, $header) = @_;
5698 my $sort_th = "";
5699 $header ||= ucfirst($name);
5701 if ($order eq $name) {
5702 $sort_th .= "<th>$header</th>\n";
5703 } else {
5704 $sort_th .= "<th>" .
5705 $cgi->a({-href => href(-replay=>1, order=>$name),
5706 -class => "header"}, $header) .
5707 "</th>\n";
5710 return $sort_th;
5713 sub git_project_list_rows {
5714 my ($projlist, $from, $to, $check_forks) = @_;
5716 $from = 0 unless defined $from;
5717 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5719 my $alternate = 1;
5720 for (my $i = $from; $i <= $to; $i++) {
5721 my $pr = $projlist->[$i];
5723 if ($alternate) {
5724 print "<tr class=\"dark\">\n";
5725 } else {
5726 print "<tr class=\"light\">\n";
5728 $alternate ^= 1;
5730 if ($check_forks) {
5731 print "<td>";
5732 if ($pr->{'forks'}) {
5733 my $nforks = scalar @{$pr->{'forks'}};
5734 if ($nforks > 0) {
5735 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5736 -title => "$nforks forks"}, "+");
5737 } else {
5738 print $cgi->span({-title => "$nforks forks"}, "+");
5741 print "</td>\n";
5743 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5744 -class => "list"},
5745 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5746 "</td>\n" .
5747 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5748 -class => "list",
5749 -title => $pr->{'descr_long'}},
5750 $search_regexp
5751 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5752 $pr->{'descr'}, $search_regexp)
5753 : esc_html($pr->{'descr'})) .
5754 "</td>\n";
5755 unless ($omit_owner) {
5756 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5758 unless ($omit_age_column) {
5759 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5760 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5762 print"<td class=\"link\">" .
5763 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5764 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5765 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5766 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5767 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5768 "</td>\n" .
5769 "</tr>\n";
5773 sub git_project_list_body {
5774 # actually uses global variable $project
5775 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5776 my @projects = @$projlist;
5778 my $check_forks = gitweb_check_feature('forks');
5779 my $show_ctags = gitweb_check_feature('ctags');
5780 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5781 $check_forks = undef
5782 if ($tagfilter || $search_regexp);
5784 # filtering out forks before filling info allows to do less work
5785 @projects = filter_forks_from_projects_list(\@projects)
5786 if ($check_forks);
5787 # search_projects_list pre-fills required info
5788 @projects = search_projects_list(\@projects,
5789 'search_regexp' => $search_regexp,
5790 'tagfilter' => $tagfilter)
5791 if ($tagfilter || $search_regexp);
5792 # fill the rest
5793 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5794 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5795 push @all_fields, 'owner' unless($omit_owner);
5796 @projects = fill_project_list_info(\@projects, @all_fields);
5798 $order ||= $default_projects_order;
5799 $from = 0 unless defined $from;
5800 $to = $#projects if (!defined $to || $#projects < $to);
5802 # short circuit
5803 if ($from > $to) {
5804 print "<center>\n".
5805 "<b>No such projects found</b><br />\n".
5806 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5807 "</center>\n<br />\n";
5808 return;
5811 @projects = sort_projects_list(\@projects, $order);
5813 if ($show_ctags) {
5814 my $ctags = git_gather_all_ctags(\@projects);
5815 my $cloud = git_populate_project_tagcloud($ctags);
5816 print git_show_project_tagcloud($cloud, 64);
5819 print "<table class=\"project_list\">\n";
5820 unless ($no_header) {
5821 print "<tr>\n";
5822 if ($check_forks) {
5823 print "<th></th>\n";
5825 print_sort_th('project', $order, 'Project');
5826 print_sort_th('descr', $order, 'Description');
5827 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5828 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5829 print "<th></th>\n" . # for links
5830 "</tr>\n";
5833 if ($projects_list_group_categories) {
5834 # only display categories with projects in the $from-$to window
5835 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5836 my %categories = build_projlist_by_category(\@projects, $from, $to);
5837 foreach my $cat (sort keys %categories) {
5838 unless ($cat eq "") {
5839 print "<tr>\n";
5840 if ($check_forks) {
5841 print "<td></td>\n";
5843 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5844 print "</tr>\n";
5847 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5849 } else {
5850 git_project_list_rows(\@projects, $from, $to, $check_forks);
5853 if (defined $extra) {
5854 print "<tr>\n";
5855 if ($check_forks) {
5856 print "<td></td>\n";
5858 print "<td colspan=\"5\">$extra</td>\n" .
5859 "</tr>\n";
5861 print "</table>\n";
5864 sub git_log_body {
5865 # uses global variable $project
5866 my ($commitlist, $from, $to, $refs, $extra) = @_;
5868 $from = 0 unless defined $from;
5869 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5871 for (my $i = 0; $i <= $to; $i++) {
5872 my %co = %{$commitlist->[$i]};
5873 next if !%co;
5874 my $commit = $co{'id'};
5875 my $ref = format_ref_marker($refs, $commit);
5876 git_print_header_div('commit',
5877 "<span class=\"age\">$co{'age_string'}</span>" .
5878 esc_html($co{'title'}) . $ref,
5879 $commit);
5880 print "<div class=\"title_text\">\n" .
5881 "<div class=\"log_link\">\n" .
5882 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5883 " | " .
5884 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5885 " | " .
5886 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5887 "<br/>\n" .
5888 "</div>\n";
5889 git_print_authorship(\%co, -tag => 'span');
5890 print "<br/>\n</div>\n";
5892 print "<div class=\"log_body\">\n";
5893 git_print_log($co{'comment'}, -final_empty_line=> 1);
5894 print "</div>\n";
5896 if ($extra) {
5897 print "<div class=\"page_nav\">\n";
5898 print "$extra\n";
5899 print "</div>\n";
5903 sub git_shortlog_body {
5904 # uses global variable $project
5905 my ($commitlist, $from, $to, $refs, $extra) = @_;
5907 $from = 0 unless defined $from;
5908 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5910 print "<table class=\"shortlog\">\n";
5911 my $alternate = 1;
5912 for (my $i = $from; $i <= $to; $i++) {
5913 my %co = %{$commitlist->[$i]};
5914 my $commit = $co{'id'};
5915 my $ref = format_ref_marker($refs, $commit);
5916 if ($alternate) {
5917 print "<tr class=\"dark\">\n";
5918 } else {
5919 print "<tr class=\"light\">\n";
5921 $alternate ^= 1;
5922 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5923 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5924 format_author_html('td', \%co, 10) . "<td>";
5925 print format_subject_html($co{'title'}, $co{'title_short'},
5926 href(action=>"commit", hash=>$commit), $ref);
5927 print "</td>\n" .
5928 "<td class=\"link\">" .
5929 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5930 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5931 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5932 my $snapshot_links = format_snapshot_links($commit);
5933 if (defined $snapshot_links) {
5934 print " | " . $snapshot_links;
5936 print "</td>\n" .
5937 "</tr>\n";
5939 if (defined $extra) {
5940 print "<tr>\n" .
5941 "<td colspan=\"4\">$extra</td>\n" .
5942 "</tr>\n";
5944 print "</table>\n";
5947 sub git_history_body {
5948 # Warning: assumes constant type (blob or tree) during history
5949 my ($commitlist, $from, $to, $refs, $extra,
5950 $file_name, $file_hash, $ftype) = @_;
5952 $from = 0 unless defined $from;
5953 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5955 print "<table class=\"history\">\n";
5956 my $alternate = 1;
5957 for (my $i = $from; $i <= $to; $i++) {
5958 my %co = %{$commitlist->[$i]};
5959 if (!%co) {
5960 next;
5962 my $commit = $co{'id'};
5964 my $ref = format_ref_marker($refs, $commit);
5966 if ($alternate) {
5967 print "<tr class=\"dark\">\n";
5968 } else {
5969 print "<tr class=\"light\">\n";
5971 $alternate ^= 1;
5972 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5973 # shortlog: format_author_html('td', \%co, 10)
5974 format_author_html('td', \%co, 15, 3) . "<td>";
5975 # originally git_history used chop_str($co{'title'}, 50)
5976 print format_subject_html($co{'title'}, $co{'title_short'},
5977 href(action=>"commit", hash=>$commit), $ref);
5978 print "</td>\n" .
5979 "<td class=\"link\">" .
5980 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5981 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5983 if ($ftype eq 'blob') {
5984 my $blob_current = $file_hash;
5985 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5986 if (defined $blob_current && defined $blob_parent &&
5987 $blob_current ne $blob_parent) {
5988 print " | " .
5989 $cgi->a({-href => href(action=>"blobdiff",
5990 hash=>$blob_current, hash_parent=>$blob_parent,
5991 hash_base=>$hash_base, hash_parent_base=>$commit,
5992 file_name=>$file_name)},
5993 "diff to current");
5996 print "</td>\n" .
5997 "</tr>\n";
5999 if (defined $extra) {
6000 print "<tr>\n" .
6001 "<td colspan=\"4\">$extra</td>\n" .
6002 "</tr>\n";
6004 print "</table>\n";
6007 sub git_tags_body {
6008 # uses global variable $project
6009 my ($taglist, $from, $to, $extra) = @_;
6010 $from = 0 unless defined $from;
6011 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6013 print "<table class=\"tags\">\n";
6014 my $alternate = 1;
6015 for (my $i = $from; $i <= $to; $i++) {
6016 my $entry = $taglist->[$i];
6017 my %tag = %$entry;
6018 my $comment = $tag{'subject'};
6019 my $comment_short;
6020 if (defined $comment) {
6021 $comment_short = chop_str($comment, 30, 5);
6023 if ($alternate) {
6024 print "<tr class=\"dark\">\n";
6025 } else {
6026 print "<tr class=\"light\">\n";
6028 $alternate ^= 1;
6029 if (defined $tag{'age'}) {
6030 print "<td><i>$tag{'age'}</i></td>\n";
6031 } else {
6032 print "<td></td>\n";
6034 print "<td>" .
6035 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6036 -class => "list name"}, esc_html($tag{'name'})) .
6037 "</td>\n" .
6038 "<td>";
6039 if (defined $comment) {
6040 print format_subject_html($comment, $comment_short,
6041 href(action=>"tag", hash=>$tag{'id'}));
6043 print "</td>\n" .
6044 "<td class=\"selflink\">";
6045 if ($tag{'type'} eq "tag") {
6046 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6047 } else {
6048 print "&nbsp;";
6050 print "</td>\n" .
6051 "<td class=\"link\">" . " | " .
6052 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6053 if ($tag{'reftype'} eq "commit") {
6054 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6055 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6056 } elsif ($tag{'reftype'} eq "blob") {
6057 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6059 print "</td>\n" .
6060 "</tr>";
6062 if (defined $extra) {
6063 print "<tr>\n" .
6064 "<td colspan=\"5\">$extra</td>\n" .
6065 "</tr>\n";
6067 print "</table>\n";
6070 sub git_heads_body {
6071 # uses global variable $project
6072 my ($headlist, $head_at, $from, $to, $extra) = @_;
6073 $from = 0 unless defined $from;
6074 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6076 print "<table class=\"heads\">\n";
6077 my $alternate = 1;
6078 for (my $i = $from; $i <= $to; $i++) {
6079 my $entry = $headlist->[$i];
6080 my %ref = %$entry;
6081 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6082 if ($alternate) {
6083 print "<tr class=\"dark\">\n";
6084 } else {
6085 print "<tr class=\"light\">\n";
6087 $alternate ^= 1;
6088 print "<td><i>$ref{'age'}</i></td>\n" .
6089 ($curr ? "<td class=\"current_head\">" : "<td>") .
6090 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6091 -class => "list name"},esc_html($ref{'name'})) .
6092 "</td>\n" .
6093 "<td class=\"link\">" .
6094 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6095 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6096 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6097 "</td>\n" .
6098 "</tr>";
6100 if (defined $extra) {
6101 print "<tr>\n" .
6102 "<td colspan=\"3\">$extra</td>\n" .
6103 "</tr>\n";
6105 print "</table>\n";
6108 # Display a single remote block
6109 sub git_remote_block {
6110 my ($remote, $rdata, $limit, $head) = @_;
6112 my $heads = $rdata->{'heads'};
6113 my $fetch = $rdata->{'fetch'};
6114 my $push = $rdata->{'push'};
6116 my $urls_table = "<table class=\"projects_list\">\n" ;
6118 if (defined $fetch) {
6119 if ($fetch eq $push) {
6120 $urls_table .= format_repo_url("URL", $fetch);
6121 } else {
6122 $urls_table .= format_repo_url("Fetch URL", $fetch);
6123 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6125 } elsif (defined $push) {
6126 $urls_table .= format_repo_url("Push URL", $push);
6127 } else {
6128 $urls_table .= format_repo_url("", "No remote URL");
6131 $urls_table .= "</table>\n";
6133 my $dots;
6134 if (defined $limit && $limit < @$heads) {
6135 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6138 print $urls_table;
6139 git_heads_body($heads, $head, 0, $limit, $dots);
6142 # Display a list of remote names with the respective fetch and push URLs
6143 sub git_remotes_list {
6144 my ($remotedata, $limit) = @_;
6145 print "<table class=\"heads\">\n";
6146 my $alternate = 1;
6147 my @remotes = sort keys %$remotedata;
6149 my $limited = $limit && $limit < @remotes;
6151 $#remotes = $limit - 1 if $limited;
6153 while (my $remote = shift @remotes) {
6154 my $rdata = $remotedata->{$remote};
6155 my $fetch = $rdata->{'fetch'};
6156 my $push = $rdata->{'push'};
6157 if ($alternate) {
6158 print "<tr class=\"dark\">\n";
6159 } else {
6160 print "<tr class=\"light\">\n";
6162 $alternate ^= 1;
6163 print "<td>" .
6164 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6165 -class=> "list name"},esc_html($remote)) .
6166 "</td>";
6167 print "<td class=\"link\">" .
6168 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6169 " | " .
6170 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6171 "</td>";
6173 print "</tr>\n";
6176 if ($limited) {
6177 print "<tr>\n" .
6178 "<td colspan=\"3\">" .
6179 $cgi->a({-href => href(action=>"remotes")}, "...") .
6180 "</td>\n" . "</tr>\n";
6183 print "</table>";
6186 # Display remote heads grouped by remote, unless there are too many
6187 # remotes, in which case we only display the remote names
6188 sub git_remotes_body {
6189 my ($remotedata, $limit, $head) = @_;
6190 if ($limit and $limit < keys %$remotedata) {
6191 git_remotes_list($remotedata, $limit);
6192 } else {
6193 fill_remote_heads($remotedata);
6194 while (my ($remote, $rdata) = each %$remotedata) {
6195 git_print_section({-class=>"remote", -id=>$remote},
6196 ["remotes", $remote, $remote], sub {
6197 git_remote_block($remote, $rdata, $limit, $head);
6203 sub git_search_message {
6204 my %co = @_;
6206 my $greptype;
6207 if ($searchtype eq 'commit') {
6208 $greptype = "--grep=";
6209 } elsif ($searchtype eq 'author') {
6210 $greptype = "--author=";
6211 } elsif ($searchtype eq 'committer') {
6212 $greptype = "--committer=";
6214 $greptype .= $searchtext;
6215 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6216 $greptype, '--regexp-ignore-case',
6217 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6219 my $paging_nav = '';
6220 if ($page > 0) {
6221 $paging_nav .=
6222 $cgi->a({-href => href(-replay=>1, page=>undef)},
6223 "first") .
6224 " &sdot; " .
6225 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6226 -accesskey => "p", -title => "Alt-p"}, "prev");
6227 } else {
6228 $paging_nav .= "first &sdot; prev";
6230 my $next_link = '';
6231 if ($#commitlist >= 100) {
6232 $next_link =
6233 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6234 -accesskey => "n", -title => "Alt-n"}, "next");
6235 $paging_nav .= " &sdot; $next_link";
6236 } else {
6237 $paging_nav .= " &sdot; next";
6240 git_header_html();
6242 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6243 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6244 if ($page == 0 && !@commitlist) {
6245 print "<p>No match.</p>\n";
6246 } else {
6247 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6250 git_footer_html();
6253 sub git_search_changes {
6254 my %co = @_;
6256 local $/ = "\n";
6257 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6258 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6259 ($search_use_regexp ? '--pickaxe-regex' : ())
6260 or die_error(500, "Open git-log failed");
6262 git_header_html();
6264 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6265 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6267 print "<table class=\"pickaxe search\">\n";
6268 my $alternate = 1;
6269 undef %co;
6270 my @files;
6271 while (my $line = <$fd>) {
6272 chomp $line;
6273 next unless $line;
6275 my %set = parse_difftree_raw_line($line);
6276 if (defined $set{'commit'}) {
6277 # finish previous commit
6278 if (%co) {
6279 print "</td>\n" .
6280 "<td class=\"link\">" .
6281 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6282 "commit") .
6283 " | " .
6284 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6285 hash_base=>$co{'id'})},
6286 "tree") .
6287 "</td>\n" .
6288 "</tr>\n";
6291 if ($alternate) {
6292 print "<tr class=\"dark\">\n";
6293 } else {
6294 print "<tr class=\"light\">\n";
6296 $alternate ^= 1;
6297 %co = parse_commit($set{'commit'});
6298 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6299 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6300 "<td><i>$author</i></td>\n" .
6301 "<td>" .
6302 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6303 -class => "list subject"},
6304 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6305 } elsif (defined $set{'to_id'}) {
6306 next if ($set{'to_id'} =~ m/^0{40}$/);
6308 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6309 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6310 -class => "list"},
6311 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6312 "<br/>\n";
6315 close $fd;
6317 # finish last commit (warning: repetition!)
6318 if (%co) {
6319 print "</td>\n" .
6320 "<td class=\"link\">" .
6321 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6322 "commit") .
6323 " | " .
6324 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6325 hash_base=>$co{'id'})},
6326 "tree") .
6327 "</td>\n" .
6328 "</tr>\n";
6331 print "</table>\n";
6333 git_footer_html();
6336 sub git_search_files {
6337 my %co = @_;
6339 local $/ = "\n";
6340 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6341 $search_use_regexp ? ('-E', '-i') : '-F',
6342 $searchtext, $co{'tree'}
6343 or die_error(500, "Open git-grep failed");
6345 git_header_html();
6347 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6348 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6350 print "<table class=\"grep_search\">\n";
6351 my $alternate = 1;
6352 my $matches = 0;
6353 my $lastfile = '';
6354 my $file_href;
6355 while (my $line = <$fd>) {
6356 chomp $line;
6357 my ($file, $lno, $ltext, $binary);
6358 last if ($matches++ > 1000);
6359 if ($line =~ /^Binary file (.+) matches$/) {
6360 $file = $1;
6361 $binary = 1;
6362 } else {
6363 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6364 $file =~ s/^$co{'tree'}://;
6366 if ($file ne $lastfile) {
6367 $lastfile and print "</td></tr>\n";
6368 if ($alternate++) {
6369 print "<tr class=\"dark\">\n";
6370 } else {
6371 print "<tr class=\"light\">\n";
6373 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6374 file_name=>$file);
6375 print "<td class=\"list\">".
6376 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6377 print "</td><td>\n";
6378 $lastfile = $file;
6380 if ($binary) {
6381 print "<div class=\"binary\">Binary file</div>\n";
6382 } else {
6383 $ltext = untabify($ltext);
6384 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6385 $ltext = esc_html($1, -nbsp=>1);
6386 $ltext .= '<span class="match">';
6387 $ltext .= esc_html($2, -nbsp=>1);
6388 $ltext .= '</span>';
6389 $ltext .= esc_html($3, -nbsp=>1);
6390 } else {
6391 $ltext = esc_html($ltext, -nbsp=>1);
6393 print "<div class=\"pre\">" .
6394 $cgi->a({-href => $file_href.'#l'.$lno,
6395 -class => "linenr"}, sprintf('%4i', $lno)) .
6396 ' ' . $ltext . "</div>\n";
6399 if ($lastfile) {
6400 print "</td></tr>\n";
6401 if ($matches > 1000) {
6402 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6404 } else {
6405 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6407 close $fd;
6409 print "</table>\n";
6411 git_footer_html();
6414 sub git_search_grep_body {
6415 my ($commitlist, $from, $to, $extra) = @_;
6416 $from = 0 unless defined $from;
6417 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6419 print "<table class=\"commit_search\">\n";
6420 my $alternate = 1;
6421 for (my $i = $from; $i <= $to; $i++) {
6422 my %co = %{$commitlist->[$i]};
6423 if (!%co) {
6424 next;
6426 my $commit = $co{'id'};
6427 if ($alternate) {
6428 print "<tr class=\"dark\">\n";
6429 } else {
6430 print "<tr class=\"light\">\n";
6432 $alternate ^= 1;
6433 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6434 format_author_html('td', \%co, 15, 5) .
6435 "<td>" .
6436 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6437 -class => "list subject"},
6438 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6439 my $comment = $co{'comment'};
6440 foreach my $line (@$comment) {
6441 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6442 my ($lead, $match, $trail) = ($1, $2, $3);
6443 $match = chop_str($match, 70, 5, 'center');
6444 my $contextlen = int((80 - length($match))/2);
6445 $contextlen = 30 if ($contextlen > 30);
6446 $lead = chop_str($lead, $contextlen, 10, 'left');
6447 $trail = chop_str($trail, $contextlen, 10, 'right');
6449 $lead = esc_html($lead);
6450 $match = esc_html($match);
6451 $trail = esc_html($trail);
6453 print "$lead<span class=\"match\">$match</span>$trail<br />";
6456 print "</td>\n" .
6457 "<td class=\"link\">" .
6458 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6459 " | " .
6460 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6461 " | " .
6462 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6463 print "</td>\n" .
6464 "</tr>\n";
6466 if (defined $extra) {
6467 print "<tr>\n" .
6468 "<td colspan=\"3\">$extra</td>\n" .
6469 "</tr>\n";
6471 print "</table>\n";
6474 ## ======================================================================
6475 ## ======================================================================
6476 ## actions
6478 sub git_project_list {
6479 my $order = $input_params{'order'};
6480 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6481 die_error(400, "Unknown order parameter");
6484 my @list = git_get_projects_list($project_filter, $strict_export);
6485 if (!@list) {
6486 die_error(404, "No projects found");
6489 git_header_html();
6490 if (defined $home_text && -f $home_text) {
6491 print "<div class=\"index_include\">\n";
6492 insert_file($home_text);
6493 print "</div>\n";
6496 git_project_search_form($searchtext, $search_use_regexp);
6497 git_project_list_body(\@list, $order);
6498 git_footer_html();
6501 sub git_forks {
6502 my $order = $input_params{'order'};
6503 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6504 die_error(400, "Unknown order parameter");
6507 my $filter = $project;
6508 $filter =~ s/\.git$//;
6509 my @list = git_get_projects_list($filter);
6510 if (!@list) {
6511 die_error(404, "No forks found");
6514 git_header_html();
6515 git_print_page_nav('','');
6516 git_print_header_div('summary', "$project forks");
6517 git_project_list_body(\@list, $order);
6518 git_footer_html();
6521 sub git_project_index {
6522 my @projects = git_get_projects_list($project_filter, $strict_export);
6523 if (!@projects) {
6524 die_error(404, "No projects found");
6527 print $cgi->header(
6528 -type => 'text/plain',
6529 -charset => 'utf-8',
6530 -content_disposition => 'inline; filename="index.aux"');
6532 foreach my $pr (@projects) {
6533 if (!exists $pr->{'owner'}) {
6534 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6537 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6538 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6539 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6540 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6541 $path =~ s/ /\+/g;
6542 $owner =~ s/ /\+/g;
6544 print "$path $owner\n";
6548 sub git_summary {
6549 my $descr = git_get_project_description($project) || "none";
6550 my %co = parse_commit("HEAD");
6551 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6552 my $head = $co{'id'};
6553 my $remote_heads = gitweb_check_feature('remote_heads');
6555 my $owner = git_get_project_owner($project);
6557 my $refs = git_get_references();
6558 # These get_*_list functions return one more to allow us to see if
6559 # there are more ...
6560 my @taglist = git_get_tags_list(16);
6561 my @headlist = git_get_heads_list(16);
6562 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6563 my @forklist;
6564 my $check_forks = gitweb_check_feature('forks');
6566 if ($check_forks) {
6567 # find forks of a project
6568 my $filter = $project;
6569 $filter =~ s/\.git$//;
6570 @forklist = git_get_projects_list($filter);
6571 # filter out forks of forks
6572 @forklist = filter_forks_from_projects_list(\@forklist)
6573 if (@forklist);
6576 git_header_html();
6577 git_print_page_nav('summary','', $head);
6579 print "<div class=\"title\">&nbsp;</div>\n";
6580 print "<table class=\"projects_list\">\n" .
6581 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6582 if ($owner and not $omit_owner) {
6583 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6585 if (defined $cd{'rfc2822'}) {
6586 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6587 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6590 # use per project git URL list in $projectroot/$project/cloneurl
6591 # or make project git URL from git base URL and project name
6592 my $url_tag = "URL";
6593 my @url_list = git_get_project_url_list($project);
6594 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6595 foreach my $git_url (@url_list) {
6596 next unless $git_url;
6597 print format_repo_url($url_tag, $git_url);
6598 $url_tag = "";
6601 # Tag cloud
6602 my $show_ctags = gitweb_check_feature('ctags');
6603 if ($show_ctags) {
6604 my $ctags = git_get_project_ctags($project);
6605 if (%$ctags) {
6606 # without ability to add tags, don't show if there are none
6607 my $cloud = git_populate_project_tagcloud($ctags);
6608 print "<tr id=\"metadata_ctags\">" .
6609 "<td>content tags</td>" .
6610 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6611 "</tr>\n";
6615 print "</table>\n";
6617 # If XSS prevention is on, we don't include README.html.
6618 # TODO: Allow a readme in some safe format.
6619 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6620 print "<div class=\"title\">readme</div>\n" .
6621 "<div class=\"readme\">\n";
6622 insert_file("$projectroot/$project/README.html");
6623 print "\n</div>\n"; # class="readme"
6626 # we need to request one more than 16 (0..15) to check if
6627 # those 16 are all
6628 my @commitlist = $head ? parse_commits($head, 17) : ();
6629 if (@commitlist) {
6630 git_print_header_div('shortlog');
6631 git_shortlog_body(\@commitlist, 0, 15, $refs,
6632 $#commitlist <= 15 ? undef :
6633 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6636 if (@taglist) {
6637 git_print_header_div('tags');
6638 git_tags_body(\@taglist, 0, 15,
6639 $#taglist <= 15 ? undef :
6640 $cgi->a({-href => href(action=>"tags")}, "..."));
6643 if (@headlist) {
6644 git_print_header_div('heads');
6645 git_heads_body(\@headlist, $head, 0, 15,
6646 $#headlist <= 15 ? undef :
6647 $cgi->a({-href => href(action=>"heads")}, "..."));
6650 if (%remotedata) {
6651 git_print_header_div('remotes');
6652 git_remotes_body(\%remotedata, 15, $head);
6655 if (@forklist) {
6656 git_print_header_div('forks');
6657 git_project_list_body(\@forklist, 'age', 0, 15,
6658 $#forklist <= 15 ? undef :
6659 $cgi->a({-href => href(action=>"forks")}, "..."),
6660 'no_header');
6663 git_footer_html();
6666 sub git_tag {
6667 my %tag = parse_tag($hash);
6669 if (! %tag) {
6670 die_error(404, "Unknown tag object");
6673 my $head = git_get_head_hash($project);
6674 git_header_html();
6675 git_print_page_nav('','', $head,undef,$head);
6676 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6677 print "<div class=\"title_text\">\n" .
6678 "<table class=\"object_header\">\n" .
6679 "<tr>\n" .
6680 "<td>object</td>\n" .
6681 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6682 $tag{'object'}) . "</td>\n" .
6683 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6684 $tag{'type'}) . "</td>\n" .
6685 "</tr>\n";
6686 if (defined($tag{'author'})) {
6687 git_print_authorship_rows(\%tag, 'author');
6689 print "</table>\n\n" .
6690 "</div>\n";
6691 print "<div class=\"page_body\">";
6692 my $comment = $tag{'comment'};
6693 foreach my $line (@$comment) {
6694 chomp $line;
6695 print esc_html($line, -nbsp=>1) . "<br/>\n";
6697 print "</div>\n";
6698 git_footer_html();
6701 sub git_blame_common {
6702 my $format = shift || 'porcelain';
6703 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6704 $format = 'incremental';
6705 $action = 'blame_incremental'; # for page title etc
6708 # permissions
6709 gitweb_check_feature('blame')
6710 or die_error(403, "Blame view not allowed");
6712 # error checking
6713 die_error(400, "No file name given") unless $file_name;
6714 $hash_base ||= git_get_head_hash($project);
6715 die_error(404, "Couldn't find base commit") unless $hash_base;
6716 my %co = parse_commit($hash_base)
6717 or die_error(404, "Commit not found");
6718 my $ftype = "blob";
6719 if (!defined $hash) {
6720 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6721 or die_error(404, "Error looking up file");
6722 } else {
6723 $ftype = git_get_type($hash);
6724 if ($ftype !~ "blob") {
6725 die_error(400, "Object is not a blob");
6729 my $fd;
6730 if ($format eq 'incremental') {
6731 # get file contents (as base)
6732 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6733 or die_error(500, "Open git-cat-file failed");
6734 } elsif ($format eq 'data') {
6735 # run git-blame --incremental
6736 open $fd, "-|", git_cmd(), "blame", "--incremental",
6737 $hash_base, "--", $file_name
6738 or die_error(500, "Open git-blame --incremental failed");
6739 } else {
6740 # run git-blame --porcelain
6741 open $fd, "-|", git_cmd(), "blame", '-p',
6742 $hash_base, '--', $file_name
6743 or die_error(500, "Open git-blame --porcelain failed");
6745 binmode $fd, ':utf8';
6747 # incremental blame data returns early
6748 if ($format eq 'data') {
6749 print $cgi->header(
6750 -type=>"text/plain", -charset => "utf-8",
6751 -status=> "200 OK");
6752 local $| = 1; # output autoflush
6753 while (my $line = <$fd>) {
6754 print to_utf8($line);
6756 close $fd
6757 or print "ERROR $!\n";
6759 print 'END';
6760 if (defined $t0 && gitweb_check_feature('timed')) {
6761 print ' '.
6762 tv_interval($t0, [ gettimeofday() ]).
6763 ' '.$number_of_git_cmds;
6765 print "\n";
6767 return;
6770 # page header
6771 git_header_html();
6772 my $formats_nav =
6773 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6774 "blob") .
6775 " | ";
6776 if ($format eq 'incremental') {
6777 $formats_nav .=
6778 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6779 "blame") . " (non-incremental)";
6780 } else {
6781 $formats_nav .=
6782 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6783 "blame") . " (incremental)";
6785 $formats_nav .=
6786 " | " .
6787 $cgi->a({-href => href(action=>"history", -replay=>1)},
6788 "history") .
6789 " | " .
6790 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6791 "HEAD");
6792 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6793 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6794 git_print_page_path($file_name, $ftype, $hash_base);
6796 # page body
6797 if ($format eq 'incremental') {
6798 print "<noscript>\n<div class=\"error\"><center><b>\n".
6799 "This page requires JavaScript to run.\n Use ".
6800 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6801 'this page').
6802 " instead.\n".
6803 "</b></center></div>\n</noscript>\n";
6805 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6808 print qq!<div class="page_body">\n!;
6809 print qq!<div id="progress_info">... / ...</div>\n!
6810 if ($format eq 'incremental');
6811 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6812 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6813 qq!<thead>\n!.
6814 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6815 qq!</thead>\n!.
6816 qq!<tbody>\n!;
6818 my @rev_color = qw(light dark);
6819 my $num_colors = scalar(@rev_color);
6820 my $current_color = 0;
6822 if ($format eq 'incremental') {
6823 my $color_class = $rev_color[$current_color];
6825 #contents of a file
6826 my $linenr = 0;
6827 LINE:
6828 while (my $line = <$fd>) {
6829 chomp $line;
6830 $linenr++;
6832 print qq!<tr id="l$linenr" class="$color_class">!.
6833 qq!<td class="sha1"><a href=""> </a></td>!.
6834 qq!<td class="linenr">!.
6835 qq!<a class="linenr" href="">$linenr</a></td>!;
6836 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6837 print qq!</tr>\n!;
6840 } else { # porcelain, i.e. ordinary blame
6841 my %metainfo = (); # saves information about commits
6843 # blame data
6844 LINE:
6845 while (my $line = <$fd>) {
6846 chomp $line;
6847 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6848 # no <lines in group> for subsequent lines in group of lines
6849 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6850 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6851 if (!exists $metainfo{$full_rev}) {
6852 $metainfo{$full_rev} = { 'nprevious' => 0 };
6854 my $meta = $metainfo{$full_rev};
6855 my $data;
6856 while ($data = <$fd>) {
6857 chomp $data;
6858 last if ($data =~ s/^\t//); # contents of line
6859 if ($data =~ /^(\S+)(?: (.*))?$/) {
6860 $meta->{$1} = $2 unless exists $meta->{$1};
6862 if ($data =~ /^previous /) {
6863 $meta->{'nprevious'}++;
6866 my $short_rev = substr($full_rev, 0, 8);
6867 my $author = $meta->{'author'};
6868 my %date =
6869 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6870 my $date = $date{'iso-tz'};
6871 if ($group_size) {
6872 $current_color = ($current_color + 1) % $num_colors;
6874 my $tr_class = $rev_color[$current_color];
6875 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6876 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6877 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6878 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6879 if ($group_size) {
6880 print "<td class=\"sha1\"";
6881 print " title=\"". esc_html($author) . ", $date\"";
6882 print " rowspan=\"$group_size\"" if ($group_size > 1);
6883 print ">";
6884 print $cgi->a({-href => href(action=>"commit",
6885 hash=>$full_rev,
6886 file_name=>$file_name)},
6887 esc_html($short_rev));
6888 if ($group_size >= 2) {
6889 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6890 if (@author_initials) {
6891 print "<br />" .
6892 esc_html(join('', @author_initials));
6893 # or join('.', ...)
6896 print "</td>\n";
6898 # 'previous' <sha1 of parent commit> <filename at commit>
6899 if (exists $meta->{'previous'} &&
6900 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6901 $meta->{'parent'} = $1;
6902 $meta->{'file_parent'} = unquote($2);
6904 my $linenr_commit =
6905 exists($meta->{'parent'}) ?
6906 $meta->{'parent'} : $full_rev;
6907 my $linenr_filename =
6908 exists($meta->{'file_parent'}) ?
6909 $meta->{'file_parent'} : unquote($meta->{'filename'});
6910 my $blamed = href(action => 'blame',
6911 file_name => $linenr_filename,
6912 hash_base => $linenr_commit);
6913 print "<td class=\"linenr\">";
6914 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6915 -class => "linenr" },
6916 esc_html($lineno));
6917 print "</td>";
6918 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6919 print "</tr>\n";
6920 } # end while
6924 # footer
6925 print "</tbody>\n".
6926 "</table>\n"; # class="blame"
6927 print "</div>\n"; # class="blame_body"
6928 close $fd
6929 or print "Reading blob failed\n";
6931 git_footer_html();
6934 sub git_blame {
6935 git_blame_common();
6938 sub git_blame_incremental {
6939 git_blame_common('incremental');
6942 sub git_blame_data {
6943 git_blame_common('data');
6946 sub git_tags {
6947 my $head = git_get_head_hash($project);
6948 git_header_html();
6949 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6950 git_print_header_div('summary', $project);
6952 my @tagslist = git_get_tags_list();
6953 if (@tagslist) {
6954 git_tags_body(\@tagslist);
6956 git_footer_html();
6959 sub git_heads {
6960 my $head = git_get_head_hash($project);
6961 git_header_html();
6962 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6963 git_print_header_div('summary', $project);
6965 my @headslist = git_get_heads_list();
6966 if (@headslist) {
6967 git_heads_body(\@headslist, $head);
6969 git_footer_html();
6972 # used both for single remote view and for list of all the remotes
6973 sub git_remotes {
6974 gitweb_check_feature('remote_heads')
6975 or die_error(403, "Remote heads view is disabled");
6977 my $head = git_get_head_hash($project);
6978 my $remote = $input_params{'hash'};
6980 my $remotedata = git_get_remotes_list($remote);
6981 die_error(500, "Unable to get remote information") unless defined $remotedata;
6983 unless (%$remotedata) {
6984 die_error(404, defined $remote ?
6985 "Remote $remote not found" :
6986 "No remotes found");
6989 git_header_html(undef, undef, -action_extra => $remote);
6990 git_print_page_nav('', '', $head, undef, $head,
6991 format_ref_views($remote ? '' : 'remotes'));
6993 fill_remote_heads($remotedata);
6994 if (defined $remote) {
6995 git_print_header_div('remotes', "$remote remote for $project");
6996 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6997 } else {
6998 git_print_header_div('summary', "$project remotes");
6999 git_remotes_body($remotedata, undef, $head);
7002 git_footer_html();
7005 sub git_blob_plain {
7006 my $type = shift;
7007 my $expires;
7009 if (!defined $hash) {
7010 if (defined $file_name) {
7011 my $base = $hash_base || git_get_head_hash($project);
7012 $hash = git_get_hash_by_path($base, $file_name, "blob")
7013 or die_error(404, "Cannot find file");
7014 } else {
7015 die_error(400, "No file name defined");
7017 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7018 # blobs defined by non-textual hash id's can be cached
7019 $expires = "+1d";
7022 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7023 or die_error(500, "Open git-cat-file blob '$hash' failed");
7025 # content-type (can include charset)
7026 $type = blob_contenttype($fd, $file_name, $type);
7028 # "save as" filename, even when no $file_name is given
7029 my $save_as = "$hash";
7030 if (defined $file_name) {
7031 $save_as = $file_name;
7032 } elsif ($type =~ m/^text\//) {
7033 $save_as .= '.txt';
7036 # With XSS prevention on, blobs of all types except a few known safe
7037 # ones are served with "Content-Disposition: attachment" to make sure
7038 # they don't run in our security domain. For certain image types,
7039 # blob view writes an <img> tag referring to blob_plain view, and we
7040 # want to be sure not to break that by serving the image as an
7041 # attachment (though Firefox 3 doesn't seem to care).
7042 my $sandbox = $prevent_xss &&
7043 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7045 # serve text/* as text/plain
7046 if ($prevent_xss &&
7047 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7048 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7049 my $rest = $1;
7050 $rest = defined $rest ? $rest : '';
7051 $type = "text/plain$rest";
7054 print $cgi->header(
7055 -type => $type,
7056 -expires => $expires,
7057 -content_disposition =>
7058 ($sandbox ? 'attachment' : 'inline')
7059 . '; filename="' . $save_as . '"');
7060 local $/ = undef;
7061 binmode STDOUT, ':raw';
7062 print <$fd>;
7063 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7064 close $fd;
7067 sub git_blob {
7068 my $expires;
7070 if (!defined $hash) {
7071 if (defined $file_name) {
7072 my $base = $hash_base || git_get_head_hash($project);
7073 $hash = git_get_hash_by_path($base, $file_name, "blob")
7074 or die_error(404, "Cannot find file");
7075 } else {
7076 die_error(400, "No file name defined");
7078 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7079 # blobs defined by non-textual hash id's can be cached
7080 $expires = "+1d";
7083 my $have_blame = gitweb_check_feature('blame');
7084 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7085 or die_error(500, "Couldn't cat $file_name, $hash");
7086 my $mimetype = blob_mimetype($fd, $file_name);
7087 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7088 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7089 close $fd;
7090 return git_blob_plain($mimetype);
7092 # we can have blame only for text/* mimetype
7093 $have_blame &&= ($mimetype =~ m!^text/!);
7095 my $highlight = gitweb_check_feature('highlight');
7096 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7097 $fd = run_highlighter($fd, $highlight, $syntax)
7098 if $syntax;
7100 git_header_html(undef, $expires);
7101 my $formats_nav = '';
7102 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7103 if (defined $file_name) {
7104 if ($have_blame) {
7105 $formats_nav .=
7106 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7107 "blame") .
7108 " | ";
7110 $formats_nav .=
7111 $cgi->a({-href => href(action=>"history", -replay=>1)},
7112 "history") .
7113 " | " .
7114 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7115 "raw") .
7116 " | " .
7117 $cgi->a({-href => href(action=>"blob",
7118 hash_base=>"HEAD", file_name=>$file_name)},
7119 "HEAD");
7120 } else {
7121 $formats_nav .=
7122 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7123 "raw");
7125 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7126 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7127 } else {
7128 print "<div class=\"page_nav\">\n" .
7129 "<br/><br/></div>\n" .
7130 "<div class=\"title\">".esc_html($hash)."</div>\n";
7132 git_print_page_path($file_name, "blob", $hash_base);
7133 print "<div class=\"page_body\">\n";
7134 if ($mimetype =~ m!^image/!) {
7135 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7136 if ($file_name) {
7137 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7139 print qq! src="! .
7140 href(action=>"blob_plain", hash=>$hash,
7141 hash_base=>$hash_base, file_name=>$file_name) .
7142 qq!" />\n!;
7143 } else {
7144 my $nr;
7145 while (my $line = <$fd>) {
7146 chomp $line;
7147 $nr++;
7148 $line = untabify($line);
7149 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7150 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7151 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7154 close $fd
7155 or print "Reading blob failed.\n";
7156 print "</div>";
7157 git_footer_html();
7160 sub git_tree {
7161 if (!defined $hash_base) {
7162 $hash_base = "HEAD";
7164 if (!defined $hash) {
7165 if (defined $file_name) {
7166 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7167 } else {
7168 $hash = $hash_base;
7171 die_error(404, "No such tree") unless defined($hash);
7173 my $show_sizes = gitweb_check_feature('show-sizes');
7174 my $have_blame = gitweb_check_feature('blame');
7176 my @entries = ();
7178 local $/ = "\0";
7179 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7180 ($show_sizes ? '-l' : ()), @extra_options, $hash
7181 or die_error(500, "Open git-ls-tree failed");
7182 @entries = map { chomp; $_ } <$fd>;
7183 close $fd
7184 or die_error(404, "Reading tree failed");
7187 my $refs = git_get_references();
7188 my $ref = format_ref_marker($refs, $hash_base);
7189 git_header_html();
7190 my $basedir = '';
7191 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7192 my @views_nav = ();
7193 if (defined $file_name) {
7194 push @views_nav,
7195 $cgi->a({-href => href(action=>"history", -replay=>1)},
7196 "history"),
7197 $cgi->a({-href => href(action=>"tree",
7198 hash_base=>"HEAD", file_name=>$file_name)},
7199 "HEAD"),
7201 my $snapshot_links = format_snapshot_links($hash);
7202 if (defined $snapshot_links) {
7203 # FIXME: Should be available when we have no hash base as well.
7204 push @views_nav, $snapshot_links;
7206 git_print_page_nav('tree','', $hash_base, undef, undef,
7207 join(' | ', @views_nav));
7208 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7209 } else {
7210 undef $hash_base;
7211 print "<div class=\"page_nav\">\n";
7212 print "<br/><br/></div>\n";
7213 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7215 if (defined $file_name) {
7216 $basedir = $file_name;
7217 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7218 $basedir .= '/';
7220 git_print_page_path($file_name, 'tree', $hash_base);
7222 print "<div class=\"page_body\">\n";
7223 print "<table class=\"tree\">\n";
7224 my $alternate = 1;
7225 # '..' (top directory) link if possible
7226 if (defined $hash_base &&
7227 defined $file_name && $file_name =~ m![^/]+$!) {
7228 if ($alternate) {
7229 print "<tr class=\"dark\">\n";
7230 } else {
7231 print "<tr class=\"light\">\n";
7233 $alternate ^= 1;
7235 my $up = $file_name;
7236 $up =~ s!/?[^/]+$!!;
7237 undef $up unless $up;
7238 # based on git_print_tree_entry
7239 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7240 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7241 print '<td class="list">';
7242 print $cgi->a({-href => href(action=>"tree",
7243 hash_base=>$hash_base,
7244 file_name=>$up)},
7245 "..");
7246 print "</td>\n";
7247 print "<td class=\"link\"></td>\n";
7249 print "</tr>\n";
7251 foreach my $line (@entries) {
7252 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7254 if ($alternate) {
7255 print "<tr class=\"dark\">\n";
7256 } else {
7257 print "<tr class=\"light\">\n";
7259 $alternate ^= 1;
7261 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7263 print "</tr>\n";
7265 print "</table>\n" .
7266 "</div>";
7267 git_footer_html();
7270 sub sanitize_for_filename {
7271 my $name = shift;
7273 $name =~ s!/!-!g;
7274 $name =~ s/[^[:alnum:]_.-]//g;
7276 return $name;
7279 sub snapshot_name {
7280 my ($project, $hash) = @_;
7282 # path/to/project.git -> project
7283 # path/to/project/.git -> project
7284 my $name = to_utf8($project);
7285 $name =~ s,([^/])/*\.git$,$1,;
7286 $name = sanitize_for_filename(basename($name));
7288 my $ver = $hash;
7289 if ($hash =~ /^[0-9a-fA-F]+$/) {
7290 # shorten SHA-1 hash
7291 my $full_hash = git_get_full_hash($project, $hash);
7292 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7293 $ver = git_get_short_hash($project, $hash);
7295 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7296 # tags don't need shortened SHA-1 hash
7297 $ver = $1;
7298 } else {
7299 # branches and other need shortened SHA-1 hash
7300 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7301 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7302 my $ref_dir = (defined $1) ? $1 : '';
7303 $ver = $2;
7305 $ref_dir = sanitize_for_filename($ref_dir);
7306 # for refs neither in heads nor remotes we want to
7307 # add a ref dir to archive name
7308 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7309 $ver = $ref_dir . '-' . $ver;
7312 $ver .= '-' . git_get_short_hash($project, $hash);
7314 # special case of sanitization for filename - we change
7315 # slashes to dots instead of dashes
7316 # in case of hierarchical branch names
7317 $ver =~ s!/!.!g;
7318 $ver =~ s/[^[:alnum:]_.-]//g;
7320 # name = project-version_string
7321 $name = "$name-$ver";
7323 return wantarray ? ($name, $name) : $name;
7326 sub exit_if_unmodified_since {
7327 my ($latest_epoch) = @_;
7328 our $cgi;
7330 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7331 if (defined $if_modified) {
7332 my $since;
7333 if (eval { require HTTP::Date; 1; }) {
7334 $since = HTTP::Date::str2time($if_modified);
7335 } elsif (eval { require Time::ParseDate; 1; }) {
7336 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7338 if (defined $since && $latest_epoch <= $since) {
7339 my %latest_date = parse_date($latest_epoch);
7340 print $cgi->header(
7341 -last_modified => $latest_date{'rfc2822'},
7342 -status => '304 Not Modified');
7343 goto DONE_GITWEB;
7348 sub git_snapshot {
7349 my $format = $input_params{'snapshot_format'};
7350 if (!@snapshot_fmts) {
7351 die_error(403, "Snapshots not allowed");
7353 # default to first supported snapshot format
7354 $format ||= $snapshot_fmts[0];
7355 if ($format !~ m/^[a-z0-9]+$/) {
7356 die_error(400, "Invalid snapshot format parameter");
7357 } elsif (!exists($known_snapshot_formats{$format})) {
7358 die_error(400, "Unknown snapshot format");
7359 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7360 die_error(403, "Snapshot format not allowed");
7361 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7362 die_error(403, "Unsupported snapshot format");
7365 my $type = git_get_type("$hash^{}");
7366 if (!$type) {
7367 die_error(404, 'Object does not exist');
7368 } elsif ($type eq 'blob') {
7369 die_error(400, 'Object is not a tree-ish');
7372 my ($name, $prefix) = snapshot_name($project, $hash);
7373 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7375 my %co = parse_commit($hash);
7376 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7378 my $cmd = quote_command(
7379 git_cmd(), 'archive',
7380 "--format=$known_snapshot_formats{$format}{'format'}",
7381 "--prefix=$prefix/", $hash);
7382 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7383 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7386 $filename =~ s/(["\\])/\\$1/g;
7387 my %latest_date;
7388 if (%co) {
7389 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7392 print $cgi->header(
7393 -type => $known_snapshot_formats{$format}{'type'},
7394 -content_disposition => 'inline; filename="' . $filename . '"',
7395 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7396 -status => '200 OK');
7398 open my $fd, "-|", $cmd
7399 or die_error(500, "Execute git-archive failed");
7400 binmode STDOUT, ':raw';
7401 print <$fd>;
7402 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7403 close $fd;
7406 sub git_log_generic {
7407 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7409 my $head = git_get_head_hash($project);
7410 if (!defined $base) {
7411 $base = $head;
7413 if (!defined $page) {
7414 $page = 0;
7416 my $refs = git_get_references();
7418 my $commit_hash = $base;
7419 if (defined $parent) {
7420 $commit_hash = "$parent..$base";
7422 my @commitlist =
7423 parse_commits($commit_hash, 101, (100 * $page),
7424 defined $file_name ? ($file_name, "--full-history") : ());
7426 my $ftype;
7427 if (!defined $file_hash && defined $file_name) {
7428 # some commits could have deleted file in question,
7429 # and not have it in tree, but one of them has to have it
7430 for (my $i = 0; $i < @commitlist; $i++) {
7431 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7432 last if defined $file_hash;
7435 if (defined $file_hash) {
7436 $ftype = git_get_type($file_hash);
7438 if (defined $file_name && !defined $ftype) {
7439 die_error(500, "Unknown type of object");
7441 my %co;
7442 if (defined $file_name) {
7443 %co = parse_commit($base)
7444 or die_error(404, "Unknown commit object");
7448 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7449 my $next_link = '';
7450 if ($#commitlist >= 100) {
7451 $next_link =
7452 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7453 -accesskey => "n", -title => "Alt-n"}, "next");
7455 my $patch_max = gitweb_get_feature('patches');
7456 if ($patch_max && !defined $file_name) {
7457 if ($patch_max < 0 || @commitlist <= $patch_max) {
7458 $paging_nav .= " &sdot; " .
7459 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7460 "patches");
7464 git_header_html();
7465 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7466 if (defined $file_name) {
7467 git_print_header_div('commit', esc_html($co{'title'}), $base);
7468 } else {
7469 git_print_header_div('summary', $project)
7471 git_print_page_path($file_name, $ftype, $hash_base)
7472 if (defined $file_name);
7474 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7475 $file_name, $file_hash, $ftype);
7477 git_footer_html();
7480 sub git_log {
7481 git_log_generic('log', \&git_log_body,
7482 $hash, $hash_parent);
7485 sub git_commit {
7486 $hash ||= $hash_base || "HEAD";
7487 my %co = parse_commit($hash)
7488 or die_error(404, "Unknown commit object");
7490 my $parent = $co{'parent'};
7491 my $parents = $co{'parents'}; # listref
7493 # we need to prepare $formats_nav before any parameter munging
7494 my $formats_nav;
7495 if (!defined $parent) {
7496 # --root commitdiff
7497 $formats_nav .= '(initial)';
7498 } elsif (@$parents == 1) {
7499 # single parent commit
7500 $formats_nav .=
7501 '(parent: ' .
7502 $cgi->a({-href => href(action=>"commit",
7503 hash=>$parent)},
7504 esc_html(substr($parent, 0, 7))) .
7505 ')';
7506 } else {
7507 # merge commit
7508 $formats_nav .=
7509 '(merge: ' .
7510 join(' ', map {
7511 $cgi->a({-href => href(action=>"commit",
7512 hash=>$_)},
7513 esc_html(substr($_, 0, 7)));
7514 } @$parents ) .
7515 ')';
7517 if (gitweb_check_feature('patches') && @$parents <= 1) {
7518 $formats_nav .= " | " .
7519 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7520 "patch");
7523 if (!defined $parent) {
7524 $parent = "--root";
7526 my @difftree;
7527 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7528 @diff_opts,
7529 (@$parents <= 1 ? $parent : '-c'),
7530 $hash, "--"
7531 or die_error(500, "Open git-diff-tree failed");
7532 @difftree = map { chomp; $_ } <$fd>;
7533 close $fd or die_error(404, "Reading git-diff-tree failed");
7535 # non-textual hash id's can be cached
7536 my $expires;
7537 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7538 $expires = "+1d";
7540 my $refs = git_get_references();
7541 my $ref = format_ref_marker($refs, $co{'id'});
7543 git_header_html(undef, $expires);
7544 git_print_page_nav('commit', '',
7545 $hash, $co{'tree'}, $hash,
7546 $formats_nav);
7548 if (defined $co{'parent'}) {
7549 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7550 } else {
7551 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7553 print "<div class=\"title_text\">\n" .
7554 "<table class=\"object_header\">\n";
7555 git_print_authorship_rows(\%co);
7556 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7557 print "<tr>" .
7558 "<td>tree</td>" .
7559 "<td class=\"sha1\">" .
7560 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7561 class => "list"}, $co{'tree'}) .
7562 "</td>" .
7563 "<td class=\"link\">" .
7564 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7565 "tree");
7566 my $snapshot_links = format_snapshot_links($hash);
7567 if (defined $snapshot_links) {
7568 print " | " . $snapshot_links;
7570 print "</td>" .
7571 "</tr>\n";
7573 foreach my $par (@$parents) {
7574 print "<tr>" .
7575 "<td>parent</td>" .
7576 "<td class=\"sha1\">" .
7577 $cgi->a({-href => href(action=>"commit", hash=>$par),
7578 class => "list"}, $par) .
7579 "</td>" .
7580 "<td class=\"link\">" .
7581 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7582 " | " .
7583 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7584 "</td>" .
7585 "</tr>\n";
7587 print "</table>".
7588 "</div>\n";
7590 print "<div class=\"page_body\">\n";
7591 git_print_log($co{'comment'});
7592 print "</div>\n";
7594 git_difftree_body(\@difftree, $hash, @$parents);
7596 git_footer_html();
7599 sub git_object {
7600 # object is defined by:
7601 # - hash or hash_base alone
7602 # - hash_base and file_name
7603 my $type;
7605 # - hash or hash_base alone
7606 if ($hash || ($hash_base && !defined $file_name)) {
7607 my $object_id = $hash || $hash_base;
7609 open my $fd, "-|", quote_command(
7610 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7611 or die_error(404, "Object does not exist");
7612 $type = <$fd>;
7613 chomp $type;
7614 close $fd
7615 or die_error(404, "Object does not exist");
7617 # - hash_base and file_name
7618 } elsif ($hash_base && defined $file_name) {
7619 $file_name =~ s,/+$,,;
7621 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7622 or die_error(404, "Base object does not exist");
7624 # here errors should not happen
7625 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7626 or die_error(500, "Open git-ls-tree failed");
7627 my $line = <$fd>;
7628 close $fd;
7630 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7631 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7632 die_error(404, "File or directory for given base does not exist");
7634 $type = $2;
7635 $hash = $3;
7636 } else {
7637 die_error(400, "Not enough information to find object");
7640 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7641 hash=>$hash, hash_base=>$hash_base,
7642 file_name=>$file_name),
7643 -status => '302 Found');
7646 sub git_blobdiff {
7647 my $format = shift || 'html';
7648 my $diff_style = $input_params{'diff_style'} || 'inline';
7650 my $fd;
7651 my @difftree;
7652 my %diffinfo;
7653 my $expires;
7655 # preparing $fd and %diffinfo for git_patchset_body
7656 # new style URI
7657 if (defined $hash_base && defined $hash_parent_base) {
7658 if (defined $file_name) {
7659 # read raw output
7660 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7661 $hash_parent_base, $hash_base,
7662 "--", (defined $file_parent ? $file_parent : ()), $file_name
7663 or die_error(500, "Open git-diff-tree failed");
7664 @difftree = map { chomp; $_ } <$fd>;
7665 close $fd
7666 or die_error(404, "Reading git-diff-tree failed");
7667 @difftree
7668 or die_error(404, "Blob diff not found");
7670 } elsif (defined $hash &&
7671 $hash =~ /[0-9a-fA-F]{40}/) {
7672 # try to find filename from $hash
7674 # read filtered raw output
7675 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7676 $hash_parent_base, $hash_base, "--"
7677 or die_error(500, "Open git-diff-tree failed");
7678 @difftree =
7679 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7680 # $hash == to_id
7681 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7682 map { chomp; $_ } <$fd>;
7683 close $fd
7684 or die_error(404, "Reading git-diff-tree failed");
7685 @difftree
7686 or die_error(404, "Blob diff not found");
7688 } else {
7689 die_error(400, "Missing one of the blob diff parameters");
7692 if (@difftree > 1) {
7693 die_error(400, "Ambiguous blob diff specification");
7696 %diffinfo = parse_difftree_raw_line($difftree[0]);
7697 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7698 $file_name ||= $diffinfo{'to_file'};
7700 $hash_parent ||= $diffinfo{'from_id'};
7701 $hash ||= $diffinfo{'to_id'};
7703 # non-textual hash id's can be cached
7704 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7705 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7706 $expires = '+1d';
7709 # open patch output
7710 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7711 '-p', ($format eq 'html' ? "--full-index" : ()),
7712 $hash_parent_base, $hash_base,
7713 "--", (defined $file_parent ? $file_parent : ()), $file_name
7714 or die_error(500, "Open git-diff-tree failed");
7717 # old/legacy style URI -- not generated anymore since 1.4.3.
7718 if (!%diffinfo) {
7719 die_error('404 Not Found', "Missing one of the blob diff parameters")
7722 # header
7723 if ($format eq 'html') {
7724 my $formats_nav =
7725 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7726 "raw");
7727 $formats_nav .= diff_style_nav($diff_style);
7728 git_header_html(undef, $expires);
7729 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7730 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7731 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7732 } else {
7733 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7734 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7736 if (defined $file_name) {
7737 git_print_page_path($file_name, "blob", $hash_base);
7738 } else {
7739 print "<div class=\"page_path\"></div>\n";
7742 } elsif ($format eq 'plain') {
7743 print $cgi->header(
7744 -type => 'text/plain',
7745 -charset => 'utf-8',
7746 -expires => $expires,
7747 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7749 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7751 } else {
7752 die_error(400, "Unknown blobdiff format");
7755 # patch
7756 if ($format eq 'html') {
7757 print "<div class=\"page_body\">\n";
7759 git_patchset_body($fd, $diff_style,
7760 [ \%diffinfo ], $hash_base, $hash_parent_base);
7761 close $fd;
7763 print "</div>\n"; # class="page_body"
7764 git_footer_html();
7766 } else {
7767 while (my $line = <$fd>) {
7768 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7769 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7771 print $line;
7773 last if $line =~ m!^\+\+\+!;
7775 local $/ = undef;
7776 print <$fd>;
7777 close $fd;
7781 sub git_blobdiff_plain {
7782 git_blobdiff('plain');
7785 # assumes that it is added as later part of already existing navigation,
7786 # so it returns "| foo | bar" rather than just "foo | bar"
7787 sub diff_style_nav {
7788 my ($diff_style, $is_combined) = @_;
7789 $diff_style ||= 'inline';
7791 return "" if ($is_combined);
7793 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7794 my %styles = @styles;
7795 @styles =
7796 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7798 return join '',
7799 map { " | ".$_ }
7800 map {
7801 $_ eq $diff_style ? $styles{$_} :
7802 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7803 } @styles;
7806 sub git_commitdiff {
7807 my %params = @_;
7808 my $format = $params{-format} || 'html';
7809 my $diff_style = $input_params{'diff_style'} || 'inline';
7811 my ($patch_max) = gitweb_get_feature('patches');
7812 if ($format eq 'patch') {
7813 die_error(403, "Patch view not allowed") unless $patch_max;
7816 $hash ||= $hash_base || "HEAD";
7817 my %co = parse_commit($hash)
7818 or die_error(404, "Unknown commit object");
7820 # choose format for commitdiff for merge
7821 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7822 $hash_parent = '--cc';
7824 # we need to prepare $formats_nav before almost any parameter munging
7825 my $formats_nav;
7826 if ($format eq 'html') {
7827 $formats_nav =
7828 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7829 "raw");
7830 if ($patch_max && @{$co{'parents'}} <= 1) {
7831 $formats_nav .= " | " .
7832 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7833 "patch");
7835 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7837 if (defined $hash_parent &&
7838 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7839 # commitdiff with two commits given
7840 my $hash_parent_short = $hash_parent;
7841 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7842 $hash_parent_short = substr($hash_parent, 0, 7);
7844 $formats_nav .=
7845 ' (from';
7846 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7847 if ($co{'parents'}[$i] eq $hash_parent) {
7848 $formats_nav .= ' parent ' . ($i+1);
7849 last;
7852 $formats_nav .= ': ' .
7853 $cgi->a({-href => href(-replay=>1,
7854 hash=>$hash_parent, hash_base=>undef)},
7855 esc_html($hash_parent_short)) .
7856 ')';
7857 } elsif (!$co{'parent'}) {
7858 # --root commitdiff
7859 $formats_nav .= ' (initial)';
7860 } elsif (scalar @{$co{'parents'}} == 1) {
7861 # single parent commit
7862 $formats_nav .=
7863 ' (parent: ' .
7864 $cgi->a({-href => href(-replay=>1,
7865 hash=>$co{'parent'}, hash_base=>undef)},
7866 esc_html(substr($co{'parent'}, 0, 7))) .
7867 ')';
7868 } else {
7869 # merge commit
7870 if ($hash_parent eq '--cc') {
7871 $formats_nav .= ' | ' .
7872 $cgi->a({-href => href(-replay=>1,
7873 hash=>$hash, hash_parent=>'-c')},
7874 'combined');
7875 } else { # $hash_parent eq '-c'
7876 $formats_nav .= ' | ' .
7877 $cgi->a({-href => href(-replay=>1,
7878 hash=>$hash, hash_parent=>'--cc')},
7879 'compact');
7881 $formats_nav .=
7882 ' (merge: ' .
7883 join(' ', map {
7884 $cgi->a({-href => href(-replay=>1,
7885 hash=>$_, hash_base=>undef)},
7886 esc_html(substr($_, 0, 7)));
7887 } @{$co{'parents'}} ) .
7888 ')';
7892 my $hash_parent_param = $hash_parent;
7893 if (!defined $hash_parent_param) {
7894 # --cc for multiple parents, --root for parentless
7895 $hash_parent_param =
7896 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7899 # read commitdiff
7900 my $fd;
7901 my @difftree;
7902 if ($format eq 'html') {
7903 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7904 "--no-commit-id", "--patch-with-raw", "--full-index",
7905 $hash_parent_param, $hash, "--"
7906 or die_error(500, "Open git-diff-tree failed");
7908 while (my $line = <$fd>) {
7909 chomp $line;
7910 # empty line ends raw part of diff-tree output
7911 last unless $line;
7912 push @difftree, scalar parse_difftree_raw_line($line);
7915 } elsif ($format eq 'plain') {
7916 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7917 '-p', $hash_parent_param, $hash, "--"
7918 or die_error(500, "Open git-diff-tree failed");
7919 } elsif ($format eq 'patch') {
7920 # For commit ranges, we limit the output to the number of
7921 # patches specified in the 'patches' feature.
7922 # For single commits, we limit the output to a single patch,
7923 # diverging from the git-format-patch default.
7924 my @commit_spec = ();
7925 if ($hash_parent) {
7926 if ($patch_max > 0) {
7927 push @commit_spec, "-$patch_max";
7929 push @commit_spec, '-n', "$hash_parent..$hash";
7930 } else {
7931 if ($params{-single}) {
7932 push @commit_spec, '-1';
7933 } else {
7934 if ($patch_max > 0) {
7935 push @commit_spec, "-$patch_max";
7937 push @commit_spec, "-n";
7939 push @commit_spec, '--root', $hash;
7941 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7942 '--encoding=utf8', '--stdout', @commit_spec
7943 or die_error(500, "Open git-format-patch failed");
7944 } else {
7945 die_error(400, "Unknown commitdiff format");
7948 # non-textual hash id's can be cached
7949 my $expires;
7950 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7951 $expires = "+1d";
7954 # write commit message
7955 if ($format eq 'html') {
7956 my $refs = git_get_references();
7957 my $ref = format_ref_marker($refs, $co{'id'});
7959 git_header_html(undef, $expires);
7960 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7961 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7962 print "<div class=\"title_text\">\n" .
7963 "<table class=\"object_header\">\n";
7964 git_print_authorship_rows(\%co);
7965 print "</table>".
7966 "</div>\n";
7967 print "<div class=\"page_body\">\n";
7968 if (@{$co{'comment'}} > 1) {
7969 print "<div class=\"log\">\n";
7970 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7971 print "</div>\n"; # class="log"
7974 } elsif ($format eq 'plain') {
7975 my $refs = git_get_references("tags");
7976 my $tagname = git_get_rev_name_tags($hash);
7977 my $filename = basename($project) . "-$hash.patch";
7979 print $cgi->header(
7980 -type => 'text/plain',
7981 -charset => 'utf-8',
7982 -expires => $expires,
7983 -content_disposition => 'inline; filename="' . "$filename" . '"');
7984 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7985 print "From: " . to_utf8($co{'author'}) . "\n";
7986 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7987 print "Subject: " . to_utf8($co{'title'}) . "\n";
7989 print "X-Git-Tag: $tagname\n" if $tagname;
7990 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7992 foreach my $line (@{$co{'comment'}}) {
7993 print to_utf8($line) . "\n";
7995 print "---\n\n";
7996 } elsif ($format eq 'patch') {
7997 my $filename = basename($project) . "-$hash.patch";
7999 print $cgi->header(
8000 -type => 'text/plain',
8001 -charset => 'utf-8',
8002 -expires => $expires,
8003 -content_disposition => 'inline; filename="' . "$filename" . '"');
8006 # write patch
8007 if ($format eq 'html') {
8008 my $use_parents = !defined $hash_parent ||
8009 $hash_parent eq '-c' || $hash_parent eq '--cc';
8010 git_difftree_body(\@difftree, $hash,
8011 $use_parents ? @{$co{'parents'}} : $hash_parent);
8012 print "<br/>\n";
8014 git_patchset_body($fd, $diff_style,
8015 \@difftree, $hash,
8016 $use_parents ? @{$co{'parents'}} : $hash_parent);
8017 close $fd;
8018 print "</div>\n"; # class="page_body"
8019 git_footer_html();
8021 } elsif ($format eq 'plain') {
8022 local $/ = undef;
8023 print <$fd>;
8024 close $fd
8025 or print "Reading git-diff-tree failed\n";
8026 } elsif ($format eq 'patch') {
8027 local $/ = undef;
8028 print <$fd>;
8029 close $fd
8030 or print "Reading git-format-patch failed\n";
8034 sub git_commitdiff_plain {
8035 git_commitdiff(-format => 'plain');
8038 # format-patch-style patches
8039 sub git_patch {
8040 git_commitdiff(-format => 'patch', -single => 1);
8043 sub git_patches {
8044 git_commitdiff(-format => 'patch');
8047 sub git_history {
8048 git_log_generic('history', \&git_history_body,
8049 $hash_base, $hash_parent_base,
8050 $file_name, $hash);
8053 sub git_search {
8054 $searchtype ||= 'commit';
8056 # check if appropriate features are enabled
8057 gitweb_check_feature('search')
8058 or die_error(403, "Search is disabled");
8059 if ($searchtype eq 'pickaxe') {
8060 # pickaxe may take all resources of your box and run for several minutes
8061 # with every query - so decide by yourself how public you make this feature
8062 gitweb_check_feature('pickaxe')
8063 or die_error(403, "Pickaxe search is disabled");
8065 if ($searchtype eq 'grep') {
8066 # grep search might be potentially CPU-intensive, too
8067 gitweb_check_feature('grep')
8068 or die_error(403, "Grep search is disabled");
8071 if (!defined $searchtext) {
8072 die_error(400, "Text field is empty");
8074 if (!defined $hash) {
8075 $hash = git_get_head_hash($project);
8077 my %co = parse_commit($hash);
8078 if (!%co) {
8079 die_error(404, "Unknown commit object");
8081 if (!defined $page) {
8082 $page = 0;
8085 if ($searchtype eq 'commit' ||
8086 $searchtype eq 'author' ||
8087 $searchtype eq 'committer') {
8088 git_search_message(%co);
8089 } elsif ($searchtype eq 'pickaxe') {
8090 git_search_changes(%co);
8091 } elsif ($searchtype eq 'grep') {
8092 git_search_files(%co);
8093 } else {
8094 die_error(400, "Unknown search type");
8098 sub git_search_help {
8099 git_header_html();
8100 git_print_page_nav('','', $hash,$hash,$hash);
8101 print <<EOT;
8102 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8103 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8104 the pattern entered is recognized as the POSIX extended
8105 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8106 insensitive).</p>
8107 <dl>
8108 <dt><b>commit</b></dt>
8109 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8111 my $have_grep = gitweb_check_feature('grep');
8112 if ($have_grep) {
8113 print <<EOT;
8114 <dt><b>grep</b></dt>
8115 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8116 a different one) are searched for the given pattern. On large trees, this search can take
8117 a while and put some strain on the server, so please use it with some consideration. Note that
8118 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8119 case-sensitive.</dd>
8122 print <<EOT;
8123 <dt><b>author</b></dt>
8124 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8125 <dt><b>committer</b></dt>
8126 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8128 my $have_pickaxe = gitweb_check_feature('pickaxe');
8129 if ($have_pickaxe) {
8130 print <<EOT;
8131 <dt><b>pickaxe</b></dt>
8132 <dd>All commits that caused the string to appear or disappear from any file (changes that
8133 added, removed or "modified" the string) will be listed. This search can take a while and
8134 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8135 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8138 print "</dl>\n";
8139 git_footer_html();
8142 sub git_shortlog {
8143 git_log_generic('shortlog', \&git_shortlog_body,
8144 $hash, $hash_parent);
8147 ## ......................................................................
8148 ## feeds (RSS, Atom; OPML)
8150 sub git_feed {
8151 my $format = shift || 'atom';
8152 my $have_blame = gitweb_check_feature('blame');
8154 # Atom: http://www.atomenabled.org/developers/syndication/
8155 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8156 if ($format ne 'rss' && $format ne 'atom') {
8157 die_error(400, "Unknown web feed format");
8160 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8161 my $head = $hash || 'HEAD';
8162 my @commitlist = parse_commits($head, 150, 0, $file_name);
8164 my %latest_commit;
8165 my %latest_date;
8166 my $content_type = "application/$format+xml";
8167 if (defined $cgi->http('HTTP_ACCEPT') &&
8168 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8169 # browser (feed reader) prefers text/xml
8170 $content_type = 'text/xml';
8172 if (defined($commitlist[0])) {
8173 %latest_commit = %{$commitlist[0]};
8174 my $latest_epoch = $latest_commit{'committer_epoch'};
8175 exit_if_unmodified_since($latest_epoch);
8176 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8178 print $cgi->header(
8179 -type => $content_type,
8180 -charset => 'utf-8',
8181 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8182 -status => '200 OK');
8184 # Optimization: skip generating the body if client asks only
8185 # for Last-Modified date.
8186 return if ($cgi->request_method() eq 'HEAD');
8188 # header variables
8189 my $title = "$site_name - $project/$action";
8190 my $feed_type = 'log';
8191 if (defined $hash) {
8192 $title .= " - '$hash'";
8193 $feed_type = 'branch log';
8194 if (defined $file_name) {
8195 $title .= " :: $file_name";
8196 $feed_type = 'history';
8198 } elsif (defined $file_name) {
8199 $title .= " - $file_name";
8200 $feed_type = 'history';
8202 $title .= " $feed_type";
8203 $title = esc_html($title);
8204 my $descr = git_get_project_description($project);
8205 if (defined $descr) {
8206 $descr = esc_html($descr);
8207 } else {
8208 $descr = "$project " .
8209 ($format eq 'rss' ? 'RSS' : 'Atom') .
8210 " feed";
8212 my $owner = git_get_project_owner($project);
8213 $owner = esc_html($owner);
8215 #header
8216 my $alt_url;
8217 if (defined $file_name) {
8218 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8219 } elsif (defined $hash) {
8220 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8221 } else {
8222 $alt_url = href(-full=>1, action=>"summary");
8224 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8225 if ($format eq 'rss') {
8226 print <<XML;
8227 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8228 <channel>
8230 print "<title>$title</title>\n" .
8231 "<link>$alt_url</link>\n" .
8232 "<description>$descr</description>\n" .
8233 "<language>en</language>\n" .
8234 # project owner is responsible for 'editorial' content
8235 "<managingEditor>$owner</managingEditor>\n";
8236 if (defined $logo || defined $favicon) {
8237 # prefer the logo to the favicon, since RSS
8238 # doesn't allow both
8239 my $img = esc_url($logo || $favicon);
8240 print "<image>\n" .
8241 "<url>$img</url>\n" .
8242 "<title>$title</title>\n" .
8243 "<link>$alt_url</link>\n" .
8244 "</image>\n";
8246 if (%latest_date) {
8247 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8248 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8250 print "<generator>gitweb v.$version/$git_version</generator>\n";
8251 } elsif ($format eq 'atom') {
8252 print <<XML;
8253 <feed xmlns="http://www.w3.org/2005/Atom">
8255 print "<title>$title</title>\n" .
8256 "<subtitle>$descr</subtitle>\n" .
8257 '<link rel="alternate" type="text/html" href="' .
8258 $alt_url . '" />' . "\n" .
8259 '<link rel="self" type="' . $content_type . '" href="' .
8260 $cgi->self_url() . '" />' . "\n" .
8261 "<id>" . href(-full=>1) . "</id>\n" .
8262 # use project owner for feed author
8263 "<author><name>$owner</name></author>\n";
8264 if (defined $favicon) {
8265 print "<icon>" . esc_url($favicon) . "</icon>\n";
8267 if (defined $logo) {
8268 # not twice as wide as tall: 72 x 27 pixels
8269 print "<logo>" . esc_url($logo) . "</logo>\n";
8271 if (! %latest_date) {
8272 # dummy date to keep the feed valid until commits trickle in:
8273 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8274 } else {
8275 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8277 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8280 # contents
8281 for (my $i = 0; $i <= $#commitlist; $i++) {
8282 my %co = %{$commitlist[$i]};
8283 my $commit = $co{'id'};
8284 # we read 150, we always show 30 and the ones more recent than 48 hours
8285 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8286 last;
8288 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8290 # get list of changed files
8291 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8292 $co{'parent'} || "--root",
8293 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8294 or next;
8295 my @difftree = map { chomp; $_ } <$fd>;
8296 close $fd
8297 or next;
8299 # print element (entry, item)
8300 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8301 if ($format eq 'rss') {
8302 print "<item>\n" .
8303 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8304 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8305 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8306 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8307 "<link>$co_url</link>\n" .
8308 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8309 "<content:encoded>" .
8310 "<![CDATA[\n";
8311 } elsif ($format eq 'atom') {
8312 print "<entry>\n" .
8313 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8314 "<updated>$cd{'iso-8601'}</updated>\n" .
8315 "<author>\n" .
8316 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8317 if ($co{'author_email'}) {
8318 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8320 print "</author>\n" .
8321 # use committer for contributor
8322 "<contributor>\n" .
8323 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8324 if ($co{'committer_email'}) {
8325 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8327 print "</contributor>\n" .
8328 "<published>$cd{'iso-8601'}</published>\n" .
8329 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8330 "<id>$co_url</id>\n" .
8331 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8332 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8334 my $comment = $co{'comment'};
8335 print "<pre>\n";
8336 foreach my $line (@$comment) {
8337 $line = esc_html($line);
8338 print "$line\n";
8340 print "</pre><ul>\n";
8341 foreach my $difftree_line (@difftree) {
8342 my %difftree = parse_difftree_raw_line($difftree_line);
8343 next if !$difftree{'from_id'};
8345 my $file = $difftree{'file'} || $difftree{'to_file'};
8347 print "<li>" .
8348 "[" .
8349 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8350 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8351 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8352 file_name=>$file, file_parent=>$difftree{'from_file'}),
8353 -title => "diff"}, 'D');
8354 if ($have_blame) {
8355 print $cgi->a({-href => href(-full=>1, action=>"blame",
8356 file_name=>$file, hash_base=>$commit),
8357 -title => "blame"}, 'B');
8359 # if this is not a feed of a file history
8360 if (!defined $file_name || $file_name ne $file) {
8361 print $cgi->a({-href => href(-full=>1, action=>"history",
8362 file_name=>$file, hash=>$commit),
8363 -title => "history"}, 'H');
8365 $file = esc_path($file);
8366 print "] ".
8367 "$file</li>\n";
8369 if ($format eq 'rss') {
8370 print "</ul>]]>\n" .
8371 "</content:encoded>\n" .
8372 "</item>\n";
8373 } elsif ($format eq 'atom') {
8374 print "</ul>\n</div>\n" .
8375 "</content>\n" .
8376 "</entry>\n";
8380 # end of feed
8381 if ($format eq 'rss') {
8382 print "</channel>\n</rss>\n";
8383 } elsif ($format eq 'atom') {
8384 print "</feed>\n";
8388 sub git_rss {
8389 git_feed('rss');
8392 sub git_atom {
8393 git_feed('atom');
8396 sub git_opml {
8397 my @list = git_get_projects_list($project_filter, $strict_export);
8398 if (!@list) {
8399 die_error(404, "No projects found");
8402 print $cgi->header(
8403 -type => 'text/xml',
8404 -charset => 'utf-8',
8405 -content_disposition => 'inline; filename="opml.xml"');
8407 my $title = esc_html($site_name);
8408 my $filter = " within subdirectory ";
8409 if (defined $project_filter) {
8410 $filter .= esc_html($project_filter);
8411 } else {
8412 $filter = "";
8414 print <<XML;
8415 <?xml version="1.0" encoding="utf-8"?>
8416 <opml version="1.0">
8417 <head>
8418 <title>$title OPML Export$filter</title>
8419 </head>
8420 <body>
8421 <outline text="git RSS feeds">
8424 foreach my $pr (@list) {
8425 my %proj = %$pr;
8426 my $head = git_get_head_hash($proj{'path'});
8427 if (!defined $head) {
8428 next;
8430 $git_dir = "$projectroot/$proj{'path'}";
8431 my %co = parse_commit($head);
8432 if (!%co) {
8433 next;
8436 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8437 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8438 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8439 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8441 print <<XML;
8442 </outline>
8443 </body>
8444 </opml>