tgupdate: merge top-bases/t/blame/incremental into t/blame/incremental
[git/gitweb.git] / gitweb / gitweb.perl
blob20f52512c470289cb1b635b74243eb31886eae1e
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 'incremental blame' blob view, which uses javascript to
324 # incrementally show the revisions of lines as they are discovered
325 # in the history. It is better for large histories, files and slow
326 # servers, but requires javascript in the client and can slow down the
327 # browser on large files.
329 # To enable system wide have in $GITWEB_CONFIG
330 # $feature{'blame_incremental'}{'default'} = [1];
331 # To have project specific config enable override in $GITWEB_CONFIG
332 # $feature{'blame_incremental'}{'override'} = 1;
333 # and in project config gitweb.blame_incremental = 0|1;
334 'blame_incremental' => {
335 'sub' => sub { feature_bool('blame_incremental', @_) },
336 'override' => 0,
337 'default' => [0]},
339 # Enable the 'snapshot' link, providing a compressed archive of any
340 # tree. This can potentially generate high traffic if you have large
341 # project.
343 # Value is a list of formats defined in %known_snapshot_formats that
344 # you wish to offer.
345 # To disable system wide have in $GITWEB_CONFIG
346 # $feature{'snapshot'}{'default'} = [];
347 # To have project specific config enable override in $GITWEB_CONFIG
348 # $feature{'snapshot'}{'override'} = 1;
349 # and in project config, a comma-separated list of formats or "none"
350 # to disable. Example: gitweb.snapshot = tbz2,zip;
351 'snapshot' => {
352 'sub' => \&feature_snapshot,
353 'override' => 0,
354 'default' => ['tgz']},
356 # Enable text search, which will list the commits which match author,
357 # committer or commit text to a given string. Enabled by default.
358 # Project specific override is not supported.
360 # Note that this controls all search features, which means that if
361 # it is disabled, then 'grep' and 'pickaxe' search would also be
362 # disabled.
363 'search' => {
364 'override' => 0,
365 'default' => [1]},
367 # Enable grep search, which will list the files in currently selected
368 # tree containing the given string. Enabled by default. This can be
369 # potentially CPU-intensive, of course.
370 # Note that you need to have 'search' feature enabled too.
372 # To enable system wide have in $GITWEB_CONFIG
373 # $feature{'grep'}{'default'} = [1];
374 # To have project specific config enable override in $GITWEB_CONFIG
375 # $feature{'grep'}{'override'} = 1;
376 # and in project config gitweb.grep = 0|1;
377 'grep' => {
378 'sub' => sub { feature_bool('grep', @_) },
379 'override' => 0,
380 'default' => [1]},
382 # Enable the pickaxe search, which will list the commits that modified
383 # a given string in a file. This can be practical and quite faster
384 # alternative to 'blame', but still potentially CPU-intensive.
385 # Note that you need to have 'search' feature enabled too.
387 # To enable system wide have in $GITWEB_CONFIG
388 # $feature{'pickaxe'}{'default'} = [1];
389 # To have project specific config enable override in $GITWEB_CONFIG
390 # $feature{'pickaxe'}{'override'} = 1;
391 # and in project config gitweb.pickaxe = 0|1;
392 'pickaxe' => {
393 'sub' => sub { feature_bool('pickaxe', @_) },
394 'override' => 0,
395 'default' => [1]},
397 # Enable showing size of blobs in a 'tree' view, in a separate
398 # column, similar to what 'ls -l' does. This cost a bit of IO.
400 # To disable system wide have in $GITWEB_CONFIG
401 # $feature{'show-sizes'}{'default'} = [0];
402 # To have project specific config enable override in $GITWEB_CONFIG
403 # $feature{'show-sizes'}{'override'} = 1;
404 # and in project config gitweb.showsizes = 0|1;
405 'show-sizes' => {
406 'sub' => sub { feature_bool('showsizes', @_) },
407 'override' => 0,
408 'default' => [1]},
410 # Make gitweb use an alternative format of the URLs which can be
411 # more readable and natural-looking: project name is embedded
412 # directly in the path and the query string contains other
413 # auxiliary information. All gitweb installations recognize
414 # URL in either format; this configures in which formats gitweb
415 # generates links.
417 # To enable system wide have in $GITWEB_CONFIG
418 # $feature{'pathinfo'}{'default'} = [1];
419 # Project specific override is not supported.
421 # Note that you will need to change the default location of CSS,
422 # favicon, logo and possibly other files to an absolute URL. Also,
423 # if gitweb.cgi serves as your indexfile, you will need to force
424 # $my_uri to contain the script name in your $GITWEB_CONFIG.
425 'pathinfo' => {
426 'override' => 0,
427 'default' => [0]},
429 # Make gitweb consider projects in project root subdirectories
430 # to be forks of existing projects. Given project $projname.git,
431 # projects matching $projname/*.git will not be shown in the main
432 # projects list, instead a '+' mark will be added to $projname
433 # there and a 'forks' view will be enabled for the project, listing
434 # all the forks. If project list is taken from a file, forks have
435 # to be listed after the main project.
437 # To enable system wide have in $GITWEB_CONFIG
438 # $feature{'forks'}{'default'} = [1];
439 # Project specific override is not supported.
440 'forks' => {
441 'override' => 0,
442 'default' => [0]},
444 # Insert custom links to the action bar of all project pages.
445 # This enables you mainly to link to third-party scripts integrating
446 # into gitweb; e.g. git-browser for graphical history representation
447 # or custom web-based repository administration interface.
449 # The 'default' value consists of a list of triplets in the form
450 # (label, link, position) where position is the label after which
451 # to insert the link and link is a format string where %n expands
452 # to the project name, %f to the project path within the filesystem,
453 # %h to the current hash (h gitweb parameter) and %b to the current
454 # hash base (hb gitweb parameter); %% expands to %.
456 # To enable system wide have in $GITWEB_CONFIG e.g.
457 # $feature{'actions'}{'default'} = [('graphiclog',
458 # '/git-browser/by-commit.html?r=%n', 'summary')];
459 # Project specific override is not supported.
460 'actions' => {
461 'override' => 0,
462 'default' => []},
464 # Allow gitweb scan project content tags of project repository,
465 # and display the popular Web 2.0-ish "tag cloud" near the projects
466 # list. Note that this is something COMPLETELY different from the
467 # normal Git tags.
469 # gitweb by itself can show existing tags, but it does not handle
470 # tagging itself; you need to do it externally, outside gitweb.
471 # The format is described in git_get_project_ctags() subroutine.
472 # You may want to install the HTML::TagCloud Perl module to get
473 # a pretty tag cloud instead of just a list of tags.
475 # To enable system wide have in $GITWEB_CONFIG
476 # $feature{'ctags'}{'default'} = [1];
477 # Project specific override is not supported.
479 # In the future whether ctags editing is enabled might depend
480 # on the value, but using 1 should always mean no editing of ctags.
481 'ctags' => {
482 'override' => 0,
483 'default' => [0]},
485 # The maximum number of patches in a patchset generated in patch
486 # view. Set this to 0 or undef to disable patch view, or to a
487 # negative number to remove any limit.
489 # To disable system wide have in $GITWEB_CONFIG
490 # $feature{'patches'}{'default'} = [0];
491 # To have project specific config enable override in $GITWEB_CONFIG
492 # $feature{'patches'}{'override'} = 1;
493 # and in project config gitweb.patches = 0|n;
494 # where n is the maximum number of patches allowed in a patchset.
495 'patches' => {
496 'sub' => \&feature_patches,
497 'override' => 0,
498 'default' => [16]},
500 # Avatar support. When this feature is enabled, views such as
501 # shortlog or commit will display an avatar associated with
502 # the email of the committer(s) and/or author(s).
504 # Currently available providers are gravatar and picon.
505 # If an unknown provider is specified, the feature is disabled.
507 # Gravatar depends on Digest::MD5.
508 # Picon currently relies on the indiana.edu database.
510 # To enable system wide have in $GITWEB_CONFIG
511 # $feature{'avatar'}{'default'} = ['<provider>'];
512 # where <provider> is either gravatar or picon.
513 # To have project specific config enable override in $GITWEB_CONFIG
514 # $feature{'avatar'}{'override'} = 1;
515 # and in project config gitweb.avatar = <provider>;
516 'avatar' => {
517 'sub' => \&feature_avatar,
518 'override' => 0,
519 'default' => ['']},
521 # Enable displaying how much time and how many git commands
522 # it took to generate and display page. Disabled by default.
523 # Project specific override is not supported.
524 'timed' => {
525 'override' => 0,
526 'default' => [0]},
528 # Enable turning some links into links to actions which require
529 # JavaScript to run (like 'blame_incremental'). Not enabled by
530 # default. Project specific override is currently not supported.
531 'javascript-actions' => {
532 'override' => 0,
533 'default' => [0]},
535 # Enable and configure ability to change common timezone for dates
536 # in gitweb output via JavaScript. Enabled by default.
537 # Project specific override is not supported.
538 'javascript-timezone' => {
539 'override' => 0,
540 'default' => [
541 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
542 # or undef to turn off this feature
543 'gitweb_tz', # name of cookie where to store selected timezone
544 'datetime', # CSS class used to mark up dates for manipulation
547 # Syntax highlighting support. This is based on Daniel Svensson's
548 # and Sham Chukoury's work in gitweb-xmms2.git.
549 # It requires the 'highlight' program present in $PATH,
550 # and therefore is disabled by default.
552 # To enable system wide have in $GITWEB_CONFIG
553 # $feature{'highlight'}{'default'} = [1];
555 'highlight' => {
556 'sub' => sub { feature_bool('highlight', @_) },
557 'override' => 0,
558 'default' => [0]},
560 # Enable displaying of remote heads in the heads list
562 # To enable system wide have in $GITWEB_CONFIG
563 # $feature{'remote_heads'}{'default'} = [1];
564 # To have project specific config enable override in $GITWEB_CONFIG
565 # $feature{'remote_heads'}{'override'} = 1;
566 # and in project config gitweb.remoteheads = 0|1;
567 'remote_heads' => {
568 'sub' => sub { feature_bool('remote_heads', @_) },
569 'override' => 0,
570 'default' => [0]},
572 # Enable showing branches under other refs in addition to heads
574 # To set system wide extra branch refs have in $GITWEB_CONFIG
575 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
576 # To have project specific config enable override in $GITWEB_CONFIG
577 # $feature{'extra-branch-refs'}{'override'} = 1;
578 # and in project config gitweb.extrabranchrefs = dirs of choice
579 # Every directory is separated with whitespace.
581 'extra-branch-refs' => {
582 'sub' => \&feature_extra_branch_refs,
583 'override' => 0,
584 'default' => []},
587 sub gitweb_get_feature {
588 my ($name) = @_;
589 return unless exists $feature{$name};
590 my ($sub, $override, @defaults) = (
591 $feature{$name}{'sub'},
592 $feature{$name}{'override'},
593 @{$feature{$name}{'default'}});
594 # project specific override is possible only if we have project
595 our $git_dir; # global variable, declared later
596 if (!$override || !defined $git_dir) {
597 return @defaults;
599 if (!defined $sub) {
600 warn "feature $name is not overridable";
601 return @defaults;
603 return $sub->(@defaults);
606 # A wrapper to check if a given feature is enabled.
607 # With this, you can say
609 # my $bool_feat = gitweb_check_feature('bool_feat');
610 # gitweb_check_feature('bool_feat') or somecode;
612 # instead of
614 # my ($bool_feat) = gitweb_get_feature('bool_feat');
615 # (gitweb_get_feature('bool_feat'))[0] or somecode;
617 sub gitweb_check_feature {
618 return (gitweb_get_feature(@_))[0];
622 sub feature_bool {
623 my $key = shift;
624 my ($val) = git_get_project_config($key, '--bool');
626 if (!defined $val) {
627 return ($_[0]);
628 } elsif ($val eq 'true') {
629 return (1);
630 } elsif ($val eq 'false') {
631 return (0);
635 sub feature_snapshot {
636 my (@fmts) = @_;
638 my ($val) = git_get_project_config('snapshot');
640 if ($val) {
641 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
644 return @fmts;
647 sub feature_patches {
648 my @val = (git_get_project_config('patches', '--int'));
650 if (@val) {
651 return @val;
654 return ($_[0]);
657 sub feature_avatar {
658 my @val = (git_get_project_config('avatar'));
660 return @val ? @val : @_;
663 sub feature_extra_branch_refs {
664 my (@branch_refs) = @_;
665 my $values = git_get_project_config('extrabranchrefs');
667 if ($values) {
668 $values = config_to_multi ($values);
669 @branch_refs = ();
670 foreach my $value (@{$values}) {
671 push @branch_refs, split /\s+/, $value;
675 return @branch_refs;
678 # checking HEAD file with -e is fragile if the repository was
679 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
680 # and then pruned.
681 sub check_head_link {
682 my ($dir) = @_;
683 my $headfile = "$dir/HEAD";
684 return ((-e $headfile) ||
685 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
688 sub check_export_ok {
689 my ($dir) = @_;
690 return (check_head_link($dir) &&
691 (!$export_ok || -e "$dir/$export_ok") &&
692 (!$export_auth_hook || $export_auth_hook->($dir)));
695 # process alternate names for backward compatibility
696 # filter out unsupported (unknown) snapshot formats
697 sub filter_snapshot_fmts {
698 my @fmts = @_;
700 @fmts = map {
701 exists $known_snapshot_format_aliases{$_} ?
702 $known_snapshot_format_aliases{$_} : $_} @fmts;
703 @fmts = grep {
704 exists $known_snapshot_formats{$_} &&
705 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
708 sub filter_and_validate_refs {
709 my @refs = @_;
710 my %unique_refs = ();
712 foreach my $ref (@refs) {
713 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
714 # 'heads' are added implicitly in get_branch_refs().
715 $unique_refs{$ref} = 1 if ($ref ne 'heads');
717 return sort keys %unique_refs;
720 # If it is set to code reference, it is code that it is to be run once per
721 # request, allowing updating configurations that change with each request,
722 # while running other code in config file only once.
724 # Otherwise, if it is false then gitweb would process config file only once;
725 # if it is true then gitweb config would be run for each request.
726 our $per_request_config = 1;
728 # read and parse gitweb config file given by its parameter.
729 # returns true on success, false on recoverable error, allowing
730 # to chain this subroutine, using first file that exists.
731 # dies on errors during parsing config file, as it is unrecoverable.
732 sub read_config_file {
733 my $filename = shift;
734 return unless defined $filename;
735 # die if there are errors parsing config file
736 if (-e $filename) {
737 do $filename;
738 die $@ if $@;
739 return 1;
741 return;
744 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
745 sub evaluate_gitweb_config {
746 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
747 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
748 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
750 # Protect against duplications of file names, to not read config twice.
751 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
752 # there possibility of duplication of filename there doesn't matter.
753 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
754 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
756 # Common system-wide settings for convenience.
757 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
758 read_config_file($GITWEB_CONFIG_COMMON);
760 # Use first config file that exists. This means use the per-instance
761 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
762 read_config_file($GITWEB_CONFIG) and return;
763 read_config_file($GITWEB_CONFIG_SYSTEM);
766 # Get loadavg of system, to compare against $maxload.
767 # Currently it requires '/proc/loadavg' present to get loadavg;
768 # if it is not present it returns 0, which means no load checking.
769 sub get_loadavg {
770 if( -e '/proc/loadavg' ){
771 open my $fd, '<', '/proc/loadavg'
772 or return 0;
773 my @load = split(/\s+/, scalar <$fd>);
774 close $fd;
776 # The first three columns measure CPU and IO utilization of the last one,
777 # five, and 10 minute periods. The fourth column shows the number of
778 # currently running processes and the total number of processes in the m/n
779 # format. The last column displays the last process ID used.
780 return $load[0] || 0;
782 # additional checks for load average should go here for things that don't export
783 # /proc/loadavg
785 return 0;
788 # version of the core git binary
789 our $git_version;
790 sub evaluate_git_version {
791 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
792 $number_of_git_cmds++;
795 sub check_loadavg {
796 if (defined $maxload && get_loadavg() > $maxload) {
797 die_error(503, "The load average on the server is too high");
801 # ======================================================================
802 # input validation and dispatch
804 # input parameters can be collected from a variety of sources (presently, CGI
805 # and PATH_INFO), so we define an %input_params hash that collects them all
806 # together during validation: this allows subsequent uses (e.g. href()) to be
807 # agnostic of the parameter origin
809 our %input_params = ();
811 # input parameters are stored with the long parameter name as key. This will
812 # also be used in the href subroutine to convert parameters to their CGI
813 # equivalent, and since the href() usage is the most frequent one, we store
814 # the name -> CGI key mapping here, instead of the reverse.
816 # XXX: Warning: If you touch this, check the search form for updating,
817 # too.
819 our @cgi_param_mapping = (
820 project => "p",
821 action => "a",
822 file_name => "f",
823 file_parent => "fp",
824 hash => "h",
825 hash_parent => "hp",
826 hash_base => "hb",
827 hash_parent_base => "hpb",
828 page => "pg",
829 order => "o",
830 searchtext => "s",
831 searchtype => "st",
832 snapshot_format => "sf",
833 extra_options => "opt",
834 search_use_regexp => "sr",
835 ctag => "by_tag",
836 diff_style => "ds",
837 project_filter => "pf",
838 # this must be last entry (for manipulation from JavaScript)
839 javascript => "js"
841 our %cgi_param_mapping = @cgi_param_mapping;
843 # we will also need to know the possible actions, for validation
844 our %actions = (
845 "blame" => \&git_blame,
846 "blame_incremental" => \&git_blame_incremental,
847 "blame_data" => \&git_blame_data,
848 "blobdiff" => \&git_blobdiff,
849 "blobdiff_plain" => \&git_blobdiff_plain,
850 "blob" => \&git_blob,
851 "blob_plain" => \&git_blob_plain,
852 "commitdiff" => \&git_commitdiff,
853 "commitdiff_plain" => \&git_commitdiff_plain,
854 "commit" => \&git_commit,
855 "forks" => \&git_forks,
856 "heads" => \&git_heads,
857 "history" => \&git_history,
858 "log" => \&git_log,
859 "patch" => \&git_patch,
860 "patches" => \&git_patches,
861 "remotes" => \&git_remotes,
862 "rss" => \&git_rss,
863 "atom" => \&git_atom,
864 "search" => \&git_search,
865 "search_help" => \&git_search_help,
866 "shortlog" => \&git_shortlog,
867 "summary" => \&git_summary,
868 "tag" => \&git_tag,
869 "tags" => \&git_tags,
870 "tree" => \&git_tree,
871 "snapshot" => \&git_snapshot,
872 "object" => \&git_object,
873 # those below don't need $project
874 "opml" => \&git_opml,
875 "project_list" => \&git_project_list,
876 "project_index" => \&git_project_index,
879 # finally, we have the hash of allowed extra_options for the commands that
880 # allow them
881 our %allowed_options = (
882 "--no-merges" => [ qw(rss atom log shortlog history) ],
885 # fill %input_params with the CGI parameters. All values except for 'opt'
886 # should be single values, but opt can be an array. We should probably
887 # build an array of parameters that can be multi-valued, but since for the time
888 # being it's only this one, we just single it out
889 sub evaluate_query_params {
890 our $cgi;
892 while (my ($name, $symbol) = each %cgi_param_mapping) {
893 if ($symbol eq 'opt') {
894 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
895 } else {
896 $input_params{$name} = decode_utf8($cgi->param($symbol));
901 # now read PATH_INFO and update the parameter list for missing parameters
902 sub evaluate_path_info {
903 return if defined $input_params{'project'};
904 return if !$path_info;
905 $path_info =~ s,^/+,,;
906 return if !$path_info;
908 # find which part of PATH_INFO is project
909 my $project = $path_info;
910 $project =~ s,/+$,,;
911 while ($project && !check_head_link("$projectroot/$project")) {
912 $project =~ s,/*[^/]*$,,;
914 return unless $project;
915 $input_params{'project'} = $project;
917 # do not change any parameters if an action is given using the query string
918 return if $input_params{'action'};
919 $path_info =~ s,^\Q$project\E/*,,;
921 # next, check if we have an action
922 my $action = $path_info;
923 $action =~ s,/.*$,,;
924 if (exists $actions{$action}) {
925 $path_info =~ s,^$action/*,,;
926 $input_params{'action'} = $action;
929 # list of actions that want hash_base instead of hash, but can have no
930 # pathname (f) parameter
931 my @wants_base = (
932 'tree',
933 'history',
936 # we want to catch, among others
937 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
938 my ($parentrefname, $parentpathname, $refname, $pathname) =
939 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
941 # first, analyze the 'current' part
942 if (defined $pathname) {
943 # we got "branch:filename" or "branch:dir/"
944 # we could use git_get_type(branch:pathname), but:
945 # - it needs $git_dir
946 # - it does a git() call
947 # - the convention of terminating directories with a slash
948 # makes it superfluous
949 # - embedding the action in the PATH_INFO would make it even
950 # more superfluous
951 $pathname =~ s,^/+,,;
952 if (!$pathname || substr($pathname, -1) eq "/") {
953 $input_params{'action'} ||= "tree";
954 $pathname =~ s,/$,,;
955 } else {
956 # the default action depends on whether we had parent info
957 # or not
958 if ($parentrefname) {
959 $input_params{'action'} ||= "blobdiff_plain";
960 } else {
961 $input_params{'action'} ||= "blob_plain";
964 $input_params{'hash_base'} ||= $refname;
965 $input_params{'file_name'} ||= $pathname;
966 } elsif (defined $refname) {
967 # we got "branch". In this case we have to choose if we have to
968 # set hash or hash_base.
970 # Most of the actions without a pathname only want hash to be
971 # set, except for the ones specified in @wants_base that want
972 # hash_base instead. It should also be noted that hand-crafted
973 # links having 'history' as an action and no pathname or hash
974 # set will fail, but that happens regardless of PATH_INFO.
975 if (defined $parentrefname) {
976 # if there is parent let the default be 'shortlog' action
977 # (for http://git.example.com/repo.git/A..B links); if there
978 # is no parent, dispatch will detect type of object and set
979 # action appropriately if required (if action is not set)
980 $input_params{'action'} ||= "shortlog";
982 if ($input_params{'action'} &&
983 grep { $_ eq $input_params{'action'} } @wants_base) {
984 $input_params{'hash_base'} ||= $refname;
985 } else {
986 $input_params{'hash'} ||= $refname;
990 # next, handle the 'parent' part, if present
991 if (defined $parentrefname) {
992 # a missing pathspec defaults to the 'current' filename, allowing e.g.
993 # someproject/blobdiff/oldrev..newrev:/filename
994 if ($parentpathname) {
995 $parentpathname =~ s,^/+,,;
996 $parentpathname =~ s,/$,,;
997 $input_params{'file_parent'} ||= $parentpathname;
998 } else {
999 $input_params{'file_parent'} ||= $input_params{'file_name'};
1001 # we assume that hash_parent_base is wanted if a path was specified,
1002 # or if the action wants hash_base instead of hash
1003 if (defined $input_params{'file_parent'} ||
1004 grep { $_ eq $input_params{'action'} } @wants_base) {
1005 $input_params{'hash_parent_base'} ||= $parentrefname;
1006 } else {
1007 $input_params{'hash_parent'} ||= $parentrefname;
1011 # for the snapshot action, we allow URLs in the form
1012 # $project/snapshot/$hash.ext
1013 # where .ext determines the snapshot and gets removed from the
1014 # passed $refname to provide the $hash.
1016 # To be able to tell that $refname includes the format extension, we
1017 # require the following two conditions to be satisfied:
1018 # - the hash input parameter MUST have been set from the $refname part
1019 # of the URL (i.e. they must be equal)
1020 # - the snapshot format MUST NOT have been defined already (e.g. from
1021 # CGI parameter sf)
1022 # It's also useless to try any matching unless $refname has a dot,
1023 # so we check for that too
1024 if (defined $input_params{'action'} &&
1025 $input_params{'action'} eq 'snapshot' &&
1026 defined $refname && index($refname, '.') != -1 &&
1027 $refname eq $input_params{'hash'} &&
1028 !defined $input_params{'snapshot_format'}) {
1029 # We loop over the known snapshot formats, checking for
1030 # extensions. Allowed extensions are both the defined suffix
1031 # (which includes the initial dot already) and the snapshot
1032 # format key itself, with a prepended dot
1033 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1034 my $hash = $refname;
1035 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1036 next;
1038 my $sfx = $1;
1039 # a valid suffix was found, so set the snapshot format
1040 # and reset the hash parameter
1041 $input_params{'snapshot_format'} = $fmt;
1042 $input_params{'hash'} = $hash;
1043 # we also set the format suffix to the one requested
1044 # in the URL: this way a request for e.g. .tgz returns
1045 # a .tgz instead of a .tar.gz
1046 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1047 last;
1052 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1053 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1054 $searchtext, $search_regexp, $project_filter);
1055 sub evaluate_and_validate_params {
1056 our $action = $input_params{'action'};
1057 if (defined $action) {
1058 if (!is_valid_action($action)) {
1059 die_error(400, "Invalid action parameter");
1063 # parameters which are pathnames
1064 our $project = $input_params{'project'};
1065 if (defined $project) {
1066 if (!is_valid_project($project)) {
1067 undef $project;
1068 die_error(404, "No such project");
1072 our $project_filter = $input_params{'project_filter'};
1073 if (defined $project_filter) {
1074 if (!is_valid_pathname($project_filter)) {
1075 die_error(404, "Invalid project_filter parameter");
1079 our $file_name = $input_params{'file_name'};
1080 if (defined $file_name) {
1081 if (!is_valid_pathname($file_name)) {
1082 die_error(400, "Invalid file parameter");
1086 our $file_parent = $input_params{'file_parent'};
1087 if (defined $file_parent) {
1088 if (!is_valid_pathname($file_parent)) {
1089 die_error(400, "Invalid file parent parameter");
1093 # parameters which are refnames
1094 our $hash = $input_params{'hash'};
1095 if (defined $hash) {
1096 if (!is_valid_refname($hash)) {
1097 die_error(400, "Invalid hash parameter");
1101 our $hash_parent = $input_params{'hash_parent'};
1102 if (defined $hash_parent) {
1103 if (!is_valid_refname($hash_parent)) {
1104 die_error(400, "Invalid hash parent parameter");
1108 our $hash_base = $input_params{'hash_base'};
1109 if (defined $hash_base) {
1110 if (!is_valid_refname($hash_base)) {
1111 die_error(400, "Invalid hash base parameter");
1115 our @extra_options = @{$input_params{'extra_options'}};
1116 # @extra_options is always defined, since it can only be (currently) set from
1117 # CGI, and $cgi->param() returns the empty array in array context if the param
1118 # is not set
1119 foreach my $opt (@extra_options) {
1120 if (not exists $allowed_options{$opt}) {
1121 die_error(400, "Invalid option parameter");
1123 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1124 die_error(400, "Invalid option parameter for this action");
1128 our $hash_parent_base = $input_params{'hash_parent_base'};
1129 if (defined $hash_parent_base) {
1130 if (!is_valid_refname($hash_parent_base)) {
1131 die_error(400, "Invalid hash parent base parameter");
1135 # other parameters
1136 our $page = $input_params{'page'};
1137 if (defined $page) {
1138 if ($page =~ m/[^0-9]/) {
1139 die_error(400, "Invalid page parameter");
1143 our $searchtype = $input_params{'searchtype'};
1144 if (defined $searchtype) {
1145 if ($searchtype =~ m/[^a-z]/) {
1146 die_error(400, "Invalid searchtype parameter");
1150 our $search_use_regexp = $input_params{'search_use_regexp'};
1152 our $searchtext = $input_params{'searchtext'};
1153 our $search_regexp = undef;
1154 if (defined $searchtext) {
1155 if (length($searchtext) < 2) {
1156 die_error(403, "At least two characters are required for search parameter");
1158 if ($search_use_regexp) {
1159 $search_regexp = $searchtext;
1160 if (!eval { qr/$search_regexp/; 1; }) {
1161 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1162 die_error(400, "Invalid search regexp '$search_regexp'",
1163 esc_html($error));
1165 } else {
1166 $search_regexp = quotemeta $searchtext;
1171 # path to the current git repository
1172 our $git_dir;
1173 sub evaluate_git_dir {
1174 our $git_dir = "$projectroot/$project" if $project;
1177 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1178 sub configure_gitweb_features {
1179 # list of supported snapshot formats
1180 our @snapshot_fmts = gitweb_get_feature('snapshot');
1181 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1183 # check that the avatar feature is set to a known provider name,
1184 # and for each provider check if the dependencies are satisfied.
1185 # if the provider name is invalid or the dependencies are not met,
1186 # reset $git_avatar to the empty string.
1187 our ($git_avatar) = gitweb_get_feature('avatar');
1188 if ($git_avatar eq 'gravatar') {
1189 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1190 } elsif ($git_avatar eq 'picon') {
1191 # no dependencies
1192 } else {
1193 $git_avatar = '';
1196 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1197 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1200 sub get_branch_refs {
1201 return ('heads', @extra_branch_refs);
1204 # custom error handler: 'die <message>' is Internal Server Error
1205 sub handle_errors_html {
1206 my $msg = shift; # it is already HTML escaped
1208 # to avoid infinite loop where error occurs in die_error,
1209 # change handler to default handler, disabling handle_errors_html
1210 set_message("Error occurred when inside die_error:\n$msg");
1212 # you cannot jump out of die_error when called as error handler;
1213 # the subroutine set via CGI::Carp::set_message is called _after_
1214 # HTTP headers are already written, so it cannot write them itself
1215 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1217 set_message(\&handle_errors_html);
1219 # dispatch
1220 sub dispatch {
1221 if (!defined $action) {
1222 if (defined $hash) {
1223 $action = git_get_type($hash);
1224 $action or die_error(404, "Object does not exist");
1225 } elsif (defined $hash_base && defined $file_name) {
1226 $action = git_get_type("$hash_base:$file_name");
1227 $action or die_error(404, "File or directory does not exist");
1228 } elsif (defined $project) {
1229 $action = 'summary';
1230 } else {
1231 $action = 'project_list';
1234 if (!defined($actions{$action})) {
1235 die_error(400, "Unknown action");
1237 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1238 !$project) {
1239 die_error(400, "Project needed");
1241 $actions{$action}->();
1244 sub reset_timer {
1245 our $t0 = [ gettimeofday() ]
1246 if defined $t0;
1247 our $number_of_git_cmds = 0;
1250 our $first_request = 1;
1251 sub run_request {
1252 reset_timer();
1254 evaluate_uri();
1255 if ($first_request) {
1256 evaluate_gitweb_config();
1257 evaluate_git_version();
1259 if ($per_request_config) {
1260 if (ref($per_request_config) eq 'CODE') {
1261 $per_request_config->();
1262 } elsif (!$first_request) {
1263 evaluate_gitweb_config();
1266 check_loadavg();
1268 # $projectroot and $projects_list might be set in gitweb config file
1269 $projects_list ||= $projectroot;
1271 evaluate_query_params();
1272 evaluate_path_info();
1273 evaluate_and_validate_params();
1274 evaluate_git_dir();
1276 configure_gitweb_features();
1278 dispatch();
1281 our $is_last_request = sub { 1 };
1282 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1283 our $CGI = 'CGI';
1284 our $cgi;
1285 sub configure_as_fcgi {
1286 require CGI::Fast;
1287 our $CGI = 'CGI::Fast';
1289 my $request_number = 0;
1290 # let each child service 100 requests
1291 our $is_last_request = sub { ++$request_number > 100 };
1293 sub evaluate_argv {
1294 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1295 configure_as_fcgi()
1296 if $script_name =~ /\.fcgi$/;
1298 return unless (@ARGV);
1300 require Getopt::Long;
1301 Getopt::Long::GetOptions(
1302 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1303 'nproc|n=i' => sub {
1304 my ($arg, $val) = @_;
1305 return unless eval { require FCGI::ProcManager; 1; };
1306 my $proc_manager = FCGI::ProcManager->new({
1307 n_processes => $val,
1309 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1310 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1311 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1316 sub run {
1317 evaluate_argv();
1319 $first_request = 1;
1320 $pre_listen_hook->()
1321 if $pre_listen_hook;
1323 REQUEST:
1324 while ($cgi = $CGI->new()) {
1325 $pre_dispatch_hook->()
1326 if $pre_dispatch_hook;
1328 run_request();
1330 $post_dispatch_hook->()
1331 if $post_dispatch_hook;
1332 $first_request = 0;
1334 last REQUEST if ($is_last_request->());
1337 DONE_GITWEB:
1341 run();
1343 if (defined caller) {
1344 # wrapped in a subroutine processing requests,
1345 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1346 return;
1347 } else {
1348 # pure CGI script, serving single request
1349 exit;
1352 ## ======================================================================
1353 ## action links
1355 # possible values of extra options
1356 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1357 # -replay => 1 - start from a current view (replay with modifications)
1358 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1359 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1360 sub href {
1361 my %params = @_;
1362 # default is to use -absolute url() i.e. $my_uri
1363 my $href = $params{-full} ? $my_url : $my_uri;
1365 # implicit -replay, must be first of implicit params
1366 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1368 $params{'project'} = $project unless exists $params{'project'};
1370 if ($params{-replay}) {
1371 while (my ($name, $symbol) = each %cgi_param_mapping) {
1372 if (!exists $params{$name}) {
1373 $params{$name} = $input_params{$name};
1378 my $use_pathinfo = gitweb_check_feature('pathinfo');
1379 if (defined $params{'project'} &&
1380 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1381 # try to put as many parameters as possible in PATH_INFO:
1382 # - project name
1383 # - action
1384 # - hash_parent or hash_parent_base:/file_parent
1385 # - hash or hash_base:/filename
1386 # - the snapshot_format as an appropriate suffix
1388 # When the script is the root DirectoryIndex for the domain,
1389 # $href here would be something like http://gitweb.example.com/
1390 # Thus, we strip any trailing / from $href, to spare us double
1391 # slashes in the final URL
1392 $href =~ s,/$,,;
1394 # Then add the project name, if present
1395 $href .= "/".esc_path_info($params{'project'});
1396 delete $params{'project'};
1398 # since we destructively absorb parameters, we keep this
1399 # boolean that remembers if we're handling a snapshot
1400 my $is_snapshot = $params{'action'} eq 'snapshot';
1402 # Summary just uses the project path URL, any other action is
1403 # added to the URL
1404 if (defined $params{'action'}) {
1405 $href .= "/".esc_path_info($params{'action'})
1406 unless $params{'action'} eq 'summary';
1407 delete $params{'action'};
1410 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1411 # stripping nonexistent or useless pieces
1412 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1413 || $params{'hash_parent'} || $params{'hash'});
1414 if (defined $params{'hash_base'}) {
1415 if (defined $params{'hash_parent_base'}) {
1416 $href .= esc_path_info($params{'hash_parent_base'});
1417 # skip the file_parent if it's the same as the file_name
1418 if (defined $params{'file_parent'}) {
1419 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1420 delete $params{'file_parent'};
1421 } elsif ($params{'file_parent'} !~ /\.\./) {
1422 $href .= ":/".esc_path_info($params{'file_parent'});
1423 delete $params{'file_parent'};
1426 $href .= "..";
1427 delete $params{'hash_parent'};
1428 delete $params{'hash_parent_base'};
1429 } elsif (defined $params{'hash_parent'}) {
1430 $href .= esc_path_info($params{'hash_parent'}). "..";
1431 delete $params{'hash_parent'};
1434 $href .= esc_path_info($params{'hash_base'});
1435 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1436 $href .= ":/".esc_path_info($params{'file_name'});
1437 delete $params{'file_name'};
1439 delete $params{'hash'};
1440 delete $params{'hash_base'};
1441 } elsif (defined $params{'hash'}) {
1442 $href .= esc_path_info($params{'hash'});
1443 delete $params{'hash'};
1446 # If the action was a snapshot, we can absorb the
1447 # snapshot_format parameter too
1448 if ($is_snapshot) {
1449 my $fmt = $params{'snapshot_format'};
1450 # snapshot_format should always be defined when href()
1451 # is called, but just in case some code forgets, we
1452 # fall back to the default
1453 $fmt ||= $snapshot_fmts[0];
1454 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1455 delete $params{'snapshot_format'};
1459 # now encode the parameters explicitly
1460 my @result = ();
1461 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1462 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1463 if (defined $params{$name}) {
1464 if (ref($params{$name}) eq "ARRAY") {
1465 foreach my $par (@{$params{$name}}) {
1466 push @result, $symbol . "=" . esc_param($par);
1468 } else {
1469 push @result, $symbol . "=" . esc_param($params{$name});
1473 $href .= "?" . join(';', @result) if scalar @result;
1475 # final transformation: trailing spaces must be escaped (URI-encoded)
1476 $href =~ s/(\s+)$/CGI::escape($1)/e;
1478 if ($params{-anchor}) {
1479 $href .= "#".esc_param($params{-anchor});
1482 return $href;
1486 ## ======================================================================
1487 ## validation, quoting/unquoting and escaping
1489 sub is_valid_action {
1490 my $input = shift;
1491 return undef unless exists $actions{$input};
1492 return 1;
1495 sub is_valid_project {
1496 my $input = shift;
1498 return unless defined $input;
1499 if (!is_valid_pathname($input) ||
1500 !(-d "$projectroot/$input") ||
1501 !check_export_ok("$projectroot/$input") ||
1502 ($strict_export && !project_in_list($input))) {
1503 return undef;
1504 } else {
1505 return 1;
1509 sub is_valid_pathname {
1510 my $input = shift;
1512 return undef unless defined $input;
1513 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1514 # at the beginning, at the end, and between slashes.
1515 # also this catches doubled slashes
1516 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1517 return undef;
1519 # no null characters
1520 if ($input =~ m!\0!) {
1521 return undef;
1523 return 1;
1526 sub is_valid_ref_format {
1527 my $input = shift;
1529 return undef unless defined $input;
1530 # restrictions on ref name according to git-check-ref-format
1531 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1532 return undef;
1534 return 1;
1537 sub is_valid_refname {
1538 my $input = shift;
1540 return undef unless defined $input;
1541 # textual hashes are O.K.
1542 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1543 return 1;
1545 # it must be correct pathname
1546 is_valid_pathname($input) or return undef;
1547 # check git-check-ref-format restrictions
1548 is_valid_ref_format($input) or return undef;
1549 return 1;
1552 # decode sequences of octets in utf8 into Perl's internal form,
1553 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1554 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1555 sub to_utf8 {
1556 my $str = shift;
1557 return undef unless defined $str;
1559 if (utf8::is_utf8($str) || utf8::decode($str)) {
1560 return $str;
1561 } else {
1562 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1566 # quote unsafe chars, but keep the slash, even when it's not
1567 # correct, but quoted slashes look too horrible in bookmarks
1568 sub esc_param {
1569 my $str = shift;
1570 return undef unless defined $str;
1571 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1572 $str =~ s/ /\+/g;
1573 return $str;
1576 # the quoting rules for path_info fragment are slightly different
1577 sub esc_path_info {
1578 my $str = shift;
1579 return undef unless defined $str;
1581 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1582 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1584 return $str;
1587 # quote unsafe chars in whole URL, so some characters cannot be quoted
1588 sub esc_url {
1589 my $str = shift;
1590 return undef unless defined $str;
1591 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1592 $str =~ s/ /\+/g;
1593 return $str;
1596 # quote unsafe characters in HTML attributes
1597 sub esc_attr {
1599 # for XHTML conformance escaping '"' to '&quot;' is not enough
1600 return esc_html(@_);
1603 # replace invalid utf8 character with SUBSTITUTION sequence
1604 sub esc_html {
1605 my $str = shift;
1606 my %opts = @_;
1608 return undef unless defined $str;
1610 $str = to_utf8($str);
1611 $str = $cgi->escapeHTML($str);
1612 if ($opts{'-nbsp'}) {
1613 $str =~ s/ /&nbsp;/g;
1615 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1616 return $str;
1619 # quote control characters and escape filename to HTML
1620 sub esc_path {
1621 my $str = shift;
1622 my %opts = @_;
1624 return undef unless defined $str;
1626 $str = to_utf8($str);
1627 $str = $cgi->escapeHTML($str);
1628 if ($opts{'-nbsp'}) {
1629 $str =~ s/ /&nbsp;/g;
1631 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1632 return $str;
1635 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1636 sub sanitize {
1637 my $str = shift;
1639 return undef unless defined $str;
1641 $str = to_utf8($str);
1642 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1643 return $str;
1646 # Make control characters "printable", using character escape codes (CEC)
1647 sub quot_cec {
1648 my $cntrl = shift;
1649 my %opts = @_;
1650 my %es = ( # character escape codes, aka escape sequences
1651 "\t" => '\t', # tab (HT)
1652 "\n" => '\n', # line feed (LF)
1653 "\r" => '\r', # carrige return (CR)
1654 "\f" => '\f', # form feed (FF)
1655 "\b" => '\b', # backspace (BS)
1656 "\a" => '\a', # alarm (bell) (BEL)
1657 "\e" => '\e', # escape (ESC)
1658 "\013" => '\v', # vertical tab (VT)
1659 "\000" => '\0', # nul character (NUL)
1661 my $chr = ( (exists $es{$cntrl})
1662 ? $es{$cntrl}
1663 : sprintf('\%2x', ord($cntrl)) );
1664 if ($opts{-nohtml}) {
1665 return $chr;
1666 } else {
1667 return "<span class=\"cntrl\">$chr</span>";
1671 # Alternatively use unicode control pictures codepoints,
1672 # Unicode "printable representation" (PR)
1673 sub quot_upr {
1674 my $cntrl = shift;
1675 my %opts = @_;
1677 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1678 if ($opts{-nohtml}) {
1679 return $chr;
1680 } else {
1681 return "<span class=\"cntrl\">$chr</span>";
1685 # git may return quoted and escaped filenames
1686 sub unquote {
1687 my $str = shift;
1689 sub unq {
1690 my $seq = shift;
1691 my %es = ( # character escape codes, aka escape sequences
1692 't' => "\t", # tab (HT, TAB)
1693 'n' => "\n", # newline (NL)
1694 'r' => "\r", # return (CR)
1695 'f' => "\f", # form feed (FF)
1696 'b' => "\b", # backspace (BS)
1697 'a' => "\a", # alarm (bell) (BEL)
1698 'e' => "\e", # escape (ESC)
1699 'v' => "\013", # vertical tab (VT)
1702 if ($seq =~ m/^[0-7]{1,3}$/) {
1703 # octal char sequence
1704 return chr(oct($seq));
1705 } elsif (exists $es{$seq}) {
1706 # C escape sequence, aka character escape code
1707 return $es{$seq};
1709 # quoted ordinary character
1710 return $seq;
1713 if ($str =~ m/^"(.*)"$/) {
1714 # needs unquoting
1715 $str = $1;
1716 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1718 return $str;
1721 # escape tabs (convert tabs to spaces)
1722 sub untabify {
1723 my $line = shift;
1725 while ((my $pos = index($line, "\t")) != -1) {
1726 if (my $count = (8 - ($pos % 8))) {
1727 my $spaces = ' ' x $count;
1728 $line =~ s/\t/$spaces/;
1732 return $line;
1735 sub project_in_list {
1736 my $project = shift;
1737 my @list = git_get_projects_list();
1738 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1741 ## ----------------------------------------------------------------------
1742 ## HTML aware string manipulation
1744 # Try to chop given string on a word boundary between position
1745 # $len and $len+$add_len. If there is no word boundary there,
1746 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1747 # (marking chopped part) would be longer than given string.
1748 sub chop_str {
1749 my $str = shift;
1750 my $len = shift;
1751 my $add_len = shift || 10;
1752 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1754 # Make sure perl knows it is utf8 encoded so we don't
1755 # cut in the middle of a utf8 multibyte char.
1756 $str = to_utf8($str);
1758 # allow only $len chars, but don't cut a word if it would fit in $add_len
1759 # if it doesn't fit, cut it if it's still longer than the dots we would add
1760 # remove chopped character entities entirely
1762 # when chopping in the middle, distribute $len into left and right part
1763 # return early if chopping wouldn't make string shorter
1764 if ($where eq 'center') {
1765 return $str if ($len + 5 >= length($str)); # filler is length 5
1766 $len = int($len/2);
1767 } else {
1768 return $str if ($len + 4 >= length($str)); # filler is length 4
1771 # regexps: ending and beginning with word part up to $add_len
1772 my $endre = qr/.{$len}\w{0,$add_len}/;
1773 my $begre = qr/\w{0,$add_len}.{$len}/;
1775 if ($where eq 'left') {
1776 $str =~ m/^(.*?)($begre)$/;
1777 my ($lead, $body) = ($1, $2);
1778 if (length($lead) > 4) {
1779 $lead = " ...";
1781 return "$lead$body";
1783 } elsif ($where eq 'center') {
1784 $str =~ m/^($endre)(.*)$/;
1785 my ($left, $str) = ($1, $2);
1786 $str =~ m/^(.*?)($begre)$/;
1787 my ($mid, $right) = ($1, $2);
1788 if (length($mid) > 5) {
1789 $mid = " ... ";
1791 return "$left$mid$right";
1793 } else {
1794 $str =~ m/^($endre)(.*)$/;
1795 my $body = $1;
1796 my $tail = $2;
1797 if (length($tail) > 4) {
1798 $tail = "... ";
1800 return "$body$tail";
1804 # takes the same arguments as chop_str, but also wraps a <span> around the
1805 # result with a title attribute if it does get chopped. Additionally, the
1806 # string is HTML-escaped.
1807 sub chop_and_escape_str {
1808 my ($str) = @_;
1810 my $chopped = chop_str(@_);
1811 $str = to_utf8($str);
1812 if ($chopped eq $str) {
1813 return esc_html($chopped);
1814 } else {
1815 $str =~ s/[[:cntrl:]]/?/g;
1816 return $cgi->span({-title=>$str}, esc_html($chopped));
1820 # Highlight selected fragments of string, using given CSS class,
1821 # and escape HTML. It is assumed that fragments do not overlap.
1822 # Regions are passed as list of pairs (array references).
1824 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1825 # '<span class="mark">foo</span>bar'
1826 sub esc_html_hl_regions {
1827 my ($str, $css_class, @sel) = @_;
1828 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1829 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1830 return esc_html($str, %opts) unless @sel;
1832 my $out = '';
1833 my $pos = 0;
1835 for my $s (@sel) {
1836 my ($begin, $end) = @$s;
1838 # Don't create empty <span> elements.
1839 next if $end <= $begin;
1841 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1842 %opts);
1844 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1845 if ($begin - $pos > 0);
1846 $out .= $cgi->span({-class => $css_class}, $escaped);
1848 $pos = $end;
1850 $out .= esc_html(substr($str, $pos), %opts)
1851 if ($pos < length($str));
1853 return $out;
1856 # return positions of beginning and end of each match
1857 sub matchpos_list {
1858 my ($str, $regexp) = @_;
1859 return unless (defined $str && defined $regexp);
1861 my @matches;
1862 while ($str =~ /$regexp/g) {
1863 push @matches, [$-[0], $+[0]];
1865 return @matches;
1868 # highlight match (if any), and escape HTML
1869 sub esc_html_match_hl {
1870 my ($str, $regexp) = @_;
1871 return esc_html($str) unless defined $regexp;
1873 my @matches = matchpos_list($str, $regexp);
1874 return esc_html($str) unless @matches;
1876 return esc_html_hl_regions($str, 'match', @matches);
1880 # highlight match (if any) of shortened string, and escape HTML
1881 sub esc_html_match_hl_chopped {
1882 my ($str, $chopped, $regexp) = @_;
1883 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1885 my @matches = matchpos_list($str, $regexp);
1886 return esc_html($chopped) unless @matches;
1888 # filter matches so that we mark chopped string
1889 my $tail = "... "; # see chop_str
1890 unless ($chopped =~ s/\Q$tail\E$//) {
1891 $tail = '';
1893 my $chop_len = length($chopped);
1894 my $tail_len = length($tail);
1895 my @filtered;
1897 for my $m (@matches) {
1898 if ($m->[0] > $chop_len) {
1899 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1900 last;
1901 } elsif ($m->[1] > $chop_len) {
1902 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1903 last;
1905 push @filtered, $m;
1908 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1911 ## ----------------------------------------------------------------------
1912 ## functions returning short strings
1914 # CSS class for given age value (in seconds)
1915 sub age_class {
1916 my $age = shift;
1918 if (!defined $age) {
1919 return "noage";
1920 } elsif ($age < 60*60*2) {
1921 return "age0";
1922 } elsif ($age < 60*60*24*2) {
1923 return "age1";
1924 } else {
1925 return "age2";
1929 # convert age in seconds to "nn units ago" string
1930 sub age_string {
1931 my $age = shift;
1932 my $age_str;
1934 if ($age > 60*60*24*365*2) {
1935 $age_str = (int $age/60/60/24/365);
1936 $age_str .= " years ago";
1937 } elsif ($age > 60*60*24*(365/12)*2) {
1938 $age_str = int $age/60/60/24/(365/12);
1939 $age_str .= " months ago";
1940 } elsif ($age > 60*60*24*7*2) {
1941 $age_str = int $age/60/60/24/7;
1942 $age_str .= " weeks ago";
1943 } elsif ($age > 60*60*24*2) {
1944 $age_str = int $age/60/60/24;
1945 $age_str .= " days ago";
1946 } elsif ($age > 60*60*2) {
1947 $age_str = int $age/60/60;
1948 $age_str .= " hours ago";
1949 } elsif ($age > 60*2) {
1950 $age_str = int $age/60;
1951 $age_str .= " min ago";
1952 } elsif ($age > 2) {
1953 $age_str = int $age;
1954 $age_str .= " sec ago";
1955 } else {
1956 $age_str .= " right now";
1958 return $age_str;
1961 use constant {
1962 S_IFINVALID => 0030000,
1963 S_IFGITLINK => 0160000,
1966 # submodule/subproject, a commit object reference
1967 sub S_ISGITLINK {
1968 my $mode = shift;
1970 return (($mode & S_IFMT) == S_IFGITLINK)
1973 # convert file mode in octal to symbolic file mode string
1974 sub mode_str {
1975 my $mode = oct shift;
1977 if (S_ISGITLINK($mode)) {
1978 return 'm---------';
1979 } elsif (S_ISDIR($mode & S_IFMT)) {
1980 return 'drwxr-xr-x';
1981 } elsif (S_ISLNK($mode)) {
1982 return 'lrwxrwxrwx';
1983 } elsif (S_ISREG($mode)) {
1984 # git cares only about the executable bit
1985 if ($mode & S_IXUSR) {
1986 return '-rwxr-xr-x';
1987 } else {
1988 return '-rw-r--r--';
1990 } else {
1991 return '----------';
1995 # convert file mode in octal to file type string
1996 sub file_type {
1997 my $mode = shift;
1999 if ($mode !~ m/^[0-7]+$/) {
2000 return $mode;
2001 } else {
2002 $mode = oct $mode;
2005 if (S_ISGITLINK($mode)) {
2006 return "submodule";
2007 } elsif (S_ISDIR($mode & S_IFMT)) {
2008 return "directory";
2009 } elsif (S_ISLNK($mode)) {
2010 return "symlink";
2011 } elsif (S_ISREG($mode)) {
2012 return "file";
2013 } else {
2014 return "unknown";
2018 # convert file mode in octal to file type description string
2019 sub file_type_long {
2020 my $mode = shift;
2022 if ($mode !~ m/^[0-7]+$/) {
2023 return $mode;
2024 } else {
2025 $mode = oct $mode;
2028 if (S_ISGITLINK($mode)) {
2029 return "submodule";
2030 } elsif (S_ISDIR($mode & S_IFMT)) {
2031 return "directory";
2032 } elsif (S_ISLNK($mode)) {
2033 return "symlink";
2034 } elsif (S_ISREG($mode)) {
2035 if ($mode & S_IXUSR) {
2036 return "executable";
2037 } else {
2038 return "file";
2040 } else {
2041 return "unknown";
2046 ## ----------------------------------------------------------------------
2047 ## functions returning short HTML fragments, or transforming HTML fragments
2048 ## which don't belong to other sections
2050 # format line of commit message.
2051 sub format_log_line_html {
2052 my $line = shift;
2054 $line = esc_html($line, -nbsp=>1);
2055 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2056 $cgi->a({-href => href(action=>"object", hash=>$1),
2057 -class => "text"}, $1);
2058 }eg;
2060 return $line;
2063 # format marker of refs pointing to given object
2065 # the destination action is chosen based on object type and current context:
2066 # - for annotated tags, we choose the tag view unless it's the current view
2067 # already, in which case we go to shortlog view
2068 # - for other refs, we keep the current view if we're in history, shortlog or
2069 # log view, and select shortlog otherwise
2070 sub format_ref_marker {
2071 my ($refs, $id) = @_;
2072 my $markers = '';
2074 if (defined $refs->{$id}) {
2075 foreach my $ref (@{$refs->{$id}}) {
2076 # this code exploits the fact that non-lightweight tags are the
2077 # only indirect objects, and that they are the only objects for which
2078 # we want to use tag instead of shortlog as action
2079 my ($type, $name) = qw();
2080 my $indirect = ($ref =~ s/\^\{\}$//);
2081 # e.g. tags/v2.6.11 or heads/next
2082 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2083 $type = $1;
2084 $name = $2;
2085 } else {
2086 $type = "ref";
2087 $name = $ref;
2090 my $class = $type;
2091 $class .= " indirect" if $indirect;
2093 my $dest_action = "shortlog";
2095 if ($indirect) {
2096 $dest_action = "tag" unless $action eq "tag";
2097 } elsif ($action =~ /^(history|(short)?log)$/) {
2098 $dest_action = $action;
2101 my $dest = "";
2102 $dest .= "refs/" unless $ref =~ m!^refs/!;
2103 $dest .= $ref;
2105 my $link = $cgi->a({
2106 -href => href(
2107 action=>$dest_action,
2108 hash=>$dest
2109 )}, $name);
2111 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2112 $link . "</span>";
2116 if ($markers) {
2117 return ' <span class="refs">'. $markers . '</span>';
2118 } else {
2119 return "";
2123 # format, perhaps shortened and with markers, title line
2124 sub format_subject_html {
2125 my ($long, $short, $href, $extra) = @_;
2126 $extra = '' unless defined($extra);
2128 if (length($short) < length($long)) {
2129 $long =~ s/[[:cntrl:]]/?/g;
2130 return $cgi->a({-href => $href, -class => "list subject",
2131 -title => to_utf8($long)},
2132 esc_html($short)) . $extra;
2133 } else {
2134 return $cgi->a({-href => $href, -class => "list subject"},
2135 esc_html($long)) . $extra;
2139 # Rather than recomputing the url for an email multiple times, we cache it
2140 # after the first hit. This gives a visible benefit in views where the avatar
2141 # for the same email is used repeatedly (e.g. shortlog).
2142 # The cache is shared by all avatar engines (currently gravatar only), which
2143 # are free to use it as preferred. Since only one avatar engine is used for any
2144 # given page, there's no risk for cache conflicts.
2145 our %avatar_cache = ();
2147 # Compute the picon url for a given email, by using the picon search service over at
2148 # http://www.cs.indiana.edu/picons/search.html
2149 sub picon_url {
2150 my $email = lc shift;
2151 if (!$avatar_cache{$email}) {
2152 my ($user, $domain) = split('@', $email);
2153 $avatar_cache{$email} =
2154 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2155 "$domain/$user/" .
2156 "users+domains+unknown/up/single";
2158 return $avatar_cache{$email};
2161 # Compute the gravatar url for a given email, if it's not in the cache already.
2162 # Gravatar stores only the part of the URL before the size, since that's the
2163 # one computationally more expensive. This also allows reuse of the cache for
2164 # different sizes (for this particular engine).
2165 sub gravatar_url {
2166 my $email = lc shift;
2167 my $size = shift;
2168 $avatar_cache{$email} ||=
2169 "//www.gravatar.com/avatar/" .
2170 Digest::MD5::md5_hex($email) . "?s=";
2171 return $avatar_cache{$email} . $size;
2174 # Insert an avatar for the given $email at the given $size if the feature
2175 # is enabled.
2176 sub git_get_avatar {
2177 my ($email, %opts) = @_;
2178 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2179 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2180 $opts{-size} ||= 'default';
2181 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2182 my $url = "";
2183 if ($git_avatar eq 'gravatar') {
2184 $url = gravatar_url($email, $size);
2185 } elsif ($git_avatar eq 'picon') {
2186 $url = picon_url($email);
2188 # Other providers can be added by extending the if chain, defining $url
2189 # as needed. If no variant puts something in $url, we assume avatars
2190 # are completely disabled/unavailable.
2191 if ($url) {
2192 return $pre_white .
2193 "<img width=\"$size\" " .
2194 "class=\"avatar\" " .
2195 "src=\"".esc_url($url)."\" " .
2196 "alt=\"\" " .
2197 "/>" . $post_white;
2198 } else {
2199 return "";
2203 sub format_search_author {
2204 my ($author, $searchtype, $displaytext) = @_;
2205 my $have_search = gitweb_check_feature('search');
2207 if ($have_search) {
2208 my $performed = "";
2209 if ($searchtype eq 'author') {
2210 $performed = "authored";
2211 } elsif ($searchtype eq 'committer') {
2212 $performed = "committed";
2215 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2216 searchtext=>$author,
2217 searchtype=>$searchtype), class=>"list",
2218 title=>"Search for commits $performed by $author"},
2219 $displaytext);
2221 } else {
2222 return $displaytext;
2226 # format the author name of the given commit with the given tag
2227 # the author name is chopped and escaped according to the other
2228 # optional parameters (see chop_str).
2229 sub format_author_html {
2230 my $tag = shift;
2231 my $co = shift;
2232 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2233 return "<$tag class=\"author\">" .
2234 format_search_author($co->{'author_name'}, "author",
2235 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2236 $author) .
2237 "</$tag>";
2240 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2241 sub format_git_diff_header_line {
2242 my $line = shift;
2243 my $diffinfo = shift;
2244 my ($from, $to) = @_;
2246 if ($diffinfo->{'nparents'}) {
2247 # combined diff
2248 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2249 if ($to->{'href'}) {
2250 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2251 esc_path($to->{'file'}));
2252 } else { # file was deleted (no href)
2253 $line .= esc_path($to->{'file'});
2255 } else {
2256 # "ordinary" diff
2257 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2258 if ($from->{'href'}) {
2259 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2260 'a/' . esc_path($from->{'file'}));
2261 } else { # file was added (no href)
2262 $line .= 'a/' . esc_path($from->{'file'});
2264 $line .= ' ';
2265 if ($to->{'href'}) {
2266 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2267 'b/' . esc_path($to->{'file'}));
2268 } else { # file was deleted
2269 $line .= 'b/' . esc_path($to->{'file'});
2273 return "<div class=\"diff header\">$line</div>\n";
2276 # format extended diff header line, before patch itself
2277 sub format_extended_diff_header_line {
2278 my $line = shift;
2279 my $diffinfo = shift;
2280 my ($from, $to) = @_;
2282 # match <path>
2283 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2284 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2285 esc_path($from->{'file'}));
2287 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2288 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2289 esc_path($to->{'file'}));
2291 # match single <mode>
2292 if ($line =~ m/\s(\d{6})$/) {
2293 $line .= '<span class="info"> (' .
2294 file_type_long($1) .
2295 ')</span>';
2297 # match <hash>
2298 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2299 # can match only for combined diff
2300 $line = 'index ';
2301 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2302 if ($from->{'href'}[$i]) {
2303 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2304 -class=>"hash"},
2305 substr($diffinfo->{'from_id'}[$i],0,7));
2306 } else {
2307 $line .= '0' x 7;
2309 # separator
2310 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2312 $line .= '..';
2313 if ($to->{'href'}) {
2314 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2315 substr($diffinfo->{'to_id'},0,7));
2316 } else {
2317 $line .= '0' x 7;
2320 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2321 # can match only for ordinary diff
2322 my ($from_link, $to_link);
2323 if ($from->{'href'}) {
2324 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2325 substr($diffinfo->{'from_id'},0,7));
2326 } else {
2327 $from_link = '0' x 7;
2329 if ($to->{'href'}) {
2330 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2331 substr($diffinfo->{'to_id'},0,7));
2332 } else {
2333 $to_link = '0' x 7;
2335 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2336 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2339 return $line . "<br/>\n";
2342 # format from-file/to-file diff header
2343 sub format_diff_from_to_header {
2344 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2345 my $line;
2346 my $result = '';
2348 $line = $from_line;
2349 #assert($line =~ m/^---/) if DEBUG;
2350 # no extra formatting for "^--- /dev/null"
2351 if (! $diffinfo->{'nparents'}) {
2352 # ordinary (single parent) diff
2353 if ($line =~ m!^--- "?a/!) {
2354 if ($from->{'href'}) {
2355 $line = '--- a/' .
2356 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2357 esc_path($from->{'file'}));
2358 } else {
2359 $line = '--- a/' .
2360 esc_path($from->{'file'});
2363 $result .= qq!<div class="diff from_file">$line</div>\n!;
2365 } else {
2366 # combined diff (merge commit)
2367 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2368 if ($from->{'href'}[$i]) {
2369 $line = '--- ' .
2370 $cgi->a({-href=>href(action=>"blobdiff",
2371 hash_parent=>$diffinfo->{'from_id'}[$i],
2372 hash_parent_base=>$parents[$i],
2373 file_parent=>$from->{'file'}[$i],
2374 hash=>$diffinfo->{'to_id'},
2375 hash_base=>$hash,
2376 file_name=>$to->{'file'}),
2377 -class=>"path",
2378 -title=>"diff" . ($i+1)},
2379 $i+1) .
2380 '/' .
2381 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2382 esc_path($from->{'file'}[$i]));
2383 } else {
2384 $line = '--- /dev/null';
2386 $result .= qq!<div class="diff from_file">$line</div>\n!;
2390 $line = $to_line;
2391 #assert($line =~ m/^\+\+\+/) if DEBUG;
2392 # no extra formatting for "^+++ /dev/null"
2393 if ($line =~ m!^\+\+\+ "?b/!) {
2394 if ($to->{'href'}) {
2395 $line = '+++ b/' .
2396 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2397 esc_path($to->{'file'}));
2398 } else {
2399 $line = '+++ b/' .
2400 esc_path($to->{'file'});
2403 $result .= qq!<div class="diff to_file">$line</div>\n!;
2405 return $result;
2408 # create note for patch simplified by combined diff
2409 sub format_diff_cc_simplified {
2410 my ($diffinfo, @parents) = @_;
2411 my $result = '';
2413 $result .= "<div class=\"diff header\">" .
2414 "diff --cc ";
2415 if (!is_deleted($diffinfo)) {
2416 $result .= $cgi->a({-href => href(action=>"blob",
2417 hash_base=>$hash,
2418 hash=>$diffinfo->{'to_id'},
2419 file_name=>$diffinfo->{'to_file'}),
2420 -class => "path"},
2421 esc_path($diffinfo->{'to_file'}));
2422 } else {
2423 $result .= esc_path($diffinfo->{'to_file'});
2425 $result .= "</div>\n" . # class="diff header"
2426 "<div class=\"diff nodifferences\">" .
2427 "Simple merge" .
2428 "</div>\n"; # class="diff nodifferences"
2430 return $result;
2433 sub diff_line_class {
2434 my ($line, $from, $to) = @_;
2436 # ordinary diff
2437 my $num_sign = 1;
2438 # combined diff
2439 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2440 $num_sign = scalar @{$from->{'href'}};
2443 my @diff_line_classifier = (
2444 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2445 { regexp => qr/^\\/, class => "incomplete" },
2446 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2447 # classifier for context must come before classifier add/rem,
2448 # or we would have to use more complicated regexp, for example
2449 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2450 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2451 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2453 for my $clsfy (@diff_line_classifier) {
2454 return $clsfy->{'class'}
2455 if ($line =~ $clsfy->{'regexp'});
2458 # fallback
2459 return "";
2462 # assumes that $from and $to are defined and correctly filled,
2463 # and that $line holds a line of chunk header for unified diff
2464 sub format_unidiff_chunk_header {
2465 my ($line, $from, $to) = @_;
2467 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2468 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2470 $from_lines = 0 unless defined $from_lines;
2471 $to_lines = 0 unless defined $to_lines;
2473 if ($from->{'href'}) {
2474 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2475 -class=>"list"}, $from_text);
2477 if ($to->{'href'}) {
2478 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2479 -class=>"list"}, $to_text);
2481 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2482 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2483 return $line;
2486 # assumes that $from and $to are defined and correctly filled,
2487 # and that $line holds a line of chunk header for combined diff
2488 sub format_cc_diff_chunk_header {
2489 my ($line, $from, $to) = @_;
2491 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2492 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2494 @from_text = split(' ', $ranges);
2495 for (my $i = 0; $i < @from_text; ++$i) {
2496 ($from_start[$i], $from_nlines[$i]) =
2497 (split(',', substr($from_text[$i], 1)), 0);
2500 $to_text = pop @from_text;
2501 $to_start = pop @from_start;
2502 $to_nlines = pop @from_nlines;
2504 $line = "<span class=\"chunk_info\">$prefix ";
2505 for (my $i = 0; $i < @from_text; ++$i) {
2506 if ($from->{'href'}[$i]) {
2507 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2508 -class=>"list"}, $from_text[$i]);
2509 } else {
2510 $line .= $from_text[$i];
2512 $line .= " ";
2514 if ($to->{'href'}) {
2515 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2516 -class=>"list"}, $to_text);
2517 } else {
2518 $line .= $to_text;
2520 $line .= " $prefix</span>" .
2521 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2522 return $line;
2525 # process patch (diff) line (not to be used for diff headers),
2526 # returning HTML-formatted (but not wrapped) line.
2527 # If the line is passed as a reference, it is treated as HTML and not
2528 # esc_html()'ed.
2529 sub format_diff_line {
2530 my ($line, $diff_class, $from, $to) = @_;
2532 if (ref($line)) {
2533 $line = $$line;
2534 } else {
2535 chomp $line;
2536 $line = untabify($line);
2538 if ($from && $to && $line =~ m/^\@{2} /) {
2539 $line = format_unidiff_chunk_header($line, $from, $to);
2540 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2541 $line = format_cc_diff_chunk_header($line, $from, $to);
2542 } else {
2543 $line = esc_html($line, -nbsp=>1);
2547 my $diff_classes = "diff";
2548 $diff_classes .= " $diff_class" if ($diff_class);
2549 $line = "<div class=\"$diff_classes\">$line</div>\n";
2551 return $line;
2554 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2555 # linked. Pass the hash of the tree/commit to snapshot.
2556 sub format_snapshot_links {
2557 my ($hash) = @_;
2558 my $num_fmts = @snapshot_fmts;
2559 if ($num_fmts > 1) {
2560 # A parenthesized list of links bearing format names.
2561 # e.g. "snapshot (_tar.gz_ _zip_)"
2562 return "snapshot (" . join(' ', map
2563 $cgi->a({
2564 -href => href(
2565 action=>"snapshot",
2566 hash=>$hash,
2567 snapshot_format=>$_
2569 }, $known_snapshot_formats{$_}{'display'})
2570 , @snapshot_fmts) . ")";
2571 } elsif ($num_fmts == 1) {
2572 # A single "snapshot" link whose tooltip bears the format name.
2573 # i.e. "_snapshot_"
2574 my ($fmt) = @snapshot_fmts;
2575 return
2576 $cgi->a({
2577 -href => href(
2578 action=>"snapshot",
2579 hash=>$hash,
2580 snapshot_format=>$fmt
2582 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2583 }, "snapshot");
2584 } else { # $num_fmts == 0
2585 return undef;
2589 ## ......................................................................
2590 ## functions returning values to be passed, perhaps after some
2591 ## transformation, to other functions; e.g. returning arguments to href()
2593 # returns hash to be passed to href to generate gitweb URL
2594 # in -title key it returns description of link
2595 sub get_feed_info {
2596 my $format = shift || 'Atom';
2597 my %res = (action => lc($format));
2598 my $matched_ref = 0;
2600 # feed links are possible only for project views
2601 return unless (defined $project);
2602 # some views should link to OPML, or to generic project feed,
2603 # or don't have specific feed yet (so they should use generic)
2604 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2606 my $branch = undef;
2607 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2608 # (fullname) to differentiate from tag links; this also makes
2609 # possible to detect branch links
2610 for my $ref (get_branch_refs()) {
2611 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2612 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2613 $branch = $1;
2614 $matched_ref = $ref;
2615 last;
2618 # find log type for feed description (title)
2619 my $type = 'log';
2620 if (defined $file_name) {
2621 $type = "history of $file_name";
2622 $type .= "/" if ($action eq 'tree');
2623 $type .= " on '$branch'" if (defined $branch);
2624 } else {
2625 $type = "log of $branch" if (defined $branch);
2628 $res{-title} = $type;
2629 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2630 $res{'file_name'} = $file_name;
2632 return %res;
2635 ## ----------------------------------------------------------------------
2636 ## git utility subroutines, invoking git commands
2638 # returns path to the core git executable and the --git-dir parameter as list
2639 sub git_cmd {
2640 $number_of_git_cmds++;
2641 return $GIT, '--git-dir='.$git_dir;
2644 # quote the given arguments for passing them to the shell
2645 # quote_command("command", "arg 1", "arg with ' and ! characters")
2646 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2647 # Try to avoid using this function wherever possible.
2648 sub quote_command {
2649 return join(' ',
2650 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2653 # get HEAD ref of given project as hash
2654 sub git_get_head_hash {
2655 return git_get_full_hash(shift, 'HEAD');
2658 sub git_get_full_hash {
2659 return git_get_hash(@_);
2662 sub git_get_short_hash {
2663 return git_get_hash(@_, '--short=7');
2666 sub git_get_hash {
2667 my ($project, $hash, @options) = @_;
2668 my $o_git_dir = $git_dir;
2669 my $retval = undef;
2670 $git_dir = "$projectroot/$project";
2671 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2672 '--verify', '-q', @options, $hash) {
2673 $retval = <$fd>;
2674 chomp $retval if defined $retval;
2675 close $fd;
2677 if (defined $o_git_dir) {
2678 $git_dir = $o_git_dir;
2680 return $retval;
2683 # get type of given object
2684 sub git_get_type {
2685 my $hash = shift;
2687 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2688 my $type = <$fd>;
2689 close $fd or return;
2690 chomp $type;
2691 return $type;
2694 # repository configuration
2695 our $config_file = '';
2696 our %config;
2698 # store multiple values for single key as anonymous array reference
2699 # single values stored directly in the hash, not as [ <value> ]
2700 sub hash_set_multi {
2701 my ($hash, $key, $value) = @_;
2703 if (!exists $hash->{$key}) {
2704 $hash->{$key} = $value;
2705 } elsif (!ref $hash->{$key}) {
2706 $hash->{$key} = [ $hash->{$key}, $value ];
2707 } else {
2708 push @{$hash->{$key}}, $value;
2712 # return hash of git project configuration
2713 # optionally limited to some section, e.g. 'gitweb'
2714 sub git_parse_project_config {
2715 my $section_regexp = shift;
2716 my %config;
2718 local $/ = "\0";
2720 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2721 or return;
2723 while (my $keyval = <$fh>) {
2724 chomp $keyval;
2725 my ($key, $value) = split(/\n/, $keyval, 2);
2727 hash_set_multi(\%config, $key, $value)
2728 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2730 close $fh;
2732 return %config;
2735 # convert config value to boolean: 'true' or 'false'
2736 # no value, number > 0, 'true' and 'yes' values are true
2737 # rest of values are treated as false (never as error)
2738 sub config_to_bool {
2739 my $val = shift;
2741 return 1 if !defined $val; # section.key
2743 # strip leading and trailing whitespace
2744 $val =~ s/^\s+//;
2745 $val =~ s/\s+$//;
2747 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2748 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2751 # convert config value to simple decimal number
2752 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2753 # to be multiplied by 1024, 1048576, or 1073741824
2754 sub config_to_int {
2755 my $val = shift;
2757 # strip leading and trailing whitespace
2758 $val =~ s/^\s+//;
2759 $val =~ s/\s+$//;
2761 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2762 $unit = lc($unit);
2763 # unknown unit is treated as 1
2764 return $num * ($unit eq 'g' ? 1073741824 :
2765 $unit eq 'm' ? 1048576 :
2766 $unit eq 'k' ? 1024 : 1);
2768 return $val;
2771 # convert config value to array reference, if needed
2772 sub config_to_multi {
2773 my $val = shift;
2775 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2778 sub git_get_project_config {
2779 my ($key, $type) = @_;
2781 return unless defined $git_dir;
2783 # key sanity check
2784 return unless ($key);
2785 # only subsection, if exists, is case sensitive,
2786 # and not lowercased by 'git config -z -l'
2787 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2788 $lo =~ s/_//g;
2789 $key = join(".", lc($hi), $mi, lc($lo));
2790 return if ($lo =~ /\W/ || $hi =~ /\W/);
2791 } else {
2792 $key = lc($key);
2793 $key =~ s/_//g;
2794 return if ($key =~ /\W/);
2796 $key =~ s/^gitweb\.//;
2798 # type sanity check
2799 if (defined $type) {
2800 $type =~ s/^--//;
2801 $type = undef
2802 unless ($type eq 'bool' || $type eq 'int');
2805 # get config
2806 if (!defined $config_file ||
2807 $config_file ne "$git_dir/config") {
2808 %config = git_parse_project_config('gitweb');
2809 $config_file = "$git_dir/config";
2812 # check if config variable (key) exists
2813 return unless exists $config{"gitweb.$key"};
2815 # ensure given type
2816 if (!defined $type) {
2817 return $config{"gitweb.$key"};
2818 } elsif ($type eq 'bool') {
2819 # backward compatibility: 'git config --bool' returns true/false
2820 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2821 } elsif ($type eq 'int') {
2822 return config_to_int($config{"gitweb.$key"});
2824 return $config{"gitweb.$key"};
2827 # get hash of given path at given ref
2828 sub git_get_hash_by_path {
2829 my $base = shift;
2830 my $path = shift || return undef;
2831 my $type = shift;
2833 $path =~ s,/+$,,;
2835 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2836 or die_error(500, "Open git-ls-tree failed");
2837 my $line = <$fd>;
2838 close $fd or return undef;
2840 if (!defined $line) {
2841 # there is no tree or hash given by $path at $base
2842 return undef;
2845 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2846 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2847 if (defined $type && $type ne $2) {
2848 # type doesn't match
2849 return undef;
2851 return $3;
2854 # get path of entry with given hash at given tree-ish (ref)
2855 # used to get 'from' filename for combined diff (merge commit) for renames
2856 sub git_get_path_by_hash {
2857 my $base = shift || return;
2858 my $hash = shift || return;
2860 local $/ = "\0";
2862 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2863 or return undef;
2864 while (my $line = <$fd>) {
2865 chomp $line;
2867 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2868 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2869 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2870 close $fd;
2871 return $1;
2874 close $fd;
2875 return undef;
2878 ## ......................................................................
2879 ## git utility functions, directly accessing git repository
2881 # get the value of config variable either from file named as the variable
2882 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2883 # configuration variable in the repository config file.
2884 sub git_get_file_or_project_config {
2885 my ($path, $name) = @_;
2887 $git_dir = "$projectroot/$path";
2888 open my $fd, '<', "$git_dir/$name"
2889 or return git_get_project_config($name);
2890 my $conf = <$fd>;
2891 close $fd;
2892 if (defined $conf) {
2893 chomp $conf;
2895 return $conf;
2898 sub git_get_project_description {
2899 my $path = shift;
2900 return git_get_file_or_project_config($path, 'description');
2903 sub git_get_project_category {
2904 my $path = shift;
2905 return git_get_file_or_project_config($path, 'category');
2909 # supported formats:
2910 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2911 # - if its contents is a number, use it as tag weight,
2912 # - otherwise add a tag with weight 1
2913 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2914 # the same value multiple times increases tag weight
2915 # * `gitweb.ctag' multi-valued repo config variable
2916 sub git_get_project_ctags {
2917 my $project = shift;
2918 my $ctags = {};
2920 $git_dir = "$projectroot/$project";
2921 if (opendir my $dh, "$git_dir/ctags") {
2922 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2923 foreach my $tagfile (@files) {
2924 open my $ct, '<', $tagfile
2925 or next;
2926 my $val = <$ct>;
2927 chomp $val if $val;
2928 close $ct;
2930 (my $ctag = $tagfile) =~ s#.*/##;
2931 if ($val =~ /^\d+$/) {
2932 $ctags->{$ctag} = $val;
2933 } else {
2934 $ctags->{$ctag} = 1;
2937 closedir $dh;
2939 } elsif (open my $fh, '<', "$git_dir/ctags") {
2940 while (my $line = <$fh>) {
2941 chomp $line;
2942 $ctags->{$line}++ if $line;
2944 close $fh;
2946 } else {
2947 my $taglist = config_to_multi(git_get_project_config('ctag'));
2948 foreach my $tag (@$taglist) {
2949 $ctags->{$tag}++;
2953 return $ctags;
2956 # return hash, where keys are content tags ('ctags'),
2957 # and values are sum of weights of given tag in every project
2958 sub git_gather_all_ctags {
2959 my $projects = shift;
2960 my $ctags = {};
2962 foreach my $p (@$projects) {
2963 foreach my $ct (keys %{$p->{'ctags'}}) {
2964 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2968 return $ctags;
2971 sub git_populate_project_tagcloud {
2972 my $ctags = shift;
2974 # First, merge different-cased tags; tags vote on casing
2975 my %ctags_lc;
2976 foreach (keys %$ctags) {
2977 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2978 if (not $ctags_lc{lc $_}->{topcount}
2979 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2980 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2981 $ctags_lc{lc $_}->{topname} = $_;
2985 my $cloud;
2986 my $matched = $input_params{'ctag'};
2987 if (eval { require HTML::TagCloud; 1; }) {
2988 $cloud = HTML::TagCloud->new;
2989 foreach my $ctag (sort keys %ctags_lc) {
2990 # Pad the title with spaces so that the cloud looks
2991 # less crammed.
2992 my $title = esc_html($ctags_lc{$ctag}->{topname});
2993 $title =~ s/ /&nbsp;/g;
2994 $title =~ s/^/&nbsp;/g;
2995 $title =~ s/$/&nbsp;/g;
2996 if (defined $matched && $matched eq $ctag) {
2997 $title = qq(<span class="match">$title</span>);
2999 $cloud->add($title, href(project=>undef, ctag=>$ctag),
3000 $ctags_lc{$ctag}->{count});
3002 } else {
3003 $cloud = {};
3004 foreach my $ctag (keys %ctags_lc) {
3005 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3006 if (defined $matched && $matched eq $ctag) {
3007 $title = qq(<span class="match">$title</span>);
3009 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3010 $cloud->{$ctag}{ctag} =
3011 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3014 return $cloud;
3017 sub git_show_project_tagcloud {
3018 my ($cloud, $count) = @_;
3019 if (ref $cloud eq 'HTML::TagCloud') {
3020 return $cloud->html_and_css($count);
3021 } else {
3022 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3023 return
3024 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3025 join (', ', map {
3026 $cloud->{$_}->{'ctag'}
3027 } splice(@tags, 0, $count)) .
3028 '</div>';
3032 sub git_get_project_url_list {
3033 my $path = shift;
3035 $git_dir = "$projectroot/$path";
3036 open my $fd, '<', "$git_dir/cloneurl"
3037 or return wantarray ?
3038 @{ config_to_multi(git_get_project_config('url')) } :
3039 config_to_multi(git_get_project_config('url'));
3040 my @git_project_url_list = map { chomp; $_ } <$fd>;
3041 close $fd;
3043 return wantarray ? @git_project_url_list : \@git_project_url_list;
3046 sub git_get_projects_list {
3047 my $filter = shift || '';
3048 my $paranoid = shift;
3049 my @list;
3051 if (-d $projects_list) {
3052 # search in directory
3053 my $dir = $projects_list;
3054 # remove the trailing "/"
3055 $dir =~ s!/+$!!;
3056 my $pfxlen = length("$dir");
3057 my $pfxdepth = ($dir =~ tr!/!!);
3058 # when filtering, search only given subdirectory
3059 if ($filter && !$paranoid) {
3060 $dir .= "/$filter";
3061 $dir =~ s!/+$!!;
3064 File::Find::find({
3065 follow_fast => 1, # follow symbolic links
3066 follow_skip => 2, # ignore duplicates
3067 dangling_symlinks => 0, # ignore dangling symlinks, silently
3068 wanted => sub {
3069 # global variables
3070 our $project_maxdepth;
3071 our $projectroot;
3072 # skip project-list toplevel, if we get it.
3073 return if (m!^[/.]$!);
3074 # only directories can be git repositories
3075 return unless (-d $_);
3076 # don't traverse too deep (Find is super slow on os x)
3077 # $project_maxdepth excludes depth of $projectroot
3078 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3079 $File::Find::prune = 1;
3080 return;
3083 my $path = substr($File::Find::name, $pfxlen + 1);
3084 # paranoidly only filter here
3085 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3086 next;
3088 # we check related file in $projectroot
3089 if (check_export_ok("$projectroot/$path")) {
3090 push @list, { path => $path };
3091 $File::Find::prune = 1;
3094 }, "$dir");
3096 } elsif (-f $projects_list) {
3097 # read from file(url-encoded):
3098 # 'git%2Fgit.git Linus+Torvalds'
3099 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3100 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3101 open my $fd, '<', $projects_list or return;
3102 PROJECT:
3103 while (my $line = <$fd>) {
3104 chomp $line;
3105 my ($path, $owner) = split ' ', $line;
3106 $path = unescape($path);
3107 $owner = unescape($owner);
3108 if (!defined $path) {
3109 next;
3111 # if $filter is rpovided, check if $path begins with $filter
3112 if ($filter && $path !~ m!^\Q$filter\E/!) {
3113 next;
3115 if (check_export_ok("$projectroot/$path")) {
3116 my $pr = {
3117 path => $path
3119 if ($owner) {
3120 $pr->{'owner'} = to_utf8($owner);
3122 push @list, $pr;
3125 close $fd;
3127 return @list;
3130 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3131 # as side effects it sets 'forks' field to list of forks for forked projects
3132 sub filter_forks_from_projects_list {
3133 my $projects = shift;
3135 my %trie; # prefix tree of directories (path components)
3136 # generate trie out of those directories that might contain forks
3137 foreach my $pr (@$projects) {
3138 my $path = $pr->{'path'};
3139 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3140 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3141 next unless ($path); # skip '.git' repository: tests, git-instaweb
3142 next unless (-d "$projectroot/$path"); # containing directory exists
3143 $pr->{'forks'} = []; # there can be 0 or more forks of project
3145 # add to trie
3146 my @dirs = split('/', $path);
3147 # walk the trie, until either runs out of components or out of trie
3148 my $ref = \%trie;
3149 while (scalar @dirs &&
3150 exists($ref->{$dirs[0]})) {
3151 $ref = $ref->{shift @dirs};
3153 # create rest of trie structure from rest of components
3154 foreach my $dir (@dirs) {
3155 $ref = $ref->{$dir} = {};
3157 # create end marker, store $pr as a data
3158 $ref->{''} = $pr if (!exists $ref->{''});
3161 # filter out forks, by finding shortest prefix match for paths
3162 my @filtered;
3163 PROJECT:
3164 foreach my $pr (@$projects) {
3165 # trie lookup
3166 my $ref = \%trie;
3167 DIR:
3168 foreach my $dir (split('/', $pr->{'path'})) {
3169 if (exists $ref->{''}) {
3170 # found [shortest] prefix, is a fork - skip it
3171 push @{$ref->{''}{'forks'}}, $pr;
3172 next PROJECT;
3174 if (!exists $ref->{$dir}) {
3175 # not in trie, cannot have prefix, not a fork
3176 push @filtered, $pr;
3177 next PROJECT;
3179 # If the dir is there, we just walk one step down the trie.
3180 $ref = $ref->{$dir};
3182 # we ran out of trie
3183 # (shouldn't happen: it's either no match, or end marker)
3184 push @filtered, $pr;
3187 return @filtered;
3190 # note: fill_project_list_info must be run first,
3191 # for 'descr_long' and 'ctags' to be filled
3192 sub search_projects_list {
3193 my ($projlist, %opts) = @_;
3194 my $tagfilter = $opts{'tagfilter'};
3195 my $search_re = $opts{'search_regexp'};
3197 return @$projlist
3198 unless ($tagfilter || $search_re);
3200 # searching projects require filling to be run before it;
3201 fill_project_list_info($projlist,
3202 $tagfilter ? 'ctags' : (),
3203 $search_re ? ('path', 'descr') : ());
3204 my @projects;
3205 PROJECT:
3206 foreach my $pr (@$projlist) {
3208 if ($tagfilter) {
3209 next unless ref($pr->{'ctags'}) eq 'HASH';
3210 next unless
3211 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3214 if ($search_re) {
3215 next unless
3216 $pr->{'path'} =~ /$search_re/ ||
3217 $pr->{'descr_long'} =~ /$search_re/;
3220 push @projects, $pr;
3223 return @projects;
3226 our $gitweb_project_owner = undef;
3227 sub git_get_project_list_from_file {
3229 return if (defined $gitweb_project_owner);
3231 $gitweb_project_owner = {};
3232 # read from file (url-encoded):
3233 # 'git%2Fgit.git Linus+Torvalds'
3234 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3235 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3236 if (-f $projects_list) {
3237 open(my $fd, '<', $projects_list);
3238 while (my $line = <$fd>) {
3239 chomp $line;
3240 my ($pr, $ow) = split ' ', $line;
3241 $pr = unescape($pr);
3242 $ow = unescape($ow);
3243 $gitweb_project_owner->{$pr} = to_utf8($ow);
3245 close $fd;
3249 sub git_get_project_owner {
3250 my $project = shift;
3251 my $owner;
3253 return undef unless $project;
3254 $git_dir = "$projectroot/$project";
3256 if (!defined $gitweb_project_owner) {
3257 git_get_project_list_from_file();
3260 if (exists $gitweb_project_owner->{$project}) {
3261 $owner = $gitweb_project_owner->{$project};
3263 if (!defined $owner){
3264 $owner = git_get_project_config('owner');
3266 if (!defined $owner) {
3267 $owner = get_file_owner("$git_dir");
3270 return $owner;
3273 sub git_get_last_activity {
3274 my ($path) = @_;
3275 my $fd;
3277 $git_dir = "$projectroot/$path";
3278 open($fd, "-|", git_cmd(), 'for-each-ref',
3279 '--format=%(committer)',
3280 '--sort=-committerdate',
3281 '--count=1',
3282 map { "refs/$_" } get_branch_refs ()) or return;
3283 my $most_recent = <$fd>;
3284 close $fd or return;
3285 if (defined $most_recent &&
3286 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3287 my $timestamp = $1;
3288 my $age = time - $timestamp;
3289 return ($age, age_string($age));
3291 return (undef, undef);
3294 # Implementation note: when a single remote is wanted, we cannot use 'git
3295 # remote show -n' because that command always work (assuming it's a remote URL
3296 # if it's not defined), and we cannot use 'git remote show' because that would
3297 # try to make a network roundtrip. So the only way to find if that particular
3298 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3299 # and when we find what we want.
3300 sub git_get_remotes_list {
3301 my $wanted = shift;
3302 my %remotes = ();
3304 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3305 return unless $fd;
3306 while (my $remote = <$fd>) {
3307 chomp $remote;
3308 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3309 next if $wanted and not $remote eq $wanted;
3310 my ($url, $key) = ($1, $2);
3312 $remotes{$remote} ||= { 'heads' => () };
3313 $remotes{$remote}{$key} = $url;
3315 close $fd or return;
3316 return wantarray ? %remotes : \%remotes;
3319 # Takes a hash of remotes as first parameter and fills it by adding the
3320 # available remote heads for each of the indicated remotes.
3321 sub fill_remote_heads {
3322 my $remotes = shift;
3323 my @heads = map { "remotes/$_" } keys %$remotes;
3324 my @remoteheads = git_get_heads_list(undef, @heads);
3325 foreach my $remote (keys %$remotes) {
3326 $remotes->{$remote}{'heads'} = [ grep {
3327 $_->{'name'} =~ s!^$remote/!!
3328 } @remoteheads ];
3332 sub git_get_references {
3333 my $type = shift || "";
3334 my %refs;
3335 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3336 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3337 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3338 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3339 or return;
3341 while (my $line = <$fd>) {
3342 chomp $line;
3343 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3344 if (defined $refs{$1}) {
3345 push @{$refs{$1}}, $2;
3346 } else {
3347 $refs{$1} = [ $2 ];
3351 close $fd or return;
3352 return \%refs;
3355 sub git_get_rev_name_tags {
3356 my $hash = shift || return undef;
3358 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3359 or return;
3360 my $name_rev = <$fd>;
3361 close $fd;
3363 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3364 return $1;
3365 } else {
3366 # catches also '$hash undefined' output
3367 return undef;
3371 ## ----------------------------------------------------------------------
3372 ## parse to hash functions
3374 sub parse_date {
3375 my $epoch = shift;
3376 my $tz = shift || "-0000";
3378 my %date;
3379 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3380 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3381 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3382 $date{'hour'} = $hour;
3383 $date{'minute'} = $min;
3384 $date{'mday'} = $mday;
3385 $date{'day'} = $days[$wday];
3386 $date{'month'} = $months[$mon];
3387 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3388 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3389 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3390 $mday, $months[$mon], $hour ,$min;
3391 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3392 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3394 my ($tz_sign, $tz_hour, $tz_min) =
3395 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3396 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3397 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3398 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3399 $date{'hour_local'} = $hour;
3400 $date{'minute_local'} = $min;
3401 $date{'tz_local'} = $tz;
3402 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3403 1900+$year, $mon+1, $mday,
3404 $hour, $min, $sec, $tz);
3405 return %date;
3408 sub parse_tag {
3409 my $tag_id = shift;
3410 my %tag;
3411 my @comment;
3413 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3414 $tag{'id'} = $tag_id;
3415 while (my $line = <$fd>) {
3416 chomp $line;
3417 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3418 $tag{'object'} = $1;
3419 } elsif ($line =~ m/^type (.+)$/) {
3420 $tag{'type'} = $1;
3421 } elsif ($line =~ m/^tag (.+)$/) {
3422 $tag{'name'} = $1;
3423 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3424 $tag{'author'} = $1;
3425 $tag{'author_epoch'} = $2;
3426 $tag{'author_tz'} = $3;
3427 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3428 $tag{'author_name'} = $1;
3429 $tag{'author_email'} = $2;
3430 } else {
3431 $tag{'author_name'} = $tag{'author'};
3433 } elsif ($line =~ m/--BEGIN/) {
3434 push @comment, $line;
3435 last;
3436 } elsif ($line eq "") {
3437 last;
3440 push @comment, <$fd>;
3441 $tag{'comment'} = \@comment;
3442 close $fd or return;
3443 if (!defined $tag{'name'}) {
3444 return
3446 return %tag
3449 sub parse_commit_text {
3450 my ($commit_text, $withparents) = @_;
3451 my @commit_lines = split '\n', $commit_text;
3452 my %co;
3454 pop @commit_lines; # Remove '\0'
3456 if (! @commit_lines) {
3457 return;
3460 my $header = shift @commit_lines;
3461 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3462 return;
3464 ($co{'id'}, my @parents) = split ' ', $header;
3465 while (my $line = shift @commit_lines) {
3466 last if $line eq "\n";
3467 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3468 $co{'tree'} = $1;
3469 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3470 push @parents, $1;
3471 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3472 $co{'author'} = to_utf8($1);
3473 $co{'author_epoch'} = $2;
3474 $co{'author_tz'} = $3;
3475 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3476 $co{'author_name'} = $1;
3477 $co{'author_email'} = $2;
3478 } else {
3479 $co{'author_name'} = $co{'author'};
3481 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3482 $co{'committer'} = to_utf8($1);
3483 $co{'committer_epoch'} = $2;
3484 $co{'committer_tz'} = $3;
3485 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3486 $co{'committer_name'} = $1;
3487 $co{'committer_email'} = $2;
3488 } else {
3489 $co{'committer_name'} = $co{'committer'};
3493 if (!defined $co{'tree'}) {
3494 return;
3496 $co{'parents'} = \@parents;
3497 $co{'parent'} = $parents[0];
3499 foreach my $title (@commit_lines) {
3500 $title =~ s/^ //;
3501 if ($title ne "") {
3502 $co{'title'} = chop_str($title, 80, 5);
3503 # remove leading stuff of merges to make the interesting part visible
3504 if (length($title) > 50) {
3505 $title =~ s/^Automatic //;
3506 $title =~ s/^merge (of|with) /Merge ... /i;
3507 if (length($title) > 50) {
3508 $title =~ s/(http|rsync):\/\///;
3510 if (length($title) > 50) {
3511 $title =~ s/(master|www|rsync)\.//;
3513 if (length($title) > 50) {
3514 $title =~ s/kernel.org:?//;
3516 if (length($title) > 50) {
3517 $title =~ s/\/pub\/scm//;
3520 $co{'title_short'} = chop_str($title, 50, 5);
3521 last;
3524 if (! defined $co{'title'} || $co{'title'} eq "") {
3525 $co{'title'} = $co{'title_short'} = '(no commit message)';
3527 # remove added spaces
3528 foreach my $line (@commit_lines) {
3529 $line =~ s/^ //;
3531 $co{'comment'} = \@commit_lines;
3533 my $age = time - $co{'committer_epoch'};
3534 $co{'age'} = $age;
3535 $co{'age_string'} = age_string($age);
3536 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3537 if ($age > 60*60*24*7*2) {
3538 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3539 $co{'age_string_age'} = $co{'age_string'};
3540 } else {
3541 $co{'age_string_date'} = $co{'age_string'};
3542 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3544 return %co;
3547 sub parse_commit {
3548 my ($commit_id) = @_;
3549 my %co;
3551 local $/ = "\0";
3553 open my $fd, "-|", git_cmd(), "rev-list",
3554 "--parents",
3555 "--header",
3556 "--max-count=1",
3557 $commit_id,
3558 "--",
3559 or die_error(500, "Open git-rev-list failed");
3560 %co = parse_commit_text(<$fd>, 1);
3561 close $fd;
3563 return %co;
3566 sub parse_commits {
3567 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3568 my @cos;
3570 $maxcount ||= 1;
3571 $skip ||= 0;
3573 local $/ = "\0";
3575 open my $fd, "-|", git_cmd(), "rev-list",
3576 "--header",
3577 @args,
3578 ("--max-count=" . $maxcount),
3579 ("--skip=" . $skip),
3580 @extra_options,
3581 $commit_id,
3582 "--",
3583 ($filename ? ($filename) : ())
3584 or die_error(500, "Open git-rev-list failed");
3585 while (my $line = <$fd>) {
3586 my %co = parse_commit_text($line);
3587 push @cos, \%co;
3589 close $fd;
3591 return wantarray ? @cos : \@cos;
3594 # parse line of git-diff-tree "raw" output
3595 sub parse_difftree_raw_line {
3596 my $line = shift;
3597 my %res;
3599 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3600 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3601 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3602 $res{'from_mode'} = $1;
3603 $res{'to_mode'} = $2;
3604 $res{'from_id'} = $3;
3605 $res{'to_id'} = $4;
3606 $res{'status'} = $5;
3607 $res{'similarity'} = $6;
3608 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3609 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3610 } else {
3611 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3614 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3615 # combined diff (for merge commit)
3616 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3617 $res{'nparents'} = length($1);
3618 $res{'from_mode'} = [ split(' ', $2) ];
3619 $res{'to_mode'} = pop @{$res{'from_mode'}};
3620 $res{'from_id'} = [ split(' ', $3) ];
3621 $res{'to_id'} = pop @{$res{'from_id'}};
3622 $res{'status'} = [ split('', $4) ];
3623 $res{'to_file'} = unquote($5);
3625 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3626 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3627 $res{'commit'} = $1;
3630 return wantarray ? %res : \%res;
3633 # wrapper: return parsed line of git-diff-tree "raw" output
3634 # (the argument might be raw line, or parsed info)
3635 sub parsed_difftree_line {
3636 my $line_or_ref = shift;
3638 if (ref($line_or_ref) eq "HASH") {
3639 # pre-parsed (or generated by hand)
3640 return $line_or_ref;
3641 } else {
3642 return parse_difftree_raw_line($line_or_ref);
3646 # parse line of git-ls-tree output
3647 sub parse_ls_tree_line {
3648 my $line = shift;
3649 my %opts = @_;
3650 my %res;
3652 if ($opts{'-l'}) {
3653 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3654 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3656 $res{'mode'} = $1;
3657 $res{'type'} = $2;
3658 $res{'hash'} = $3;
3659 $res{'size'} = $4;
3660 if ($opts{'-z'}) {
3661 $res{'name'} = $5;
3662 } else {
3663 $res{'name'} = unquote($5);
3665 } else {
3666 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3667 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3669 $res{'mode'} = $1;
3670 $res{'type'} = $2;
3671 $res{'hash'} = $3;
3672 if ($opts{'-z'}) {
3673 $res{'name'} = $4;
3674 } else {
3675 $res{'name'} = unquote($4);
3679 return wantarray ? %res : \%res;
3682 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3683 sub parse_from_to_diffinfo {
3684 my ($diffinfo, $from, $to, @parents) = @_;
3686 if ($diffinfo->{'nparents'}) {
3687 # combined diff
3688 $from->{'file'} = [];
3689 $from->{'href'} = [];
3690 fill_from_file_info($diffinfo, @parents)
3691 unless exists $diffinfo->{'from_file'};
3692 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3693 $from->{'file'}[$i] =
3694 defined $diffinfo->{'from_file'}[$i] ?
3695 $diffinfo->{'from_file'}[$i] :
3696 $diffinfo->{'to_file'};
3697 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3698 $from->{'href'}[$i] = href(action=>"blob",
3699 hash_base=>$parents[$i],
3700 hash=>$diffinfo->{'from_id'}[$i],
3701 file_name=>$from->{'file'}[$i]);
3702 } else {
3703 $from->{'href'}[$i] = undef;
3706 } else {
3707 # ordinary (not combined) diff
3708 $from->{'file'} = $diffinfo->{'from_file'};
3709 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3710 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3711 hash=>$diffinfo->{'from_id'},
3712 file_name=>$from->{'file'});
3713 } else {
3714 delete $from->{'href'};
3718 $to->{'file'} = $diffinfo->{'to_file'};
3719 if (!is_deleted($diffinfo)) { # file exists in result
3720 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3721 hash=>$diffinfo->{'to_id'},
3722 file_name=>$to->{'file'});
3723 } else {
3724 delete $to->{'href'};
3728 ## ......................................................................
3729 ## parse to array of hashes functions
3731 sub git_get_heads_list {
3732 my ($limit, @classes) = @_;
3733 @classes = get_branch_refs() unless @classes;
3734 my @patterns = map { "refs/$_" } @classes;
3735 my @headslist;
3737 open my $fd, '-|', git_cmd(), 'for-each-ref',
3738 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3739 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3740 @patterns
3741 or return;
3742 while (my $line = <$fd>) {
3743 my %ref_item;
3745 chomp $line;
3746 my ($refinfo, $committerinfo) = split(/\0/, $line);
3747 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3748 my ($committer, $epoch, $tz) =
3749 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3750 $ref_item{'fullname'} = $name;
3751 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3752 $name =~ s!^refs/($strip_refs|remotes)/!!;
3753 $ref_item{'name'} = $name;
3754 # for refs neither in 'heads' nor 'remotes' we want to
3755 # show their ref dir
3756 my $ref_dir = (defined $1) ? $1 : '';
3757 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3758 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3761 $ref_item{'id'} = $hash;
3762 $ref_item{'title'} = $title || '(no commit message)';
3763 $ref_item{'epoch'} = $epoch;
3764 if ($epoch) {
3765 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3766 } else {
3767 $ref_item{'age'} = "unknown";
3770 push @headslist, \%ref_item;
3772 close $fd;
3774 return wantarray ? @headslist : \@headslist;
3777 sub git_get_tags_list {
3778 my $limit = shift;
3779 my @tagslist;
3781 open my $fd, '-|', git_cmd(), 'for-each-ref',
3782 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3783 '--format=%(objectname) %(objecttype) %(refname) '.
3784 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3785 'refs/tags'
3786 or return;
3787 while (my $line = <$fd>) {
3788 my %ref_item;
3790 chomp $line;
3791 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3792 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3793 my ($creator, $epoch, $tz) =
3794 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3795 $ref_item{'fullname'} = $name;
3796 $name =~ s!^refs/tags/!!;
3798 $ref_item{'type'} = $type;
3799 $ref_item{'id'} = $id;
3800 $ref_item{'name'} = $name;
3801 if ($type eq "tag") {
3802 $ref_item{'subject'} = $title;
3803 $ref_item{'reftype'} = $reftype;
3804 $ref_item{'refid'} = $refid;
3805 } else {
3806 $ref_item{'reftype'} = $type;
3807 $ref_item{'refid'} = $id;
3810 if ($type eq "tag" || $type eq "commit") {
3811 $ref_item{'epoch'} = $epoch;
3812 if ($epoch) {
3813 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3814 } else {
3815 $ref_item{'age'} = "unknown";
3819 push @tagslist, \%ref_item;
3821 close $fd;
3823 return wantarray ? @tagslist : \@tagslist;
3826 ## ----------------------------------------------------------------------
3827 ## filesystem-related functions
3829 sub get_file_owner {
3830 my $path = shift;
3832 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3833 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3834 if (!defined $gcos) {
3835 return undef;
3837 my $owner = $gcos;
3838 $owner =~ s/[,;].*$//;
3839 return to_utf8($owner);
3842 # assume that file exists
3843 sub insert_file {
3844 my $filename = shift;
3846 open my $fd, '<', $filename;
3847 print map { to_utf8($_) } <$fd>;
3848 close $fd;
3851 ## ......................................................................
3852 ## mimetype related functions
3854 sub mimetype_guess_file {
3855 my $filename = shift;
3856 my $mimemap = shift;
3857 -r $mimemap or return undef;
3859 my %mimemap;
3860 open(my $mh, '<', $mimemap) or return undef;
3861 while (<$mh>) {
3862 next if m/^#/; # skip comments
3863 my ($mimetype, @exts) = split(/\s+/);
3864 foreach my $ext (@exts) {
3865 $mimemap{$ext} = $mimetype;
3868 close($mh);
3870 $filename =~ /\.([^.]*)$/;
3871 return $mimemap{$1};
3874 sub mimetype_guess {
3875 my $filename = shift;
3876 my $mime;
3877 $filename =~ /\./ or return undef;
3879 if ($mimetypes_file) {
3880 my $file = $mimetypes_file;
3881 if ($file !~ m!^/!) { # if it is relative path
3882 # it is relative to project
3883 $file = "$projectroot/$project/$file";
3885 $mime = mimetype_guess_file($filename, $file);
3887 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3888 return $mime;
3891 sub blob_mimetype {
3892 my $fd = shift;
3893 my $filename = shift;
3895 if ($filename) {
3896 my $mime = mimetype_guess($filename);
3897 $mime and return $mime;
3900 # just in case
3901 return $default_blob_plain_mimetype unless $fd;
3903 if (-T $fd) {
3904 return 'text/plain';
3905 } elsif (! $filename) {
3906 return 'application/octet-stream';
3907 } elsif ($filename =~ m/\.png$/i) {
3908 return 'image/png';
3909 } elsif ($filename =~ m/\.gif$/i) {
3910 return 'image/gif';
3911 } elsif ($filename =~ m/\.jpe?g$/i) {
3912 return 'image/jpeg';
3913 } else {
3914 return 'application/octet-stream';
3918 sub blob_contenttype {
3919 my ($fd, $file_name, $type) = @_;
3921 $type ||= blob_mimetype($fd, $file_name);
3922 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3923 $type .= "; charset=$default_text_plain_charset";
3926 return $type;
3929 # guess file syntax for syntax highlighting; return undef if no highlighting
3930 # the name of syntax can (in the future) depend on syntax highlighter used
3931 sub guess_file_syntax {
3932 my ($highlight, $mimetype, $file_name) = @_;
3933 return undef unless ($highlight && defined $file_name);
3934 my $basename = basename($file_name, '.in');
3935 return $highlight_basename{$basename}
3936 if exists $highlight_basename{$basename};
3938 $basename =~ /\.([^.]*)$/;
3939 my $ext = $1 or return undef;
3940 return $highlight_ext{$ext}
3941 if exists $highlight_ext{$ext};
3943 return undef;
3946 # run highlighter and return FD of its output,
3947 # or return original FD if no highlighting
3948 sub run_highlighter {
3949 my ($fd, $highlight, $syntax) = @_;
3950 return $fd unless ($highlight && defined $syntax);
3952 close $fd;
3953 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3954 quote_command($^X, '-CO', '-MEncode=decode,FB_DEFAULT', '-pse',
3955 '$_ = decode($fe, $_, FB_DEFAULT) if !utf8::decode($_);',
3956 '--', "-fe=$fallback_encoding")." | ".
3957 quote_command($highlight_bin).
3958 " --replace-tabs=8 --fragment --syntax $syntax |"
3959 or die_error(500, "Couldn't open file or run syntax highlighter");
3960 return $fd;
3963 ## ======================================================================
3964 ## functions printing HTML: header, footer, error page
3966 sub get_page_title {
3967 my $title = to_utf8($site_name);
3969 unless (defined $project) {
3970 if (defined $project_filter) {
3971 $title .= " - projects in '" . esc_path($project_filter) . "'";
3973 return $title;
3975 $title .= " - " . to_utf8($project);
3977 return $title unless (defined $action);
3978 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3980 return $title unless (defined $file_name);
3981 $title .= " - " . esc_path($file_name);
3982 if ($action eq "tree" && $file_name !~ m|/$|) {
3983 $title .= "/";
3986 return $title;
3989 sub get_content_type_html {
3990 # require explicit support from the UA if we are to send the page as
3991 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3992 # we have to do this because MSIE sometimes globs '*/*', pretending to
3993 # support xhtml+xml but choking when it gets what it asked for.
3994 if (defined $cgi->http('HTTP_ACCEPT') &&
3995 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3996 $cgi->Accept('application/xhtml+xml') != 0) {
3997 return 'application/xhtml+xml';
3998 } else {
3999 return 'text/html';
4003 sub print_feed_meta {
4004 if (defined $project) {
4005 my %href_params = get_feed_info();
4006 if (!exists $href_params{'-title'}) {
4007 $href_params{'-title'} = 'log';
4010 foreach my $format (qw(RSS Atom)) {
4011 my $type = lc($format);
4012 my %link_attr = (
4013 '-rel' => 'alternate',
4014 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4015 '-type' => "application/$type+xml"
4018 $href_params{'extra_options'} = undef;
4019 $href_params{'action'} = $type;
4020 $link_attr{'-href'} = href(%href_params);
4021 print "<link ".
4022 "rel=\"$link_attr{'-rel'}\" ".
4023 "title=\"$link_attr{'-title'}\" ".
4024 "href=\"$link_attr{'-href'}\" ".
4025 "type=\"$link_attr{'-type'}\" ".
4026 "/>\n";
4028 $href_params{'extra_options'} = '--no-merges';
4029 $link_attr{'-href'} = href(%href_params);
4030 $link_attr{'-title'} .= ' (no merges)';
4031 print "<link ".
4032 "rel=\"$link_attr{'-rel'}\" ".
4033 "title=\"$link_attr{'-title'}\" ".
4034 "href=\"$link_attr{'-href'}\" ".
4035 "type=\"$link_attr{'-type'}\" ".
4036 "/>\n";
4039 } else {
4040 printf('<link rel="alternate" title="%s projects list" '.
4041 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4042 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4043 printf('<link rel="alternate" title="%s projects feeds" '.
4044 'href="%s" type="text/x-opml" />'."\n",
4045 esc_attr($site_name), href(project=>undef, action=>"opml"));
4049 sub print_header_links {
4050 my $status = shift;
4052 # print out each stylesheet that exist, providing backwards capability
4053 # for those people who defined $stylesheet in a config file
4054 if (defined $stylesheet) {
4055 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4056 } else {
4057 foreach my $stylesheet (@stylesheets) {
4058 next unless $stylesheet;
4059 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4062 print_feed_meta()
4063 if ($status eq '200 OK');
4064 if (defined $favicon) {
4065 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4069 sub print_nav_breadcrumbs_path {
4070 my $dirprefix = undef;
4071 while (my $part = shift) {
4072 $dirprefix .= "/" if defined $dirprefix;
4073 $dirprefix .= $part;
4074 print $cgi->a({-href => href(project => undef,
4075 project_filter => $dirprefix,
4076 action => "project_list")},
4077 esc_html($part)) . " / ";
4081 sub print_nav_breadcrumbs {
4082 my %opts = @_;
4084 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4085 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4087 if (defined $project) {
4088 my @dirname = split '/', $project;
4089 my $projectbasename = pop @dirname;
4090 print_nav_breadcrumbs_path(@dirname);
4091 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4092 if (defined $action) {
4093 my $action_print = $action ;
4094 if (defined $opts{-action_extra}) {
4095 $action_print = $cgi->a({-href => href(action=>$action)},
4096 $action);
4098 print " / $action_print";
4100 if (defined $opts{-action_extra}) {
4101 print " / $opts{-action_extra}";
4103 print "\n";
4104 } elsif (defined $project_filter) {
4105 print_nav_breadcrumbs_path(split '/', $project_filter);
4109 sub print_search_form {
4110 if (!defined $searchtext) {
4111 $searchtext = "";
4113 my $search_hash;
4114 if (defined $hash_base) {
4115 $search_hash = $hash_base;
4116 } elsif (defined $hash) {
4117 $search_hash = $hash;
4118 } else {
4119 $search_hash = "HEAD";
4121 my $action = $my_uri;
4122 my $use_pathinfo = gitweb_check_feature('pathinfo');
4123 if ($use_pathinfo) {
4124 $action .= "/".esc_url($project);
4126 print $cgi->start_form(-method => "get", -action => $action) .
4127 "<div class=\"search\">\n" .
4128 (!$use_pathinfo &&
4129 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4130 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4131 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4132 $cgi->popup_menu(-name => 'st', -default => 'commit',
4133 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4134 " " . $cgi->a({-href => href(action=>"search_help"),
4135 -title => "search help" }, "?") . " search:\n",
4136 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4137 "<span title=\"Extended regular expression\">" .
4138 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4139 -checked => $search_use_regexp) .
4140 "</span>" .
4141 "</div>" .
4142 $cgi->end_form() . "\n";
4145 sub git_header_html {
4146 my $status = shift || "200 OK";
4147 my $expires = shift;
4148 my %opts = @_;
4150 my $title = get_page_title();
4151 my $content_type = get_content_type_html();
4152 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4153 -status=> $status, -expires => $expires)
4154 unless ($opts{'-no_http_header'});
4155 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4156 print <<EOF;
4157 <?xml version="1.0" encoding="utf-8"?>
4158 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4159 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4160 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4161 <!-- git core binaries version $git_version -->
4162 <head>
4163 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4164 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4165 <meta name="robots" content="index, nofollow"/>
4166 <title>$title</title>
4167 <script type="text/javascript">/* <![CDATA[ */
4168 function fixBlameLinks() {
4169 var allLinks = document.getElementsByTagName("a");
4170 for (var i = 0; i < allLinks.length; i++) {
4171 var link = allLinks.item(i);
4172 if (link.className == 'blamelink')
4173 link.href = link.href.replace("/blame/", "/blame_incremental/");
4176 /* ]]> */</script>
4178 # the stylesheet, favicon etc urls won't work correctly with path_info
4179 # unless we set the appropriate base URL
4180 if ($ENV{'PATH_INFO'}) {
4181 print "<base href=\"".esc_url($base_url)."\" />\n";
4183 print_header_links($status);
4185 if (defined $site_html_head_string) {
4186 print to_utf8($site_html_head_string);
4189 print "</head>\n" .
4190 "<body>\n";
4192 if (defined $site_header && -f $site_header) {
4193 insert_file($site_header);
4196 print "<div class=\"page_header\">\n";
4197 if (defined $logo) {
4198 print $cgi->a({-href => esc_url($logo_url),
4199 -title => $logo_label},
4200 $cgi->img({-src => esc_url($logo),
4201 -width => 72, -height => 27,
4202 -alt => "git",
4203 -class => "logo"}));
4205 print_nav_breadcrumbs(%opts);
4206 print "</div>\n";
4208 my $have_search = gitweb_check_feature('search');
4209 if (defined $project && $have_search) {
4210 print_search_form();
4214 sub git_footer_html {
4215 my $feed_class = 'rss_logo';
4217 print "<div class=\"page_footer\">\n";
4218 if (defined $project) {
4219 my $descr = git_get_project_description($project);
4220 if (defined $descr) {
4221 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4224 my %href_params = get_feed_info();
4225 if (!%href_params) {
4226 $feed_class .= ' generic';
4228 $href_params{'-title'} ||= 'log';
4230 foreach my $format (qw(RSS Atom)) {
4231 $href_params{'action'} = lc($format);
4232 print $cgi->a({-href => href(%href_params),
4233 -title => "$href_params{'-title'} $format feed",
4234 -class => $feed_class}, $format)."\n";
4237 } else {
4238 print $cgi->a({-href => href(project=>undef, action=>"opml",
4239 project_filter => $project_filter),
4240 -class => $feed_class}, "OPML") . " ";
4241 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4242 project_filter => $project_filter),
4243 -class => $feed_class}, "TXT") . "\n";
4245 print "</div>\n"; # class="page_footer"
4247 if (defined $t0 && gitweb_check_feature('timed')) {
4248 print "<div id=\"generating_info\">\n";
4249 print 'This page took '.
4250 '<span id="generating_time" class="time_span">'.
4251 tv_interval($t0, [ gettimeofday() ]).
4252 ' seconds </span>'.
4253 ' and '.
4254 '<span id="generating_cmd">'.
4255 $number_of_git_cmds.
4256 '</span> git commands '.
4257 " to generate.\n";
4258 print "</div>\n"; # class="page_footer"
4261 if (defined $site_footer && -f $site_footer) {
4262 insert_file($site_footer);
4265 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4266 if (defined $action &&
4267 $action eq 'blame_incremental') {
4268 print qq!<script type="text/javascript">\n!.
4269 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4270 qq! "!. href() .qq!");\n!.
4271 qq!</script>\n!;
4272 } else {
4273 my ($jstimezone, $tz_cookie, $datetime_class) =
4274 gitweb_get_feature('javascript-timezone');
4276 print qq!<script type="text/javascript">\n!.
4277 qq!window.onload = function () {\n!;
4278 if (gitweb_check_feature('blame_incremental')) {
4279 print qq! fixBlameLinks();\n!;
4281 if (gitweb_check_feature('javascript-actions')) {
4282 print qq! fixLinks();\n!;
4284 if ($jstimezone && $tz_cookie && $datetime_class) {
4285 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4286 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4288 print qq!};\n!.
4289 qq!</script>\n!;
4292 print "</body>\n" .
4293 "</html>";
4296 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4297 # Example: die_error(404, 'Hash not found')
4298 # By convention, use the following status codes (as defined in RFC 2616):
4299 # 400: Invalid or missing CGI parameters, or
4300 # requested object exists but has wrong type.
4301 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4302 # this server or project.
4303 # 404: Requested object/revision/project doesn't exist.
4304 # 500: The server isn't configured properly, or
4305 # an internal error occurred (e.g. failed assertions caused by bugs), or
4306 # an unknown error occurred (e.g. the git binary died unexpectedly).
4307 # 503: The server is currently unavailable (because it is overloaded,
4308 # or down for maintenance). Generally, this is a temporary state.
4309 sub die_error {
4310 my $status = shift || 500;
4311 my $error = esc_html(shift) || "Internal Server Error";
4312 my $extra = shift;
4313 my %opts = @_;
4315 my %http_responses = (
4316 400 => '400 Bad Request',
4317 403 => '403 Forbidden',
4318 404 => '404 Not Found',
4319 500 => '500 Internal Server Error',
4320 503 => '503 Service Unavailable',
4322 git_header_html($http_responses{$status}, undef, %opts);
4323 print <<EOF;
4324 <div class="page_body">
4325 <br /><br />
4326 $status - $error
4327 <br />
4329 if (defined $extra) {
4330 print "<hr />\n" .
4331 "$extra\n";
4333 print "</div>\n";
4335 git_footer_html();
4336 goto DONE_GITWEB
4337 unless ($opts{'-error_handler'});
4340 ## ----------------------------------------------------------------------
4341 ## functions printing or outputting HTML: navigation
4343 sub git_print_page_nav {
4344 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4345 $extra = '' if !defined $extra; # pager or formats
4347 my @navs = qw(summary shortlog log commit commitdiff tree);
4348 if ($suppress) {
4349 @navs = grep { $_ ne $suppress } @navs;
4352 my %arg = map { $_ => {action=>$_} } @navs;
4353 if (defined $head) {
4354 for (qw(commit commitdiff)) {
4355 $arg{$_}{'hash'} = $head;
4357 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4358 for (qw(shortlog log)) {
4359 $arg{$_}{'hash'} = $head;
4364 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4365 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4367 my @actions = gitweb_get_feature('actions');
4368 my %repl = (
4369 '%' => '%',
4370 'n' => $project, # project name
4371 'f' => $git_dir, # project path within filesystem
4372 'h' => $treehead || '', # current hash ('h' parameter)
4373 'b' => $treebase || '', # hash base ('hb' parameter)
4375 while (@actions) {
4376 my ($label, $link, $pos) = splice(@actions,0,3);
4377 # insert
4378 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4379 # munch munch
4380 $link =~ s/%([%nfhb])/$repl{$1}/g;
4381 $arg{$label}{'_href'} = $link;
4384 print "<div class=\"page_nav\">\n" .
4385 (join " | ",
4386 map { $_ eq $current ?
4387 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4388 } @navs);
4389 print "<br/>\n$extra<br/>\n" .
4390 "</div>\n";
4393 # returns a submenu for the nagivation of the refs views (tags, heads,
4394 # remotes) with the current view disabled and the remotes view only
4395 # available if the feature is enabled
4396 sub format_ref_views {
4397 my ($current) = @_;
4398 my @ref_views = qw{tags heads};
4399 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4400 return join " | ", map {
4401 $_ eq $current ? $_ :
4402 $cgi->a({-href => href(action=>$_)}, $_)
4403 } @ref_views
4406 sub format_paging_nav {
4407 my ($action, $page, $has_next_link) = @_;
4408 my $paging_nav;
4411 if ($page > 0) {
4412 $paging_nav .=
4413 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4414 " &sdot; " .
4415 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4416 -accesskey => "p", -title => "Alt-p"}, "prev");
4417 } else {
4418 $paging_nav .= "first &sdot; prev";
4421 if ($has_next_link) {
4422 $paging_nav .= " &sdot; " .
4423 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4424 -accesskey => "n", -title => "Alt-n"}, "next");
4425 } else {
4426 $paging_nav .= " &sdot; next";
4429 return $paging_nav;
4432 ## ......................................................................
4433 ## functions printing or outputting HTML: div
4435 sub git_print_header_div {
4436 my ($action, $title, $hash, $hash_base) = @_;
4437 my %args = ();
4439 $args{'action'} = $action;
4440 $args{'hash'} = $hash if $hash;
4441 $args{'hash_base'} = $hash_base if $hash_base;
4443 print "<div class=\"header\">\n" .
4444 $cgi->a({-href => href(%args), -class => "title"},
4445 $title ? $title : $action) .
4446 "\n</div>\n";
4449 sub format_repo_url {
4450 my ($name, $url) = @_;
4451 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4454 # Group output by placing it in a DIV element and adding a header.
4455 # Options for start_div() can be provided by passing a hash reference as the
4456 # first parameter to the function.
4457 # Options to git_print_header_div() can be provided by passing an array
4458 # reference. This must follow the options to start_div if they are present.
4459 # The content can be a scalar, which is output as-is, a scalar reference, which
4460 # is output after html escaping, an IO handle passed either as *handle or
4461 # *handle{IO}, or a function reference. In the latter case all following
4462 # parameters will be taken as argument to the content function call.
4463 sub git_print_section {
4464 my ($div_args, $header_args, $content);
4465 my $arg = shift;
4466 if (ref($arg) eq 'HASH') {
4467 $div_args = $arg;
4468 $arg = shift;
4470 if (ref($arg) eq 'ARRAY') {
4471 $header_args = $arg;
4472 $arg = shift;
4474 $content = $arg;
4476 print $cgi->start_div($div_args);
4477 git_print_header_div(@$header_args);
4479 if (ref($content) eq 'CODE') {
4480 $content->(@_);
4481 } elsif (ref($content) eq 'SCALAR') {
4482 print esc_html($$content);
4483 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4484 print <$content>;
4485 } elsif (!ref($content) && defined($content)) {
4486 print $content;
4489 print $cgi->end_div;
4492 sub format_timestamp_html {
4493 my $date = shift;
4494 my $strtime = $date->{'rfc2822'};
4496 my (undef, undef, $datetime_class) =
4497 gitweb_get_feature('javascript-timezone');
4498 if ($datetime_class) {
4499 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4502 my $localtime_format = '(%02d:%02d %s)';
4503 if ($date->{'hour_local'} < 6) {
4504 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4506 $strtime .= ' ' .
4507 sprintf($localtime_format,
4508 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4510 return $strtime;
4513 # Outputs the author name and date in long form
4514 sub git_print_authorship {
4515 my $co = shift;
4516 my %opts = @_;
4517 my $tag = $opts{-tag} || 'div';
4518 my $author = $co->{'author_name'};
4520 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4521 print "<$tag class=\"author_date\">" .
4522 format_search_author($author, "author", esc_html($author)) .
4523 " [".format_timestamp_html(\%ad)."]".
4524 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4525 "</$tag>\n";
4528 # Outputs table rows containing the full author or committer information,
4529 # in the format expected for 'commit' view (& similar).
4530 # Parameters are a commit hash reference, followed by the list of people
4531 # to output information for. If the list is empty it defaults to both
4532 # author and committer.
4533 sub git_print_authorship_rows {
4534 my $co = shift;
4535 # too bad we can't use @people = @_ || ('author', 'committer')
4536 my @people = @_;
4537 @people = ('author', 'committer') unless @people;
4538 foreach my $who (@people) {
4539 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4540 print "<tr><td>$who</td><td>" .
4541 format_search_author($co->{"${who}_name"}, $who,
4542 esc_html($co->{"${who}_name"})) . " " .
4543 format_search_author($co->{"${who}_email"}, $who,
4544 esc_html("<" . $co->{"${who}_email"} . ">")) .
4545 "</td><td rowspan=\"2\">" .
4546 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4547 "</td></tr>\n" .
4548 "<tr>" .
4549 "<td></td><td>" .
4550 format_timestamp_html(\%wd) .
4551 "</td>" .
4552 "</tr>\n";
4556 sub git_print_page_path {
4557 my $name = shift;
4558 my $type = shift;
4559 my $hb = shift;
4562 print "<div class=\"page_path\">";
4563 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4564 -title => 'tree root'}, to_utf8("[$project]"));
4565 print " / ";
4566 if (defined $name) {
4567 my @dirname = split '/', $name;
4568 my $basename = pop @dirname;
4569 my $fullname = '';
4571 foreach my $dir (@dirname) {
4572 $fullname .= ($fullname ? '/' : '') . $dir;
4573 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4574 hash_base=>$hb),
4575 -title => $fullname}, esc_path($dir));
4576 print " / ";
4578 if (defined $type && $type eq 'blob') {
4579 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4580 hash_base=>$hb),
4581 -title => $name}, esc_path($basename));
4582 } elsif (defined $type && $type eq 'tree') {
4583 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4584 hash_base=>$hb),
4585 -title => $name}, esc_path($basename));
4586 print " / ";
4587 } else {
4588 print esc_path($basename);
4591 print "<br/></div>\n";
4594 sub git_print_log {
4595 my $log = shift;
4596 my %opts = @_;
4598 if ($opts{'-remove_title'}) {
4599 # remove title, i.e. first line of log
4600 shift @$log;
4602 # remove leading empty lines
4603 while (defined $log->[0] && $log->[0] eq "") {
4604 shift @$log;
4607 # print log
4608 my $skip_blank_line = 0;
4609 foreach my $line (@$log) {
4610 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4611 if (! $opts{'-remove_signoff'}) {
4612 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4613 $skip_blank_line = 1;
4615 next;
4618 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4619 if (! $opts{'-remove_signoff'}) {
4620 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4621 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4622 "</span><br/>\n";
4623 $skip_blank_line = 1;
4625 next;
4628 # print only one empty line
4629 # do not print empty line after signoff
4630 if ($line eq "") {
4631 next if ($skip_blank_line);
4632 $skip_blank_line = 1;
4633 } else {
4634 $skip_blank_line = 0;
4637 print format_log_line_html($line) . "<br/>\n";
4640 if ($opts{'-final_empty_line'}) {
4641 # end with single empty line
4642 print "<br/>\n" unless $skip_blank_line;
4646 # return link target (what link points to)
4647 sub git_get_link_target {
4648 my $hash = shift;
4649 my $link_target;
4651 # read link
4652 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4653 or return;
4655 local $/ = undef;
4656 $link_target = <$fd>;
4658 close $fd
4659 or return;
4661 return $link_target;
4664 # given link target, and the directory (basedir) the link is in,
4665 # return target of link relative to top directory (top tree);
4666 # return undef if it is not possible (including absolute links).
4667 sub normalize_link_target {
4668 my ($link_target, $basedir) = @_;
4670 # absolute symlinks (beginning with '/') cannot be normalized
4671 return if (substr($link_target, 0, 1) eq '/');
4673 # normalize link target to path from top (root) tree (dir)
4674 my $path;
4675 if ($basedir) {
4676 $path = $basedir . '/' . $link_target;
4677 } else {
4678 # we are in top (root) tree (dir)
4679 $path = $link_target;
4682 # remove //, /./, and /../
4683 my @path_parts;
4684 foreach my $part (split('/', $path)) {
4685 # discard '.' and ''
4686 next if (!$part || $part eq '.');
4687 # handle '..'
4688 if ($part eq '..') {
4689 if (@path_parts) {
4690 pop @path_parts;
4691 } else {
4692 # link leads outside repository (outside top dir)
4693 return;
4695 } else {
4696 push @path_parts, $part;
4699 $path = join('/', @path_parts);
4701 return $path;
4704 # print tree entry (row of git_tree), but without encompassing <tr> element
4705 sub git_print_tree_entry {
4706 my ($t, $basedir, $hash_base, $have_blame) = @_;
4708 my %base_key = ();
4709 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4711 # The format of a table row is: mode list link. Where mode is
4712 # the mode of the entry, list is the name of the entry, an href,
4713 # and link is the action links of the entry.
4715 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4716 if (exists $t->{'size'}) {
4717 print "<td class=\"size\">$t->{'size'}</td>\n";
4719 if ($t->{'type'} eq "blob") {
4720 print "<td class=\"list\">" .
4721 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4722 file_name=>"$basedir$t->{'name'}", %base_key),
4723 -class => "list"}, esc_path($t->{'name'}));
4724 if (S_ISLNK(oct $t->{'mode'})) {
4725 my $link_target = git_get_link_target($t->{'hash'});
4726 if ($link_target) {
4727 my $norm_target = normalize_link_target($link_target, $basedir);
4728 if (defined $norm_target) {
4729 print " -> " .
4730 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4731 file_name=>$norm_target),
4732 -title => $norm_target}, esc_path($link_target));
4733 } else {
4734 print " -> " . esc_path($link_target);
4738 print "</td>\n";
4739 print "<td class=\"link\">";
4740 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4741 file_name=>"$basedir$t->{'name'}", %base_key)},
4742 "blob");
4743 if ($have_blame) {
4744 print " | " .
4745 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4746 file_name=>"$basedir$t->{'name'}", %base_key),
4747 -class => "blamelink"},
4748 "blame");
4750 if (defined $hash_base) {
4751 print " | " .
4752 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4753 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4754 "history");
4756 print " | " .
4757 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4758 file_name=>"$basedir$t->{'name'}")},
4759 "raw");
4760 print "</td>\n";
4762 } elsif ($t->{'type'} eq "tree") {
4763 print "<td class=\"list\">";
4764 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4765 file_name=>"$basedir$t->{'name'}",
4766 %base_key)},
4767 esc_path($t->{'name'}));
4768 print "</td>\n";
4769 print "<td class=\"link\">";
4770 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4771 file_name=>"$basedir$t->{'name'}",
4772 %base_key)},
4773 "tree");
4774 if (defined $hash_base) {
4775 print " | " .
4776 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4777 file_name=>"$basedir$t->{'name'}")},
4778 "history");
4780 print "</td>\n";
4781 } else {
4782 # unknown object: we can only present history for it
4783 # (this includes 'commit' object, i.e. submodule support)
4784 print "<td class=\"list\">" .
4785 esc_path($t->{'name'}) .
4786 "</td>\n";
4787 print "<td class=\"link\">";
4788 if (defined $hash_base) {
4789 print $cgi->a({-href => href(action=>"history",
4790 hash_base=>$hash_base,
4791 file_name=>"$basedir$t->{'name'}")},
4792 "history");
4794 print "</td>\n";
4798 ## ......................................................................
4799 ## functions printing large fragments of HTML
4801 # get pre-image filenames for merge (combined) diff
4802 sub fill_from_file_info {
4803 my ($diff, @parents) = @_;
4805 $diff->{'from_file'} = [ ];
4806 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4807 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4808 if ($diff->{'status'}[$i] eq 'R' ||
4809 $diff->{'status'}[$i] eq 'C') {
4810 $diff->{'from_file'}[$i] =
4811 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4815 return $diff;
4818 # is current raw difftree line of file deletion
4819 sub is_deleted {
4820 my $diffinfo = shift;
4822 return $diffinfo->{'to_id'} eq ('0' x 40);
4825 # does patch correspond to [previous] difftree raw line
4826 # $diffinfo - hashref of parsed raw diff format
4827 # $patchinfo - hashref of parsed patch diff format
4828 # (the same keys as in $diffinfo)
4829 sub is_patch_split {
4830 my ($diffinfo, $patchinfo) = @_;
4832 return defined $diffinfo && defined $patchinfo
4833 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4837 sub git_difftree_body {
4838 my ($difftree, $hash, @parents) = @_;
4839 my ($parent) = $parents[0];
4840 my $have_blame = gitweb_check_feature('blame');
4841 print "<div class=\"list_head\">\n";
4842 if ($#{$difftree} > 10) {
4843 print(($#{$difftree} + 1) . " files changed:\n");
4845 print "</div>\n";
4847 print "<table class=\"" .
4848 (@parents > 1 ? "combined " : "") .
4849 "diff_tree\">\n";
4851 # header only for combined diff in 'commitdiff' view
4852 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4853 if ($has_header) {
4854 # table header
4855 print "<thead><tr>\n" .
4856 "<th></th><th></th>\n"; # filename, patchN link
4857 for (my $i = 0; $i < @parents; $i++) {
4858 my $par = $parents[$i];
4859 print "<th>" .
4860 $cgi->a({-href => href(action=>"commitdiff",
4861 hash=>$hash, hash_parent=>$par),
4862 -title => 'commitdiff to parent number ' .
4863 ($i+1) . ': ' . substr($par,0,7)},
4864 $i+1) .
4865 "&nbsp;</th>\n";
4867 print "</tr></thead>\n<tbody>\n";
4870 my $alternate = 1;
4871 my $patchno = 0;
4872 foreach my $line (@{$difftree}) {
4873 my $diff = parsed_difftree_line($line);
4875 if ($alternate) {
4876 print "<tr class=\"dark\">\n";
4877 } else {
4878 print "<tr class=\"light\">\n";
4880 $alternate ^= 1;
4882 if (exists $diff->{'nparents'}) { # combined diff
4884 fill_from_file_info($diff, @parents)
4885 unless exists $diff->{'from_file'};
4887 if (!is_deleted($diff)) {
4888 # file exists in the result (child) commit
4889 print "<td>" .
4890 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4891 file_name=>$diff->{'to_file'},
4892 hash_base=>$hash),
4893 -class => "list"}, esc_path($diff->{'to_file'})) .
4894 "</td>\n";
4895 } else {
4896 print "<td>" .
4897 esc_path($diff->{'to_file'}) .
4898 "</td>\n";
4901 if ($action eq 'commitdiff') {
4902 # link to patch
4903 $patchno++;
4904 print "<td class=\"link\">" .
4905 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4906 "patch") .
4907 " | " .
4908 "</td>\n";
4911 my $has_history = 0;
4912 my $not_deleted = 0;
4913 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4914 my $hash_parent = $parents[$i];
4915 my $from_hash = $diff->{'from_id'}[$i];
4916 my $from_path = $diff->{'from_file'}[$i];
4917 my $status = $diff->{'status'}[$i];
4919 $has_history ||= ($status ne 'A');
4920 $not_deleted ||= ($status ne 'D');
4922 if ($status eq 'A') {
4923 print "<td class=\"link\" align=\"right\"> | </td>\n";
4924 } elsif ($status eq 'D') {
4925 print "<td class=\"link\">" .
4926 $cgi->a({-href => href(action=>"blob",
4927 hash_base=>$hash,
4928 hash=>$from_hash,
4929 file_name=>$from_path)},
4930 "blob" . ($i+1)) .
4931 " | </td>\n";
4932 } else {
4933 if ($diff->{'to_id'} eq $from_hash) {
4934 print "<td class=\"link nochange\">";
4935 } else {
4936 print "<td class=\"link\">";
4938 print $cgi->a({-href => href(action=>"blobdiff",
4939 hash=>$diff->{'to_id'},
4940 hash_parent=>$from_hash,
4941 hash_base=>$hash,
4942 hash_parent_base=>$hash_parent,
4943 file_name=>$diff->{'to_file'},
4944 file_parent=>$from_path)},
4945 "diff" . ($i+1)) .
4946 " | </td>\n";
4950 print "<td class=\"link\">";
4951 if ($not_deleted) {
4952 print $cgi->a({-href => href(action=>"blob",
4953 hash=>$diff->{'to_id'},
4954 file_name=>$diff->{'to_file'},
4955 hash_base=>$hash)},
4956 "blob");
4957 print " | " if ($has_history);
4959 if ($has_history) {
4960 print $cgi->a({-href => href(action=>"history",
4961 file_name=>$diff->{'to_file'},
4962 hash_base=>$hash)},
4963 "history");
4965 print "</td>\n";
4967 print "</tr>\n";
4968 next; # instead of 'else' clause, to avoid extra indent
4970 # else ordinary diff
4972 my ($to_mode_oct, $to_mode_str, $to_file_type);
4973 my ($from_mode_oct, $from_mode_str, $from_file_type);
4974 if ($diff->{'to_mode'} ne ('0' x 6)) {
4975 $to_mode_oct = oct $diff->{'to_mode'};
4976 if (S_ISREG($to_mode_oct)) { # only for regular file
4977 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4979 $to_file_type = file_type($diff->{'to_mode'});
4981 if ($diff->{'from_mode'} ne ('0' x 6)) {
4982 $from_mode_oct = oct $diff->{'from_mode'};
4983 if (S_ISREG($from_mode_oct)) { # only for regular file
4984 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4986 $from_file_type = file_type($diff->{'from_mode'});
4989 if ($diff->{'status'} eq "A") { # created
4990 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4991 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4992 $mode_chng .= "]</span>";
4993 print "<td>";
4994 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4995 hash_base=>$hash, file_name=>$diff->{'file'}),
4996 -class => "list"}, esc_path($diff->{'file'}));
4997 print "</td>\n";
4998 print "<td>$mode_chng</td>\n";
4999 print "<td class=\"link\">";
5000 if ($action eq 'commitdiff') {
5001 # link to patch
5002 $patchno++;
5003 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5004 "patch") .
5005 " | ";
5007 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5008 hash_base=>$hash, file_name=>$diff->{'file'})},
5009 "blob");
5010 print "</td>\n";
5012 } elsif ($diff->{'status'} eq "D") { # deleted
5013 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5014 print "<td>";
5015 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5016 hash_base=>$parent, file_name=>$diff->{'file'}),
5017 -class => "list"}, esc_path($diff->{'file'}));
5018 print "</td>\n";
5019 print "<td>$mode_chng</td>\n";
5020 print "<td class=\"link\">";
5021 if ($action eq 'commitdiff') {
5022 # link to patch
5023 $patchno++;
5024 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5025 "patch") .
5026 " | ";
5028 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5029 hash_base=>$parent, file_name=>$diff->{'file'})},
5030 "blob") . " | ";
5031 if ($have_blame) {
5032 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5033 file_name=>$diff->{'file'}),
5034 -class => "blamelink"},
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 -class => "blamelink"},
5087 "blame") . " | ";
5089 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5090 file_name=>$diff->{'file'})},
5091 "history");
5092 print "</td>\n";
5094 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5095 my %status_name = ('R' => 'moved', 'C' => 'copied');
5096 my $nstatus = $status_name{$diff->{'status'}};
5097 my $mode_chng = "";
5098 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5099 # mode also for directories, so we cannot use $to_mode_str
5100 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5102 print "<td>" .
5103 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5104 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5105 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5106 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5107 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5108 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5109 -class => "list"}, esc_path($diff->{'from_file'})) .
5110 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5111 "<td class=\"link\">";
5112 if ($action eq 'commitdiff') {
5113 # link to patch
5114 $patchno++;
5115 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5116 "patch") .
5117 " | ";
5118 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5119 # "commit" view and modified file (not only pure rename or copy)
5120 print $cgi->a({-href => href(action=>"blobdiff",
5121 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5122 hash_base=>$hash, hash_parent_base=>$parent,
5123 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5124 "diff") .
5125 " | ";
5127 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5128 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5129 "blob") . " | ";
5130 if ($have_blame) {
5131 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5132 file_name=>$diff->{'to_file'}),
5133 -class => "blamelink"},
5134 "blame") . " | ";
5136 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5137 file_name=>$diff->{'to_file'})},
5138 "history");
5139 print "</td>\n";
5141 } # we should not encounter Unmerged (U) or Unknown (X) status
5142 print "</tr>\n";
5144 print "</tbody>" if $has_header;
5145 print "</table>\n";
5148 # Print context lines and then rem/add lines in a side-by-side manner.
5149 sub print_sidebyside_diff_lines {
5150 my ($ctx, $rem, $add) = @_;
5152 # print context block before add/rem block
5153 if (@$ctx) {
5154 print join '',
5155 '<div class="chunk_block ctx">',
5156 '<div class="old">',
5157 @$ctx,
5158 '</div>',
5159 '<div class="new">',
5160 @$ctx,
5161 '</div>',
5162 '</div>';
5165 if (!@$add) {
5166 # pure removal
5167 print join '',
5168 '<div class="chunk_block rem">',
5169 '<div class="old">',
5170 @$rem,
5171 '</div>',
5172 '</div>';
5173 } elsif (!@$rem) {
5174 # pure addition
5175 print join '',
5176 '<div class="chunk_block add">',
5177 '<div class="new">',
5178 @$add,
5179 '</div>',
5180 '</div>';
5181 } else {
5182 print join '',
5183 '<div class="chunk_block chg">',
5184 '<div class="old">',
5185 @$rem,
5186 '</div>',
5187 '<div class="new">',
5188 @$add,
5189 '</div>',
5190 '</div>';
5194 # Print context lines and then rem/add lines in inline manner.
5195 sub print_inline_diff_lines {
5196 my ($ctx, $rem, $add) = @_;
5198 print @$ctx, @$rem, @$add;
5201 # Format removed and added line, mark changed part and HTML-format them.
5202 # Implementation is based on contrib/diff-highlight
5203 sub format_rem_add_lines_pair {
5204 my ($rem, $add, $num_parents) = @_;
5206 # We need to untabify lines before split()'ing them;
5207 # otherwise offsets would be invalid.
5208 chomp $rem;
5209 chomp $add;
5210 $rem = untabify($rem);
5211 $add = untabify($add);
5213 my @rem = split(//, $rem);
5214 my @add = split(//, $add);
5215 my ($esc_rem, $esc_add);
5216 # Ignore leading +/- characters for each parent.
5217 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5218 my ($prefix_has_nonspace, $suffix_has_nonspace);
5220 my $shorter = (@rem < @add) ? @rem : @add;
5221 while ($prefix_len < $shorter) {
5222 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5224 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5225 $prefix_len++;
5228 while ($prefix_len + $suffix_len < $shorter) {
5229 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5231 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5232 $suffix_len++;
5235 # Mark lines that are different from each other, but have some common
5236 # part that isn't whitespace. If lines are completely different, don't
5237 # mark them because that would make output unreadable, especially if
5238 # diff consists of multiple lines.
5239 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5240 $esc_rem = esc_html_hl_regions($rem, 'marked',
5241 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5242 $esc_add = esc_html_hl_regions($add, 'marked',
5243 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5244 } else {
5245 $esc_rem = esc_html($rem, -nbsp=>1);
5246 $esc_add = esc_html($add, -nbsp=>1);
5249 return format_diff_line(\$esc_rem, 'rem'),
5250 format_diff_line(\$esc_add, 'add');
5253 # HTML-format diff context, removed and added lines.
5254 sub format_ctx_rem_add_lines {
5255 my ($ctx, $rem, $add, $num_parents) = @_;
5256 my (@new_ctx, @new_rem, @new_add);
5257 my $can_highlight = 0;
5258 my $is_combined = ($num_parents > 1);
5260 # Highlight if every removed line has a corresponding added line.
5261 if (@$add > 0 && @$add == @$rem) {
5262 $can_highlight = 1;
5264 # Highlight lines in combined diff only if the chunk contains
5265 # diff between the same version, e.g.
5267 # - a
5268 # - b
5269 # + c
5270 # + d
5272 # Otherwise the highlightling would be confusing.
5273 if ($is_combined) {
5274 for (my $i = 0; $i < @$add; $i++) {
5275 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5276 my $prefix_add = substr($add->[$i], 0, $num_parents);
5278 $prefix_rem =~ s/-/+/g;
5280 if ($prefix_rem ne $prefix_add) {
5281 $can_highlight = 0;
5282 last;
5288 if ($can_highlight) {
5289 for (my $i = 0; $i < @$add; $i++) {
5290 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5291 $rem->[$i], $add->[$i], $num_parents);
5292 push @new_rem, $line_rem;
5293 push @new_add, $line_add;
5295 } else {
5296 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5297 @new_add = map { format_diff_line($_, 'add') } @$add;
5300 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5302 return (\@new_ctx, \@new_rem, \@new_add);
5305 # Print context lines and then rem/add lines.
5306 sub print_diff_lines {
5307 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5308 my $is_combined = $num_parents > 1;
5310 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5311 $num_parents);
5313 if ($diff_style eq 'sidebyside' && !$is_combined) {
5314 print_sidebyside_diff_lines($ctx, $rem, $add);
5315 } else {
5316 # default 'inline' style and unknown styles
5317 print_inline_diff_lines($ctx, $rem, $add);
5321 sub print_diff_chunk {
5322 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5323 my (@ctx, @rem, @add);
5325 # The class of the previous line.
5326 my $prev_class = '';
5328 return unless @chunk;
5330 # incomplete last line might be among removed or added lines,
5331 # or both, or among context lines: find which
5332 for (my $i = 1; $i < @chunk; $i++) {
5333 if ($chunk[$i][0] eq 'incomplete') {
5334 $chunk[$i][0] = $chunk[$i-1][0];
5338 # guardian
5339 push @chunk, ["", ""];
5341 foreach my $line_info (@chunk) {
5342 my ($class, $line) = @$line_info;
5344 # print chunk headers
5345 if ($class && $class eq 'chunk_header') {
5346 print format_diff_line($line, $class, $from, $to);
5347 next;
5350 ## print from accumulator when have some add/rem lines or end
5351 # of chunk (flush context lines), or when have add and rem
5352 # lines and new block is reached (otherwise add/rem lines could
5353 # be reordered)
5354 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5355 (@rem && @add && $class ne $prev_class)) {
5356 print_diff_lines(\@ctx, \@rem, \@add,
5357 $diff_style, $num_parents);
5358 @ctx = @rem = @add = ();
5361 ## adding lines to accumulator
5362 # guardian value
5363 last unless $line;
5364 # rem, add or change
5365 if ($class eq 'rem') {
5366 push @rem, $line;
5367 } elsif ($class eq 'add') {
5368 push @add, $line;
5370 # context line
5371 if ($class eq 'ctx') {
5372 push @ctx, $line;
5375 $prev_class = $class;
5379 sub git_patchset_body {
5380 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5381 my ($hash_parent) = $hash_parents[0];
5383 my $is_combined = (@hash_parents > 1);
5384 my $patch_idx = 0;
5385 my $patch_number = 0;
5386 my $patch_line;
5387 my $diffinfo;
5388 my $to_name;
5389 my (%from, %to);
5390 my @chunk; # for side-by-side diff
5392 print "<div class=\"patchset\">\n";
5394 # skip to first patch
5395 while ($patch_line = <$fd>) {
5396 chomp $patch_line;
5398 last if ($patch_line =~ m/^diff /);
5401 PATCH:
5402 while ($patch_line) {
5404 # parse "git diff" header line
5405 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5406 # $1 is from_name, which we do not use
5407 $to_name = unquote($2);
5408 $to_name =~ s!^b/!!;
5409 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5410 # $1 is 'cc' or 'combined', which we do not use
5411 $to_name = unquote($2);
5412 } else {
5413 $to_name = undef;
5416 # check if current patch belong to current raw line
5417 # and parse raw git-diff line if needed
5418 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5419 # this is continuation of a split patch
5420 print "<div class=\"patch cont\">\n";
5421 } else {
5422 # advance raw git-diff output if needed
5423 $patch_idx++ if defined $diffinfo;
5425 # read and prepare patch information
5426 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5428 # compact combined diff output can have some patches skipped
5429 # find which patch (using pathname of result) we are at now;
5430 if ($is_combined) {
5431 while ($to_name ne $diffinfo->{'to_file'}) {
5432 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5433 format_diff_cc_simplified($diffinfo, @hash_parents) .
5434 "</div>\n"; # class="patch"
5436 $patch_idx++;
5437 $patch_number++;
5439 last if $patch_idx > $#$difftree;
5440 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5444 # modifies %from, %to hashes
5445 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5447 # this is first patch for raw difftree line with $patch_idx index
5448 # we index @$difftree array from 0, but number patches from 1
5449 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5452 # git diff header
5453 #assert($patch_line =~ m/^diff /) if DEBUG;
5454 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5455 $patch_number++;
5456 # print "git diff" header
5457 print format_git_diff_header_line($patch_line, $diffinfo,
5458 \%from, \%to);
5460 # print extended diff header
5461 print "<div class=\"diff extended_header\">\n";
5462 EXTENDED_HEADER:
5463 while ($patch_line = <$fd>) {
5464 chomp $patch_line;
5466 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5468 print format_extended_diff_header_line($patch_line, $diffinfo,
5469 \%from, \%to);
5471 print "</div>\n"; # class="diff extended_header"
5473 # from-file/to-file diff header
5474 if (! $patch_line) {
5475 print "</div>\n"; # class="patch"
5476 last PATCH;
5478 next PATCH if ($patch_line =~ m/^diff /);
5479 #assert($patch_line =~ m/^---/) if DEBUG;
5481 my $last_patch_line = $patch_line;
5482 $patch_line = <$fd>;
5483 chomp $patch_line;
5484 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5486 print format_diff_from_to_header($last_patch_line, $patch_line,
5487 $diffinfo, \%from, \%to,
5488 @hash_parents);
5490 # the patch itself
5491 LINE:
5492 while ($patch_line = <$fd>) {
5493 chomp $patch_line;
5495 next PATCH if ($patch_line =~ m/^diff /);
5497 my $class = diff_line_class($patch_line, \%from, \%to);
5499 if ($class eq 'chunk_header') {
5500 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5501 @chunk = ();
5504 push @chunk, [ $class, $patch_line ];
5507 } continue {
5508 if (@chunk) {
5509 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5510 @chunk = ();
5512 print "</div>\n"; # class="patch"
5515 # for compact combined (--cc) format, with chunk and patch simplification
5516 # the patchset might be empty, but there might be unprocessed raw lines
5517 for (++$patch_idx if $patch_number > 0;
5518 $patch_idx < @$difftree;
5519 ++$patch_idx) {
5520 # read and prepare patch information
5521 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5523 # generate anchor for "patch" links in difftree / whatchanged part
5524 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5525 format_diff_cc_simplified($diffinfo, @hash_parents) .
5526 "</div>\n"; # class="patch"
5528 $patch_number++;
5531 if ($patch_number == 0) {
5532 if (@hash_parents > 1) {
5533 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5534 } else {
5535 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5539 print "</div>\n"; # class="patchset"
5542 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5544 sub git_project_search_form {
5545 my ($searchtext, $search_use_regexp) = @_;
5547 my $limit = '';
5548 if ($project_filter) {
5549 $limit = " in '$project_filter/'";
5552 print "<div class=\"projsearch\">\n";
5553 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5554 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5555 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5556 if (defined $project_filter);
5557 print $cgi->textfield(-name => 's', -value => $searchtext,
5558 -title => "Search project by name and description$limit",
5559 -size => 60) . "\n" .
5560 "<span title=\"Extended regular expression\">" .
5561 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5562 -checked => $search_use_regexp) .
5563 "</span>\n" .
5564 $cgi->submit(-name => 'btnS', -value => 'Search') .
5565 $cgi->end_form() . "\n" .
5566 $cgi->a({-href => href(project => undef, searchtext => undef,
5567 project_filter => $project_filter)},
5568 esc_html("List all projects$limit")) . "<br />\n";
5569 print "</div>\n";
5572 # entry for given @keys needs filling if at least one of keys in list
5573 # is not present in %$project_info
5574 sub project_info_needs_filling {
5575 my ($project_info, @keys) = @_;
5577 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5578 foreach my $key (@keys) {
5579 if (!exists $project_info->{$key}) {
5580 return 1;
5583 return;
5586 # fills project list info (age, description, owner, category, forks, etc.)
5587 # for each project in the list, removing invalid projects from
5588 # returned list, or fill only specified info.
5590 # Invalid projects are removed from the returned list if and only if you
5591 # ask 'age' or 'age_string' to be filled, because they are the only fields
5592 # that run unconditionally git command that requires repository, and
5593 # therefore do always check if project repository is invalid.
5595 # USAGE:
5596 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5597 # ensures that 'descr_long' and 'ctags' fields are filled
5598 # * @project_list = fill_project_list_info(\@project_list)
5599 # ensures that all fields are filled (and invalid projects removed)
5601 # NOTE: modifies $projlist, but does not remove entries from it
5602 sub fill_project_list_info {
5603 my ($projlist, @wanted_keys) = @_;
5604 my @projects;
5605 my $filter_set = sub { return @_; };
5606 if (@wanted_keys) {
5607 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5608 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5611 my $show_ctags = gitweb_check_feature('ctags');
5612 PROJECT:
5613 foreach my $pr (@$projlist) {
5614 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5615 my (@activity) = git_get_last_activity($pr->{'path'});
5616 unless (@activity) {
5617 next PROJECT;
5619 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5621 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5622 my $descr = git_get_project_description($pr->{'path'}) || "";
5623 $descr = to_utf8($descr);
5624 $pr->{'descr_long'} = $descr;
5625 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5627 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5628 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5630 if ($show_ctags &&
5631 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5632 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5634 if ($projects_list_group_categories &&
5635 project_info_needs_filling($pr, $filter_set->('category'))) {
5636 my $cat = git_get_project_category($pr->{'path'}) ||
5637 $project_list_default_category;
5638 $pr->{'category'} = to_utf8($cat);
5641 push @projects, $pr;
5644 return @projects;
5647 sub sort_projects_list {
5648 my ($projlist, $order) = @_;
5650 sub order_str {
5651 my $key = shift;
5652 return sub { $a->{$key} cmp $b->{$key} };
5655 sub order_num_then_undef {
5656 my $key = shift;
5657 return sub {
5658 defined $a->{$key} ?
5659 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5660 (defined $b->{$key} ? 1 : 0)
5664 my %orderings = (
5665 project => order_str('path'),
5666 descr => order_str('descr_long'),
5667 owner => order_str('owner'),
5668 age => order_num_then_undef('age'),
5671 my $ordering = $orderings{$order};
5672 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5675 # returns a hash of categories, containing the list of project
5676 # belonging to each category
5677 sub build_projlist_by_category {
5678 my ($projlist, $from, $to) = @_;
5679 my %categories;
5681 $from = 0 unless defined $from;
5682 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5684 for (my $i = $from; $i <= $to; $i++) {
5685 my $pr = $projlist->[$i];
5686 push @{$categories{ $pr->{'category'} }}, $pr;
5689 return wantarray ? %categories : \%categories;
5692 # print 'sort by' <th> element, generating 'sort by $name' replay link
5693 # if that order is not selected
5694 sub print_sort_th {
5695 print format_sort_th(@_);
5698 sub format_sort_th {
5699 my ($name, $order, $header) = @_;
5700 my $sort_th = "";
5701 $header ||= ucfirst($name);
5703 if ($order eq $name) {
5704 $sort_th .= "<th>$header</th>\n";
5705 } else {
5706 $sort_th .= "<th>" .
5707 $cgi->a({-href => href(-replay=>1, order=>$name),
5708 -class => "header"}, $header) .
5709 "</th>\n";
5712 return $sort_th;
5715 sub git_project_list_rows {
5716 my ($projlist, $from, $to, $check_forks) = @_;
5718 $from = 0 unless defined $from;
5719 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5721 my $alternate = 1;
5722 for (my $i = $from; $i <= $to; $i++) {
5723 my $pr = $projlist->[$i];
5725 if ($alternate) {
5726 print "<tr class=\"dark\">\n";
5727 } else {
5728 print "<tr class=\"light\">\n";
5730 $alternate ^= 1;
5732 if ($check_forks) {
5733 print "<td>";
5734 if ($pr->{'forks'}) {
5735 my $nforks = scalar @{$pr->{'forks'}};
5736 if ($nforks > 0) {
5737 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5738 -title => "$nforks forks"}, "+");
5739 } else {
5740 print $cgi->span({-title => "$nforks forks"}, "+");
5743 print "</td>\n";
5745 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5746 -class => "list"},
5747 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5748 "</td>\n" .
5749 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5750 -class => "list",
5751 -title => $pr->{'descr_long'}},
5752 $search_regexp
5753 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5754 $pr->{'descr'}, $search_regexp)
5755 : esc_html($pr->{'descr'})) .
5756 "</td>\n";
5757 unless ($omit_owner) {
5758 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5760 unless ($omit_age_column) {
5761 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5762 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5764 print"<td class=\"link\">" .
5765 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5766 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5767 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5768 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5769 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5770 "</td>\n" .
5771 "</tr>\n";
5775 sub git_project_list_body {
5776 # actually uses global variable $project
5777 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5778 my @projects = @$projlist;
5780 my $check_forks = gitweb_check_feature('forks');
5781 my $show_ctags = gitweb_check_feature('ctags');
5782 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5783 $check_forks = undef
5784 if ($tagfilter || $search_regexp);
5786 # filtering out forks before filling info allows to do less work
5787 @projects = filter_forks_from_projects_list(\@projects)
5788 if ($check_forks);
5789 # search_projects_list pre-fills required info
5790 @projects = search_projects_list(\@projects,
5791 'search_regexp' => $search_regexp,
5792 'tagfilter' => $tagfilter)
5793 if ($tagfilter || $search_regexp);
5794 # fill the rest
5795 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5796 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5797 push @all_fields, 'owner' unless($omit_owner);
5798 @projects = fill_project_list_info(\@projects, @all_fields);
5800 $order ||= $default_projects_order;
5801 $from = 0 unless defined $from;
5802 $to = $#projects if (!defined $to || $#projects < $to);
5804 # short circuit
5805 if ($from > $to) {
5806 print "<center>\n".
5807 "<b>No such projects found</b><br />\n".
5808 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5809 "</center>\n<br />\n";
5810 return;
5813 @projects = sort_projects_list(\@projects, $order);
5815 if ($show_ctags) {
5816 my $ctags = git_gather_all_ctags(\@projects);
5817 my $cloud = git_populate_project_tagcloud($ctags);
5818 print git_show_project_tagcloud($cloud, 64);
5821 print "<table class=\"project_list\">\n";
5822 unless ($no_header) {
5823 print "<tr>\n";
5824 if ($check_forks) {
5825 print "<th></th>\n";
5827 print_sort_th('project', $order, 'Project');
5828 print_sort_th('descr', $order, 'Description');
5829 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5830 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5831 print "<th></th>\n" . # for links
5832 "</tr>\n";
5835 if ($projects_list_group_categories) {
5836 # only display categories with projects in the $from-$to window
5837 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5838 my %categories = build_projlist_by_category(\@projects, $from, $to);
5839 foreach my $cat (sort keys %categories) {
5840 unless ($cat eq "") {
5841 print "<tr>\n";
5842 if ($check_forks) {
5843 print "<td></td>\n";
5845 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5846 print "</tr>\n";
5849 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5851 } else {
5852 git_project_list_rows(\@projects, $from, $to, $check_forks);
5855 if (defined $extra) {
5856 print "<tr>\n";
5857 if ($check_forks) {
5858 print "<td></td>\n";
5860 print "<td colspan=\"5\">$extra</td>\n" .
5861 "</tr>\n";
5863 print "</table>\n";
5866 sub git_log_body {
5867 # uses global variable $project
5868 my ($commitlist, $from, $to, $refs, $extra) = @_;
5870 $from = 0 unless defined $from;
5871 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5873 for (my $i = 0; $i <= $to; $i++) {
5874 my %co = %{$commitlist->[$i]};
5875 next if !%co;
5876 my $commit = $co{'id'};
5877 my $ref = format_ref_marker($refs, $commit);
5878 git_print_header_div('commit',
5879 "<span class=\"age\">$co{'age_string'}</span>" .
5880 esc_html($co{'title'}) . $ref,
5881 $commit);
5882 print "<div class=\"title_text\">\n" .
5883 "<div class=\"log_link\">\n" .
5884 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5885 " | " .
5886 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5887 " | " .
5888 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5889 "<br/>\n" .
5890 "</div>\n";
5891 git_print_authorship(\%co, -tag => 'span');
5892 print "<br/>\n</div>\n";
5894 print "<div class=\"log_body\">\n";
5895 git_print_log($co{'comment'}, -final_empty_line=> 1);
5896 print "</div>\n";
5898 if ($extra) {
5899 print "<div class=\"page_nav\">\n";
5900 print "$extra\n";
5901 print "</div>\n";
5905 sub git_shortlog_body {
5906 # uses global variable $project
5907 my ($commitlist, $from, $to, $refs, $extra) = @_;
5909 $from = 0 unless defined $from;
5910 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5912 print "<table class=\"shortlog\">\n";
5913 my $alternate = 1;
5914 for (my $i = $from; $i <= $to; $i++) {
5915 my %co = %{$commitlist->[$i]};
5916 my $commit = $co{'id'};
5917 my $ref = format_ref_marker($refs, $commit);
5918 if ($alternate) {
5919 print "<tr class=\"dark\">\n";
5920 } else {
5921 print "<tr class=\"light\">\n";
5923 $alternate ^= 1;
5924 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5925 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5926 format_author_html('td', \%co, 10) . "<td>";
5927 print format_subject_html($co{'title'}, $co{'title_short'},
5928 href(action=>"commit", hash=>$commit), $ref);
5929 print "</td>\n" .
5930 "<td class=\"link\">" .
5931 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5932 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5933 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5934 my $snapshot_links = format_snapshot_links($commit);
5935 if (defined $snapshot_links) {
5936 print " | " . $snapshot_links;
5938 print "</td>\n" .
5939 "</tr>\n";
5941 if (defined $extra) {
5942 print "<tr>\n" .
5943 "<td colspan=\"4\">$extra</td>\n" .
5944 "</tr>\n";
5946 print "</table>\n";
5949 sub git_history_body {
5950 # Warning: assumes constant type (blob or tree) during history
5951 my ($commitlist, $from, $to, $refs, $extra,
5952 $file_name, $file_hash, $ftype) = @_;
5954 $from = 0 unless defined $from;
5955 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5957 print "<table class=\"history\">\n";
5958 my $alternate = 1;
5959 for (my $i = $from; $i <= $to; $i++) {
5960 my %co = %{$commitlist->[$i]};
5961 if (!%co) {
5962 next;
5964 my $commit = $co{'id'};
5966 my $ref = format_ref_marker($refs, $commit);
5968 if ($alternate) {
5969 print "<tr class=\"dark\">\n";
5970 } else {
5971 print "<tr class=\"light\">\n";
5973 $alternate ^= 1;
5974 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5975 # shortlog: format_author_html('td', \%co, 10)
5976 format_author_html('td', \%co, 15, 3) . "<td>";
5977 # originally git_history used chop_str($co{'title'}, 50)
5978 print format_subject_html($co{'title'}, $co{'title_short'},
5979 href(action=>"commit", hash=>$commit), $ref);
5980 print "</td>\n" .
5981 "<td class=\"link\">" .
5982 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5983 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5985 if ($ftype eq 'blob') {
5986 my $blob_current = $file_hash;
5987 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5988 if (defined $blob_current && defined $blob_parent &&
5989 $blob_current ne $blob_parent) {
5990 print " | " .
5991 $cgi->a({-href => href(action=>"blobdiff",
5992 hash=>$blob_current, hash_parent=>$blob_parent,
5993 hash_base=>$hash_base, hash_parent_base=>$commit,
5994 file_name=>$file_name)},
5995 "diff to current");
5998 print "</td>\n" .
5999 "</tr>\n";
6001 if (defined $extra) {
6002 print "<tr>\n" .
6003 "<td colspan=\"4\">$extra</td>\n" .
6004 "</tr>\n";
6006 print "</table>\n";
6009 sub git_tags_body {
6010 # uses global variable $project
6011 my ($taglist, $from, $to, $extra) = @_;
6012 $from = 0 unless defined $from;
6013 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6015 print "<table class=\"tags\">\n";
6016 my $alternate = 1;
6017 for (my $i = $from; $i <= $to; $i++) {
6018 my $entry = $taglist->[$i];
6019 my %tag = %$entry;
6020 my $comment = $tag{'subject'};
6021 my $comment_short;
6022 if (defined $comment) {
6023 $comment_short = chop_str($comment, 30, 5);
6025 if ($alternate) {
6026 print "<tr class=\"dark\">\n";
6027 } else {
6028 print "<tr class=\"light\">\n";
6030 $alternate ^= 1;
6031 if (defined $tag{'age'}) {
6032 print "<td><i>$tag{'age'}</i></td>\n";
6033 } else {
6034 print "<td></td>\n";
6036 print "<td>" .
6037 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6038 -class => "list name"}, esc_html($tag{'name'})) .
6039 "</td>\n" .
6040 "<td>";
6041 if (defined $comment) {
6042 print format_subject_html($comment, $comment_short,
6043 href(action=>"tag", hash=>$tag{'id'}));
6045 print "</td>\n" .
6046 "<td class=\"selflink\">";
6047 if ($tag{'type'} eq "tag") {
6048 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6049 } else {
6050 print "&nbsp;";
6052 print "</td>\n" .
6053 "<td class=\"link\">" . " | " .
6054 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6055 if ($tag{'reftype'} eq "commit") {
6056 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6057 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6058 } elsif ($tag{'reftype'} eq "blob") {
6059 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6061 print "</td>\n" .
6062 "</tr>";
6064 if (defined $extra) {
6065 print "<tr>\n" .
6066 "<td colspan=\"5\">$extra</td>\n" .
6067 "</tr>\n";
6069 print "</table>\n";
6072 sub git_heads_body {
6073 # uses global variable $project
6074 my ($headlist, $head_at, $from, $to, $extra) = @_;
6075 $from = 0 unless defined $from;
6076 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6078 print "<table class=\"heads\">\n";
6079 my $alternate = 1;
6080 for (my $i = $from; $i <= $to; $i++) {
6081 my $entry = $headlist->[$i];
6082 my %ref = %$entry;
6083 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6084 if ($alternate) {
6085 print "<tr class=\"dark\">\n";
6086 } else {
6087 print "<tr class=\"light\">\n";
6089 $alternate ^= 1;
6090 print "<td><i>$ref{'age'}</i></td>\n" .
6091 ($curr ? "<td class=\"current_head\">" : "<td>") .
6092 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6093 -class => "list name"},esc_html($ref{'name'})) .
6094 "</td>\n" .
6095 "<td class=\"link\">" .
6096 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6097 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6098 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6099 "</td>\n" .
6100 "</tr>";
6102 if (defined $extra) {
6103 print "<tr>\n" .
6104 "<td colspan=\"3\">$extra</td>\n" .
6105 "</tr>\n";
6107 print "</table>\n";
6110 # Display a single remote block
6111 sub git_remote_block {
6112 my ($remote, $rdata, $limit, $head) = @_;
6114 my $heads = $rdata->{'heads'};
6115 my $fetch = $rdata->{'fetch'};
6116 my $push = $rdata->{'push'};
6118 my $urls_table = "<table class=\"projects_list\">\n" ;
6120 if (defined $fetch) {
6121 if ($fetch eq $push) {
6122 $urls_table .= format_repo_url("URL", $fetch);
6123 } else {
6124 $urls_table .= format_repo_url("Fetch URL", $fetch);
6125 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6127 } elsif (defined $push) {
6128 $urls_table .= format_repo_url("Push URL", $push);
6129 } else {
6130 $urls_table .= format_repo_url("", "No remote URL");
6133 $urls_table .= "</table>\n";
6135 my $dots;
6136 if (defined $limit && $limit < @$heads) {
6137 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6140 print $urls_table;
6141 git_heads_body($heads, $head, 0, $limit, $dots);
6144 # Display a list of remote names with the respective fetch and push URLs
6145 sub git_remotes_list {
6146 my ($remotedata, $limit) = @_;
6147 print "<table class=\"heads\">\n";
6148 my $alternate = 1;
6149 my @remotes = sort keys %$remotedata;
6151 my $limited = $limit && $limit < @remotes;
6153 $#remotes = $limit - 1 if $limited;
6155 while (my $remote = shift @remotes) {
6156 my $rdata = $remotedata->{$remote};
6157 my $fetch = $rdata->{'fetch'};
6158 my $push = $rdata->{'push'};
6159 if ($alternate) {
6160 print "<tr class=\"dark\">\n";
6161 } else {
6162 print "<tr class=\"light\">\n";
6164 $alternate ^= 1;
6165 print "<td>" .
6166 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6167 -class=> "list name"},esc_html($remote)) .
6168 "</td>";
6169 print "<td class=\"link\">" .
6170 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6171 " | " .
6172 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6173 "</td>";
6175 print "</tr>\n";
6178 if ($limited) {
6179 print "<tr>\n" .
6180 "<td colspan=\"3\">" .
6181 $cgi->a({-href => href(action=>"remotes")}, "...") .
6182 "</td>\n" . "</tr>\n";
6185 print "</table>";
6188 # Display remote heads grouped by remote, unless there are too many
6189 # remotes, in which case we only display the remote names
6190 sub git_remotes_body {
6191 my ($remotedata, $limit, $head) = @_;
6192 if ($limit and $limit < keys %$remotedata) {
6193 git_remotes_list($remotedata, $limit);
6194 } else {
6195 fill_remote_heads($remotedata);
6196 while (my ($remote, $rdata) = each %$remotedata) {
6197 git_print_section({-class=>"remote", -id=>$remote},
6198 ["remotes", $remote, $remote], sub {
6199 git_remote_block($remote, $rdata, $limit, $head);
6205 sub git_search_message {
6206 my %co = @_;
6208 my $greptype;
6209 if ($searchtype eq 'commit') {
6210 $greptype = "--grep=";
6211 } elsif ($searchtype eq 'author') {
6212 $greptype = "--author=";
6213 } elsif ($searchtype eq 'committer') {
6214 $greptype = "--committer=";
6216 $greptype .= $searchtext;
6217 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6218 $greptype, '--regexp-ignore-case',
6219 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6221 my $paging_nav = '';
6222 if ($page > 0) {
6223 $paging_nav .=
6224 $cgi->a({-href => href(-replay=>1, page=>undef)},
6225 "first") .
6226 " &sdot; " .
6227 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6228 -accesskey => "p", -title => "Alt-p"}, "prev");
6229 } else {
6230 $paging_nav .= "first &sdot; prev";
6232 my $next_link = '';
6233 if ($#commitlist >= 100) {
6234 $next_link =
6235 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6236 -accesskey => "n", -title => "Alt-n"}, "next");
6237 $paging_nav .= " &sdot; $next_link";
6238 } else {
6239 $paging_nav .= " &sdot; next";
6242 git_header_html();
6244 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6245 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6246 if ($page == 0 && !@commitlist) {
6247 print "<p>No match.</p>\n";
6248 } else {
6249 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6252 git_footer_html();
6255 sub git_search_changes {
6256 my %co = @_;
6258 local $/ = "\n";
6259 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6260 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6261 ($search_use_regexp ? '--pickaxe-regex' : ())
6262 or die_error(500, "Open git-log failed");
6264 git_header_html();
6266 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6267 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6269 print "<table class=\"pickaxe search\">\n";
6270 my $alternate = 1;
6271 undef %co;
6272 my @files;
6273 while (my $line = <$fd>) {
6274 chomp $line;
6275 next unless $line;
6277 my %set = parse_difftree_raw_line($line);
6278 if (defined $set{'commit'}) {
6279 # finish previous commit
6280 if (%co) {
6281 print "</td>\n" .
6282 "<td class=\"link\">" .
6283 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6284 "commit") .
6285 " | " .
6286 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6287 hash_base=>$co{'id'})},
6288 "tree") .
6289 "</td>\n" .
6290 "</tr>\n";
6293 if ($alternate) {
6294 print "<tr class=\"dark\">\n";
6295 } else {
6296 print "<tr class=\"light\">\n";
6298 $alternate ^= 1;
6299 %co = parse_commit($set{'commit'});
6300 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6301 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6302 "<td><i>$author</i></td>\n" .
6303 "<td>" .
6304 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6305 -class => "list subject"},
6306 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6307 } elsif (defined $set{'to_id'}) {
6308 next if ($set{'to_id'} =~ m/^0{40}$/);
6310 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6311 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6312 -class => "list"},
6313 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6314 "<br/>\n";
6317 close $fd;
6319 # finish last commit (warning: repetition!)
6320 if (%co) {
6321 print "</td>\n" .
6322 "<td class=\"link\">" .
6323 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6324 "commit") .
6325 " | " .
6326 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6327 hash_base=>$co{'id'})},
6328 "tree") .
6329 "</td>\n" .
6330 "</tr>\n";
6333 print "</table>\n";
6335 git_footer_html();
6338 sub git_search_files {
6339 my %co = @_;
6341 local $/ = "\n";
6342 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6343 $search_use_regexp ? ('-E', '-i') : '-F',
6344 $searchtext, $co{'tree'}
6345 or die_error(500, "Open git-grep failed");
6347 git_header_html();
6349 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6350 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6352 print "<table class=\"grep_search\">\n";
6353 my $alternate = 1;
6354 my $matches = 0;
6355 my $lastfile = '';
6356 my $file_href;
6357 while (my $line = <$fd>) {
6358 chomp $line;
6359 my ($file, $lno, $ltext, $binary);
6360 last if ($matches++ > 1000);
6361 if ($line =~ /^Binary file (.+) matches$/) {
6362 $file = $1;
6363 $binary = 1;
6364 } else {
6365 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6366 $file =~ s/^$co{'tree'}://;
6368 if ($file ne $lastfile) {
6369 $lastfile and print "</td></tr>\n";
6370 if ($alternate++) {
6371 print "<tr class=\"dark\">\n";
6372 } else {
6373 print "<tr class=\"light\">\n";
6375 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6376 file_name=>$file);
6377 print "<td class=\"list\">".
6378 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6379 print "</td><td>\n";
6380 $lastfile = $file;
6382 if ($binary) {
6383 print "<div class=\"binary\">Binary file</div>\n";
6384 } else {
6385 $ltext = untabify($ltext);
6386 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6387 $ltext = esc_html($1, -nbsp=>1);
6388 $ltext .= '<span class="match">';
6389 $ltext .= esc_html($2, -nbsp=>1);
6390 $ltext .= '</span>';
6391 $ltext .= esc_html($3, -nbsp=>1);
6392 } else {
6393 $ltext = esc_html($ltext, -nbsp=>1);
6395 print "<div class=\"pre\">" .
6396 $cgi->a({-href => $file_href.'#l'.$lno,
6397 -class => "linenr"}, sprintf('%4i', $lno)) .
6398 ' ' . $ltext . "</div>\n";
6401 if ($lastfile) {
6402 print "</td></tr>\n";
6403 if ($matches > 1000) {
6404 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6406 } else {
6407 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6409 close $fd;
6411 print "</table>\n";
6413 git_footer_html();
6416 sub git_search_grep_body {
6417 my ($commitlist, $from, $to, $extra) = @_;
6418 $from = 0 unless defined $from;
6419 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6421 print "<table class=\"commit_search\">\n";
6422 my $alternate = 1;
6423 for (my $i = $from; $i <= $to; $i++) {
6424 my %co = %{$commitlist->[$i]};
6425 if (!%co) {
6426 next;
6428 my $commit = $co{'id'};
6429 if ($alternate) {
6430 print "<tr class=\"dark\">\n";
6431 } else {
6432 print "<tr class=\"light\">\n";
6434 $alternate ^= 1;
6435 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6436 format_author_html('td', \%co, 15, 5) .
6437 "<td>" .
6438 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6439 -class => "list subject"},
6440 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6441 my $comment = $co{'comment'};
6442 foreach my $line (@$comment) {
6443 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6444 my ($lead, $match, $trail) = ($1, $2, $3);
6445 $match = chop_str($match, 70, 5, 'center');
6446 my $contextlen = int((80 - length($match))/2);
6447 $contextlen = 30 if ($contextlen > 30);
6448 $lead = chop_str($lead, $contextlen, 10, 'left');
6449 $trail = chop_str($trail, $contextlen, 10, 'right');
6451 $lead = esc_html($lead);
6452 $match = esc_html($match);
6453 $trail = esc_html($trail);
6455 print "$lead<span class=\"match\">$match</span>$trail<br />";
6458 print "</td>\n" .
6459 "<td class=\"link\">" .
6460 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6461 " | " .
6462 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6463 " | " .
6464 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6465 print "</td>\n" .
6466 "</tr>\n";
6468 if (defined $extra) {
6469 print "<tr>\n" .
6470 "<td colspan=\"3\">$extra</td>\n" .
6471 "</tr>\n";
6473 print "</table>\n";
6476 ## ======================================================================
6477 ## ======================================================================
6478 ## actions
6480 sub git_project_list {
6481 my $order = $input_params{'order'};
6482 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6483 die_error(400, "Unknown order parameter");
6486 my @list = git_get_projects_list($project_filter, $strict_export);
6487 if (!@list) {
6488 die_error(404, "No projects found");
6491 git_header_html();
6492 if (defined $home_text && -f $home_text) {
6493 print "<div class=\"index_include\">\n";
6494 insert_file($home_text);
6495 print "</div>\n";
6498 git_project_search_form($searchtext, $search_use_regexp);
6499 git_project_list_body(\@list, $order);
6500 git_footer_html();
6503 sub git_forks {
6504 my $order = $input_params{'order'};
6505 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6506 die_error(400, "Unknown order parameter");
6509 my $filter = $project;
6510 $filter =~ s/\.git$//;
6511 my @list = git_get_projects_list($filter);
6512 if (!@list) {
6513 die_error(404, "No forks found");
6516 git_header_html();
6517 git_print_page_nav('','');
6518 git_print_header_div('summary', "$project forks");
6519 git_project_list_body(\@list, $order);
6520 git_footer_html();
6523 sub git_project_index {
6524 my @projects = git_get_projects_list($project_filter, $strict_export);
6525 if (!@projects) {
6526 die_error(404, "No projects found");
6529 print $cgi->header(
6530 -type => 'text/plain',
6531 -charset => 'utf-8',
6532 -content_disposition => 'inline; filename="index.aux"');
6534 foreach my $pr (@projects) {
6535 if (!exists $pr->{'owner'}) {
6536 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6539 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6540 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6541 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6542 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6543 $path =~ s/ /\+/g;
6544 $owner =~ s/ /\+/g;
6546 print "$path $owner\n";
6550 sub git_summary {
6551 my $descr = git_get_project_description($project) || "none";
6552 my %co = parse_commit("HEAD");
6553 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6554 my $head = $co{'id'};
6555 my $remote_heads = gitweb_check_feature('remote_heads');
6557 my $owner = git_get_project_owner($project);
6559 my $refs = git_get_references();
6560 # These get_*_list functions return one more to allow us to see if
6561 # there are more ...
6562 my @taglist = git_get_tags_list(16);
6563 my @headlist = git_get_heads_list(16);
6564 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6565 my @forklist;
6566 my $check_forks = gitweb_check_feature('forks');
6568 if ($check_forks) {
6569 # find forks of a project
6570 my $filter = $project;
6571 $filter =~ s/\.git$//;
6572 @forklist = git_get_projects_list($filter);
6573 # filter out forks of forks
6574 @forklist = filter_forks_from_projects_list(\@forklist)
6575 if (@forklist);
6578 git_header_html();
6579 git_print_page_nav('summary','', $head);
6581 print "<div class=\"title\">&nbsp;</div>\n";
6582 print "<table class=\"projects_list\">\n" .
6583 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6584 if ($owner and not $omit_owner) {
6585 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6587 if (defined $cd{'rfc2822'}) {
6588 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6589 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6592 # use per project git URL list in $projectroot/$project/cloneurl
6593 # or make project git URL from git base URL and project name
6594 my $url_tag = "URL";
6595 my @url_list = git_get_project_url_list($project);
6596 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6597 foreach my $git_url (@url_list) {
6598 next unless $git_url;
6599 print format_repo_url($url_tag, $git_url);
6600 $url_tag = "";
6603 # Tag cloud
6604 my $show_ctags = gitweb_check_feature('ctags');
6605 if ($show_ctags) {
6606 my $ctags = git_get_project_ctags($project);
6607 if (%$ctags) {
6608 # without ability to add tags, don't show if there are none
6609 my $cloud = git_populate_project_tagcloud($ctags);
6610 print "<tr id=\"metadata_ctags\">" .
6611 "<td>content tags</td>" .
6612 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6613 "</tr>\n";
6617 print "</table>\n";
6619 # If XSS prevention is on, we don't include README.html.
6620 # TODO: Allow a readme in some safe format.
6621 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6622 print "<div class=\"title\">readme</div>\n" .
6623 "<div class=\"readme\">\n";
6624 insert_file("$projectroot/$project/README.html");
6625 print "\n</div>\n"; # class="readme"
6628 # we need to request one more than 16 (0..15) to check if
6629 # those 16 are all
6630 my @commitlist = $head ? parse_commits($head, 17) : ();
6631 if (@commitlist) {
6632 git_print_header_div('shortlog');
6633 git_shortlog_body(\@commitlist, 0, 15, $refs,
6634 $#commitlist <= 15 ? undef :
6635 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6638 if (@taglist) {
6639 git_print_header_div('tags');
6640 git_tags_body(\@taglist, 0, 15,
6641 $#taglist <= 15 ? undef :
6642 $cgi->a({-href => href(action=>"tags")}, "..."));
6645 if (@headlist) {
6646 git_print_header_div('heads');
6647 git_heads_body(\@headlist, $head, 0, 15,
6648 $#headlist <= 15 ? undef :
6649 $cgi->a({-href => href(action=>"heads")}, "..."));
6652 if (%remotedata) {
6653 git_print_header_div('remotes');
6654 git_remotes_body(\%remotedata, 15, $head);
6657 if (@forklist) {
6658 git_print_header_div('forks');
6659 git_project_list_body(\@forklist, 'age', 0, 15,
6660 $#forklist <= 15 ? undef :
6661 $cgi->a({-href => href(action=>"forks")}, "..."),
6662 'no_header');
6665 git_footer_html();
6668 sub git_tag {
6669 my %tag = parse_tag($hash);
6671 if (! %tag) {
6672 die_error(404, "Unknown tag object");
6675 my $head = git_get_head_hash($project);
6676 git_header_html();
6677 git_print_page_nav('','', $head,undef,$head);
6678 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6679 print "<div class=\"title_text\">\n" .
6680 "<table class=\"object_header\">\n" .
6681 "<tr>\n" .
6682 "<td>object</td>\n" .
6683 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6684 $tag{'object'}) . "</td>\n" .
6685 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6686 $tag{'type'}) . "</td>\n" .
6687 "</tr>\n";
6688 if (defined($tag{'author'})) {
6689 git_print_authorship_rows(\%tag, 'author');
6691 print "</table>\n\n" .
6692 "</div>\n";
6693 print "<div class=\"page_body\">";
6694 my $comment = $tag{'comment'};
6695 foreach my $line (@$comment) {
6696 chomp $line;
6697 print esc_html($line, -nbsp=>1) . "<br/>\n";
6699 print "</div>\n";
6700 git_footer_html();
6703 sub git_blame_common {
6704 my $format = shift || 'porcelain';
6705 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6706 $format = 'incremental';
6707 $action = 'blame_incremental'; # for page title etc
6710 # permissions
6711 gitweb_check_feature('blame')
6712 or die_error(403, "Blame view not allowed");
6714 # error checking
6715 die_error(400, "No file name given") unless $file_name;
6716 $hash_base ||= git_get_head_hash($project);
6717 die_error(404, "Couldn't find base commit") unless $hash_base;
6718 my %co = parse_commit($hash_base)
6719 or die_error(404, "Commit not found");
6720 my $ftype = "blob";
6721 if (!defined $hash) {
6722 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6723 or die_error(404, "Error looking up file");
6724 } else {
6725 $ftype = git_get_type($hash);
6726 if ($ftype !~ "blob") {
6727 die_error(400, "Object is not a blob");
6731 my $fd;
6732 if ($format eq 'incremental') {
6733 # get file contents (as base)
6734 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6735 or die_error(500, "Open git-cat-file failed");
6736 } elsif ($format eq 'data') {
6737 # run git-blame --incremental
6738 open $fd, "-|", git_cmd(), "blame", "--incremental",
6739 $hash_base, "--", $file_name
6740 or die_error(500, "Open git-blame --incremental failed");
6741 } else {
6742 # run git-blame --porcelain
6743 open $fd, "-|", git_cmd(), "blame", '-p',
6744 $hash_base, '--', $file_name
6745 or die_error(500, "Open git-blame --porcelain failed");
6747 binmode $fd, ':utf8';
6749 # incremental blame data returns early
6750 if ($format eq 'data') {
6751 print $cgi->header(
6752 -type=>"text/plain", -charset => "utf-8",
6753 -status=> "200 OK");
6754 local $| = 1; # output autoflush
6755 while (my $line = <$fd>) {
6756 print to_utf8($line);
6758 close $fd
6759 or print "ERROR $!\n";
6761 print 'END';
6762 if (defined $t0 && gitweb_check_feature('timed')) {
6763 print ' '.
6764 tv_interval($t0, [ gettimeofday() ]).
6765 ' '.$number_of_git_cmds;
6767 print "\n";
6769 return;
6772 # page header
6773 git_header_html();
6774 my $formats_nav =
6775 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6776 "blob") .
6777 " | ";
6778 if ($format eq 'incremental') {
6779 $formats_nav .=
6780 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6781 "blame") . " (non-incremental)";
6782 } else {
6783 $formats_nav .=
6784 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6785 "blame") . " (incremental)";
6787 $formats_nav .=
6788 " | " .
6789 $cgi->a({-href => href(action=>"history", -replay=>1)},
6790 "history") .
6791 " | " .
6792 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6793 "HEAD");
6794 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6795 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6796 git_print_page_path($file_name, $ftype, $hash_base);
6798 # page body
6799 if ($format eq 'incremental') {
6800 print "<noscript>\n<div class=\"error\"><center><b>\n".
6801 "This page requires JavaScript to run.\n Use ".
6802 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6803 'this page').
6804 " instead.\n".
6805 "</b></center></div>\n</noscript>\n";
6807 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6810 print qq!<div class="page_body">\n!;
6811 print qq!<div id="progress_info">... / ...</div>\n!
6812 if ($format eq 'incremental');
6813 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6814 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6815 qq!<thead>\n!.
6816 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6817 qq!</thead>\n!.
6818 qq!<tbody>\n!;
6820 my @rev_color = qw(light dark);
6821 my $num_colors = scalar(@rev_color);
6822 my $current_color = 0;
6824 if ($format eq 'incremental') {
6825 my $color_class = $rev_color[$current_color];
6827 #contents of a file
6828 my $linenr = 0;
6829 LINE:
6830 while (my $line = <$fd>) {
6831 chomp $line;
6832 $linenr++;
6834 print qq!<tr id="l$linenr" class="$color_class">!.
6835 qq!<td class="sha1"><a href=""> </a></td>!.
6836 qq!<td class="linenr">!.
6837 qq!<a class="linenr" href="">$linenr</a></td>!;
6838 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6839 print qq!</tr>\n!;
6842 } else { # porcelain, i.e. ordinary blame
6843 my %metainfo = (); # saves information about commits
6845 # blame data
6846 LINE:
6847 while (my $line = <$fd>) {
6848 chomp $line;
6849 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6850 # no <lines in group> for subsequent lines in group of lines
6851 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6852 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6853 if (!exists $metainfo{$full_rev}) {
6854 $metainfo{$full_rev} = { 'nprevious' => 0 };
6856 my $meta = $metainfo{$full_rev};
6857 my $data;
6858 while ($data = <$fd>) {
6859 chomp $data;
6860 last if ($data =~ s/^\t//); # contents of line
6861 if ($data =~ /^(\S+)(?: (.*))?$/) {
6862 $meta->{$1} = $2 unless exists $meta->{$1};
6864 if ($data =~ /^previous /) {
6865 $meta->{'nprevious'}++;
6868 my $short_rev = substr($full_rev, 0, 8);
6869 my $author = $meta->{'author'};
6870 my %date =
6871 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6872 my $date = $date{'iso-tz'};
6873 if ($group_size) {
6874 $current_color = ($current_color + 1) % $num_colors;
6876 my $tr_class = $rev_color[$current_color];
6877 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6878 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6879 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6880 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6881 if ($group_size) {
6882 print "<td class=\"sha1\"";
6883 print " title=\"". esc_html($author) . ", $date\"";
6884 print " rowspan=\"$group_size\"" if ($group_size > 1);
6885 print ">";
6886 print $cgi->a({-href => href(action=>"commit",
6887 hash=>$full_rev,
6888 file_name=>$file_name)},
6889 esc_html($short_rev));
6890 if ($group_size >= 2) {
6891 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6892 if (@author_initials) {
6893 print "<br />" .
6894 esc_html(join('', @author_initials));
6895 # or join('.', ...)
6898 print "</td>\n";
6900 # 'previous' <sha1 of parent commit> <filename at commit>
6901 if (exists $meta->{'previous'} &&
6902 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6903 $meta->{'parent'} = $1;
6904 $meta->{'file_parent'} = unquote($2);
6906 my $linenr_commit =
6907 exists($meta->{'parent'}) ?
6908 $meta->{'parent'} : $full_rev;
6909 my $linenr_filename =
6910 exists($meta->{'file_parent'}) ?
6911 $meta->{'file_parent'} : unquote($meta->{'filename'});
6912 my $blamed = href(action => 'blame',
6913 file_name => $linenr_filename,
6914 hash_base => $linenr_commit);
6915 print "<td class=\"linenr\">";
6916 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6917 -class => "linenr" },
6918 esc_html($lineno));
6919 print "</td>";
6920 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6921 print "</tr>\n";
6922 } # end while
6926 # footer
6927 print "</tbody>\n".
6928 "</table>\n"; # class="blame"
6929 print "</div>\n"; # class="blame_body"
6930 close $fd
6931 or print "Reading blob failed\n";
6933 git_footer_html();
6936 sub git_blame {
6937 git_blame_common();
6940 sub git_blame_incremental {
6941 git_blame_common('incremental');
6944 sub git_blame_data {
6945 git_blame_common('data');
6948 sub git_tags {
6949 my $head = git_get_head_hash($project);
6950 git_header_html();
6951 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6952 git_print_header_div('summary', $project);
6954 my @tagslist = git_get_tags_list();
6955 if (@tagslist) {
6956 git_tags_body(\@tagslist);
6958 git_footer_html();
6961 sub git_heads {
6962 my $head = git_get_head_hash($project);
6963 git_header_html();
6964 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6965 git_print_header_div('summary', $project);
6967 my @headslist = git_get_heads_list();
6968 if (@headslist) {
6969 git_heads_body(\@headslist, $head);
6971 git_footer_html();
6974 # used both for single remote view and for list of all the remotes
6975 sub git_remotes {
6976 gitweb_check_feature('remote_heads')
6977 or die_error(403, "Remote heads view is disabled");
6979 my $head = git_get_head_hash($project);
6980 my $remote = $input_params{'hash'};
6982 my $remotedata = git_get_remotes_list($remote);
6983 die_error(500, "Unable to get remote information") unless defined $remotedata;
6985 unless (%$remotedata) {
6986 die_error(404, defined $remote ?
6987 "Remote $remote not found" :
6988 "No remotes found");
6991 git_header_html(undef, undef, -action_extra => $remote);
6992 git_print_page_nav('', '', $head, undef, $head,
6993 format_ref_views($remote ? '' : 'remotes'));
6995 fill_remote_heads($remotedata);
6996 if (defined $remote) {
6997 git_print_header_div('remotes', "$remote remote for $project");
6998 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6999 } else {
7000 git_print_header_div('summary', "$project remotes");
7001 git_remotes_body($remotedata, undef, $head);
7004 git_footer_html();
7007 sub git_blob_plain {
7008 my $type = shift;
7009 my $expires;
7011 if (!defined $hash) {
7012 if (defined $file_name) {
7013 my $base = $hash_base || git_get_head_hash($project);
7014 $hash = git_get_hash_by_path($base, $file_name, "blob")
7015 or die_error(404, "Cannot find file");
7016 } else {
7017 die_error(400, "No file name defined");
7019 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7020 # blobs defined by non-textual hash id's can be cached
7021 $expires = "+1d";
7024 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7025 or die_error(500, "Open git-cat-file blob '$hash' failed");
7027 # content-type (can include charset)
7028 $type = blob_contenttype($fd, $file_name, $type);
7030 # "save as" filename, even when no $file_name is given
7031 my $save_as = "$hash";
7032 if (defined $file_name) {
7033 $save_as = $file_name;
7034 } elsif ($type =~ m/^text\//) {
7035 $save_as .= '.txt';
7038 # With XSS prevention on, blobs of all types except a few known safe
7039 # ones are served with "Content-Disposition: attachment" to make sure
7040 # they don't run in our security domain. For certain image types,
7041 # blob view writes an <img> tag referring to blob_plain view, and we
7042 # want to be sure not to break that by serving the image as an
7043 # attachment (though Firefox 3 doesn't seem to care).
7044 my $sandbox = $prevent_xss &&
7045 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7047 # serve text/* as text/plain
7048 if ($prevent_xss &&
7049 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7050 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7051 my $rest = $1;
7052 $rest = defined $rest ? $rest : '';
7053 $type = "text/plain$rest";
7056 print $cgi->header(
7057 -type => $type,
7058 -expires => $expires,
7059 -content_disposition =>
7060 ($sandbox ? 'attachment' : 'inline')
7061 . '; filename="' . $save_as . '"');
7062 local $/ = undef;
7063 binmode STDOUT, ':raw';
7064 print <$fd>;
7065 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7066 close $fd;
7069 sub git_blob {
7070 my $expires;
7072 if (!defined $hash) {
7073 if (defined $file_name) {
7074 my $base = $hash_base || git_get_head_hash($project);
7075 $hash = git_get_hash_by_path($base, $file_name, "blob")
7076 or die_error(404, "Cannot find file");
7077 } else {
7078 die_error(400, "No file name defined");
7080 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7081 # blobs defined by non-textual hash id's can be cached
7082 $expires = "+1d";
7085 my $have_blame = gitweb_check_feature('blame');
7086 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7087 or die_error(500, "Couldn't cat $file_name, $hash");
7088 my $mimetype = blob_mimetype($fd, $file_name);
7089 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7090 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7091 close $fd;
7092 return git_blob_plain($mimetype);
7094 # we can have blame only for text/* mimetype
7095 $have_blame &&= ($mimetype =~ m!^text/!);
7097 my $highlight = gitweb_check_feature('highlight');
7098 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7099 $fd = run_highlighter($fd, $highlight, $syntax)
7100 if $syntax;
7102 git_header_html(undef, $expires);
7103 my $formats_nav = '';
7104 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7105 if (defined $file_name) {
7106 if ($have_blame) {
7107 $formats_nav .=
7108 $cgi->a({-href => href(action=>"blame", -replay=>1),
7109 -class => "blamelink"},
7110 "blame") .
7111 " | ";
7113 $formats_nav .=
7114 $cgi->a({-href => href(action=>"history", -replay=>1)},
7115 "history") .
7116 " | " .
7117 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7118 "raw") .
7119 " | " .
7120 $cgi->a({-href => href(action=>"blob",
7121 hash_base=>"HEAD", file_name=>$file_name)},
7122 "HEAD");
7123 } else {
7124 $formats_nav .=
7125 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7126 "raw");
7128 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7129 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7130 } else {
7131 print "<div class=\"page_nav\">\n" .
7132 "<br/><br/></div>\n" .
7133 "<div class=\"title\">".esc_html($hash)."</div>\n";
7135 git_print_page_path($file_name, "blob", $hash_base);
7136 print "<div class=\"page_body\">\n";
7137 if ($mimetype =~ m!^image/!) {
7138 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7139 if ($file_name) {
7140 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7142 print qq! src="! .
7143 href(action=>"blob_plain", hash=>$hash,
7144 hash_base=>$hash_base, file_name=>$file_name) .
7145 qq!" />\n!;
7146 } else {
7147 my $nr;
7148 while (my $line = <$fd>) {
7149 chomp $line;
7150 $nr++;
7151 $line = untabify($line);
7152 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7153 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7154 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7157 close $fd
7158 or print "Reading blob failed.\n";
7159 print "</div>";
7160 git_footer_html();
7163 sub git_tree {
7164 if (!defined $hash_base) {
7165 $hash_base = "HEAD";
7167 if (!defined $hash) {
7168 if (defined $file_name) {
7169 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7170 } else {
7171 $hash = $hash_base;
7174 die_error(404, "No such tree") unless defined($hash);
7176 my $show_sizes = gitweb_check_feature('show-sizes');
7177 my $have_blame = gitweb_check_feature('blame');
7179 my @entries = ();
7181 local $/ = "\0";
7182 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7183 ($show_sizes ? '-l' : ()), @extra_options, $hash
7184 or die_error(500, "Open git-ls-tree failed");
7185 @entries = map { chomp; $_ } <$fd>;
7186 close $fd
7187 or die_error(404, "Reading tree failed");
7190 my $refs = git_get_references();
7191 my $ref = format_ref_marker($refs, $hash_base);
7192 git_header_html();
7193 my $basedir = '';
7194 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7195 my @views_nav = ();
7196 if (defined $file_name) {
7197 push @views_nav,
7198 $cgi->a({-href => href(action=>"history", -replay=>1)},
7199 "history"),
7200 $cgi->a({-href => href(action=>"tree",
7201 hash_base=>"HEAD", file_name=>$file_name)},
7202 "HEAD"),
7204 my $snapshot_links = format_snapshot_links($hash);
7205 if (defined $snapshot_links) {
7206 # FIXME: Should be available when we have no hash base as well.
7207 push @views_nav, $snapshot_links;
7209 git_print_page_nav('tree','', $hash_base, undef, undef,
7210 join(' | ', @views_nav));
7211 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7212 } else {
7213 undef $hash_base;
7214 print "<div class=\"page_nav\">\n";
7215 print "<br/><br/></div>\n";
7216 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7218 if (defined $file_name) {
7219 $basedir = $file_name;
7220 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7221 $basedir .= '/';
7223 git_print_page_path($file_name, 'tree', $hash_base);
7225 print "<div class=\"page_body\">\n";
7226 print "<table class=\"tree\">\n";
7227 my $alternate = 1;
7228 # '..' (top directory) link if possible
7229 if (defined $hash_base &&
7230 defined $file_name && $file_name =~ m![^/]+$!) {
7231 if ($alternate) {
7232 print "<tr class=\"dark\">\n";
7233 } else {
7234 print "<tr class=\"light\">\n";
7236 $alternate ^= 1;
7238 my $up = $file_name;
7239 $up =~ s!/?[^/]+$!!;
7240 undef $up unless $up;
7241 # based on git_print_tree_entry
7242 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7243 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7244 print '<td class="list">';
7245 print $cgi->a({-href => href(action=>"tree",
7246 hash_base=>$hash_base,
7247 file_name=>$up)},
7248 "..");
7249 print "</td>\n";
7250 print "<td class=\"link\"></td>\n";
7252 print "</tr>\n";
7254 foreach my $line (@entries) {
7255 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7257 if ($alternate) {
7258 print "<tr class=\"dark\">\n";
7259 } else {
7260 print "<tr class=\"light\">\n";
7262 $alternate ^= 1;
7264 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7266 print "</tr>\n";
7268 print "</table>\n" .
7269 "</div>";
7270 git_footer_html();
7273 sub sanitize_for_filename {
7274 my $name = shift;
7276 $name =~ s!/!-!g;
7277 $name =~ s/[^[:alnum:]_.-]//g;
7279 return $name;
7282 sub snapshot_name {
7283 my ($project, $hash) = @_;
7285 # path/to/project.git -> project
7286 # path/to/project/.git -> project
7287 my $name = to_utf8($project);
7288 $name =~ s,([^/])/*\.git$,$1,;
7289 $name = sanitize_for_filename(basename($name));
7291 my $ver = $hash;
7292 if ($hash =~ /^[0-9a-fA-F]+$/) {
7293 # shorten SHA-1 hash
7294 my $full_hash = git_get_full_hash($project, $hash);
7295 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7296 $ver = git_get_short_hash($project, $hash);
7298 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7299 # tags don't need shortened SHA-1 hash
7300 $ver = $1;
7301 } else {
7302 # branches and other need shortened SHA-1 hash
7303 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7304 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7305 my $ref_dir = (defined $1) ? $1 : '';
7306 $ver = $2;
7308 $ref_dir = sanitize_for_filename($ref_dir);
7309 # for refs neither in heads nor remotes we want to
7310 # add a ref dir to archive name
7311 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7312 $ver = $ref_dir . '-' . $ver;
7315 $ver .= '-' . git_get_short_hash($project, $hash);
7317 # special case of sanitization for filename - we change
7318 # slashes to dots instead of dashes
7319 # in case of hierarchical branch names
7320 $ver =~ s!/!.!g;
7321 $ver =~ s/[^[:alnum:]_.-]//g;
7323 # name = project-version_string
7324 $name = "$name-$ver";
7326 return wantarray ? ($name, $name) : $name;
7329 sub exit_if_unmodified_since {
7330 my ($latest_epoch) = @_;
7331 our $cgi;
7333 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7334 if (defined $if_modified) {
7335 my $since;
7336 if (eval { require HTTP::Date; 1; }) {
7337 $since = HTTP::Date::str2time($if_modified);
7338 } elsif (eval { require Time::ParseDate; 1; }) {
7339 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7341 if (defined $since && $latest_epoch <= $since) {
7342 my %latest_date = parse_date($latest_epoch);
7343 print $cgi->header(
7344 -last_modified => $latest_date{'rfc2822'},
7345 -status => '304 Not Modified');
7346 goto DONE_GITWEB;
7351 sub git_snapshot {
7352 my $format = $input_params{'snapshot_format'};
7353 if (!@snapshot_fmts) {
7354 die_error(403, "Snapshots not allowed");
7356 # default to first supported snapshot format
7357 $format ||= $snapshot_fmts[0];
7358 if ($format !~ m/^[a-z0-9]+$/) {
7359 die_error(400, "Invalid snapshot format parameter");
7360 } elsif (!exists($known_snapshot_formats{$format})) {
7361 die_error(400, "Unknown snapshot format");
7362 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7363 die_error(403, "Snapshot format not allowed");
7364 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7365 die_error(403, "Unsupported snapshot format");
7368 my $type = git_get_type("$hash^{}");
7369 if (!$type) {
7370 die_error(404, 'Object does not exist');
7371 } elsif ($type eq 'blob') {
7372 die_error(400, 'Object is not a tree-ish');
7375 my ($name, $prefix) = snapshot_name($project, $hash);
7376 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7378 my %co = parse_commit($hash);
7379 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7381 my $cmd = quote_command(
7382 git_cmd(), 'archive',
7383 "--format=$known_snapshot_formats{$format}{'format'}",
7384 "--prefix=$prefix/", $hash);
7385 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7386 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7389 $filename =~ s/(["\\])/\\$1/g;
7390 my %latest_date;
7391 if (%co) {
7392 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7395 print $cgi->header(
7396 -type => $known_snapshot_formats{$format}{'type'},
7397 -content_disposition => 'inline; filename="' . $filename . '"',
7398 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7399 -status => '200 OK');
7401 open my $fd, "-|", $cmd
7402 or die_error(500, "Execute git-archive failed");
7403 binmode STDOUT, ':raw';
7404 print <$fd>;
7405 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7406 close $fd;
7409 sub git_log_generic {
7410 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7412 my $head = git_get_head_hash($project);
7413 if (!defined $base) {
7414 $base = $head;
7416 if (!defined $page) {
7417 $page = 0;
7419 my $refs = git_get_references();
7421 my $commit_hash = $base;
7422 if (defined $parent) {
7423 $commit_hash = "$parent..$base";
7425 my @commitlist =
7426 parse_commits($commit_hash, 101, (100 * $page),
7427 defined $file_name ? ($file_name, "--full-history") : ());
7429 my $ftype;
7430 if (!defined $file_hash && defined $file_name) {
7431 # some commits could have deleted file in question,
7432 # and not have it in tree, but one of them has to have it
7433 for (my $i = 0; $i < @commitlist; $i++) {
7434 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7435 last if defined $file_hash;
7438 if (defined $file_hash) {
7439 $ftype = git_get_type($file_hash);
7441 if (defined $file_name && !defined $ftype) {
7442 die_error(500, "Unknown type of object");
7444 my %co;
7445 if (defined $file_name) {
7446 %co = parse_commit($base)
7447 or die_error(404, "Unknown commit object");
7451 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7452 my $next_link = '';
7453 if ($#commitlist >= 100) {
7454 $next_link =
7455 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7456 -accesskey => "n", -title => "Alt-n"}, "next");
7458 my $patch_max = gitweb_get_feature('patches');
7459 if ($patch_max && !defined $file_name) {
7460 if ($patch_max < 0 || @commitlist <= $patch_max) {
7461 $paging_nav .= " &sdot; " .
7462 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7463 "patches");
7467 git_header_html();
7468 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7469 if (defined $file_name) {
7470 git_print_header_div('commit', esc_html($co{'title'}), $base);
7471 } else {
7472 git_print_header_div('summary', $project)
7474 git_print_page_path($file_name, $ftype, $hash_base)
7475 if (defined $file_name);
7477 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7478 $file_name, $file_hash, $ftype);
7480 git_footer_html();
7483 sub git_log {
7484 git_log_generic('log', \&git_log_body,
7485 $hash, $hash_parent);
7488 sub git_commit {
7489 $hash ||= $hash_base || "HEAD";
7490 my %co = parse_commit($hash)
7491 or die_error(404, "Unknown commit object");
7493 my $parent = $co{'parent'};
7494 my $parents = $co{'parents'}; # listref
7496 # we need to prepare $formats_nav before any parameter munging
7497 my $formats_nav;
7498 if (!defined $parent) {
7499 # --root commitdiff
7500 $formats_nav .= '(initial)';
7501 } elsif (@$parents == 1) {
7502 # single parent commit
7503 $formats_nav .=
7504 '(parent: ' .
7505 $cgi->a({-href => href(action=>"commit",
7506 hash=>$parent)},
7507 esc_html(substr($parent, 0, 7))) .
7508 ')';
7509 } else {
7510 # merge commit
7511 $formats_nav .=
7512 '(merge: ' .
7513 join(' ', map {
7514 $cgi->a({-href => href(action=>"commit",
7515 hash=>$_)},
7516 esc_html(substr($_, 0, 7)));
7517 } @$parents ) .
7518 ')';
7520 if (gitweb_check_feature('patches') && @$parents <= 1) {
7521 $formats_nav .= " | " .
7522 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7523 "patch");
7526 if (!defined $parent) {
7527 $parent = "--root";
7529 my @difftree;
7530 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7531 @diff_opts,
7532 (@$parents <= 1 ? $parent : '-c'),
7533 $hash, "--"
7534 or die_error(500, "Open git-diff-tree failed");
7535 @difftree = map { chomp; $_ } <$fd>;
7536 close $fd or die_error(404, "Reading git-diff-tree failed");
7538 # non-textual hash id's can be cached
7539 my $expires;
7540 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7541 $expires = "+1d";
7543 my $refs = git_get_references();
7544 my $ref = format_ref_marker($refs, $co{'id'});
7546 git_header_html(undef, $expires);
7547 git_print_page_nav('commit', '',
7548 $hash, $co{'tree'}, $hash,
7549 $formats_nav);
7551 if (defined $co{'parent'}) {
7552 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7553 } else {
7554 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7556 print "<div class=\"title_text\">\n" .
7557 "<table class=\"object_header\">\n";
7558 git_print_authorship_rows(\%co);
7559 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7560 print "<tr>" .
7561 "<td>tree</td>" .
7562 "<td class=\"sha1\">" .
7563 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7564 class => "list"}, $co{'tree'}) .
7565 "</td>" .
7566 "<td class=\"link\">" .
7567 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7568 "tree");
7569 my $snapshot_links = format_snapshot_links($hash);
7570 if (defined $snapshot_links) {
7571 print " | " . $snapshot_links;
7573 print "</td>" .
7574 "</tr>\n";
7576 foreach my $par (@$parents) {
7577 print "<tr>" .
7578 "<td>parent</td>" .
7579 "<td class=\"sha1\">" .
7580 $cgi->a({-href => href(action=>"commit", hash=>$par),
7581 class => "list"}, $par) .
7582 "</td>" .
7583 "<td class=\"link\">" .
7584 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7585 " | " .
7586 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7587 "</td>" .
7588 "</tr>\n";
7590 print "</table>".
7591 "</div>\n";
7593 print "<div class=\"page_body\">\n";
7594 git_print_log($co{'comment'});
7595 print "</div>\n";
7597 git_difftree_body(\@difftree, $hash, @$parents);
7599 git_footer_html();
7602 sub git_object {
7603 # object is defined by:
7604 # - hash or hash_base alone
7605 # - hash_base and file_name
7606 my $type;
7608 # - hash or hash_base alone
7609 if ($hash || ($hash_base && !defined $file_name)) {
7610 my $object_id = $hash || $hash_base;
7612 open my $fd, "-|", quote_command(
7613 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7614 or die_error(404, "Object does not exist");
7615 $type = <$fd>;
7616 defined $type && chomp $type;
7617 close $fd
7618 or die_error(404, "Object does not exist");
7620 # - hash_base and file_name
7621 } elsif ($hash_base && defined $file_name) {
7622 $file_name =~ s,/+$,,;
7624 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7625 or die_error(404, "Base object does not exist");
7627 # here errors should not happen
7628 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7629 or die_error(500, "Open git-ls-tree failed");
7630 my $line = <$fd>;
7631 close $fd;
7633 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7634 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7635 die_error(404, "File or directory for given base does not exist");
7637 $type = $2;
7638 $hash = $3;
7639 } else {
7640 die_error(400, "Not enough information to find object");
7643 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7644 hash=>$hash, hash_base=>$hash_base,
7645 file_name=>$file_name),
7646 -status => '302 Found');
7649 sub git_blobdiff {
7650 my $format = shift || 'html';
7651 my $diff_style = $input_params{'diff_style'} || 'inline';
7653 my $fd;
7654 my @difftree;
7655 my %diffinfo;
7656 my $expires;
7658 # preparing $fd and %diffinfo for git_patchset_body
7659 # new style URI
7660 if (defined $hash_base && defined $hash_parent_base) {
7661 if (defined $file_name) {
7662 # read raw output
7663 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7664 $hash_parent_base, $hash_base,
7665 "--", (defined $file_parent ? $file_parent : ()), $file_name
7666 or die_error(500, "Open git-diff-tree failed");
7667 @difftree = map { chomp; $_ } <$fd>;
7668 close $fd
7669 or die_error(404, "Reading git-diff-tree failed");
7670 @difftree
7671 or die_error(404, "Blob diff not found");
7673 } elsif (defined $hash &&
7674 $hash =~ /[0-9a-fA-F]{40}/) {
7675 # try to find filename from $hash
7677 # read filtered raw output
7678 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7679 $hash_parent_base, $hash_base, "--"
7680 or die_error(500, "Open git-diff-tree failed");
7681 @difftree =
7682 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7683 # $hash == to_id
7684 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7685 map { chomp; $_ } <$fd>;
7686 close $fd
7687 or die_error(404, "Reading git-diff-tree failed");
7688 @difftree
7689 or die_error(404, "Blob diff not found");
7691 } else {
7692 die_error(400, "Missing one of the blob diff parameters");
7695 if (@difftree > 1) {
7696 die_error(400, "Ambiguous blob diff specification");
7699 %diffinfo = parse_difftree_raw_line($difftree[0]);
7700 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7701 $file_name ||= $diffinfo{'to_file'};
7703 $hash_parent ||= $diffinfo{'from_id'};
7704 $hash ||= $diffinfo{'to_id'};
7706 # non-textual hash id's can be cached
7707 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7708 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7709 $expires = '+1d';
7712 # open patch output
7713 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7714 '-p', ($format eq 'html' ? "--full-index" : ()),
7715 $hash_parent_base, $hash_base,
7716 "--", (defined $file_parent ? $file_parent : ()), $file_name
7717 or die_error(500, "Open git-diff-tree failed");
7720 # old/legacy style URI -- not generated anymore since 1.4.3.
7721 if (!%diffinfo) {
7722 die_error('404 Not Found', "Missing one of the blob diff parameters")
7725 # header
7726 if ($format eq 'html') {
7727 my $formats_nav =
7728 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7729 "raw");
7730 $formats_nav .= diff_style_nav($diff_style);
7731 git_header_html(undef, $expires);
7732 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7733 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7734 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7735 } else {
7736 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7737 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7739 if (defined $file_name) {
7740 git_print_page_path($file_name, "blob", $hash_base);
7741 } else {
7742 print "<div class=\"page_path\"></div>\n";
7745 } elsif ($format eq 'plain') {
7746 print $cgi->header(
7747 -type => 'text/plain',
7748 -charset => 'utf-8',
7749 -expires => $expires,
7750 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7752 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7754 } else {
7755 die_error(400, "Unknown blobdiff format");
7758 # patch
7759 if ($format eq 'html') {
7760 print "<div class=\"page_body\">\n";
7762 git_patchset_body($fd, $diff_style,
7763 [ \%diffinfo ], $hash_base, $hash_parent_base);
7764 close $fd;
7766 print "</div>\n"; # class="page_body"
7767 git_footer_html();
7769 } else {
7770 while (my $line = <$fd>) {
7771 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7772 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7774 print $line;
7776 last if $line =~ m!^\+\+\+!;
7778 local $/ = undef;
7779 print <$fd>;
7780 close $fd;
7784 sub git_blobdiff_plain {
7785 git_blobdiff('plain');
7788 # assumes that it is added as later part of already existing navigation,
7789 # so it returns "| foo | bar" rather than just "foo | bar"
7790 sub diff_style_nav {
7791 my ($diff_style, $is_combined) = @_;
7792 $diff_style ||= 'inline';
7794 return "" if ($is_combined);
7796 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7797 my %styles = @styles;
7798 @styles =
7799 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7801 return join '',
7802 map { " | ".$_ }
7803 map {
7804 $_ eq $diff_style ? $styles{$_} :
7805 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7806 } @styles;
7809 sub git_commitdiff {
7810 my %params = @_;
7811 my $format = $params{-format} || 'html';
7812 my $diff_style = $input_params{'diff_style'} || 'inline';
7814 my ($patch_max) = gitweb_get_feature('patches');
7815 if ($format eq 'patch') {
7816 die_error(403, "Patch view not allowed") unless $patch_max;
7819 $hash ||= $hash_base || "HEAD";
7820 my %co = parse_commit($hash)
7821 or die_error(404, "Unknown commit object");
7823 # choose format for commitdiff for merge
7824 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7825 $hash_parent = '--cc';
7827 # we need to prepare $formats_nav before almost any parameter munging
7828 my $formats_nav;
7829 if ($format eq 'html') {
7830 $formats_nav =
7831 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7832 "raw");
7833 if ($patch_max && @{$co{'parents'}} <= 1) {
7834 $formats_nav .= " | " .
7835 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7836 "patch");
7838 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7840 if (defined $hash_parent &&
7841 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7842 # commitdiff with two commits given
7843 my $hash_parent_short = $hash_parent;
7844 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7845 $hash_parent_short = substr($hash_parent, 0, 7);
7847 $formats_nav .=
7848 ' (from';
7849 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7850 if ($co{'parents'}[$i] eq $hash_parent) {
7851 $formats_nav .= ' parent ' . ($i+1);
7852 last;
7855 $formats_nav .= ': ' .
7856 $cgi->a({-href => href(-replay=>1,
7857 hash=>$hash_parent, hash_base=>undef)},
7858 esc_html($hash_parent_short)) .
7859 ')';
7860 } elsif (!$co{'parent'}) {
7861 # --root commitdiff
7862 $formats_nav .= ' (initial)';
7863 } elsif (scalar @{$co{'parents'}} == 1) {
7864 # single parent commit
7865 $formats_nav .=
7866 ' (parent: ' .
7867 $cgi->a({-href => href(-replay=>1,
7868 hash=>$co{'parent'}, hash_base=>undef)},
7869 esc_html(substr($co{'parent'}, 0, 7))) .
7870 ')';
7871 } else {
7872 # merge commit
7873 if ($hash_parent eq '--cc') {
7874 $formats_nav .= ' | ' .
7875 $cgi->a({-href => href(-replay=>1,
7876 hash=>$hash, hash_parent=>'-c')},
7877 'combined');
7878 } else { # $hash_parent eq '-c'
7879 $formats_nav .= ' | ' .
7880 $cgi->a({-href => href(-replay=>1,
7881 hash=>$hash, hash_parent=>'--cc')},
7882 'compact');
7884 $formats_nav .=
7885 ' (merge: ' .
7886 join(' ', map {
7887 $cgi->a({-href => href(-replay=>1,
7888 hash=>$_, hash_base=>undef)},
7889 esc_html(substr($_, 0, 7)));
7890 } @{$co{'parents'}} ) .
7891 ')';
7895 my $hash_parent_param = $hash_parent;
7896 if (!defined $hash_parent_param) {
7897 # --cc for multiple parents, --root for parentless
7898 $hash_parent_param =
7899 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7902 # read commitdiff
7903 my $fd;
7904 my @difftree;
7905 if ($format eq 'html') {
7906 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7907 "--no-commit-id", "--patch-with-raw", "--full-index",
7908 $hash_parent_param, $hash, "--"
7909 or die_error(500, "Open git-diff-tree failed");
7911 while (my $line = <$fd>) {
7912 chomp $line;
7913 # empty line ends raw part of diff-tree output
7914 last unless $line;
7915 push @difftree, scalar parse_difftree_raw_line($line);
7918 } elsif ($format eq 'plain') {
7919 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7920 '-p', $hash_parent_param, $hash, "--"
7921 or die_error(500, "Open git-diff-tree failed");
7922 } elsif ($format eq 'patch') {
7923 # For commit ranges, we limit the output to the number of
7924 # patches specified in the 'patches' feature.
7925 # For single commits, we limit the output to a single patch,
7926 # diverging from the git-format-patch default.
7927 my @commit_spec = ();
7928 if ($hash_parent) {
7929 if ($patch_max > 0) {
7930 push @commit_spec, "-$patch_max";
7932 push @commit_spec, '-n', "$hash_parent..$hash";
7933 } else {
7934 if ($params{-single}) {
7935 push @commit_spec, '-1';
7936 } else {
7937 if ($patch_max > 0) {
7938 push @commit_spec, "-$patch_max";
7940 push @commit_spec, "-n";
7942 push @commit_spec, '--root', $hash;
7944 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7945 '--encoding=utf8', '--stdout', @commit_spec
7946 or die_error(500, "Open git-format-patch failed");
7947 } else {
7948 die_error(400, "Unknown commitdiff format");
7951 # non-textual hash id's can be cached
7952 my $expires;
7953 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7954 $expires = "+1d";
7957 # write commit message
7958 if ($format eq 'html') {
7959 my $refs = git_get_references();
7960 my $ref = format_ref_marker($refs, $co{'id'});
7962 git_header_html(undef, $expires);
7963 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7964 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7965 print "<div class=\"title_text\">\n" .
7966 "<table class=\"object_header\">\n";
7967 git_print_authorship_rows(\%co);
7968 print "</table>".
7969 "</div>\n";
7970 print "<div class=\"page_body\">\n";
7971 if (@{$co{'comment'}} > 1) {
7972 print "<div class=\"log\">\n";
7973 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7974 print "</div>\n"; # class="log"
7977 } elsif ($format eq 'plain') {
7978 my $refs = git_get_references("tags");
7979 my $tagname = git_get_rev_name_tags($hash);
7980 my $filename = basename($project) . "-$hash.patch";
7982 print $cgi->header(
7983 -type => 'text/plain',
7984 -charset => 'utf-8',
7985 -expires => $expires,
7986 -content_disposition => 'inline; filename="' . "$filename" . '"');
7987 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7988 print "From: " . to_utf8($co{'author'}) . "\n";
7989 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7990 print "Subject: " . to_utf8($co{'title'}) . "\n";
7992 print "X-Git-Tag: $tagname\n" if $tagname;
7993 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7995 foreach my $line (@{$co{'comment'}}) {
7996 print to_utf8($line) . "\n";
7998 print "---\n\n";
7999 } elsif ($format eq 'patch') {
8000 my $filename = basename($project) . "-$hash.patch";
8002 print $cgi->header(
8003 -type => 'text/plain',
8004 -charset => 'utf-8',
8005 -expires => $expires,
8006 -content_disposition => 'inline; filename="' . "$filename" . '"');
8009 # write patch
8010 if ($format eq 'html') {
8011 my $use_parents = !defined $hash_parent ||
8012 $hash_parent eq '-c' || $hash_parent eq '--cc';
8013 git_difftree_body(\@difftree, $hash,
8014 $use_parents ? @{$co{'parents'}} : $hash_parent);
8015 print "<br/>\n";
8017 git_patchset_body($fd, $diff_style,
8018 \@difftree, $hash,
8019 $use_parents ? @{$co{'parents'}} : $hash_parent);
8020 close $fd;
8021 print "</div>\n"; # class="page_body"
8022 git_footer_html();
8024 } elsif ($format eq 'plain') {
8025 local $/ = undef;
8026 print <$fd>;
8027 close $fd
8028 or print "Reading git-diff-tree failed\n";
8029 } elsif ($format eq 'patch') {
8030 local $/ = undef;
8031 print <$fd>;
8032 close $fd
8033 or print "Reading git-format-patch failed\n";
8037 sub git_commitdiff_plain {
8038 git_commitdiff(-format => 'plain');
8041 # format-patch-style patches
8042 sub git_patch {
8043 git_commitdiff(-format => 'patch', -single => 1);
8046 sub git_patches {
8047 git_commitdiff(-format => 'patch');
8050 sub git_history {
8051 git_log_generic('history', \&git_history_body,
8052 $hash_base, $hash_parent_base,
8053 $file_name, $hash);
8056 sub git_search {
8057 $searchtype ||= 'commit';
8059 # check if appropriate features are enabled
8060 gitweb_check_feature('search')
8061 or die_error(403, "Search is disabled");
8062 if ($searchtype eq 'pickaxe') {
8063 # pickaxe may take all resources of your box and run for several minutes
8064 # with every query - so decide by yourself how public you make this feature
8065 gitweb_check_feature('pickaxe')
8066 or die_error(403, "Pickaxe search is disabled");
8068 if ($searchtype eq 'grep') {
8069 # grep search might be potentially CPU-intensive, too
8070 gitweb_check_feature('grep')
8071 or die_error(403, "Grep search is disabled");
8074 if (!defined $searchtext) {
8075 die_error(400, "Text field is empty");
8077 if (!defined $hash) {
8078 $hash = git_get_head_hash($project);
8080 my %co = parse_commit($hash);
8081 if (!%co) {
8082 die_error(404, "Unknown commit object");
8084 if (!defined $page) {
8085 $page = 0;
8088 if ($searchtype eq 'commit' ||
8089 $searchtype eq 'author' ||
8090 $searchtype eq 'committer') {
8091 git_search_message(%co);
8092 } elsif ($searchtype eq 'pickaxe') {
8093 git_search_changes(%co);
8094 } elsif ($searchtype eq 'grep') {
8095 git_search_files(%co);
8096 } else {
8097 die_error(400, "Unknown search type");
8101 sub git_search_help {
8102 git_header_html();
8103 git_print_page_nav('','', $hash,$hash,$hash);
8104 print <<EOT;
8105 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8106 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8107 the pattern entered is recognized as the POSIX extended
8108 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8109 insensitive).</p>
8110 <dl>
8111 <dt><b>commit</b></dt>
8112 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8114 my $have_grep = gitweb_check_feature('grep');
8115 if ($have_grep) {
8116 print <<EOT;
8117 <dt><b>grep</b></dt>
8118 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8119 a different one) are searched for the given pattern. On large trees, this search can take
8120 a while and put some strain on the server, so please use it with some consideration. Note that
8121 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8122 case-sensitive.</dd>
8125 print <<EOT;
8126 <dt><b>author</b></dt>
8127 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8128 <dt><b>committer</b></dt>
8129 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8131 my $have_pickaxe = gitweb_check_feature('pickaxe');
8132 if ($have_pickaxe) {
8133 print <<EOT;
8134 <dt><b>pickaxe</b></dt>
8135 <dd>All commits that caused the string to appear or disappear from any file (changes that
8136 added, removed or "modified" the string) will be listed. This search can take a while and
8137 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8138 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8141 print "</dl>\n";
8142 git_footer_html();
8145 sub git_shortlog {
8146 git_log_generic('shortlog', \&git_shortlog_body,
8147 $hash, $hash_parent);
8150 ## ......................................................................
8151 ## feeds (RSS, Atom; OPML)
8153 sub git_feed {
8154 my $format = shift || 'atom';
8155 my $have_blame = gitweb_check_feature('blame');
8157 # Atom: http://www.atomenabled.org/developers/syndication/
8158 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8159 if ($format ne 'rss' && $format ne 'atom') {
8160 die_error(400, "Unknown web feed format");
8163 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8164 my $head = $hash || 'HEAD';
8165 my @commitlist = parse_commits($head, 150, 0, $file_name);
8167 my %latest_commit;
8168 my %latest_date;
8169 my $content_type = "application/$format+xml";
8170 if (defined $cgi->http('HTTP_ACCEPT') &&
8171 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8172 # browser (feed reader) prefers text/xml
8173 $content_type = 'text/xml';
8175 if (defined($commitlist[0])) {
8176 %latest_commit = %{$commitlist[0]};
8177 my $latest_epoch = $latest_commit{'committer_epoch'};
8178 exit_if_unmodified_since($latest_epoch);
8179 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8181 print $cgi->header(
8182 -type => $content_type,
8183 -charset => 'utf-8',
8184 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8185 -status => '200 OK');
8187 # Optimization: skip generating the body if client asks only
8188 # for Last-Modified date.
8189 return if ($cgi->request_method() eq 'HEAD');
8191 # header variables
8192 my $title = "$site_name - $project/$action";
8193 my $feed_type = 'log';
8194 if (defined $hash) {
8195 $title .= " - '$hash'";
8196 $feed_type = 'branch log';
8197 if (defined $file_name) {
8198 $title .= " :: $file_name";
8199 $feed_type = 'history';
8201 } elsif (defined $file_name) {
8202 $title .= " - $file_name";
8203 $feed_type = 'history';
8205 $title .= " $feed_type";
8206 $title = esc_html($title);
8207 my $descr = git_get_project_description($project);
8208 if (defined $descr) {
8209 $descr = esc_html($descr);
8210 } else {
8211 $descr = "$project " .
8212 ($format eq 'rss' ? 'RSS' : 'Atom') .
8213 " feed";
8215 my $owner = git_get_project_owner($project);
8216 $owner = esc_html($owner);
8218 #header
8219 my $alt_url;
8220 if (defined $file_name) {
8221 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8222 } elsif (defined $hash) {
8223 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8224 } else {
8225 $alt_url = href(-full=>1, action=>"summary");
8227 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8228 if ($format eq 'rss') {
8229 print <<XML;
8230 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8231 <channel>
8233 print "<title>$title</title>\n" .
8234 "<link>$alt_url</link>\n" .
8235 "<description>$descr</description>\n" .
8236 "<language>en</language>\n" .
8237 # project owner is responsible for 'editorial' content
8238 "<managingEditor>$owner</managingEditor>\n";
8239 if (defined $logo || defined $favicon) {
8240 # prefer the logo to the favicon, since RSS
8241 # doesn't allow both
8242 my $img = esc_url($logo || $favicon);
8243 print "<image>\n" .
8244 "<url>$img</url>\n" .
8245 "<title>$title</title>\n" .
8246 "<link>$alt_url</link>\n" .
8247 "</image>\n";
8249 if (%latest_date) {
8250 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8251 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8253 print "<generator>gitweb v.$version/$git_version</generator>\n";
8254 } elsif ($format eq 'atom') {
8255 print <<XML;
8256 <feed xmlns="http://www.w3.org/2005/Atom">
8258 print "<title>$title</title>\n" .
8259 "<subtitle>$descr</subtitle>\n" .
8260 '<link rel="alternate" type="text/html" href="' .
8261 $alt_url . '" />' . "\n" .
8262 '<link rel="self" type="' . $content_type . '" href="' .
8263 $cgi->self_url() . '" />' . "\n" .
8264 "<id>" . href(-full=>1) . "</id>\n" .
8265 # use project owner for feed author
8266 "<author><name>$owner</name></author>\n";
8267 if (defined $favicon) {
8268 print "<icon>" . esc_url($favicon) . "</icon>\n";
8270 if (defined $logo) {
8271 # not twice as wide as tall: 72 x 27 pixels
8272 print "<logo>" . esc_url($logo) . "</logo>\n";
8274 if (! %latest_date) {
8275 # dummy date to keep the feed valid until commits trickle in:
8276 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8277 } else {
8278 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8280 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8283 # contents
8284 for (my $i = 0; $i <= $#commitlist; $i++) {
8285 my %co = %{$commitlist[$i]};
8286 my $commit = $co{'id'};
8287 # we read 150, we always show 30 and the ones more recent than 48 hours
8288 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8289 last;
8291 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8293 # get list of changed files
8294 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8295 $co{'parent'} || "--root",
8296 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8297 or next;
8298 my @difftree = map { chomp; $_ } <$fd>;
8299 close $fd
8300 or next;
8302 # print element (entry, item)
8303 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8304 if ($format eq 'rss') {
8305 print "<item>\n" .
8306 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8307 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8308 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8309 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8310 "<link>$co_url</link>\n" .
8311 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8312 "<content:encoded>" .
8313 "<![CDATA[\n";
8314 } elsif ($format eq 'atom') {
8315 print "<entry>\n" .
8316 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8317 "<updated>$cd{'iso-8601'}</updated>\n" .
8318 "<author>\n" .
8319 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8320 if ($co{'author_email'}) {
8321 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8323 print "</author>\n" .
8324 # use committer for contributor
8325 "<contributor>\n" .
8326 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8327 if ($co{'committer_email'}) {
8328 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8330 print "</contributor>\n" .
8331 "<published>$cd{'iso-8601'}</published>\n" .
8332 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8333 "<id>$co_url</id>\n" .
8334 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8335 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8337 my $comment = $co{'comment'};
8338 print "<pre>\n";
8339 foreach my $line (@$comment) {
8340 $line = esc_html($line);
8341 print "$line\n";
8343 print "</pre><ul>\n";
8344 foreach my $difftree_line (@difftree) {
8345 my %difftree = parse_difftree_raw_line($difftree_line);
8346 next if !$difftree{'from_id'};
8348 my $file = $difftree{'file'} || $difftree{'to_file'};
8350 print "<li>" .
8351 "[" .
8352 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8353 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8354 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8355 file_name=>$file, file_parent=>$difftree{'from_file'}),
8356 -title => "diff"}, 'D');
8357 if ($have_blame) {
8358 print $cgi->a({-href => href(-full=>1, action=>"blame",
8359 file_name=>$file, hash_base=>$commit),
8360 -class => "blamelink",
8361 -title => "blame"}, 'B');
8363 # if this is not a feed of a file history
8364 if (!defined $file_name || $file_name ne $file) {
8365 print $cgi->a({-href => href(-full=>1, action=>"history",
8366 file_name=>$file, hash=>$commit),
8367 -title => "history"}, 'H');
8369 $file = esc_path($file);
8370 print "] ".
8371 "$file</li>\n";
8373 if ($format eq 'rss') {
8374 print "</ul>]]>\n" .
8375 "</content:encoded>\n" .
8376 "</item>\n";
8377 } elsif ($format eq 'atom') {
8378 print "</ul>\n</div>\n" .
8379 "</content>\n" .
8380 "</entry>\n";
8384 # end of feed
8385 if ($format eq 'rss') {
8386 print "</channel>\n</rss>\n";
8387 } elsif ($format eq 'atom') {
8388 print "</feed>\n";
8392 sub git_rss {
8393 git_feed('rss');
8396 sub git_atom {
8397 git_feed('atom');
8400 sub git_opml {
8401 my @list = git_get_projects_list($project_filter, $strict_export);
8402 if (!@list) {
8403 die_error(404, "No projects found");
8406 print $cgi->header(
8407 -type => 'text/xml',
8408 -charset => 'utf-8',
8409 -content_disposition => 'inline; filename="opml.xml"');
8411 my $title = esc_html($site_name);
8412 my $filter = " within subdirectory ";
8413 if (defined $project_filter) {
8414 $filter .= esc_html($project_filter);
8415 } else {
8416 $filter = "";
8418 print <<XML;
8419 <?xml version="1.0" encoding="utf-8"?>
8420 <opml version="1.0">
8421 <head>
8422 <title>$title OPML Export$filter</title>
8423 </head>
8424 <body>
8425 <outline text="git RSS feeds">
8428 foreach my $pr (@list) {
8429 my %proj = %$pr;
8430 my $head = git_get_head_hash($proj{'path'});
8431 if (!defined $head) {
8432 next;
8434 $git_dir = "$projectroot/$proj{'path'}";
8435 my %co = parse_commit($head);
8436 if (!%co) {
8437 next;
8440 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8441 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8442 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8443 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8445 print <<XML;
8446 </outline>
8447 </body>
8448 </opml>