gitweb.psgi: Allow passing arguments to Plack::Runner
[git/jnareb-git.git] / gitweb / gitweb.perl
blobb82c3665afd810814016715a01ca41abec8818d5
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;
14 use File::Spec;
15 # __DIR__ is taken from Dir::Self __DIR__ fragment
16 sub __DIR__ () {
17 File::Spec->rel2abs(join '', (File::Spec->splitpath(__FILE__))[0, 1]);
19 use lib __DIR__ . '/lib';
21 use CGI qw(:standard :escapeHTML -nosticky);
22 use CGI::Util qw(unescape);
23 use CGI::Carp qw(fatalsToBrowser set_message);
24 use Encode;
25 use Fcntl ':mode';
26 use File::Find qw();
27 use File::Basename qw(basename);
28 use Time::HiRes qw(gettimeofday tv_interval);
29 binmode STDOUT, ':utf8';
31 our $t0 = [ gettimeofday() ];
32 our $number_of_git_cmds = 0;
34 BEGIN {
35 CGI->compile() if $ENV{'MOD_PERL'};
38 our $version = "++GIT_VERSION++";
40 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
41 sub evaluate_uri {
42 our $cgi;
44 our $my_url = $cgi->url();
45 our $my_uri = $cgi->url(-absolute => 1);
47 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
48 # needed and used only for URLs with nonempty PATH_INFO
49 our $base_url = $my_url;
51 # When the script is used as DirectoryIndex, the URL does not contain the name
52 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
53 # have to do it ourselves. We make $path_info global because it's also used
54 # later on.
56 # Another issue with the script being the DirectoryIndex is that the resulting
57 # $my_url data is not the full script URL: this is good, because we want
58 # generated links to keep implying the script name if it wasn't explicitly
59 # indicated in the URL we're handling, but it means that $my_url cannot be used
60 # as base URL.
61 # Therefore, if we needed to strip PATH_INFO, then we know that we have
62 # to build the base URL ourselves:
63 our $path_info = decode_utf8($ENV{"PATH_INFO"});
64 if ($path_info) {
65 if ($my_url =~ s,\Q$path_info\E$,, &&
66 $my_uri =~ s,\Q$path_info\E$,, &&
67 defined $ENV{'SCRIPT_NAME'}) {
68 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
72 # target of the home link on top of all pages
73 our $home_link = $my_uri || "/";
76 # core git executable to use
77 # this can just be "git" if your webserver has a sensible PATH
78 our $GIT = "++GIT_BINDIR++/git";
80 # absolute fs-path which will be prepended to the project path
81 #our $projectroot = "/pub/scm";
82 our $projectroot = "++GITWEB_PROJECTROOT++";
84 # fs traversing limit for getting project list
85 # the number is relative to the projectroot
86 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
88 # string of the home link on top of all pages
89 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
91 # name of your site or organization to appear in page titles
92 # replace this with something more descriptive for clearer bookmarks
93 our $site_name = "++GITWEB_SITENAME++"
94 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
96 # html snippet to include in the <head> section of each page
97 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
98 # filename of html text to include at top of each page
99 our $site_header = "++GITWEB_SITE_HEADER++";
100 # html text to include at home page
101 our $home_text = "++GITWEB_HOMETEXT++";
102 # filename of html text to include at bottom of each page
103 our $site_footer = "++GITWEB_SITE_FOOTER++";
105 # URI of stylesheets
106 our @stylesheets = ("++GITWEB_CSS++");
107 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
108 our $stylesheet = undef;
109 # URI of GIT logo (72x27 size)
110 our $logo = "++GITWEB_LOGO++";
111 # URI of GIT favicon, assumed to be image/png type
112 our $favicon = "++GITWEB_FAVICON++";
113 # URI of gitweb.js (JavaScript code for gitweb)
114 our $javascript = "++GITWEB_JS++";
116 # URI and label (title) of GIT logo link
117 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
118 #our $logo_label = "git documentation";
119 our $logo_url = "http://git-scm.com/";
120 our $logo_label = "git homepage";
122 # source of projects list
123 our $projects_list = "++GITWEB_LIST++";
125 # the width (in characters) of the projects list "Description" column
126 our $projects_list_description_width = 25;
128 # group projects by category on the projects list
129 # (enabled if this variable evaluates to true)
130 our $projects_list_group_categories = 0;
132 # default category if none specified
133 # (leave the empty string for no category)
134 our $project_list_default_category = "";
136 # default order of projects list
137 # valid values are none, project, descr, owner, and age
138 our $default_projects_order = "project";
140 # show repository only if this file exists
141 # (only effective if this variable evaluates to true)
142 our $export_ok = "++GITWEB_EXPORT_OK++";
144 # don't generate age column on the projects list page
145 our $omit_age_column = 0;
147 # don't generate information about owners of repositories
148 our $omit_owner=0;
150 # show repository only if this subroutine returns true
151 # when given the path to the project, for example:
152 # sub { return -e "$_[0]/git-daemon-export-ok"; }
153 our $export_auth_hook = undef;
155 # only allow viewing of repositories also shown on the overview page
156 our $strict_export = "++GITWEB_STRICT_EXPORT++";
158 # list of git base URLs used for URL to where fetch project from,
159 # i.e. full URL is "$git_base_url/$project"
160 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
162 # default blob_plain mimetype and default charset for text/plain blob
163 our $default_blob_plain_mimetype = 'text/plain';
164 our $default_text_plain_charset = undef;
166 # file to use for guessing MIME types before trying /etc/mime.types
167 # (relative to the current git repository)
168 our $mimetypes_file = undef;
170 # assume this charset if line contains non-UTF-8 characters;
171 # it should be valid encoding (see Encoding::Supported(3pm) for list),
172 # for which encoding all byte sequences are valid, for example
173 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
174 # could be even 'utf-8' for the old behavior)
175 our $fallback_encoding = 'latin1';
177 # rename detection options for git-diff and git-diff-tree
178 # - default is '-M', with the cost proportional to
179 # (number of removed files) * (number of new files).
180 # - more costly is '-C' (which implies '-M'), with the cost proportional to
181 # (number of changed files + number of removed files) * (number of new files)
182 # - even more costly is '-C', '--find-copies-harder' with cost
183 # (number of files in the original tree) * (number of new files)
184 # - one might want to include '-B' option, e.g. '-B', '-M'
185 our @diff_opts = ('-M'); # taken from git_commit
187 # Disables features that would allow repository owners to inject script into
188 # the gitweb domain.
189 our $prevent_xss = 0;
191 # Path to the highlight executable to use (must be the one from
192 # http://www.andre-simon.de due to assumptions about parameters and output).
193 # Useful if highlight is not installed on your webserver's PATH.
194 # [Default: highlight]
195 our $highlight_bin = "++HIGHLIGHT_BIN++";
197 # information about snapshot formats that gitweb is capable of serving
198 our %known_snapshot_formats = (
199 # name => {
200 # 'display' => display name,
201 # 'type' => mime type,
202 # 'suffix' => filename suffix,
203 # 'format' => --format for git-archive,
204 # 'compressor' => [compressor command and arguments]
205 # (array reference, optional)
206 # 'disabled' => boolean (optional)}
208 'tgz' => {
209 'display' => 'tar.gz',
210 'type' => 'application/x-gzip',
211 'suffix' => '.tar.gz',
212 'format' => 'tar',
213 'compressor' => ['gzip', '-n']},
215 'tbz2' => {
216 'display' => 'tar.bz2',
217 'type' => 'application/x-bzip2',
218 'suffix' => '.tar.bz2',
219 'format' => 'tar',
220 'compressor' => ['bzip2']},
222 'txz' => {
223 'display' => 'tar.xz',
224 'type' => 'application/x-xz',
225 'suffix' => '.tar.xz',
226 'format' => 'tar',
227 'compressor' => ['xz'],
228 'disabled' => 1},
230 'zip' => {
231 'display' => 'zip',
232 'type' => 'application/x-zip',
233 'suffix' => '.zip',
234 'format' => 'zip'},
237 # Aliases so we understand old gitweb.snapshot values in repository
238 # configuration.
239 our %known_snapshot_format_aliases = (
240 'gzip' => 'tgz',
241 'bzip2' => 'tbz2',
242 'xz' => 'txz',
244 # backward compatibility: legacy gitweb config support
245 'x-gzip' => undef, 'gz' => undef,
246 'x-bzip2' => undef, 'bz2' => undef,
247 'x-zip' => undef, '' => undef,
250 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
251 # are changed, it may be appropriate to change these values too via
252 # $GITWEB_CONFIG.
253 our %avatar_size = (
254 'default' => 16,
255 'double' => 32
258 # Used to set the maximum load that we will still respond to gitweb queries.
259 # If server load exceed this value then return "503 server busy" error.
260 # If gitweb cannot determined server load, it is taken to be 0.
261 # Leave it undefined (or set to 'undef') to turn off load checking.
262 our $maxload = 300;
264 # configuration for 'highlight' (http://www.andre-simon.de/)
265 # match by basename
266 our %highlight_basename = (
267 #'Program' => 'py',
268 #'Library' => 'py',
269 'SConstruct' => 'py', # SCons equivalent of Makefile
270 'Makefile' => 'make',
272 # match by extension
273 our %highlight_ext = (
274 # main extensions, defining name of syntax;
275 # see files in /usr/share/highlight/langDefs/ directory
276 map { $_ => $_ }
277 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make),
278 # alternate extensions, see /etc/highlight/filetypes.conf
279 'h' => 'c',
280 map { $_ => 'sh' } qw(bash zsh ksh),
281 map { $_ => 'cpp' } qw(cxx c++ cc),
282 map { $_ => 'php' } qw(php3 php4 php5 phps),
283 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
284 map { $_ => 'make'} qw(mak mk),
285 map { $_ => 'xml' } qw(xhtml html htm),
288 # You define site-wide feature defaults here; override them with
289 # $GITWEB_CONFIG as necessary.
290 our %feature = (
291 # feature => {
292 # 'sub' => feature-sub (subroutine),
293 # 'override' => allow-override (boolean),
294 # 'default' => [ default options...] (array reference)}
296 # if feature is overridable (it means that allow-override has true value),
297 # then feature-sub will be called with default options as parameters;
298 # return value of feature-sub indicates if to enable specified feature
300 # if there is no 'sub' key (no feature-sub), then feature cannot be
301 # overridden
303 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
304 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
305 # is enabled
307 # Enable the 'blame' blob view, showing the last commit that modified
308 # each line in the file. This can be very CPU-intensive.
310 # To enable system wide have in $GITWEB_CONFIG
311 # $feature{'blame'}{'default'} = [1];
312 # To have project specific config enable override in $GITWEB_CONFIG
313 # $feature{'blame'}{'override'} = 1;
314 # and in project config gitweb.blame = 0|1;
315 'blame' => {
316 'sub' => sub { feature_bool('blame', @_) },
317 'override' => 0,
318 'default' => [0]},
320 # Enable the 'snapshot' link, providing a compressed archive of any
321 # tree. This can potentially generate high traffic if you have large
322 # project.
324 # Value is a list of formats defined in %known_snapshot_formats that
325 # you wish to offer.
326 # To disable system wide have in $GITWEB_CONFIG
327 # $feature{'snapshot'}{'default'} = [];
328 # To have project specific config enable override in $GITWEB_CONFIG
329 # $feature{'snapshot'}{'override'} = 1;
330 # and in project config, a comma-separated list of formats or "none"
331 # to disable. Example: gitweb.snapshot = tbz2,zip;
332 'snapshot' => {
333 'sub' => \&feature_snapshot,
334 'override' => 0,
335 'default' => ['tgz']},
337 # Enable text search, which will list the commits which match author,
338 # committer or commit text to a given string. Enabled by default.
339 # Project specific override is not supported.
341 # Note that this controls all search features, which means that if
342 # it is disabled, then 'grep' and 'pickaxe' search would also be
343 # disabled.
344 'search' => {
345 'override' => 0,
346 'default' => [1]},
348 # Enable grep search, which will list the files in currently selected
349 # tree containing the given string. Enabled by default. This can be
350 # potentially CPU-intensive, of course.
351 # Note that you need to have 'search' feature enabled too.
353 # To enable system wide have in $GITWEB_CONFIG
354 # $feature{'grep'}{'default'} = [1];
355 # To have project specific config enable override in $GITWEB_CONFIG
356 # $feature{'grep'}{'override'} = 1;
357 # and in project config gitweb.grep = 0|1;
358 'grep' => {
359 'sub' => sub { feature_bool('grep', @_) },
360 'override' => 0,
361 'default' => [1]},
363 # Enable the pickaxe search, which will list the commits that modified
364 # a given string in a file. This can be practical and quite faster
365 # alternative to 'blame', but still potentially CPU-intensive.
366 # Note that you need to have 'search' feature enabled too.
368 # To enable system wide have in $GITWEB_CONFIG
369 # $feature{'pickaxe'}{'default'} = [1];
370 # To have project specific config enable override in $GITWEB_CONFIG
371 # $feature{'pickaxe'}{'override'} = 1;
372 # and in project config gitweb.pickaxe = 0|1;
373 'pickaxe' => {
374 'sub' => sub { feature_bool('pickaxe', @_) },
375 'override' => 0,
376 'default' => [1]},
378 # Enable showing size of blobs in a 'tree' view, in a separate
379 # column, similar to what 'ls -l' does. This cost a bit of IO.
381 # To disable system wide have in $GITWEB_CONFIG
382 # $feature{'show-sizes'}{'default'} = [0];
383 # To have project specific config enable override in $GITWEB_CONFIG
384 # $feature{'show-sizes'}{'override'} = 1;
385 # and in project config gitweb.showsizes = 0|1;
386 'show-sizes' => {
387 'sub' => sub { feature_bool('showsizes', @_) },
388 'override' => 0,
389 'default' => [1]},
391 # Make gitweb use an alternative format of the URLs which can be
392 # more readable and natural-looking: project name is embedded
393 # directly in the path and the query string contains other
394 # auxiliary information. All gitweb installations recognize
395 # URL in either format; this configures in which formats gitweb
396 # generates links.
398 # To enable system wide have in $GITWEB_CONFIG
399 # $feature{'pathinfo'}{'default'} = [1];
400 # Project specific override is not supported.
402 # Note that you will need to change the default location of CSS,
403 # favicon, logo and possibly other files to an absolute URL. Also,
404 # if gitweb.cgi serves as your indexfile, you will need to force
405 # $my_uri to contain the script name in your $GITWEB_CONFIG.
406 'pathinfo' => {
407 'override' => 0,
408 'default' => [0]},
410 # Make gitweb consider projects in project root subdirectories
411 # to be forks of existing projects. Given project $projname.git,
412 # projects matching $projname/*.git will not be shown in the main
413 # projects list, instead a '+' mark will be added to $projname
414 # there and a 'forks' view will be enabled for the project, listing
415 # all the forks. If project list is taken from a file, forks have
416 # to be listed after the main project.
418 # To enable system wide have in $GITWEB_CONFIG
419 # $feature{'forks'}{'default'} = [1];
420 # Project specific override is not supported.
421 'forks' => {
422 'override' => 0,
423 'default' => [0]},
425 # Insert custom links to the action bar of all project pages.
426 # This enables you mainly to link to third-party scripts integrating
427 # into gitweb; e.g. git-browser for graphical history representation
428 # or custom web-based repository administration interface.
430 # The 'default' value consists of a list of triplets in the form
431 # (label, link, position) where position is the label after which
432 # to insert the link and link is a format string where %n expands
433 # to the project name, %f to the project path within the filesystem,
434 # %h to the current hash (h gitweb parameter) and %b to the current
435 # hash base (hb gitweb parameter); %% expands to %.
437 # To enable system wide have in $GITWEB_CONFIG e.g.
438 # $feature{'actions'}{'default'} = [('graphiclog',
439 # '/git-browser/by-commit.html?r=%n', 'summary')];
440 # Project specific override is not supported.
441 'actions' => {
442 'override' => 0,
443 'default' => []},
445 # Allow gitweb scan project content tags of project repository,
446 # and display the popular Web 2.0-ish "tag cloud" near the projects
447 # list. Note that this is something COMPLETELY different from the
448 # normal Git tags.
450 # gitweb by itself can show existing tags, but it does not handle
451 # tagging itself; you need to do it externally, outside gitweb.
452 # The format is described in git_get_project_ctags() subroutine.
453 # You may want to install the HTML::TagCloud Perl module to get
454 # a pretty tag cloud instead of just a list of tags.
456 # To enable system wide have in $GITWEB_CONFIG
457 # $feature{'ctags'}{'default'} = [1];
458 # Project specific override is not supported.
460 # In the future whether ctags editing is enabled might depend
461 # on the value, but using 1 should always mean no editing of ctags.
462 'ctags' => {
463 'override' => 0,
464 'default' => [0]},
466 # The maximum number of patches in a patchset generated in patch
467 # view. Set this to 0 or undef to disable patch view, or to a
468 # negative number to remove any limit.
470 # To disable system wide have in $GITWEB_CONFIG
471 # $feature{'patches'}{'default'} = [0];
472 # To have project specific config enable override in $GITWEB_CONFIG
473 # $feature{'patches'}{'override'} = 1;
474 # and in project config gitweb.patches = 0|n;
475 # where n is the maximum number of patches allowed in a patchset.
476 'patches' => {
477 'sub' => \&feature_patches,
478 'override' => 0,
479 'default' => [16]},
481 # Avatar support. When this feature is enabled, views such as
482 # shortlog or commit will display an avatar associated with
483 # the email of the committer(s) and/or author(s).
485 # Currently available providers are gravatar and picon.
486 # If an unknown provider is specified, the feature is disabled.
488 # Gravatar depends on Digest::MD5.
489 # Picon currently relies on the indiana.edu database.
491 # To enable system wide have in $GITWEB_CONFIG
492 # $feature{'avatar'}{'default'} = ['<provider>'];
493 # where <provider> is either gravatar or picon.
494 # To have project specific config enable override in $GITWEB_CONFIG
495 # $feature{'avatar'}{'override'} = 1;
496 # and in project config gitweb.avatar = <provider>;
497 'avatar' => {
498 'sub' => \&feature_avatar,
499 'override' => 0,
500 'default' => ['']},
502 # Enable displaying how much time and how many git commands
503 # it took to generate and display page. Disabled by default.
504 # Project specific override is not supported.
505 'timed' => {
506 'override' => 0,
507 'default' => [0]},
509 # Enable turning some links into links to actions which require
510 # JavaScript to run (like 'blame_incremental'). Not enabled by
511 # default. Project specific override is currently not supported.
512 'javascript-actions' => {
513 'override' => 0,
514 'default' => [0]},
516 # Enable and configure ability to change common timezone for dates
517 # in gitweb output via JavaScript. Enabled by default.
518 # Project specific override is not supported.
519 'javascript-timezone' => {
520 'override' => 0,
521 'default' => [
522 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
523 # or undef to turn off this feature
524 'gitweb_tz', # name of cookie where to store selected timezone
525 'datetime', # CSS class used to mark up dates for manipulation
528 # Syntax highlighting support. This is based on Daniel Svensson's
529 # and Sham Chukoury's work in gitweb-xmms2.git.
530 # It requires the 'highlight' program present in $PATH,
531 # and therefore is disabled by default.
533 # To enable system wide have in $GITWEB_CONFIG
534 # $feature{'highlight'}{'default'} = [1];
536 'highlight' => {
537 'sub' => sub { feature_bool('highlight', @_) },
538 'override' => 0,
539 'default' => [0]},
541 # Enable displaying of remote heads in the heads list
543 # To enable system wide have in $GITWEB_CONFIG
544 # $feature{'remote_heads'}{'default'} = [1];
545 # To have project specific config enable override in $GITWEB_CONFIG
546 # $feature{'remote_heads'}{'override'} = 1;
547 # and in project config gitweb.remote_heads = 0|1;
548 'remote_heads' => {
549 'sub' => sub { feature_bool('remote_heads', @_) },
550 'override' => 0,
551 'default' => [0]},
554 sub gitweb_get_feature {
555 my ($name) = @_;
556 return unless exists $feature{$name};
557 my ($sub, $override, @defaults) = (
558 $feature{$name}{'sub'},
559 $feature{$name}{'override'},
560 @{$feature{$name}{'default'}});
561 # project specific override is possible only if we have project
562 our $git_dir; # global variable, declared later
563 if (!$override || !defined $git_dir) {
564 return @defaults;
566 if (!defined $sub) {
567 warn "feature $name is not overridable";
568 return @defaults;
570 return $sub->(@defaults);
573 # A wrapper to check if a given feature is enabled.
574 # With this, you can say
576 # my $bool_feat = gitweb_check_feature('bool_feat');
577 # gitweb_check_feature('bool_feat') or somecode;
579 # instead of
581 # my ($bool_feat) = gitweb_get_feature('bool_feat');
582 # (gitweb_get_feature('bool_feat'))[0] or somecode;
584 sub gitweb_check_feature {
585 return (gitweb_get_feature(@_))[0];
589 sub feature_bool {
590 my $key = shift;
591 my ($val) = git_get_project_config($key, '--bool');
593 if (!defined $val) {
594 return ($_[0]);
595 } elsif ($val eq 'true') {
596 return (1);
597 } elsif ($val eq 'false') {
598 return (0);
602 sub feature_snapshot {
603 my (@fmts) = @_;
605 my ($val) = git_get_project_config('snapshot');
607 if ($val) {
608 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
611 return @fmts;
614 sub feature_patches {
615 my @val = (git_get_project_config('patches', '--int'));
617 if (@val) {
618 return @val;
621 return ($_[0]);
624 sub feature_avatar {
625 my @val = (git_get_project_config('avatar'));
627 return @val ? @val : @_;
630 # checking HEAD file with -e is fragile if the repository was
631 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
632 # and then pruned.
633 sub check_head_link {
634 my ($dir) = @_;
635 my $headfile = "$dir/HEAD";
636 return ((-e $headfile) ||
637 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
640 sub check_export_ok {
641 my ($dir) = @_;
642 return (check_head_link($dir) &&
643 (!$export_ok || -e "$dir/$export_ok") &&
644 (!$export_auth_hook || $export_auth_hook->($dir)));
647 # process alternate names for backward compatibility
648 # filter out unsupported (unknown) snapshot formats
649 sub filter_snapshot_fmts {
650 my @fmts = @_;
652 @fmts = map {
653 exists $known_snapshot_format_aliases{$_} ?
654 $known_snapshot_format_aliases{$_} : $_} @fmts;
655 @fmts = grep {
656 exists $known_snapshot_formats{$_} &&
657 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
660 # If it is set to code reference, it is code that it is to be run once per
661 # request, allowing updating configurations that change with each request,
662 # while running other code in config file only once.
664 # Otherwise, if it is false then gitweb would process config file only once;
665 # if it is true then gitweb config would be run for each request.
666 our $per_request_config = 1;
668 # read and parse gitweb config file given by its parameter.
669 # returns true on success, false on recoverable error, allowing
670 # to chain this subroutine, using first file that exists.
671 # dies on errors during parsing config file, as it is unrecoverable.
672 sub read_config_file {
673 my $filename = shift;
674 return unless defined $filename;
675 # die if there are errors parsing config file
676 if (-e $filename) {
677 do $filename;
678 die $@ if $@;
679 return 1;
681 return;
684 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
685 sub evaluate_gitweb_config {
686 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
687 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
688 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
690 # Protect agains duplications of file names, to not read config twice.
691 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
692 # there possibility of duplication of filename there doesn't matter.
693 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
694 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
696 # Common system-wide settings for convenience.
697 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
698 read_config_file($GITWEB_CONFIG_COMMON);
700 # Use first config file that exists. This means use the per-instance
701 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
702 read_config_file($GITWEB_CONFIG) and return;
703 read_config_file($GITWEB_CONFIG_SYSTEM);
706 # Get loadavg of system, to compare against $maxload.
707 # Currently it requires '/proc/loadavg' present to get loadavg;
708 # if it is not present it returns 0, which means no load checking.
709 sub get_loadavg {
710 if( -e '/proc/loadavg' ){
711 open my $fd, '<', '/proc/loadavg'
712 or return 0;
713 my @load = split(/\s+/, scalar <$fd>);
714 close $fd;
716 # The first three columns measure CPU and IO utilization of the last one,
717 # five, and 10 minute periods. The fourth column shows the number of
718 # currently running processes and the total number of processes in the m/n
719 # format. The last column displays the last process ID used.
720 return $load[0] || 0;
722 # additional checks for load average should go here for things that don't export
723 # /proc/loadavg
725 return 0;
728 # version of the core git binary
729 our $git_version;
730 sub evaluate_git_version {
731 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
732 $number_of_git_cmds++;
735 sub check_loadavg {
736 if (defined $maxload && get_loadavg() > $maxload) {
737 die_error(503, "The load average on the server is too high");
741 # ======================================================================
742 # input validation and dispatch
744 # input parameters can be collected from a variety of sources (presently, CGI
745 # and PATH_INFO), so we define an %input_params hash that collects them all
746 # together during validation: this allows subsequent uses (e.g. href()) to be
747 # agnostic of the parameter origin
749 our %input_params = ();
751 # input parameters are stored with the long parameter name as key. This will
752 # also be used in the href subroutine to convert parameters to their CGI
753 # equivalent, and since the href() usage is the most frequent one, we store
754 # the name -> CGI key mapping here, instead of the reverse.
756 # XXX: Warning: If you touch this, check the search form for updating,
757 # too.
759 our @cgi_param_mapping = (
760 project => "p",
761 action => "a",
762 file_name => "f",
763 file_parent => "fp",
764 hash => "h",
765 hash_parent => "hp",
766 hash_base => "hb",
767 hash_parent_base => "hpb",
768 page => "pg",
769 order => "o",
770 searchtext => "s",
771 searchtype => "st",
772 snapshot_format => "sf",
773 extra_options => "opt",
774 search_use_regexp => "sr",
775 ctag => "by_tag",
776 diff_style => "ds",
777 project_filter => "pf",
778 # this must be last entry (for manipulation from JavaScript)
779 javascript => "js"
781 our %cgi_param_mapping = @cgi_param_mapping;
783 # we will also need to know the possible actions, for validation
784 our %actions = (
785 "blame" => \&git_blame,
786 "blame_incremental" => \&git_blame_incremental,
787 "blame_data" => \&git_blame_data,
788 "blobdiff" => \&git_blobdiff,
789 "blobdiff_plain" => \&git_blobdiff_plain,
790 "blob" => \&git_blob,
791 "blob_plain" => \&git_blob_plain,
792 "commitdiff" => \&git_commitdiff,
793 "commitdiff_plain" => \&git_commitdiff_plain,
794 "commit" => \&git_commit,
795 "forks" => \&git_forks,
796 "heads" => \&git_heads,
797 "history" => \&git_history,
798 "log" => \&git_log,
799 "patch" => \&git_patch,
800 "patches" => \&git_patches,
801 "remotes" => \&git_remotes,
802 "rss" => \&git_rss,
803 "atom" => \&git_atom,
804 "search" => \&git_search,
805 "search_help" => \&git_search_help,
806 "shortlog" => \&git_shortlog,
807 "summary" => \&git_summary,
808 "tag" => \&git_tag,
809 "tags" => \&git_tags,
810 "tree" => \&git_tree,
811 "snapshot" => \&git_snapshot,
812 "object" => \&git_object,
813 # those below don't need $project
814 "opml" => \&git_opml,
815 "project_list" => \&git_project_list,
816 "project_index" => \&git_project_index,
819 # finally, we have the hash of allowed extra_options for the commands that
820 # allow them
821 our %allowed_options = (
822 "--no-merges" => [ qw(rss atom log shortlog history) ],
825 # fill %input_params with the CGI parameters. All values except for 'opt'
826 # should be single values, but opt can be an array. We should probably
827 # build an array of parameters that can be multi-valued, but since for the time
828 # being it's only this one, we just single it out
829 sub evaluate_query_params {
830 our $cgi;
832 while (my ($name, $symbol) = each %cgi_param_mapping) {
833 if ($symbol eq 'opt') {
834 $input_params{$name} = [ map { decode_utf8($_) } $cgi->param($symbol) ];
835 } else {
836 $input_params{$name} = decode_utf8($cgi->param($symbol));
841 # now read PATH_INFO and update the parameter list for missing parameters
842 sub evaluate_path_info {
843 return if defined $input_params{'project'};
844 return if !$path_info;
845 $path_info =~ s,^/+,,;
846 return if !$path_info;
848 # find which part of PATH_INFO is project
849 my $project = $path_info;
850 $project =~ s,/+$,,;
851 while ($project && !check_head_link("$projectroot/$project")) {
852 $project =~ s,/*[^/]*$,,;
854 return unless $project;
855 $input_params{'project'} = $project;
857 # do not change any parameters if an action is given using the query string
858 return if $input_params{'action'};
859 $path_info =~ s,^\Q$project\E/*,,;
861 # next, check if we have an action
862 my $action = $path_info;
863 $action =~ s,/.*$,,;
864 if (exists $actions{$action}) {
865 $path_info =~ s,^$action/*,,;
866 $input_params{'action'} = $action;
869 # list of actions that want hash_base instead of hash, but can have no
870 # pathname (f) parameter
871 my @wants_base = (
872 'tree',
873 'history',
876 # we want to catch, among others
877 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
878 my ($parentrefname, $parentpathname, $refname, $pathname) =
879 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
881 # first, analyze the 'current' part
882 if (defined $pathname) {
883 # we got "branch:filename" or "branch:dir/"
884 # we could use git_get_type(branch:pathname), but:
885 # - it needs $git_dir
886 # - it does a git() call
887 # - the convention of terminating directories with a slash
888 # makes it superfluous
889 # - embedding the action in the PATH_INFO would make it even
890 # more superfluous
891 $pathname =~ s,^/+,,;
892 if (!$pathname || substr($pathname, -1) eq "/") {
893 $input_params{'action'} ||= "tree";
894 $pathname =~ s,/$,,;
895 } else {
896 # the default action depends on whether we had parent info
897 # or not
898 if ($parentrefname) {
899 $input_params{'action'} ||= "blobdiff_plain";
900 } else {
901 $input_params{'action'} ||= "blob_plain";
904 $input_params{'hash_base'} ||= $refname;
905 $input_params{'file_name'} ||= $pathname;
906 } elsif (defined $refname) {
907 # we got "branch". In this case we have to choose if we have to
908 # set hash or hash_base.
910 # Most of the actions without a pathname only want hash to be
911 # set, except for the ones specified in @wants_base that want
912 # hash_base instead. It should also be noted that hand-crafted
913 # links having 'history' as an action and no pathname or hash
914 # set will fail, but that happens regardless of PATH_INFO.
915 if (defined $parentrefname) {
916 # if there is parent let the default be 'shortlog' action
917 # (for http://git.example.com/repo.git/A..B links); if there
918 # is no parent, dispatch will detect type of object and set
919 # action appropriately if required (if action is not set)
920 $input_params{'action'} ||= "shortlog";
922 if ($input_params{'action'} &&
923 grep { $_ eq $input_params{'action'} } @wants_base) {
924 $input_params{'hash_base'} ||= $refname;
925 } else {
926 $input_params{'hash'} ||= $refname;
930 # next, handle the 'parent' part, if present
931 if (defined $parentrefname) {
932 # a missing pathspec defaults to the 'current' filename, allowing e.g.
933 # someproject/blobdiff/oldrev..newrev:/filename
934 if ($parentpathname) {
935 $parentpathname =~ s,^/+,,;
936 $parentpathname =~ s,/$,,;
937 $input_params{'file_parent'} ||= $parentpathname;
938 } else {
939 $input_params{'file_parent'} ||= $input_params{'file_name'};
941 # we assume that hash_parent_base is wanted if a path was specified,
942 # or if the action wants hash_base instead of hash
943 if (defined $input_params{'file_parent'} ||
944 grep { $_ eq $input_params{'action'} } @wants_base) {
945 $input_params{'hash_parent_base'} ||= $parentrefname;
946 } else {
947 $input_params{'hash_parent'} ||= $parentrefname;
951 # for the snapshot action, we allow URLs in the form
952 # $project/snapshot/$hash.ext
953 # where .ext determines the snapshot and gets removed from the
954 # passed $refname to provide the $hash.
956 # To be able to tell that $refname includes the format extension, we
957 # require the following two conditions to be satisfied:
958 # - the hash input parameter MUST have been set from the $refname part
959 # of the URL (i.e. they must be equal)
960 # - the snapshot format MUST NOT have been defined already (e.g. from
961 # CGI parameter sf)
962 # It's also useless to try any matching unless $refname has a dot,
963 # so we check for that too
964 if (defined $input_params{'action'} &&
965 $input_params{'action'} eq 'snapshot' &&
966 defined $refname && index($refname, '.') != -1 &&
967 $refname eq $input_params{'hash'} &&
968 !defined $input_params{'snapshot_format'}) {
969 # We loop over the known snapshot formats, checking for
970 # extensions. Allowed extensions are both the defined suffix
971 # (which includes the initial dot already) and the snapshot
972 # format key itself, with a prepended dot
973 while (my ($fmt, $opt) = each %known_snapshot_formats) {
974 my $hash = $refname;
975 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
976 next;
978 my $sfx = $1;
979 # a valid suffix was found, so set the snapshot format
980 # and reset the hash parameter
981 $input_params{'snapshot_format'} = $fmt;
982 $input_params{'hash'} = $hash;
983 # we also set the format suffix to the one requested
984 # in the URL: this way a request for e.g. .tgz returns
985 # a .tgz instead of a .tar.gz
986 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
987 last;
992 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
993 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
994 $searchtext, $search_regexp, $project_filter);
995 sub evaluate_and_validate_params {
996 our $action = $input_params{'action'};
997 if (defined $action) {
998 if (!validate_action($action)) {
999 die_error(400, "Invalid action parameter");
1003 # parameters which are pathnames
1004 our $project = $input_params{'project'};
1005 if (defined $project) {
1006 if (!validate_project($project)) {
1007 undef $project;
1008 die_error(404, "No such project");
1012 our $project_filter = $input_params{'project_filter'};
1013 if (defined $project_filter) {
1014 if (!validate_pathname($project_filter)) {
1015 die_error(404, "Invalid project_filter parameter");
1019 our $file_name = $input_params{'file_name'};
1020 if (defined $file_name) {
1021 if (!validate_pathname($file_name)) {
1022 die_error(400, "Invalid file parameter");
1026 our $file_parent = $input_params{'file_parent'};
1027 if (defined $file_parent) {
1028 if (!validate_pathname($file_parent)) {
1029 die_error(400, "Invalid file parent parameter");
1033 # parameters which are refnames
1034 our $hash = $input_params{'hash'};
1035 if (defined $hash) {
1036 if (!validate_refname($hash)) {
1037 die_error(400, "Invalid hash parameter");
1041 our $hash_parent = $input_params{'hash_parent'};
1042 if (defined $hash_parent) {
1043 if (!validate_refname($hash_parent)) {
1044 die_error(400, "Invalid hash parent parameter");
1048 our $hash_base = $input_params{'hash_base'};
1049 if (defined $hash_base) {
1050 if (!validate_refname($hash_base)) {
1051 die_error(400, "Invalid hash base parameter");
1055 our @extra_options = @{$input_params{'extra_options'}};
1056 # @extra_options is always defined, since it can only be (currently) set from
1057 # CGI, and $cgi->param() returns the empty array in array context if the param
1058 # is not set
1059 foreach my $opt (@extra_options) {
1060 if (not exists $allowed_options{$opt}) {
1061 die_error(400, "Invalid option parameter");
1063 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1064 die_error(400, "Invalid option parameter for this action");
1068 our $hash_parent_base = $input_params{'hash_parent_base'};
1069 if (defined $hash_parent_base) {
1070 if (!validate_refname($hash_parent_base)) {
1071 die_error(400, "Invalid hash parent base parameter");
1075 # other parameters
1076 our $page = $input_params{'page'};
1077 if (defined $page) {
1078 if ($page =~ m/[^0-9]/) {
1079 die_error(400, "Invalid page parameter");
1083 our $searchtype = $input_params{'searchtype'};
1084 if (defined $searchtype) {
1085 if ($searchtype =~ m/[^a-z]/) {
1086 die_error(400, "Invalid searchtype parameter");
1090 our $search_use_regexp = $input_params{'search_use_regexp'};
1092 our $searchtext = $input_params{'searchtext'};
1093 our $search_regexp;
1094 if (defined $searchtext) {
1095 if (length($searchtext) < 2) {
1096 die_error(403, "At least two characters are required for search parameter");
1098 if ($search_use_regexp) {
1099 $search_regexp = $searchtext;
1100 if (!eval { qr/$search_regexp/; 1; }) {
1101 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1102 die_error(400, "Invalid search regexp '$search_regexp'",
1103 esc_html($error));
1105 } else {
1106 $search_regexp = quotemeta $searchtext;
1111 # path to the current git repository
1112 our $git_dir;
1113 sub evaluate_git_dir {
1114 our $git_dir = "$projectroot/$project" if $project;
1117 our (@snapshot_fmts, $git_avatar);
1118 sub configure_gitweb_features {
1119 # list of supported snapshot formats
1120 our @snapshot_fmts = gitweb_get_feature('snapshot');
1121 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1123 # check that the avatar feature is set to a known provider name,
1124 # and for each provider check if the dependencies are satisfied.
1125 # if the provider name is invalid or the dependencies are not met,
1126 # reset $git_avatar to the empty string.
1127 our ($git_avatar) = gitweb_get_feature('avatar');
1128 if ($git_avatar eq 'gravatar') {
1129 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1130 } elsif ($git_avatar eq 'picon') {
1131 # no dependencies
1132 } else {
1133 $git_avatar = '';
1137 # custom error handler: 'die <message>' is Internal Server Error
1138 sub handle_errors_html {
1139 my $msg = shift; # it is already HTML escaped
1141 # to avoid infinite loop where error occurs in die_error,
1142 # change handler to default handler, disabling handle_errors_html
1143 set_message("Error occured when inside die_error:\n$msg");
1145 # you cannot jump out of die_error when called as error handler;
1146 # the subroutine set via CGI::Carp::set_message is called _after_
1147 # HTTP headers are already written, so it cannot write them itself
1148 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1150 set_message(\&handle_errors_html);
1152 # dispatch
1153 sub dispatch {
1154 if (!defined $action) {
1155 if (defined $hash) {
1156 $action = git_get_type($hash);
1157 $action or die_error(404, "Object does not exist");
1158 } elsif (defined $hash_base && defined $file_name) {
1159 $action = git_get_type("$hash_base:$file_name");
1160 $action or die_error(404, "File or directory does not exist");
1161 } elsif (defined $project) {
1162 $action = 'summary';
1163 } else {
1164 $action = 'project_list';
1167 if (!defined($actions{$action})) {
1168 die_error(400, "Unknown action");
1170 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1171 !$project) {
1172 die_error(400, "Project needed");
1174 $actions{$action}->();
1177 sub reset_timer {
1178 our $t0 = [ gettimeofday() ]
1179 if defined $t0;
1180 our $number_of_git_cmds = 0;
1183 our $first_request = 1;
1184 sub run_request {
1185 reset_timer();
1187 evaluate_uri();
1188 if ($first_request) {
1189 evaluate_gitweb_config();
1190 evaluate_git_version();
1192 if ($per_request_config) {
1193 if (ref($per_request_config) eq 'CODE') {
1194 $per_request_config->();
1195 } elsif (!$first_request) {
1196 evaluate_gitweb_config();
1199 check_loadavg();
1201 # $projectroot and $projects_list might be set in gitweb config file
1202 $projects_list ||= $projectroot;
1204 evaluate_query_params();
1205 evaluate_path_info();
1206 evaluate_and_validate_params();
1207 evaluate_git_dir();
1209 configure_gitweb_features();
1211 dispatch();
1214 DONE_REQUEST:
1218 our $is_last_request = sub { 1 };
1219 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1220 our $CGI = 'CGI';
1221 our $cgi;
1222 sub configure_as_fcgi {
1223 require CGI::Fast;
1224 our $CGI = 'CGI::Fast';
1226 my $request_number = 0;
1227 # let each child service 100 requests
1228 our $is_last_request = sub { ++$request_number > 100 };
1230 sub configure_as_psgi {
1231 our $CGI = 'PSGI'; # fake
1233 sub evaluate_argv {
1234 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1235 configure_as_fcgi()
1236 if $script_name =~ /\.fcgi$/;
1237 configure_as_psgi()
1238 if $script_name =~ /\.psgi$/;
1240 return unless (@ARGV);
1242 require Getopt::Long;
1243 Getopt::Long::GetOptions(
1244 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1245 'psgi|plack' => \&configure_as_psgi,
1246 'nproc|n=i' => sub {
1247 my ($arg, $val) = @_;
1248 return unless eval { require FCGI::ProcManager; 1; };
1249 my $proc_manager = FCGI::ProcManager->new({
1250 n_processes => $val,
1252 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1253 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1254 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1259 # it is very similar to run() subroutine, but it would be hard to
1260 # extract common code; note that $*_hook variables can be set only
1261 # for FastCGI, so they are absent here
1262 sub to_psgi_app {
1263 require CGI::Emulate::PSGI;
1265 our $CGI = 'CGI';
1266 our $first_request = 1;
1268 my $app = CGI::Emulate::PSGI->handler(sub {
1269 CGI::initialize_globals();
1270 our $cgi = CGI->new();
1272 run_request();
1274 $first_request = 0;
1276 return $app;
1279 sub build_psgi_app {
1280 require Plack::Builder;
1281 require Plack::Middleware::Static;
1283 my $sigchld_mw = sub {
1284 my $app = shift;
1285 sub {
1286 my $env = shift;
1287 local $SIG{'CHLD'} = 'DEFAULT';
1288 local $SIG{'CLD'} = 'DEFAULT';
1289 $app->($env);
1293 # you're supposed to "add" middleware from outer to inner.
1294 # note: Plack::Builder DSL (builder, enable_if, enable) won't work
1295 # with "require Plack::Builder" outside BEGIN section.
1296 my $app = to_psgi_app();
1297 $app = Plack::Middleware::Static->wrap($app,
1298 path => qr{(?:^|/)static/.*\.(?:js|css|png)$},
1299 root => __DIR__,
1300 encoding => 'utf-8', # encoding for 'text/plain' files
1302 $app = $sigchld_mw->($app)
1303 if (defined $SIG{'CHLD'} && $SIG{'CHLD'} eq 'IGNORE');
1305 return $app;
1308 sub run_psgi_app {
1309 my $app = build_psgi_app();
1311 # make it runnable as standalone app,
1312 # like it would be run via 'plackup' utility.
1313 # PLACK_ENV is set by plackup etc.
1314 if ($ENV{'PLACK_ENV'} || $ENV{'PLACK_SERVER'}) {
1315 return $app;
1316 } else {
1317 require Plack::Runner;
1319 my $runner = Plack::Runner->new();
1320 $runner->parse_options(qw(--env deployment),
1321 qw(--host 127.0.0.1),
1322 @ARGV);
1323 $runner->run($app);
1327 sub run {
1328 evaluate_argv();
1329 if ($CGI eq 'PSGI' || $ENV{'PLACK_ENV'} || $ENV{'PLACK_SERVER'}) {
1330 return run_psgi_app();
1333 $first_request = 1;
1334 $pre_listen_hook->()
1335 if $pre_listen_hook;
1337 REQUEST:
1338 while ($cgi = $CGI->new()) {
1339 $pre_dispatch_hook->()
1340 if $pre_dispatch_hook;
1342 run_request();
1344 $post_dispatch_hook->()
1345 if $post_dispatch_hook;
1346 $first_request = 0;
1348 last REQUEST if ($is_last_request->());
1352 our $app = run();
1354 if (defined caller) {
1355 # wrapped in a subroutine processing requests,
1356 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1357 return $app;
1358 } else {
1359 # pure CGI script, serving single request
1360 exit;
1363 ## ======================================================================
1364 ## action links
1366 # possible values of extra options
1367 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1368 # -replay => 1 - start from a current view (replay with modifications)
1369 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1370 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1371 sub href {
1372 my %params = @_;
1373 # default is to use -absolute url() i.e. $my_uri
1374 my $href = $params{-full} ? $my_url : $my_uri;
1376 # implicit -replay, must be first of implicit params
1377 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1379 $params{'project'} = $project unless exists $params{'project'};
1381 if ($params{-replay}) {
1382 while (my ($name, $symbol) = each %cgi_param_mapping) {
1383 if (!exists $params{$name}) {
1384 $params{$name} = $input_params{$name};
1389 my $use_pathinfo = gitweb_check_feature('pathinfo');
1390 if (defined $params{'project'} &&
1391 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1392 # try to put as many parameters as possible in PATH_INFO:
1393 # - project name
1394 # - action
1395 # - hash_parent or hash_parent_base:/file_parent
1396 # - hash or hash_base:/filename
1397 # - the snapshot_format as an appropriate suffix
1399 # When the script is the root DirectoryIndex for the domain,
1400 # $href here would be something like http://gitweb.example.com/
1401 # Thus, we strip any trailing / from $href, to spare us double
1402 # slashes in the final URL
1403 $href =~ s,/$,,;
1405 # Then add the project name, if present
1406 $href .= "/".esc_path_info($params{'project'});
1407 delete $params{'project'};
1409 # since we destructively absorb parameters, we keep this
1410 # boolean that remembers if we're handling a snapshot
1411 my $is_snapshot = $params{'action'} eq 'snapshot';
1413 # Summary just uses the project path URL, any other action is
1414 # added to the URL
1415 if (defined $params{'action'}) {
1416 $href .= "/".esc_path_info($params{'action'})
1417 unless $params{'action'} eq 'summary';
1418 delete $params{'action'};
1421 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1422 # stripping nonexistent or useless pieces
1423 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1424 || $params{'hash_parent'} || $params{'hash'});
1425 if (defined $params{'hash_base'}) {
1426 if (defined $params{'hash_parent_base'}) {
1427 $href .= esc_path_info($params{'hash_parent_base'});
1428 # skip the file_parent if it's the same as the file_name
1429 if (defined $params{'file_parent'}) {
1430 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1431 delete $params{'file_parent'};
1432 } elsif ($params{'file_parent'} !~ /\.\./) {
1433 $href .= ":/".esc_path_info($params{'file_parent'});
1434 delete $params{'file_parent'};
1437 $href .= "..";
1438 delete $params{'hash_parent'};
1439 delete $params{'hash_parent_base'};
1440 } elsif (defined $params{'hash_parent'}) {
1441 $href .= esc_path_info($params{'hash_parent'}). "..";
1442 delete $params{'hash_parent'};
1445 $href .= esc_path_info($params{'hash_base'});
1446 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1447 $href .= ":/".esc_path_info($params{'file_name'});
1448 delete $params{'file_name'};
1450 delete $params{'hash'};
1451 delete $params{'hash_base'};
1452 } elsif (defined $params{'hash'}) {
1453 $href .= esc_path_info($params{'hash'});
1454 delete $params{'hash'};
1457 # If the action was a snapshot, we can absorb the
1458 # snapshot_format parameter too
1459 if ($is_snapshot) {
1460 my $fmt = $params{'snapshot_format'};
1461 # snapshot_format should always be defined when href()
1462 # is called, but just in case some code forgets, we
1463 # fall back to the default
1464 $fmt ||= $snapshot_fmts[0];
1465 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1466 delete $params{'snapshot_format'};
1470 # now encode the parameters explicitly
1471 my @result = ();
1472 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1473 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1474 if (defined $params{$name}) {
1475 if (ref($params{$name}) eq "ARRAY") {
1476 foreach my $par (@{$params{$name}}) {
1477 push @result, $symbol . "=" . esc_param($par);
1479 } else {
1480 push @result, $symbol . "=" . esc_param($params{$name});
1484 $href .= "?" . join(';', @result) if scalar @result;
1486 # final transformation: trailing spaces must be escaped (URI-encoded)
1487 $href =~ s/(\s+)$/CGI::escape($1)/e;
1489 if ($params{-anchor}) {
1490 $href .= "#".esc_param($params{-anchor});
1493 return $href;
1497 ## ======================================================================
1498 ## validation, quoting/unquoting and escaping
1500 sub validate_action {
1501 my $input = shift || return undef;
1502 return undef unless exists $actions{$input};
1503 return $input;
1506 sub validate_project {
1507 my $input = shift || return undef;
1508 if (!validate_pathname($input) ||
1509 !(-d "$projectroot/$input") ||
1510 !check_export_ok("$projectroot/$input") ||
1511 ($strict_export && !project_in_list($input))) {
1512 return undef;
1513 } else {
1514 return $input;
1518 sub validate_pathname {
1519 my $input = shift || return undef;
1521 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1522 # at the beginning, at the end, and between slashes.
1523 # also this catches doubled slashes
1524 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1525 return undef;
1527 # no null characters
1528 if ($input =~ m!\0!) {
1529 return undef;
1531 return $input;
1534 sub validate_refname {
1535 my $input = shift || return undef;
1537 # textual hashes are O.K.
1538 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1539 return $input;
1541 # it must be correct pathname
1542 $input = validate_pathname($input)
1543 or return undef;
1544 # restrictions on ref name according to git-check-ref-format
1545 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1546 return undef;
1548 return $input;
1551 # decode sequences of octets in utf8 into Perl's internal form,
1552 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1553 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1554 sub to_utf8 {
1555 my $str = shift;
1556 return undef unless defined $str;
1558 if (utf8::is_utf8($str) || utf8::decode($str)) {
1559 return $str;
1560 } else {
1561 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1565 # quote unsafe chars, but keep the slash, even when it's not
1566 # correct, but quoted slashes look too horrible in bookmarks
1567 sub esc_param {
1568 my $str = shift;
1569 return undef unless defined $str;
1570 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1571 $str =~ s/ /\+/g;
1572 return $str;
1575 # the quoting rules for path_info fragment are slightly different
1576 sub esc_path_info {
1577 my $str = shift;
1578 return undef unless defined $str;
1580 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1581 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1583 return $str;
1586 # quote unsafe chars in whole URL, so some characters cannot be quoted
1587 sub esc_url {
1588 my $str = shift;
1589 return undef unless defined $str;
1590 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1591 $str =~ s/ /\+/g;
1592 return $str;
1595 # quote unsafe characters in HTML attributes
1596 sub esc_attr {
1598 # for XHTML conformance escaping '"' to '&quot;' is not enough
1599 return esc_html(@_);
1602 # replace invalid utf8 character with SUBSTITUTION sequence
1603 sub esc_html {
1604 my $str = shift;
1605 my %opts = @_;
1607 return undef unless defined $str;
1609 $str = to_utf8($str);
1610 $str = $cgi->escapeHTML($str);
1611 if ($opts{'-nbsp'}) {
1612 $str =~ s/ /&nbsp;/g;
1614 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1615 return $str;
1618 # quote control characters and escape filename to HTML
1619 sub esc_path {
1620 my $str = shift;
1621 my %opts = @_;
1623 return undef unless defined $str;
1625 $str = to_utf8($str);
1626 $str = $cgi->escapeHTML($str);
1627 if ($opts{'-nbsp'}) {
1628 $str =~ s/ /&nbsp;/g;
1630 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1631 return $str;
1634 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1635 sub sanitize {
1636 my $str = shift;
1638 return undef unless defined $str;
1640 $str = to_utf8($str);
1641 $str =~ s|([[:cntrl:]])|($1 =~ /[\t\n\r]/ ? $1 : quot_cec($1))|eg;
1642 return $str;
1645 # Make control characters "printable", using character escape codes (CEC)
1646 sub quot_cec {
1647 my $cntrl = shift;
1648 my %opts = @_;
1649 my %es = ( # character escape codes, aka escape sequences
1650 "\t" => '\t', # tab (HT)
1651 "\n" => '\n', # line feed (LF)
1652 "\r" => '\r', # carrige return (CR)
1653 "\f" => '\f', # form feed (FF)
1654 "\b" => '\b', # backspace (BS)
1655 "\a" => '\a', # alarm (bell) (BEL)
1656 "\e" => '\e', # escape (ESC)
1657 "\013" => '\v', # vertical tab (VT)
1658 "\000" => '\0', # nul character (NUL)
1660 my $chr = ( (exists $es{$cntrl})
1661 ? $es{$cntrl}
1662 : sprintf('\%2x', ord($cntrl)) );
1663 if ($opts{-nohtml}) {
1664 return $chr;
1665 } else {
1666 return "<span class=\"cntrl\">$chr</span>";
1670 # Alternatively use unicode control pictures codepoints,
1671 # Unicode "printable representation" (PR)
1672 sub quot_upr {
1673 my $cntrl = shift;
1674 my %opts = @_;
1676 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1677 if ($opts{-nohtml}) {
1678 return $chr;
1679 } else {
1680 return "<span class=\"cntrl\">$chr</span>";
1684 # git may return quoted and escaped filenames
1685 sub unquote {
1686 my $str = shift;
1688 sub unq {
1689 my $seq = shift;
1690 my %es = ( # character escape codes, aka escape sequences
1691 't' => "\t", # tab (HT, TAB)
1692 'n' => "\n", # newline (NL)
1693 'r' => "\r", # return (CR)
1694 'f' => "\f", # form feed (FF)
1695 'b' => "\b", # backspace (BS)
1696 'a' => "\a", # alarm (bell) (BEL)
1697 'e' => "\e", # escape (ESC)
1698 'v' => "\013", # vertical tab (VT)
1701 if ($seq =~ m/^[0-7]{1,3}$/) {
1702 # octal char sequence
1703 return chr(oct($seq));
1704 } elsif (exists $es{$seq}) {
1705 # C escape sequence, aka character escape code
1706 return $es{$seq};
1708 # quoted ordinary character
1709 return $seq;
1712 if ($str =~ m/^"(.*)"$/) {
1713 # needs unquoting
1714 $str = $1;
1715 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1717 return $str;
1720 # escape tabs (convert tabs to spaces)
1721 sub untabify {
1722 my $line = shift;
1724 while ((my $pos = index($line, "\t")) != -1) {
1725 if (my $count = (8 - ($pos % 8))) {
1726 my $spaces = ' ' x $count;
1727 $line =~ s/\t/$spaces/;
1731 return $line;
1734 sub project_in_list {
1735 my $project = shift;
1736 my @list = git_get_projects_list();
1737 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1740 ## ----------------------------------------------------------------------
1741 ## HTML aware string manipulation
1743 # Try to chop given string on a word boundary between position
1744 # $len and $len+$add_len. If there is no word boundary there,
1745 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1746 # (marking chopped part) would be longer than given string.
1747 sub chop_str {
1748 my $str = shift;
1749 my $len = shift;
1750 my $add_len = shift || 10;
1751 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1753 # Make sure perl knows it is utf8 encoded so we don't
1754 # cut in the middle of a utf8 multibyte char.
1755 $str = to_utf8($str);
1757 # allow only $len chars, but don't cut a word if it would fit in $add_len
1758 # if it doesn't fit, cut it if it's still longer than the dots we would add
1759 # remove chopped character entities entirely
1761 # when chopping in the middle, distribute $len into left and right part
1762 # return early if chopping wouldn't make string shorter
1763 if ($where eq 'center') {
1764 return $str if ($len + 5 >= length($str)); # filler is length 5
1765 $len = int($len/2);
1766 } else {
1767 return $str if ($len + 4 >= length($str)); # filler is length 4
1770 # regexps: ending and beginning with word part up to $add_len
1771 my $endre = qr/.{$len}\w{0,$add_len}/;
1772 my $begre = qr/\w{0,$add_len}.{$len}/;
1774 if ($where eq 'left') {
1775 $str =~ m/^(.*?)($begre)$/;
1776 my ($lead, $body) = ($1, $2);
1777 if (length($lead) > 4) {
1778 $lead = " ...";
1780 return "$lead$body";
1782 } elsif ($where eq 'center') {
1783 $str =~ m/^($endre)(.*)$/;
1784 my ($left, $str) = ($1, $2);
1785 $str =~ m/^(.*?)($begre)$/;
1786 my ($mid, $right) = ($1, $2);
1787 if (length($mid) > 5) {
1788 $mid = " ... ";
1790 return "$left$mid$right";
1792 } else {
1793 $str =~ m/^($endre)(.*)$/;
1794 my $body = $1;
1795 my $tail = $2;
1796 if (length($tail) > 4) {
1797 $tail = "... ";
1799 return "$body$tail";
1803 # takes the same arguments as chop_str, but also wraps a <span> around the
1804 # result with a title attribute if it does get chopped. Additionally, the
1805 # string is HTML-escaped.
1806 sub chop_and_escape_str {
1807 my ($str) = @_;
1809 my $chopped = chop_str(@_);
1810 $str = to_utf8($str);
1811 if ($chopped eq $str) {
1812 return esc_html($chopped);
1813 } else {
1814 $str =~ s/[[:cntrl:]]/?/g;
1815 return $cgi->span({-title=>$str}, esc_html($chopped));
1819 # Highlight selected fragments of string, using given CSS class,
1820 # and escape HTML. It is assumed that fragments do not overlap.
1821 # Regions are passed as list of pairs (array references).
1823 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1824 # '<span class="mark">foo</span>bar'
1825 sub esc_html_hl_regions {
1826 my ($str, $css_class, @sel) = @_;
1827 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1828 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1829 return esc_html($str, %opts) unless @sel;
1831 my $out = '';
1832 my $pos = 0;
1834 for my $s (@sel) {
1835 my ($begin, $end) = @$s;
1837 # Don't create empty <span> elements.
1838 next if $end <= $begin;
1840 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1841 %opts);
1843 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1844 if ($begin - $pos > 0);
1845 $out .= $cgi->span({-class => $css_class}, $escaped);
1847 $pos = $end;
1849 $out .= esc_html(substr($str, $pos), %opts)
1850 if ($pos < length($str));
1852 return $out;
1855 # return positions of beginning and end of each match
1856 sub matchpos_list {
1857 my ($str, $regexp) = @_;
1858 return unless (defined $str && defined $regexp);
1860 my @matches;
1861 while ($str =~ /$regexp/g) {
1862 push @matches, [$-[0], $+[0]];
1864 return @matches;
1867 # highlight match (if any), and escape HTML
1868 sub esc_html_match_hl {
1869 my ($str, $regexp) = @_;
1870 return esc_html($str) unless defined $regexp;
1872 my @matches = matchpos_list($str, $regexp);
1873 return esc_html($str) unless @matches;
1875 return esc_html_hl_regions($str, 'match', @matches);
1879 # highlight match (if any) of shortened string, and escape HTML
1880 sub esc_html_match_hl_chopped {
1881 my ($str, $chopped, $regexp) = @_;
1882 return esc_html_match_hl($str, $regexp) unless defined $chopped;
1884 my @matches = matchpos_list($str, $regexp);
1885 return esc_html($chopped) unless @matches;
1887 # filter matches so that we mark chopped string
1888 my $tail = "... "; # see chop_str
1889 unless ($chopped =~ s/\Q$tail\E$//) {
1890 $tail = '';
1892 my $chop_len = length($chopped);
1893 my $tail_len = length($tail);
1894 my @filtered;
1896 for my $m (@matches) {
1897 if ($m->[0] > $chop_len) {
1898 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1899 last;
1900 } elsif ($m->[1] > $chop_len) {
1901 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1902 last;
1904 push @filtered, $m;
1907 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1910 ## ----------------------------------------------------------------------
1911 ## functions returning short strings
1913 # CSS class for given age value (in seconds)
1914 sub age_class {
1915 my $age = shift;
1917 if (!defined $age) {
1918 return "noage";
1919 } elsif ($age < 60*60*2) {
1920 return "age0";
1921 } elsif ($age < 60*60*24*2) {
1922 return "age1";
1923 } else {
1924 return "age2";
1928 # convert age in seconds to "nn units ago" string
1929 sub age_string {
1930 my $age = shift;
1931 my $age_str;
1933 if ($age > 60*60*24*365*2) {
1934 $age_str = (int $age/60/60/24/365);
1935 $age_str .= " years ago";
1936 } elsif ($age > 60*60*24*(365/12)*2) {
1937 $age_str = int $age/60/60/24/(365/12);
1938 $age_str .= " months ago";
1939 } elsif ($age > 60*60*24*7*2) {
1940 $age_str = int $age/60/60/24/7;
1941 $age_str .= " weeks ago";
1942 } elsif ($age > 60*60*24*2) {
1943 $age_str = int $age/60/60/24;
1944 $age_str .= " days ago";
1945 } elsif ($age > 60*60*2) {
1946 $age_str = int $age/60/60;
1947 $age_str .= " hours ago";
1948 } elsif ($age > 60*2) {
1949 $age_str = int $age/60;
1950 $age_str .= " min ago";
1951 } elsif ($age > 2) {
1952 $age_str = int $age;
1953 $age_str .= " sec ago";
1954 } else {
1955 $age_str .= " right now";
1957 return $age_str;
1960 use constant {
1961 S_IFINVALID => 0030000,
1962 S_IFGITLINK => 0160000,
1965 # submodule/subproject, a commit object reference
1966 sub S_ISGITLINK {
1967 my $mode = shift;
1969 return (($mode & S_IFMT) == S_IFGITLINK)
1972 # convert file mode in octal to symbolic file mode string
1973 sub mode_str {
1974 my $mode = oct shift;
1976 if (S_ISGITLINK($mode)) {
1977 return 'm---------';
1978 } elsif (S_ISDIR($mode & S_IFMT)) {
1979 return 'drwxr-xr-x';
1980 } elsif (S_ISLNK($mode)) {
1981 return 'lrwxrwxrwx';
1982 } elsif (S_ISREG($mode)) {
1983 # git cares only about the executable bit
1984 if ($mode & S_IXUSR) {
1985 return '-rwxr-xr-x';
1986 } else {
1987 return '-rw-r--r--';
1989 } else {
1990 return '----------';
1994 # convert file mode in octal to file type string
1995 sub file_type {
1996 my $mode = shift;
1998 if ($mode !~ m/^[0-7]+$/) {
1999 return $mode;
2000 } else {
2001 $mode = oct $mode;
2004 if (S_ISGITLINK($mode)) {
2005 return "submodule";
2006 } elsif (S_ISDIR($mode & S_IFMT)) {
2007 return "directory";
2008 } elsif (S_ISLNK($mode)) {
2009 return "symlink";
2010 } elsif (S_ISREG($mode)) {
2011 return "file";
2012 } else {
2013 return "unknown";
2017 # convert file mode in octal to file type description string
2018 sub file_type_long {
2019 my $mode = shift;
2021 if ($mode !~ m/^[0-7]+$/) {
2022 return $mode;
2023 } else {
2024 $mode = oct $mode;
2027 if (S_ISGITLINK($mode)) {
2028 return "submodule";
2029 } elsif (S_ISDIR($mode & S_IFMT)) {
2030 return "directory";
2031 } elsif (S_ISLNK($mode)) {
2032 return "symlink";
2033 } elsif (S_ISREG($mode)) {
2034 if ($mode & S_IXUSR) {
2035 return "executable";
2036 } else {
2037 return "file";
2039 } else {
2040 return "unknown";
2045 ## ----------------------------------------------------------------------
2046 ## functions returning short HTML fragments, or transforming HTML fragments
2047 ## which don't belong to other sections
2049 # format line of commit message.
2050 sub format_log_line_html {
2051 my $line = shift;
2053 $line = esc_html($line, -nbsp=>1);
2054 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2055 $cgi->a({-href => href(action=>"object", hash=>$1),
2056 -class => "text"}, $1);
2057 }eg;
2059 return $line;
2062 # format marker of refs pointing to given object
2064 # the destination action is chosen based on object type and current context:
2065 # - for annotated tags, we choose the tag view unless it's the current view
2066 # already, in which case we go to shortlog view
2067 # - for other refs, we keep the current view if we're in history, shortlog or
2068 # log view, and select shortlog otherwise
2069 sub format_ref_marker {
2070 my ($refs, $id) = @_;
2071 my $markers = '';
2073 if (defined $refs->{$id}) {
2074 foreach my $ref (@{$refs->{$id}}) {
2075 # this code exploits the fact that non-lightweight tags are the
2076 # only indirect objects, and that they are the only objects for which
2077 # we want to use tag instead of shortlog as action
2078 my ($type, $name) = qw();
2079 my $indirect = ($ref =~ s/\^\{\}$//);
2080 # e.g. tags/v2.6.11 or heads/next
2081 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2082 $type = $1;
2083 $name = $2;
2084 } else {
2085 $type = "ref";
2086 $name = $ref;
2089 my $class = $type;
2090 $class .= " indirect" if $indirect;
2092 my $dest_action = "shortlog";
2094 if ($indirect) {
2095 $dest_action = "tag" unless $action eq "tag";
2096 } elsif ($action =~ /^(history|(short)?log)$/) {
2097 $dest_action = $action;
2100 my $dest = "";
2101 $dest .= "refs/" unless $ref =~ m!^refs/!;
2102 $dest .= $ref;
2104 my $link = $cgi->a({
2105 -href => href(
2106 action=>$dest_action,
2107 hash=>$dest
2108 )}, $name);
2110 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2111 $link . "</span>";
2115 if ($markers) {
2116 return ' <span class="refs">'. $markers . '</span>';
2117 } else {
2118 return "";
2122 # format, perhaps shortened and with markers, title line
2123 sub format_subject_html {
2124 my ($long, $short, $href, $extra) = @_;
2125 $extra = '' unless defined($extra);
2127 if (length($short) < length($long)) {
2128 $long =~ s/[[:cntrl:]]/?/g;
2129 return $cgi->a({-href => $href, -class => "list subject",
2130 -title => to_utf8($long)},
2131 esc_html($short)) . $extra;
2132 } else {
2133 return $cgi->a({-href => $href, -class => "list subject"},
2134 esc_html($long)) . $extra;
2138 # Rather than recomputing the url for an email multiple times, we cache it
2139 # after the first hit. This gives a visible benefit in views where the avatar
2140 # for the same email is used repeatedly (e.g. shortlog).
2141 # The cache is shared by all avatar engines (currently gravatar only), which
2142 # are free to use it as preferred. Since only one avatar engine is used for any
2143 # given page, there's no risk for cache conflicts.
2144 our %avatar_cache = ();
2146 # Compute the picon url for a given email, by using the picon search service over at
2147 # http://www.cs.indiana.edu/picons/search.html
2148 sub picon_url {
2149 my $email = lc shift;
2150 if (!$avatar_cache{$email}) {
2151 my ($user, $domain) = split('@', $email);
2152 $avatar_cache{$email} =
2153 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2154 "$domain/$user/" .
2155 "users+domains+unknown/up/single";
2157 return $avatar_cache{$email};
2160 # Compute the gravatar url for a given email, if it's not in the cache already.
2161 # Gravatar stores only the part of the URL before the size, since that's the
2162 # one computationally more expensive. This also allows reuse of the cache for
2163 # different sizes (for this particular engine).
2164 sub gravatar_url {
2165 my $email = lc shift;
2166 my $size = shift;
2167 $avatar_cache{$email} ||=
2168 "http://www.gravatar.com/avatar/" .
2169 Digest::MD5::md5_hex($email) . "?s=";
2170 return $avatar_cache{$email} . $size;
2173 # Insert an avatar for the given $email at the given $size if the feature
2174 # is enabled.
2175 sub git_get_avatar {
2176 my ($email, %opts) = @_;
2177 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2178 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2179 $opts{-size} ||= 'default';
2180 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2181 my $url = "";
2182 if ($git_avatar eq 'gravatar') {
2183 $url = gravatar_url($email, $size);
2184 } elsif ($git_avatar eq 'picon') {
2185 $url = picon_url($email);
2187 # Other providers can be added by extending the if chain, defining $url
2188 # as needed. If no variant puts something in $url, we assume avatars
2189 # are completely disabled/unavailable.
2190 if ($url) {
2191 return $pre_white .
2192 "<img width=\"$size\" " .
2193 "class=\"avatar\" " .
2194 "src=\"".esc_url($url)."\" " .
2195 "alt=\"\" " .
2196 "/>" . $post_white;
2197 } else {
2198 return "";
2202 sub format_search_author {
2203 my ($author, $searchtype, $displaytext) = @_;
2204 my $have_search = gitweb_check_feature('search');
2206 if ($have_search) {
2207 my $performed = "";
2208 if ($searchtype eq 'author') {
2209 $performed = "authored";
2210 } elsif ($searchtype eq 'committer') {
2211 $performed = "committed";
2214 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2215 searchtext=>$author,
2216 searchtype=>$searchtype), class=>"list",
2217 title=>"Search for commits $performed by $author"},
2218 $displaytext);
2220 } else {
2221 return $displaytext;
2225 # format the author name of the given commit with the given tag
2226 # the author name is chopped and escaped according to the other
2227 # optional parameters (see chop_str).
2228 sub format_author_html {
2229 my $tag = shift;
2230 my $co = shift;
2231 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2232 return "<$tag class=\"author\">" .
2233 format_search_author($co->{'author_name'}, "author",
2234 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2235 $author) .
2236 "</$tag>";
2239 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2240 sub format_git_diff_header_line {
2241 my $line = shift;
2242 my $diffinfo = shift;
2243 my ($from, $to) = @_;
2245 if ($diffinfo->{'nparents'}) {
2246 # combined diff
2247 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2248 if ($to->{'href'}) {
2249 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2250 esc_path($to->{'file'}));
2251 } else { # file was deleted (no href)
2252 $line .= esc_path($to->{'file'});
2254 } else {
2255 # "ordinary" diff
2256 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2257 if ($from->{'href'}) {
2258 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2259 'a/' . esc_path($from->{'file'}));
2260 } else { # file was added (no href)
2261 $line .= 'a/' . esc_path($from->{'file'});
2263 $line .= ' ';
2264 if ($to->{'href'}) {
2265 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2266 'b/' . esc_path($to->{'file'}));
2267 } else { # file was deleted
2268 $line .= 'b/' . esc_path($to->{'file'});
2272 return "<div class=\"diff header\">$line</div>\n";
2275 # format extended diff header line, before patch itself
2276 sub format_extended_diff_header_line {
2277 my $line = shift;
2278 my $diffinfo = shift;
2279 my ($from, $to) = @_;
2281 # match <path>
2282 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2283 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2284 esc_path($from->{'file'}));
2286 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2287 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2288 esc_path($to->{'file'}));
2290 # match single <mode>
2291 if ($line =~ m/\s(\d{6})$/) {
2292 $line .= '<span class="info"> (' .
2293 file_type_long($1) .
2294 ')</span>';
2296 # match <hash>
2297 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2298 # can match only for combined diff
2299 $line = 'index ';
2300 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2301 if ($from->{'href'}[$i]) {
2302 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2303 -class=>"hash"},
2304 substr($diffinfo->{'from_id'}[$i],0,7));
2305 } else {
2306 $line .= '0' x 7;
2308 # separator
2309 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2311 $line .= '..';
2312 if ($to->{'href'}) {
2313 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2314 substr($diffinfo->{'to_id'},0,7));
2315 } else {
2316 $line .= '0' x 7;
2319 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2320 # can match only for ordinary diff
2321 my ($from_link, $to_link);
2322 if ($from->{'href'}) {
2323 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2324 substr($diffinfo->{'from_id'},0,7));
2325 } else {
2326 $from_link = '0' x 7;
2328 if ($to->{'href'}) {
2329 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2330 substr($diffinfo->{'to_id'},0,7));
2331 } else {
2332 $to_link = '0' x 7;
2334 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2335 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2338 return $line . "<br/>\n";
2341 # format from-file/to-file diff header
2342 sub format_diff_from_to_header {
2343 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2344 my $line;
2345 my $result = '';
2347 $line = $from_line;
2348 #assert($line =~ m/^---/) if DEBUG;
2349 # no extra formatting for "^--- /dev/null"
2350 if (! $diffinfo->{'nparents'}) {
2351 # ordinary (single parent) diff
2352 if ($line =~ m!^--- "?a/!) {
2353 if ($from->{'href'}) {
2354 $line = '--- a/' .
2355 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2356 esc_path($from->{'file'}));
2357 } else {
2358 $line = '--- a/' .
2359 esc_path($from->{'file'});
2362 $result .= qq!<div class="diff from_file">$line</div>\n!;
2364 } else {
2365 # combined diff (merge commit)
2366 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2367 if ($from->{'href'}[$i]) {
2368 $line = '--- ' .
2369 $cgi->a({-href=>href(action=>"blobdiff",
2370 hash_parent=>$diffinfo->{'from_id'}[$i],
2371 hash_parent_base=>$parents[$i],
2372 file_parent=>$from->{'file'}[$i],
2373 hash=>$diffinfo->{'to_id'},
2374 hash_base=>$hash,
2375 file_name=>$to->{'file'}),
2376 -class=>"path",
2377 -title=>"diff" . ($i+1)},
2378 $i+1) .
2379 '/' .
2380 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2381 esc_path($from->{'file'}[$i]));
2382 } else {
2383 $line = '--- /dev/null';
2385 $result .= qq!<div class="diff from_file">$line</div>\n!;
2389 $line = $to_line;
2390 #assert($line =~ m/^\+\+\+/) if DEBUG;
2391 # no extra formatting for "^+++ /dev/null"
2392 if ($line =~ m!^\+\+\+ "?b/!) {
2393 if ($to->{'href'}) {
2394 $line = '+++ b/' .
2395 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2396 esc_path($to->{'file'}));
2397 } else {
2398 $line = '+++ b/' .
2399 esc_path($to->{'file'});
2402 $result .= qq!<div class="diff to_file">$line</div>\n!;
2404 return $result;
2407 # create note for patch simplified by combined diff
2408 sub format_diff_cc_simplified {
2409 my ($diffinfo, @parents) = @_;
2410 my $result = '';
2412 $result .= "<div class=\"diff header\">" .
2413 "diff --cc ";
2414 if (!is_deleted($diffinfo)) {
2415 $result .= $cgi->a({-href => href(action=>"blob",
2416 hash_base=>$hash,
2417 hash=>$diffinfo->{'to_id'},
2418 file_name=>$diffinfo->{'to_file'}),
2419 -class => "path"},
2420 esc_path($diffinfo->{'to_file'}));
2421 } else {
2422 $result .= esc_path($diffinfo->{'to_file'});
2424 $result .= "</div>\n" . # class="diff header"
2425 "<div class=\"diff nodifferences\">" .
2426 "Simple merge" .
2427 "</div>\n"; # class="diff nodifferences"
2429 return $result;
2432 sub diff_line_class {
2433 my ($line, $from, $to) = @_;
2435 # ordinary diff
2436 my $num_sign = 1;
2437 # combined diff
2438 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2439 $num_sign = scalar @{$from->{'href'}};
2442 my @diff_line_classifier = (
2443 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2444 { regexp => qr/^\\/, class => "incomplete" },
2445 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2446 # classifier for context must come before classifier add/rem,
2447 # or we would have to use more complicated regexp, for example
2448 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2449 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2450 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2452 for my $clsfy (@diff_line_classifier) {
2453 return $clsfy->{'class'}
2454 if ($line =~ $clsfy->{'regexp'});
2457 # fallback
2458 return "";
2461 # assumes that $from and $to are defined and correctly filled,
2462 # and that $line holds a line of chunk header for unified diff
2463 sub format_unidiff_chunk_header {
2464 my ($line, $from, $to) = @_;
2466 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2467 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2469 $from_lines = 0 unless defined $from_lines;
2470 $to_lines = 0 unless defined $to_lines;
2472 if ($from->{'href'}) {
2473 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2474 -class=>"list"}, $from_text);
2476 if ($to->{'href'}) {
2477 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2478 -class=>"list"}, $to_text);
2480 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2481 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2482 return $line;
2485 # assumes that $from and $to are defined and correctly filled,
2486 # and that $line holds a line of chunk header for combined diff
2487 sub format_cc_diff_chunk_header {
2488 my ($line, $from, $to) = @_;
2490 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2491 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2493 @from_text = split(' ', $ranges);
2494 for (my $i = 0; $i < @from_text; ++$i) {
2495 ($from_start[$i], $from_nlines[$i]) =
2496 (split(',', substr($from_text[$i], 1)), 0);
2499 $to_text = pop @from_text;
2500 $to_start = pop @from_start;
2501 $to_nlines = pop @from_nlines;
2503 $line = "<span class=\"chunk_info\">$prefix ";
2504 for (my $i = 0; $i < @from_text; ++$i) {
2505 if ($from->{'href'}[$i]) {
2506 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2507 -class=>"list"}, $from_text[$i]);
2508 } else {
2509 $line .= $from_text[$i];
2511 $line .= " ";
2513 if ($to->{'href'}) {
2514 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2515 -class=>"list"}, $to_text);
2516 } else {
2517 $line .= $to_text;
2519 $line .= " $prefix</span>" .
2520 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2521 return $line;
2524 # process patch (diff) line (not to be used for diff headers),
2525 # returning HTML-formatted (but not wrapped) line.
2526 # If the line is passed as a reference, it is treated as HTML and not
2527 # esc_html()'ed.
2528 sub format_diff_line {
2529 my ($line, $diff_class, $from, $to) = @_;
2531 if (ref($line)) {
2532 $line = $$line;
2533 } else {
2534 chomp $line;
2535 $line = untabify($line);
2537 if ($from && $to && $line =~ m/^\@{2} /) {
2538 $line = format_unidiff_chunk_header($line, $from, $to);
2539 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2540 $line = format_cc_diff_chunk_header($line, $from, $to);
2541 } else {
2542 $line = esc_html($line, -nbsp=>1);
2546 my $diff_classes = "diff";
2547 $diff_classes .= " $diff_class" if ($diff_class);
2548 $line = "<div class=\"$diff_classes\">$line</div>\n";
2550 return $line;
2553 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2554 # linked. Pass the hash of the tree/commit to snapshot.
2555 sub format_snapshot_links {
2556 my ($hash) = @_;
2557 my $num_fmts = @snapshot_fmts;
2558 if ($num_fmts > 1) {
2559 # A parenthesized list of links bearing format names.
2560 # e.g. "snapshot (_tar.gz_ _zip_)"
2561 return "snapshot (" . join(' ', map
2562 $cgi->a({
2563 -href => href(
2564 action=>"snapshot",
2565 hash=>$hash,
2566 snapshot_format=>$_
2568 }, $known_snapshot_formats{$_}{'display'})
2569 , @snapshot_fmts) . ")";
2570 } elsif ($num_fmts == 1) {
2571 # A single "snapshot" link whose tooltip bears the format name.
2572 # i.e. "_snapshot_"
2573 my ($fmt) = @snapshot_fmts;
2574 return
2575 $cgi->a({
2576 -href => href(
2577 action=>"snapshot",
2578 hash=>$hash,
2579 snapshot_format=>$fmt
2581 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2582 }, "snapshot");
2583 } else { # $num_fmts == 0
2584 return undef;
2588 ## ......................................................................
2589 ## functions returning values to be passed, perhaps after some
2590 ## transformation, to other functions; e.g. returning arguments to href()
2592 # returns hash to be passed to href to generate gitweb URL
2593 # in -title key it returns description of link
2594 sub get_feed_info {
2595 my $format = shift || 'Atom';
2596 my %res = (action => lc($format));
2598 # feed links are possible only for project views
2599 return unless (defined $project);
2600 # some views should link to OPML, or to generic project feed,
2601 # or don't have specific feed yet (so they should use generic)
2602 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2604 my $branch;
2605 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2606 # from tag links; this also makes possible to detect branch links
2607 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2608 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2609 $branch = $1;
2611 # find log type for feed description (title)
2612 my $type = 'log';
2613 if (defined $file_name) {
2614 $type = "history of $file_name";
2615 $type .= "/" if ($action eq 'tree');
2616 $type .= " on '$branch'" if (defined $branch);
2617 } else {
2618 $type = "log of $branch" if (defined $branch);
2621 $res{-title} = $type;
2622 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2623 $res{'file_name'} = $file_name;
2625 return %res;
2628 ## ----------------------------------------------------------------------
2629 ## git utility subroutines, invoking git commands
2631 # returns path to the core git executable and the --git-dir parameter as list
2632 sub git_cmd {
2633 $number_of_git_cmds++;
2634 return $GIT, '--git-dir='.$git_dir;
2637 # quote the given arguments for passing them to the shell
2638 # quote_command("command", "arg 1", "arg with ' and ! characters")
2639 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2640 # Try to avoid using this function wherever possible.
2641 sub quote_command {
2642 return join(' ',
2643 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2646 # get HEAD ref of given project as hash
2647 sub git_get_head_hash {
2648 return git_get_full_hash(shift, 'HEAD');
2651 sub git_get_full_hash {
2652 return git_get_hash(@_);
2655 sub git_get_short_hash {
2656 return git_get_hash(@_, '--short=7');
2659 sub git_get_hash {
2660 my ($project, $hash, @options) = @_;
2661 my $o_git_dir = $git_dir;
2662 my $retval = undef;
2663 $git_dir = "$projectroot/$project";
2664 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2665 '--verify', '-q', @options, $hash) {
2666 $retval = <$fd>;
2667 chomp $retval if defined $retval;
2668 close $fd;
2670 if (defined $o_git_dir) {
2671 $git_dir = $o_git_dir;
2673 return $retval;
2676 # get type of given object
2677 sub git_get_type {
2678 my $hash = shift;
2680 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2681 my $type = <$fd>;
2682 close $fd or return;
2683 chomp $type;
2684 return $type;
2687 # repository configuration
2688 our $config_file = '';
2689 our %config;
2691 # store multiple values for single key as anonymous array reference
2692 # single values stored directly in the hash, not as [ <value> ]
2693 sub hash_set_multi {
2694 my ($hash, $key, $value) = @_;
2696 if (!exists $hash->{$key}) {
2697 $hash->{$key} = $value;
2698 } elsif (!ref $hash->{$key}) {
2699 $hash->{$key} = [ $hash->{$key}, $value ];
2700 } else {
2701 push @{$hash->{$key}}, $value;
2705 # return hash of git project configuration
2706 # optionally limited to some section, e.g. 'gitweb'
2707 sub git_parse_project_config {
2708 my $section_regexp = shift;
2709 my %config;
2711 local $/ = "\0";
2713 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2714 or return;
2716 while (my $keyval = <$fh>) {
2717 chomp $keyval;
2718 my ($key, $value) = split(/\n/, $keyval, 2);
2720 hash_set_multi(\%config, $key, $value)
2721 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2723 close $fh;
2725 return %config;
2728 # convert config value to boolean: 'true' or 'false'
2729 # no value, number > 0, 'true' and 'yes' values are true
2730 # rest of values are treated as false (never as error)
2731 sub config_to_bool {
2732 my $val = shift;
2734 return 1 if !defined $val; # section.key
2736 # strip leading and trailing whitespace
2737 $val =~ s/^\s+//;
2738 $val =~ s/\s+$//;
2740 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2741 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2744 # convert config value to simple decimal number
2745 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2746 # to be multiplied by 1024, 1048576, or 1073741824
2747 sub config_to_int {
2748 my $val = shift;
2750 # strip leading and trailing whitespace
2751 $val =~ s/^\s+//;
2752 $val =~ s/\s+$//;
2754 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2755 $unit = lc($unit);
2756 # unknown unit is treated as 1
2757 return $num * ($unit eq 'g' ? 1073741824 :
2758 $unit eq 'm' ? 1048576 :
2759 $unit eq 'k' ? 1024 : 1);
2761 return $val;
2764 # convert config value to array reference, if needed
2765 sub config_to_multi {
2766 my $val = shift;
2768 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2771 sub git_get_project_config {
2772 my ($key, $type) = @_;
2774 return unless defined $git_dir;
2776 # key sanity check
2777 return unless ($key);
2778 # only subsection, if exists, is case sensitive,
2779 # and not lowercased by 'git config -z -l'
2780 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2781 $key = join(".", lc($hi), $mi, lc($lo));
2782 } else {
2783 $key = lc($key);
2785 $key =~ s/^gitweb\.//;
2786 return if ($key =~ m/\W/);
2788 # type sanity check
2789 if (defined $type) {
2790 $type =~ s/^--//;
2791 $type = undef
2792 unless ($type eq 'bool' || $type eq 'int');
2795 # get config
2796 if (!defined $config_file ||
2797 $config_file ne "$git_dir/config") {
2798 %config = git_parse_project_config('gitweb');
2799 $config_file = "$git_dir/config";
2802 # check if config variable (key) exists
2803 return unless exists $config{"gitweb.$key"};
2805 # ensure given type
2806 if (!defined $type) {
2807 return $config{"gitweb.$key"};
2808 } elsif ($type eq 'bool') {
2809 # backward compatibility: 'git config --bool' returns true/false
2810 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2811 } elsif ($type eq 'int') {
2812 return config_to_int($config{"gitweb.$key"});
2814 return $config{"gitweb.$key"};
2817 # get hash of given path at given ref
2818 sub git_get_hash_by_path {
2819 my $base = shift;
2820 my $path = shift || return undef;
2821 my $type = shift;
2823 $path =~ s,/+$,,;
2825 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2826 or die_error(500, "Open git-ls-tree failed");
2827 my $line = <$fd>;
2828 close $fd or return undef;
2830 if (!defined $line) {
2831 # there is no tree or hash given by $path at $base
2832 return undef;
2835 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2836 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2837 if (defined $type && $type ne $2) {
2838 # type doesn't match
2839 return undef;
2841 return $3;
2844 # get path of entry with given hash at given tree-ish (ref)
2845 # used to get 'from' filename for combined diff (merge commit) for renames
2846 sub git_get_path_by_hash {
2847 my $base = shift || return;
2848 my $hash = shift || return;
2850 local $/ = "\0";
2852 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2853 or return undef;
2854 while (my $line = <$fd>) {
2855 chomp $line;
2857 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2858 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2859 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2860 close $fd;
2861 return $1;
2864 close $fd;
2865 return undef;
2868 ## ......................................................................
2869 ## git utility functions, directly accessing git repository
2871 # get the value of config variable either from file named as the variable
2872 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2873 # configuration variable in the repository config file.
2874 sub git_get_file_or_project_config {
2875 my ($path, $name) = @_;
2877 $git_dir = "$projectroot/$path";
2878 open my $fd, '<', "$git_dir/$name"
2879 or return git_get_project_config($name);
2880 my $conf = <$fd>;
2881 close $fd;
2882 if (defined $conf) {
2883 chomp $conf;
2885 return $conf;
2888 sub git_get_project_description {
2889 my $path = shift;
2890 return git_get_file_or_project_config($path, 'description');
2893 sub git_get_project_category {
2894 my $path = shift;
2895 return git_get_file_or_project_config($path, 'category');
2899 # supported formats:
2900 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2901 # - if its contents is a number, use it as tag weight,
2902 # - otherwise add a tag with weight 1
2903 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2904 # the same value multiple times increases tag weight
2905 # * `gitweb.ctag' multi-valued repo config variable
2906 sub git_get_project_ctags {
2907 my $project = shift;
2908 my $ctags = {};
2910 $git_dir = "$projectroot/$project";
2911 if (opendir my $dh, "$git_dir/ctags") {
2912 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2913 foreach my $tagfile (@files) {
2914 open my $ct, '<', $tagfile
2915 or next;
2916 my $val = <$ct>;
2917 chomp $val if $val;
2918 close $ct;
2920 (my $ctag = $tagfile) =~ s#.*/##;
2921 if ($val =~ /^\d+$/) {
2922 $ctags->{$ctag} = $val;
2923 } else {
2924 $ctags->{$ctag} = 1;
2927 closedir $dh;
2929 } elsif (open my $fh, '<', "$git_dir/ctags") {
2930 while (my $line = <$fh>) {
2931 chomp $line;
2932 $ctags->{$line}++ if $line;
2934 close $fh;
2936 } else {
2937 my $taglist = config_to_multi(git_get_project_config('ctag'));
2938 foreach my $tag (@$taglist) {
2939 $ctags->{$tag}++;
2943 return $ctags;
2946 # return hash, where keys are content tags ('ctags'),
2947 # and values are sum of weights of given tag in every project
2948 sub git_gather_all_ctags {
2949 my $projects = shift;
2950 my $ctags = {};
2952 foreach my $p (@$projects) {
2953 foreach my $ct (keys %{$p->{'ctags'}}) {
2954 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2958 return $ctags;
2961 sub git_populate_project_tagcloud {
2962 my $ctags = shift;
2964 # First, merge different-cased tags; tags vote on casing
2965 my %ctags_lc;
2966 foreach (keys %$ctags) {
2967 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2968 if (not $ctags_lc{lc $_}->{topcount}
2969 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2970 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2971 $ctags_lc{lc $_}->{topname} = $_;
2975 my $cloud;
2976 my $matched = $input_params{'ctag'};
2977 if (eval { require HTML::TagCloud; 1; }) {
2978 $cloud = HTML::TagCloud->new;
2979 foreach my $ctag (sort keys %ctags_lc) {
2980 # Pad the title with spaces so that the cloud looks
2981 # less crammed.
2982 my $title = esc_html($ctags_lc{$ctag}->{topname});
2983 $title =~ s/ /&nbsp;/g;
2984 $title =~ s/^/&nbsp;/g;
2985 $title =~ s/$/&nbsp;/g;
2986 if (defined $matched && $matched eq $ctag) {
2987 $title = qq(<span class="match">$title</span>);
2989 $cloud->add($title, href(project=>undef, ctag=>$ctag),
2990 $ctags_lc{$ctag}->{count});
2992 } else {
2993 $cloud = {};
2994 foreach my $ctag (keys %ctags_lc) {
2995 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
2996 if (defined $matched && $matched eq $ctag) {
2997 $title = qq(<span class="match">$title</span>);
2999 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3000 $cloud->{$ctag}{ctag} =
3001 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3004 return $cloud;
3007 sub git_show_project_tagcloud {
3008 my ($cloud, $count) = @_;
3009 if (ref $cloud eq 'HTML::TagCloud') {
3010 return $cloud->html_and_css($count);
3011 } else {
3012 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3013 return
3014 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3015 join (', ', map {
3016 $cloud->{$_}->{'ctag'}
3017 } splice(@tags, 0, $count)) .
3018 '</div>';
3022 sub git_get_project_url_list {
3023 my $path = shift;
3025 $git_dir = "$projectroot/$path";
3026 open my $fd, '<', "$git_dir/cloneurl"
3027 or return wantarray ?
3028 @{ config_to_multi(git_get_project_config('url')) } :
3029 config_to_multi(git_get_project_config('url'));
3030 my @git_project_url_list = map { chomp; $_ } <$fd>;
3031 close $fd;
3033 return wantarray ? @git_project_url_list : \@git_project_url_list;
3036 sub git_get_projects_list {
3037 my $filter = shift || '';
3038 my $paranoid = shift;
3039 my @list;
3041 if (-d $projects_list) {
3042 # search in directory
3043 my $dir = $projects_list;
3044 # remove the trailing "/"
3045 $dir =~ s!/+$!!;
3046 my $pfxlen = length("$dir");
3047 my $pfxdepth = ($dir =~ tr!/!!);
3048 # when filtering, search only given subdirectory
3049 if ($filter && !$paranoid) {
3050 $dir .= "/$filter";
3051 $dir =~ s!/+$!!;
3054 File::Find::find({
3055 follow_fast => 1, # follow symbolic links
3056 follow_skip => 2, # ignore duplicates
3057 dangling_symlinks => 0, # ignore dangling symlinks, silently
3058 wanted => sub {
3059 # global variables
3060 our $project_maxdepth;
3061 our $projectroot;
3062 # skip project-list toplevel, if we get it.
3063 return if (m!^[/.]$!);
3064 # only directories can be git repositories
3065 return unless (-d $_);
3066 # don't traverse too deep (Find is super slow on os x)
3067 # $project_maxdepth excludes depth of $projectroot
3068 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3069 $File::Find::prune = 1;
3070 return;
3073 my $path = substr($File::Find::name, $pfxlen + 1);
3074 # paranoidly only filter here
3075 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3076 next;
3078 # we check related file in $projectroot
3079 if (check_export_ok("$projectroot/$path")) {
3080 push @list, { path => $path };
3081 $File::Find::prune = 1;
3084 }, "$dir");
3086 } elsif (-f $projects_list) {
3087 # read from file(url-encoded):
3088 # 'git%2Fgit.git Linus+Torvalds'
3089 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3090 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3091 open my $fd, '<', $projects_list or return;
3092 PROJECT:
3093 while (my $line = <$fd>) {
3094 chomp $line;
3095 my ($path, $owner) = split ' ', $line;
3096 $path = unescape($path);
3097 $owner = unescape($owner);
3098 if (!defined $path) {
3099 next;
3101 # if $filter is rpovided, check if $path begins with $filter
3102 if ($filter && $path !~ m!^\Q$filter\E/!) {
3103 next;
3105 if (check_export_ok("$projectroot/$path")) {
3106 my $pr = {
3107 path => $path
3109 if ($owner) {
3110 $pr->{'owner'} = to_utf8($owner);
3112 push @list, $pr;
3115 close $fd;
3117 return @list;
3120 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3121 # as side effects it sets 'forks' field to list of forks for forked projects
3122 sub filter_forks_from_projects_list {
3123 my $projects = shift;
3125 my %trie; # prefix tree of directories (path components)
3126 # generate trie out of those directories that might contain forks
3127 foreach my $pr (@$projects) {
3128 my $path = $pr->{'path'};
3129 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3130 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3131 next unless ($path); # skip '.git' repository: tests, git-instaweb
3132 next unless (-d "$projectroot/$path"); # containing directory exists
3133 $pr->{'forks'} = []; # there can be 0 or more forks of project
3135 # add to trie
3136 my @dirs = split('/', $path);
3137 # walk the trie, until either runs out of components or out of trie
3138 my $ref = \%trie;
3139 while (scalar @dirs &&
3140 exists($ref->{$dirs[0]})) {
3141 $ref = $ref->{shift @dirs};
3143 # create rest of trie structure from rest of components
3144 foreach my $dir (@dirs) {
3145 $ref = $ref->{$dir} = {};
3147 # create end marker, store $pr as a data
3148 $ref->{''} = $pr if (!exists $ref->{''});
3151 # filter out forks, by finding shortest prefix match for paths
3152 my @filtered;
3153 PROJECT:
3154 foreach my $pr (@$projects) {
3155 # trie lookup
3156 my $ref = \%trie;
3157 DIR:
3158 foreach my $dir (split('/', $pr->{'path'})) {
3159 if (exists $ref->{''}) {
3160 # found [shortest] prefix, is a fork - skip it
3161 push @{$ref->{''}{'forks'}}, $pr;
3162 next PROJECT;
3164 if (!exists $ref->{$dir}) {
3165 # not in trie, cannot have prefix, not a fork
3166 push @filtered, $pr;
3167 next PROJECT;
3169 # If the dir is there, we just walk one step down the trie.
3170 $ref = $ref->{$dir};
3172 # we ran out of trie
3173 # (shouldn't happen: it's either no match, or end marker)
3174 push @filtered, $pr;
3177 return @filtered;
3180 # note: fill_project_list_info must be run first,
3181 # for 'descr_long' and 'ctags' to be filled
3182 sub search_projects_list {
3183 my ($projlist, %opts) = @_;
3184 my $tagfilter = $opts{'tagfilter'};
3185 my $search_re = $opts{'search_regexp'};
3187 return @$projlist
3188 unless ($tagfilter || $search_re);
3190 # searching projects require filling to be run before it;
3191 fill_project_list_info($projlist,
3192 $tagfilter ? 'ctags' : (),
3193 $search_re ? ('path', 'descr') : ());
3194 my @projects;
3195 PROJECT:
3196 foreach my $pr (@$projlist) {
3198 if ($tagfilter) {
3199 next unless ref($pr->{'ctags'}) eq 'HASH';
3200 next unless
3201 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3204 if ($search_re) {
3205 next unless
3206 $pr->{'path'} =~ /$search_re/ ||
3207 $pr->{'descr_long'} =~ /$search_re/;
3210 push @projects, $pr;
3213 return @projects;
3216 our $gitweb_project_owner = undef;
3217 sub git_get_project_list_from_file {
3219 return if (defined $gitweb_project_owner);
3221 $gitweb_project_owner = {};
3222 # read from file (url-encoded):
3223 # 'git%2Fgit.git Linus+Torvalds'
3224 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3225 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3226 if (-f $projects_list) {
3227 open(my $fd, '<', $projects_list);
3228 while (my $line = <$fd>) {
3229 chomp $line;
3230 my ($pr, $ow) = split ' ', $line;
3231 $pr = unescape($pr);
3232 $ow = unescape($ow);
3233 $gitweb_project_owner->{$pr} = to_utf8($ow);
3235 close $fd;
3239 sub git_get_project_owner {
3240 my $project = shift;
3241 my $owner;
3243 return undef unless $project;
3244 $git_dir = "$projectroot/$project";
3246 if (!defined $gitweb_project_owner) {
3247 git_get_project_list_from_file();
3250 if (exists $gitweb_project_owner->{$project}) {
3251 $owner = $gitweb_project_owner->{$project};
3253 if (!defined $owner){
3254 $owner = git_get_project_config('owner');
3256 if (!defined $owner) {
3257 $owner = get_file_owner("$git_dir");
3260 return $owner;
3263 sub git_get_last_activity {
3264 my ($path) = @_;
3265 my $fd;
3267 $git_dir = "$projectroot/$path";
3268 open($fd, "-|", git_cmd(), 'for-each-ref',
3269 '--format=%(committer)',
3270 '--sort=-committerdate',
3271 '--count=1',
3272 'refs/heads') or return;
3273 my $most_recent = <$fd>;
3274 close $fd or return;
3275 if (defined $most_recent &&
3276 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3277 my $timestamp = $1;
3278 my $age = time - $timestamp;
3279 return ($age, age_string($age));
3281 return (undef, undef);
3284 # Implementation note: when a single remote is wanted, we cannot use 'git
3285 # remote show -n' because that command always work (assuming it's a remote URL
3286 # if it's not defined), and we cannot use 'git remote show' because that would
3287 # try to make a network roundtrip. So the only way to find if that particular
3288 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3289 # and when we find what we want.
3290 sub git_get_remotes_list {
3291 my $wanted = shift;
3292 my %remotes = ();
3294 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3295 return unless $fd;
3296 while (my $remote = <$fd>) {
3297 chomp $remote;
3298 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3299 next if $wanted and not $remote eq $wanted;
3300 my ($url, $key) = ($1, $2);
3302 $remotes{$remote} ||= { 'heads' => () };
3303 $remotes{$remote}{$key} = $url;
3305 close $fd or return;
3306 return wantarray ? %remotes : \%remotes;
3309 # Takes a hash of remotes as first parameter and fills it by adding the
3310 # available remote heads for each of the indicated remotes.
3311 sub fill_remote_heads {
3312 my $remotes = shift;
3313 my @heads = map { "remotes/$_" } keys %$remotes;
3314 my @remoteheads = git_get_heads_list(undef, @heads);
3315 foreach my $remote (keys %$remotes) {
3316 $remotes->{$remote}{'heads'} = [ grep {
3317 $_->{'name'} =~ s!^$remote/!!
3318 } @remoteheads ];
3322 sub git_get_references {
3323 my $type = shift || "";
3324 my %refs;
3325 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3326 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3327 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3328 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3329 or return;
3331 while (my $line = <$fd>) {
3332 chomp $line;
3333 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3334 if (defined $refs{$1}) {
3335 push @{$refs{$1}}, $2;
3336 } else {
3337 $refs{$1} = [ $2 ];
3341 close $fd or return;
3342 return \%refs;
3345 sub git_get_rev_name_tags {
3346 my $hash = shift || return undef;
3348 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3349 or return;
3350 my $name_rev = <$fd>;
3351 close $fd;
3353 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3354 return $1;
3355 } else {
3356 # catches also '$hash undefined' output
3357 return undef;
3361 ## ----------------------------------------------------------------------
3362 ## parse to hash functions
3364 sub parse_date {
3365 my $epoch = shift;
3366 my $tz = shift || "-0000";
3368 my %date;
3369 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3370 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3371 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3372 $date{'hour'} = $hour;
3373 $date{'minute'} = $min;
3374 $date{'mday'} = $mday;
3375 $date{'day'} = $days[$wday];
3376 $date{'month'} = $months[$mon];
3377 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3378 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3379 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3380 $mday, $months[$mon], $hour ,$min;
3381 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3382 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3384 my ($tz_sign, $tz_hour, $tz_min) =
3385 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3386 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3387 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3388 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3389 $date{'hour_local'} = $hour;
3390 $date{'minute_local'} = $min;
3391 $date{'tz_local'} = $tz;
3392 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3393 1900+$year, $mon+1, $mday,
3394 $hour, $min, $sec, $tz);
3395 return %date;
3398 sub parse_tag {
3399 my $tag_id = shift;
3400 my %tag;
3401 my @comment;
3403 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3404 $tag{'id'} = $tag_id;
3405 while (my $line = <$fd>) {
3406 chomp $line;
3407 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3408 $tag{'object'} = $1;
3409 } elsif ($line =~ m/^type (.+)$/) {
3410 $tag{'type'} = $1;
3411 } elsif ($line =~ m/^tag (.+)$/) {
3412 $tag{'name'} = $1;
3413 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3414 $tag{'author'} = $1;
3415 $tag{'author_epoch'} = $2;
3416 $tag{'author_tz'} = $3;
3417 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3418 $tag{'author_name'} = $1;
3419 $tag{'author_email'} = $2;
3420 } else {
3421 $tag{'author_name'} = $tag{'author'};
3423 } elsif ($line =~ m/--BEGIN/) {
3424 push @comment, $line;
3425 last;
3426 } elsif ($line eq "") {
3427 last;
3430 push @comment, <$fd>;
3431 $tag{'comment'} = \@comment;
3432 close $fd or return;
3433 if (!defined $tag{'name'}) {
3434 return
3436 return %tag
3439 sub parse_commit_text {
3440 my ($commit_text, $withparents) = @_;
3441 my @commit_lines = split '\n', $commit_text;
3442 my %co;
3444 pop @commit_lines; # Remove '\0'
3446 if (! @commit_lines) {
3447 return;
3450 my $header = shift @commit_lines;
3451 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3452 return;
3454 ($co{'id'}, my @parents) = split ' ', $header;
3455 while (my $line = shift @commit_lines) {
3456 last if $line eq "\n";
3457 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3458 $co{'tree'} = $1;
3459 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3460 push @parents, $1;
3461 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3462 $co{'author'} = to_utf8($1);
3463 $co{'author_epoch'} = $2;
3464 $co{'author_tz'} = $3;
3465 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3466 $co{'author_name'} = $1;
3467 $co{'author_email'} = $2;
3468 } else {
3469 $co{'author_name'} = $co{'author'};
3471 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3472 $co{'committer'} = to_utf8($1);
3473 $co{'committer_epoch'} = $2;
3474 $co{'committer_tz'} = $3;
3475 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3476 $co{'committer_name'} = $1;
3477 $co{'committer_email'} = $2;
3478 } else {
3479 $co{'committer_name'} = $co{'committer'};
3483 if (!defined $co{'tree'}) {
3484 return;
3486 $co{'parents'} = \@parents;
3487 $co{'parent'} = $parents[0];
3489 foreach my $title (@commit_lines) {
3490 $title =~ s/^ //;
3491 if ($title ne "") {
3492 $co{'title'} = chop_str($title, 80, 5);
3493 # remove leading stuff of merges to make the interesting part visible
3494 if (length($title) > 50) {
3495 $title =~ s/^Automatic //;
3496 $title =~ s/^merge (of|with) /Merge ... /i;
3497 if (length($title) > 50) {
3498 $title =~ s/(http|rsync):\/\///;
3500 if (length($title) > 50) {
3501 $title =~ s/(master|www|rsync)\.//;
3503 if (length($title) > 50) {
3504 $title =~ s/kernel.org:?//;
3506 if (length($title) > 50) {
3507 $title =~ s/\/pub\/scm//;
3510 $co{'title_short'} = chop_str($title, 50, 5);
3511 last;
3514 if (! defined $co{'title'} || $co{'title'} eq "") {
3515 $co{'title'} = $co{'title_short'} = '(no commit message)';
3517 # remove added spaces
3518 foreach my $line (@commit_lines) {
3519 $line =~ s/^ //;
3521 $co{'comment'} = \@commit_lines;
3523 my $age = time - $co{'committer_epoch'};
3524 $co{'age'} = $age;
3525 $co{'age_string'} = age_string($age);
3526 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3527 if ($age > 60*60*24*7*2) {
3528 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3529 $co{'age_string_age'} = $co{'age_string'};
3530 } else {
3531 $co{'age_string_date'} = $co{'age_string'};
3532 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3534 return %co;
3537 sub parse_commit {
3538 my ($commit_id) = @_;
3539 my %co;
3541 return unless defined $commit_id;
3543 local $/ = "\0";
3545 open my $fd, "-|", quote_command(
3546 git_cmd(), "rev-list",
3547 "--parents",
3548 "--header",
3549 "--max-count=1",
3550 $commit_id,
3551 "--") . ' 2>/dev/null',
3552 or die_error(500, "Open git-rev-list failed");
3553 my $commit_text = <$fd>;
3554 %co = parse_commit_text($commit_text, 1)
3555 if defined $commit_text;
3556 close $fd;
3558 return %co;
3561 sub parse_commits {
3562 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3563 my @cos;
3565 return unless defined $commit_id;
3566 $maxcount ||= 1;
3567 $skip ||= 0;
3569 local $/ = "\0";
3571 open my $fd, "-|", quote_command(
3572 git_cmd(), "rev-list",
3573 "--header",
3574 @args,
3575 ("--max-count=" . $maxcount),
3576 ("--skip=" . $skip),
3577 @extra_options,
3578 $commit_id,
3579 "--",
3580 ($filename ? ($filename) : ())) . ' 2>/dev/null'
3581 or die_error(500, "Open git-rev-list failed");
3582 while (my $line = <$fd>) {
3583 my %co = parse_commit_text($line);
3584 push @cos, \%co;
3586 close $fd;
3588 return wantarray ? @cos : \@cos;
3591 # parse line of git-diff-tree "raw" output
3592 sub parse_difftree_raw_line {
3593 my $line = shift;
3594 my %res;
3596 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3597 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3598 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3599 $res{'from_mode'} = $1;
3600 $res{'to_mode'} = $2;
3601 $res{'from_id'} = $3;
3602 $res{'to_id'} = $4;
3603 $res{'status'} = $5;
3604 $res{'similarity'} = $6;
3605 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3606 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3607 } else {
3608 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3611 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3612 # combined diff (for merge commit)
3613 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3614 $res{'nparents'} = length($1);
3615 $res{'from_mode'} = [ split(' ', $2) ];
3616 $res{'to_mode'} = pop @{$res{'from_mode'}};
3617 $res{'from_id'} = [ split(' ', $3) ];
3618 $res{'to_id'} = pop @{$res{'from_id'}};
3619 $res{'status'} = [ split('', $4) ];
3620 $res{'to_file'} = unquote($5);
3622 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3623 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3624 $res{'commit'} = $1;
3627 return wantarray ? %res : \%res;
3630 # wrapper: return parsed line of git-diff-tree "raw" output
3631 # (the argument might be raw line, or parsed info)
3632 sub parsed_difftree_line {
3633 my $line_or_ref = shift;
3635 if (ref($line_or_ref) eq "HASH") {
3636 # pre-parsed (or generated by hand)
3637 return $line_or_ref;
3638 } else {
3639 return parse_difftree_raw_line($line_or_ref);
3643 # parse line of git-ls-tree output
3644 sub parse_ls_tree_line {
3645 my $line = shift;
3646 my %opts = @_;
3647 my %res;
3649 if ($opts{'-l'}) {
3650 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3651 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3653 $res{'mode'} = $1;
3654 $res{'type'} = $2;
3655 $res{'hash'} = $3;
3656 $res{'size'} = $4;
3657 if ($opts{'-z'}) {
3658 $res{'name'} = $5;
3659 } else {
3660 $res{'name'} = unquote($5);
3662 } else {
3663 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3664 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3666 $res{'mode'} = $1;
3667 $res{'type'} = $2;
3668 $res{'hash'} = $3;
3669 if ($opts{'-z'}) {
3670 $res{'name'} = $4;
3671 } else {
3672 $res{'name'} = unquote($4);
3676 return wantarray ? %res : \%res;
3679 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3680 sub parse_from_to_diffinfo {
3681 my ($diffinfo, $from, $to, @parents) = @_;
3683 if ($diffinfo->{'nparents'}) {
3684 # combined diff
3685 $from->{'file'} = [];
3686 $from->{'href'} = [];
3687 fill_from_file_info($diffinfo, @parents)
3688 unless exists $diffinfo->{'from_file'};
3689 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3690 $from->{'file'}[$i] =
3691 defined $diffinfo->{'from_file'}[$i] ?
3692 $diffinfo->{'from_file'}[$i] :
3693 $diffinfo->{'to_file'};
3694 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3695 $from->{'href'}[$i] = href(action=>"blob",
3696 hash_base=>$parents[$i],
3697 hash=>$diffinfo->{'from_id'}[$i],
3698 file_name=>$from->{'file'}[$i]);
3699 } else {
3700 $from->{'href'}[$i] = undef;
3703 } else {
3704 # ordinary (not combined) diff
3705 $from->{'file'} = $diffinfo->{'from_file'};
3706 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3707 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3708 hash=>$diffinfo->{'from_id'},
3709 file_name=>$from->{'file'});
3710 } else {
3711 delete $from->{'href'};
3715 $to->{'file'} = $diffinfo->{'to_file'};
3716 if (!is_deleted($diffinfo)) { # file exists in result
3717 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3718 hash=>$diffinfo->{'to_id'},
3719 file_name=>$to->{'file'});
3720 } else {
3721 delete $to->{'href'};
3725 ## ......................................................................
3726 ## parse to array of hashes functions
3728 sub git_get_heads_list {
3729 my ($limit, @classes) = @_;
3730 @classes = ('heads') unless @classes;
3731 my @patterns = map { "refs/$_" } @classes;
3732 my @headslist;
3734 open my $fd, '-|', git_cmd(), 'for-each-ref',
3735 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3736 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3737 @patterns
3738 or return;
3739 while (my $line = <$fd>) {
3740 my %ref_item;
3742 chomp $line;
3743 my ($refinfo, $committerinfo) = split(/\0/, $line);
3744 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3745 my ($committer, $epoch, $tz) =
3746 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3747 $ref_item{'fullname'} = $name;
3748 $name =~ s!^refs/(?:head|remote)s/!!;
3750 $ref_item{'name'} = $name;
3751 $ref_item{'id'} = $hash;
3752 $ref_item{'title'} = $title || '(no commit message)';
3753 $ref_item{'epoch'} = $epoch;
3754 if ($epoch) {
3755 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3756 } else {
3757 $ref_item{'age'} = "unknown";
3760 push @headslist, \%ref_item;
3762 close $fd;
3764 return wantarray ? @headslist : \@headslist;
3767 sub git_get_tags_list {
3768 my $limit = shift;
3769 my @tagslist;
3771 open my $fd, '-|', git_cmd(), 'for-each-ref',
3772 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3773 '--format=%(objectname) %(objecttype) %(refname) '.
3774 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3775 'refs/tags'
3776 or return;
3777 while (my $line = <$fd>) {
3778 my %ref_item;
3780 chomp $line;
3781 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3782 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3783 my ($creator, $epoch, $tz) =
3784 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3785 $ref_item{'fullname'} = $name;
3786 $name =~ s!^refs/tags/!!;
3788 $ref_item{'type'} = $type;
3789 $ref_item{'id'} = $id;
3790 $ref_item{'name'} = $name;
3791 if ($type eq "tag") {
3792 $ref_item{'subject'} = $title;
3793 $ref_item{'reftype'} = $reftype;
3794 $ref_item{'refid'} = $refid;
3795 } else {
3796 $ref_item{'reftype'} = $type;
3797 $ref_item{'refid'} = $id;
3800 if ($type eq "tag" || $type eq "commit") {
3801 $ref_item{'epoch'} = $epoch;
3802 if ($epoch) {
3803 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3804 } else {
3805 $ref_item{'age'} = "unknown";
3809 push @tagslist, \%ref_item;
3811 close $fd;
3813 return wantarray ? @tagslist : \@tagslist;
3816 ## ----------------------------------------------------------------------
3817 ## filesystem-related functions
3819 sub get_file_owner {
3820 my $path = shift;
3822 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3823 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3824 if (!defined $gcos) {
3825 return undef;
3827 my $owner = $gcos;
3828 $owner =~ s/[,;].*$//;
3829 return to_utf8($owner);
3832 # assume that file exists
3833 sub insert_file {
3834 my $filename = shift;
3836 open my $fd, '<', $filename;
3837 print map { to_utf8($_) } <$fd>;
3838 close $fd;
3841 ## ......................................................................
3842 ## mimetype related functions
3844 sub mimetype_guess_file {
3845 my $filename = shift;
3846 my $mimemap = shift;
3847 -r $mimemap or return undef;
3849 my %mimemap;
3850 open(my $mh, '<', $mimemap) or return undef;
3851 while (<$mh>) {
3852 next if m/^#/; # skip comments
3853 my ($mimetype, @exts) = split(/\s+/);
3854 foreach my $ext (@exts) {
3855 $mimemap{$ext} = $mimetype;
3858 close($mh);
3860 $filename =~ /\.([^.]*)$/;
3861 return $mimemap{$1};
3864 sub mimetype_guess {
3865 my $filename = shift;
3866 my $mime;
3867 $filename =~ /\./ or return undef;
3869 if ($mimetypes_file) {
3870 my $file = $mimetypes_file;
3871 if ($file !~ m!^/!) { # if it is relative path
3872 # it is relative to project
3873 $file = "$projectroot/$project/$file";
3875 $mime = mimetype_guess_file($filename, $file);
3877 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3878 return $mime;
3881 sub blob_mimetype {
3882 my $fd = shift;
3883 my $filename = shift;
3885 if ($filename) {
3886 my $mime = mimetype_guess($filename);
3887 $mime and return $mime;
3890 # just in case
3891 return $default_blob_plain_mimetype unless $fd;
3893 if (-T $fd) {
3894 return 'text/plain';
3895 } elsif (! $filename) {
3896 return 'application/octet-stream';
3897 } elsif ($filename =~ m/\.png$/i) {
3898 return 'image/png';
3899 } elsif ($filename =~ m/\.gif$/i) {
3900 return 'image/gif';
3901 } elsif ($filename =~ m/\.jpe?g$/i) {
3902 return 'image/jpeg';
3903 } else {
3904 return 'application/octet-stream';
3908 sub blob_contenttype {
3909 my ($fd, $file_name, $type) = @_;
3911 $type ||= blob_mimetype($fd, $file_name);
3912 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3913 $type .= "; charset=$default_text_plain_charset";
3916 return $type;
3919 # guess file syntax for syntax highlighting; return undef if no highlighting
3920 # the name of syntax can (in the future) depend on syntax highlighter used
3921 sub guess_file_syntax {
3922 my ($highlight, $mimetype, $file_name) = @_;
3923 return undef unless ($highlight && defined $file_name);
3924 my $basename = basename($file_name, '.in');
3925 return $highlight_basename{$basename}
3926 if exists $highlight_basename{$basename};
3928 $basename =~ /\.([^.]*)$/;
3929 my $ext = $1 or return undef;
3930 return $highlight_ext{$ext}
3931 if exists $highlight_ext{$ext};
3933 return undef;
3936 # run highlighter and return FD of its output,
3937 # or return original FD if no highlighting
3938 sub run_highlighter {
3939 my ($fd, $highlight, $syntax) = @_;
3940 return $fd unless ($highlight && defined $syntax);
3942 close $fd;
3943 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3944 quote_command($highlight_bin).
3945 " --replace-tabs=8 --fragment --syntax $syntax |"
3946 or die_error(500, "Couldn't open file or run syntax highlighter");
3947 return $fd;
3950 ## ======================================================================
3951 ## functions printing HTML: header, footer, error page
3953 sub get_page_title {
3954 my $title = to_utf8($site_name);
3956 unless (defined $project) {
3957 if (defined $project_filter) {
3958 $title .= " - projects in '" . esc_path($project_filter) . "'";
3960 return $title;
3962 $title .= " - " . to_utf8($project);
3964 return $title unless (defined $action);
3965 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3967 return $title unless (defined $file_name);
3968 $title .= " - " . esc_path($file_name);
3969 if ($action eq "tree" && $file_name !~ m|/$|) {
3970 $title .= "/";
3973 return $title;
3976 sub get_content_type_html {
3977 # require explicit support from the UA if we are to send the page as
3978 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3979 # we have to do this because MSIE sometimes globs '*/*', pretending to
3980 # support xhtml+xml but choking when it gets what it asked for.
3981 if (defined $cgi->http('HTTP_ACCEPT') &&
3982 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3983 $cgi->Accept('application/xhtml+xml') != 0) {
3984 return 'application/xhtml+xml';
3985 } else {
3986 return 'text/html';
3990 sub print_feed_meta {
3991 if (defined $project) {
3992 my %href_params = get_feed_info();
3993 if (!exists $href_params{'-title'}) {
3994 $href_params{'-title'} = 'log';
3997 foreach my $format (qw(RSS Atom)) {
3998 my $type = lc($format);
3999 my %link_attr = (
4000 '-rel' => 'alternate',
4001 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4002 '-type' => "application/$type+xml"
4005 $href_params{'extra_options'} = undef;
4006 $href_params{'action'} = $type;
4007 $link_attr{'-href'} = href(%href_params);
4008 print "<link ".
4009 "rel=\"$link_attr{'-rel'}\" ".
4010 "title=\"$link_attr{'-title'}\" ".
4011 "href=\"$link_attr{'-href'}\" ".
4012 "type=\"$link_attr{'-type'}\" ".
4013 "/>\n";
4015 $href_params{'extra_options'} = '--no-merges';
4016 $link_attr{'-href'} = href(%href_params);
4017 $link_attr{'-title'} .= ' (no merges)';
4018 print "<link ".
4019 "rel=\"$link_attr{'-rel'}\" ".
4020 "title=\"$link_attr{'-title'}\" ".
4021 "href=\"$link_attr{'-href'}\" ".
4022 "type=\"$link_attr{'-type'}\" ".
4023 "/>\n";
4026 } else {
4027 printf('<link rel="alternate" title="%s projects list" '.
4028 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4029 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4030 printf('<link rel="alternate" title="%s projects feeds" '.
4031 'href="%s" type="text/x-opml" />'."\n",
4032 esc_attr($site_name), href(project=>undef, action=>"opml"));
4036 sub print_header_links {
4037 my $status = shift;
4039 # print out each stylesheet that exist, providing backwards capability
4040 # for those people who defined $stylesheet in a config file
4041 if (defined $stylesheet) {
4042 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4043 } else {
4044 foreach my $stylesheet (@stylesheets) {
4045 next unless $stylesheet;
4046 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4049 print_feed_meta()
4050 if ($status eq '200 OK');
4051 if (defined $favicon) {
4052 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4056 sub print_nav_breadcrumbs_path {
4057 my $dirprefix = undef;
4058 while (my $part = shift) {
4059 $dirprefix .= "/" if defined $dirprefix;
4060 $dirprefix .= $part;
4061 print $cgi->a({-href => href(project => undef,
4062 project_filter => $dirprefix,
4063 action => "project_list")},
4064 esc_html($part)) . " / ";
4068 sub print_nav_breadcrumbs {
4069 my %opts = @_;
4071 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
4072 if (defined $project) {
4073 my @dirname = split '/', $project;
4074 my $projectbasename = pop @dirname;
4075 print_nav_breadcrumbs_path(@dirname);
4076 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4077 if (defined $action) {
4078 my $action_print = $action ;
4079 if (defined $opts{-action_extra}) {
4080 $action_print = $cgi->a({-href => href(action=>$action)},
4081 $action);
4083 print " / $action_print";
4085 if (defined $opts{-action_extra}) {
4086 print " / $opts{-action_extra}";
4088 print "\n";
4089 } elsif (defined $project_filter) {
4090 print_nav_breadcrumbs_path(split '/', $project_filter);
4094 sub print_search_form {
4095 if (!defined $searchtext) {
4096 $searchtext = "";
4098 my $search_hash;
4099 if (defined $hash_base) {
4100 $search_hash = $hash_base;
4101 } elsif (defined $hash) {
4102 $search_hash = $hash;
4103 } else {
4104 $search_hash = "HEAD";
4106 my $action = $my_uri;
4107 my $use_pathinfo = gitweb_check_feature('pathinfo');
4108 if ($use_pathinfo) {
4109 $action .= "/".esc_url($project);
4111 print $cgi->startform(-method => "get", -action => $action) .
4112 "<div class=\"search\">\n" .
4113 (!$use_pathinfo &&
4114 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4115 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4116 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4117 $cgi->popup_menu(-name => 'st', -default => 'commit',
4118 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4119 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
4120 " search:\n",
4121 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4122 "<span title=\"Extended regular expression\">" .
4123 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4124 -checked => $search_use_regexp) .
4125 "</span>" .
4126 "</div>" .
4127 $cgi->end_form() . "\n";
4130 sub git_header_html {
4131 my $status = shift || "200 OK";
4132 my $expires = shift;
4133 my %opts = @_;
4135 my $title = get_page_title();
4136 my $content_type = get_content_type_html();
4137 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4138 -status=> $status, -expires => $expires)
4139 unless ($opts{'-no_http_header'});
4140 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4141 print <<EOF;
4142 <?xml version="1.0" encoding="utf-8"?>
4143 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4144 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4145 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4146 <!-- git core binaries version $git_version -->
4147 <head>
4148 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4149 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4150 <meta name="robots" content="index, nofollow"/>
4151 <title>$title</title>
4153 # the stylesheet, favicon etc urls won't work correctly with path_info
4154 # unless we set the appropriate base URL
4155 if ($ENV{'PATH_INFO'}) {
4156 print "<base href=\"".esc_url($base_url)."\" />\n";
4158 print_header_links($status);
4160 if (defined $site_html_head_string) {
4161 print to_utf8($site_html_head_string);
4164 print "</head>\n" .
4165 "<body>\n";
4167 if (defined $site_header && -f $site_header) {
4168 insert_file($site_header);
4171 print "<div class=\"page_header\">\n";
4172 if (defined $logo) {
4173 print $cgi->a({-href => esc_url($logo_url),
4174 -title => $logo_label},
4175 $cgi->img({-src => esc_url($logo),
4176 -width => 72, -height => 27,
4177 -alt => "git",
4178 -class => "logo"}));
4180 print_nav_breadcrumbs(%opts);
4181 print "</div>\n";
4183 my $have_search = gitweb_check_feature('search');
4184 if (defined $project && $have_search) {
4185 print_search_form();
4189 sub git_footer_html {
4190 my $feed_class = 'rss_logo';
4192 print "<div class=\"page_footer\">\n";
4193 if (defined $project) {
4194 my $descr = git_get_project_description($project);
4195 if (defined $descr) {
4196 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4199 my %href_params = get_feed_info();
4200 if (!%href_params) {
4201 $feed_class .= ' generic';
4203 $href_params{'-title'} ||= 'log';
4205 foreach my $format (qw(RSS Atom)) {
4206 $href_params{'action'} = lc($format);
4207 print $cgi->a({-href => href(%href_params),
4208 -title => "$href_params{'-title'} $format feed",
4209 -class => $feed_class}, $format)."\n";
4212 } else {
4213 print $cgi->a({-href => href(project=>undef, action=>"opml",
4214 project_filter => $project_filter),
4215 -class => $feed_class}, "OPML") . " ";
4216 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4217 project_filter => $project_filter),
4218 -class => $feed_class}, "TXT") . "\n";
4220 print "</div>\n"; # class="page_footer"
4222 if (defined $t0 && gitweb_check_feature('timed')) {
4223 print "<div id=\"generating_info\">\n";
4224 print 'This page took '.
4225 '<span id="generating_time" class="time_span">'.
4226 tv_interval($t0, [ gettimeofday() ]).
4227 ' seconds </span>'.
4228 ' and '.
4229 '<span id="generating_cmd">'.
4230 $number_of_git_cmds.
4231 '</span> git commands '.
4232 " to generate.\n";
4233 print "</div>\n"; # class="page_footer"
4236 if (defined $site_footer && -f $site_footer) {
4237 insert_file($site_footer);
4240 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4241 if (defined $action &&
4242 $action eq 'blame_incremental') {
4243 print qq!<script type="text/javascript">\n!.
4244 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4245 qq! "!. href() .qq!");\n!.
4246 qq!</script>\n!;
4247 } else {
4248 my ($jstimezone, $tz_cookie, $datetime_class) =
4249 gitweb_get_feature('javascript-timezone');
4251 print qq!<script type="text/javascript">\n!.
4252 qq!window.onload = function () {\n!;
4253 if (gitweb_check_feature('javascript-actions')) {
4254 print qq! fixLinks();\n!;
4256 if ($jstimezone && $tz_cookie && $datetime_class) {
4257 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4258 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4260 print qq!};\n!.
4261 qq!</script>\n!;
4264 print "</body>\n" .
4265 "</html>";
4268 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4269 # Example: die_error(404, 'Hash not found')
4270 # By convention, use the following status codes (as defined in RFC 2616):
4271 # 400: Invalid or missing CGI parameters, or
4272 # requested object exists but has wrong type.
4273 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4274 # this server or project.
4275 # 404: Requested object/revision/project doesn't exist.
4276 # 500: The server isn't configured properly, or
4277 # an internal error occurred (e.g. failed assertions caused by bugs), or
4278 # an unknown error occurred (e.g. the git binary died unexpectedly).
4279 # 503: The server is currently unavailable (because it is overloaded,
4280 # or down for maintenance). Generally, this is a temporary state.
4281 sub die_error {
4282 my $status = shift || 500;
4283 my $error = esc_html(shift) || "Internal Server Error";
4284 my $extra = shift;
4285 my %opts = @_;
4287 my %http_responses = (
4288 400 => '400 Bad Request',
4289 403 => '403 Forbidden',
4290 404 => '404 Not Found',
4291 500 => '500 Internal Server Error',
4292 503 => '503 Service Unavailable',
4294 git_header_html($http_responses{$status}, undef, %opts);
4295 print <<EOF;
4296 <div class="page_body">
4297 <br /><br />
4298 $status - $error
4299 <br />
4301 if (defined $extra) {
4302 print "<hr />\n" .
4303 "$extra\n";
4305 print "</div>\n";
4307 git_footer_html();
4308 goto DONE_REQUEST
4309 unless ($opts{'-error_handler'});
4312 ## ----------------------------------------------------------------------
4313 ## functions printing or outputting HTML: navigation
4315 sub git_print_page_nav {
4316 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4317 $extra = '' if !defined $extra; # pager or formats
4319 my @navs = qw(summary shortlog log commit commitdiff tree);
4320 if ($suppress) {
4321 @navs = grep { $_ ne $suppress } @navs;
4324 my %arg = map { $_ => {action=>$_} } @navs;
4325 if (defined $head) {
4326 for (qw(commit commitdiff)) {
4327 $arg{$_}{'hash'} = $head;
4329 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4330 for (qw(shortlog log)) {
4331 $arg{$_}{'hash'} = $head;
4336 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4337 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4339 my @actions = gitweb_get_feature('actions');
4340 my %repl = (
4341 '%' => '%',
4342 'n' => $project, # project name
4343 'f' => $git_dir, # project path within filesystem
4344 'h' => $treehead || '', # current hash ('h' parameter)
4345 'b' => $treebase || '', # hash base ('hb' parameter)
4347 while (@actions) {
4348 my ($label, $link, $pos) = splice(@actions,0,3);
4349 # insert
4350 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4351 # munch munch
4352 $link =~ s/%([%nfhb])/$repl{$1}/g;
4353 $arg{$label}{'_href'} = $link;
4356 print "<div class=\"page_nav\">\n" .
4357 (join " | ",
4358 map { $_ eq $current ?
4359 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4360 } @navs);
4361 print "<br/>\n$extra<br/>\n" .
4362 "</div>\n";
4365 # returns a submenu for the nagivation of the refs views (tags, heads,
4366 # remotes) with the current view disabled and the remotes view only
4367 # available if the feature is enabled
4368 sub format_ref_views {
4369 my ($current) = @_;
4370 my @ref_views = qw{tags heads};
4371 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4372 return join " | ", map {
4373 $_ eq $current ? $_ :
4374 $cgi->a({-href => href(action=>$_)}, $_)
4375 } @ref_views
4378 sub format_paging_nav {
4379 my ($action, $page, $has_next_link) = @_;
4380 my $paging_nav;
4383 if ($page > 0) {
4384 $paging_nav .=
4385 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4386 " &sdot; " .
4387 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4388 -accesskey => "p", -title => "Alt-p"}, "prev");
4389 } else {
4390 $paging_nav .= "first &sdot; prev";
4393 if ($has_next_link) {
4394 $paging_nav .= " &sdot; " .
4395 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4396 -accesskey => "n", -title => "Alt-n"}, "next");
4397 } else {
4398 $paging_nav .= " &sdot; next";
4401 return $paging_nav;
4404 ## ......................................................................
4405 ## functions printing or outputting HTML: div
4407 sub git_print_header_div {
4408 my ($action, $title, $hash, $hash_base) = @_;
4409 my %args = ();
4411 $args{'action'} = $action;
4412 $args{'hash'} = $hash if $hash;
4413 $args{'hash_base'} = $hash_base if $hash_base;
4415 print "<div class=\"header\">\n" .
4416 $cgi->a({-href => href(%args), -class => "title"},
4417 $title ? $title : $action) .
4418 "\n</div>\n";
4421 sub format_repo_url {
4422 my ($name, $url) = @_;
4423 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4426 # Group output by placing it in a DIV element and adding a header.
4427 # Options for start_div() can be provided by passing a hash reference as the
4428 # first parameter to the function.
4429 # Options to git_print_header_div() can be provided by passing an array
4430 # reference. This must follow the options to start_div if they are present.
4431 # The content can be a scalar, which is output as-is, a scalar reference, which
4432 # is output after html escaping, an IO handle passed either as *handle or
4433 # *handle{IO}, or a function reference. In the latter case all following
4434 # parameters will be taken as argument to the content function call.
4435 sub git_print_section {
4436 my ($div_args, $header_args, $content);
4437 my $arg = shift;
4438 if (ref($arg) eq 'HASH') {
4439 $div_args = $arg;
4440 $arg = shift;
4442 if (ref($arg) eq 'ARRAY') {
4443 $header_args = $arg;
4444 $arg = shift;
4446 $content = $arg;
4448 print $cgi->start_div($div_args);
4449 git_print_header_div(@$header_args);
4451 if (ref($content) eq 'CODE') {
4452 $content->(@_);
4453 } elsif (ref($content) eq 'SCALAR') {
4454 print esc_html($$content);
4455 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4456 print <$content>;
4457 } elsif (!ref($content) && defined($content)) {
4458 print $content;
4461 print $cgi->end_div;
4464 sub format_timestamp_html {
4465 my $date = shift;
4466 my $strtime = $date->{'rfc2822'};
4468 my (undef, undef, $datetime_class) =
4469 gitweb_get_feature('javascript-timezone');
4470 if ($datetime_class) {
4471 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4474 my $localtime_format = '(%02d:%02d %s)';
4475 if ($date->{'hour_local'} < 6) {
4476 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4478 $strtime .= ' ' .
4479 sprintf($localtime_format,
4480 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4482 return $strtime;
4485 # Outputs the author name and date in long form
4486 sub git_print_authorship {
4487 my $co = shift;
4488 my %opts = @_;
4489 my $tag = $opts{-tag} || 'div';
4490 my $author = $co->{'author_name'};
4492 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4493 print "<$tag class=\"author_date\">" .
4494 format_search_author($author, "author", esc_html($author)) .
4495 " [".format_timestamp_html(\%ad)."]".
4496 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4497 "</$tag>\n";
4500 # Outputs table rows containing the full author or committer information,
4501 # in the format expected for 'commit' view (& similar).
4502 # Parameters are a commit hash reference, followed by the list of people
4503 # to output information for. If the list is empty it defaults to both
4504 # author and committer.
4505 sub git_print_authorship_rows {
4506 my $co = shift;
4507 # too bad we can't use @people = @_ || ('author', 'committer')
4508 my @people = @_;
4509 @people = ('author', 'committer') unless @people;
4510 foreach my $who (@people) {
4511 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4512 print "<tr><td>$who</td><td>" .
4513 format_search_author($co->{"${who}_name"}, $who,
4514 esc_html($co->{"${who}_name"})) . " " .
4515 format_search_author($co->{"${who}_email"}, $who,
4516 esc_html("<" . $co->{"${who}_email"} . ">")) .
4517 "</td><td rowspan=\"2\">" .
4518 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4519 "</td></tr>\n" .
4520 "<tr>" .
4521 "<td></td><td>" .
4522 format_timestamp_html(\%wd) .
4523 "</td>" .
4524 "</tr>\n";
4528 sub git_print_page_path {
4529 my $name = shift;
4530 my $type = shift;
4531 my $hb = shift;
4534 print "<div class=\"page_path\">";
4535 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4536 -title => 'tree root'}, to_utf8("[$project]"));
4537 print " / ";
4538 if (defined $name) {
4539 my @dirname = split '/', $name;
4540 my $basename = pop @dirname;
4541 my $fullname = '';
4543 foreach my $dir (@dirname) {
4544 $fullname .= ($fullname ? '/' : '') . $dir;
4545 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4546 hash_base=>$hb),
4547 -title => $fullname}, esc_path($dir));
4548 print " / ";
4550 if (defined $type && $type eq 'blob') {
4551 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4552 hash_base=>$hb),
4553 -title => $name}, esc_path($basename));
4554 } elsif (defined $type && $type eq 'tree') {
4555 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4556 hash_base=>$hb),
4557 -title => $name}, esc_path($basename));
4558 print " / ";
4559 } else {
4560 print esc_path($basename);
4563 print "<br/></div>\n";
4566 sub git_print_log {
4567 my $log = shift;
4568 my %opts = @_;
4570 if ($opts{'-remove_title'}) {
4571 # remove title, i.e. first line of log
4572 shift @$log;
4574 # remove leading empty lines
4575 while (defined $log->[0] && $log->[0] eq "") {
4576 shift @$log;
4579 # print log
4580 my $signoff = 0;
4581 my $empty = 0;
4582 foreach my $line (@$log) {
4583 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4584 $signoff = 1;
4585 $empty = 0;
4586 if (! $opts{'-remove_signoff'}) {
4587 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4588 next;
4589 } else {
4590 # remove signoff lines
4591 next;
4593 } else {
4594 $signoff = 0;
4597 # print only one empty line
4598 # do not print empty line after signoff
4599 if ($line eq "") {
4600 next if ($empty || $signoff);
4601 $empty = 1;
4602 } else {
4603 $empty = 0;
4606 print format_log_line_html($line) . "<br/>\n";
4609 if ($opts{'-final_empty_line'}) {
4610 # end with single empty line
4611 print "<br/>\n" unless $empty;
4615 # return link target (what link points to)
4616 sub git_get_link_target {
4617 my $hash = shift;
4618 my $link_target;
4620 # read link
4621 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4622 or return;
4624 local $/ = undef;
4625 $link_target = <$fd>;
4627 close $fd
4628 or return;
4630 return $link_target;
4633 # given link target, and the directory (basedir) the link is in,
4634 # return target of link relative to top directory (top tree);
4635 # return undef if it is not possible (including absolute links).
4636 sub normalize_link_target {
4637 my ($link_target, $basedir) = @_;
4639 # absolute symlinks (beginning with '/') cannot be normalized
4640 return if (substr($link_target, 0, 1) eq '/');
4642 # normalize link target to path from top (root) tree (dir)
4643 my $path;
4644 if ($basedir) {
4645 $path = $basedir . '/' . $link_target;
4646 } else {
4647 # we are in top (root) tree (dir)
4648 $path = $link_target;
4651 # remove //, /./, and /../
4652 my @path_parts;
4653 foreach my $part (split('/', $path)) {
4654 # discard '.' and ''
4655 next if (!$part || $part eq '.');
4656 # handle '..'
4657 if ($part eq '..') {
4658 if (@path_parts) {
4659 pop @path_parts;
4660 } else {
4661 # link leads outside repository (outside top dir)
4662 return;
4664 } else {
4665 push @path_parts, $part;
4668 $path = join('/', @path_parts);
4670 return $path;
4673 # print tree entry (row of git_tree), but without encompassing <tr> element
4674 sub git_print_tree_entry {
4675 my ($t, $basedir, $hash_base, $have_blame) = @_;
4677 my %base_key = ();
4678 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4680 # The format of a table row is: mode list link. Where mode is
4681 # the mode of the entry, list is the name of the entry, an href,
4682 # and link is the action links of the entry.
4684 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4685 if (exists $t->{'size'}) {
4686 print "<td class=\"size\">$t->{'size'}</td>\n";
4688 if ($t->{'type'} eq "blob") {
4689 print "<td class=\"list\">" .
4690 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4691 file_name=>"$basedir$t->{'name'}", %base_key),
4692 -class => "list"}, esc_path($t->{'name'}));
4693 if (S_ISLNK(oct $t->{'mode'})) {
4694 my $link_target = git_get_link_target($t->{'hash'});
4695 if ($link_target) {
4696 my $norm_target = normalize_link_target($link_target, $basedir);
4697 if (defined $norm_target) {
4698 print " -> " .
4699 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4700 file_name=>$norm_target),
4701 -title => $norm_target}, esc_path($link_target));
4702 } else {
4703 print " -> " . esc_path($link_target);
4707 print "</td>\n";
4708 print "<td class=\"link\">";
4709 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4710 file_name=>"$basedir$t->{'name'}", %base_key)},
4711 "blob");
4712 if ($have_blame) {
4713 print " | " .
4714 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4715 file_name=>"$basedir$t->{'name'}", %base_key)},
4716 "blame");
4718 if (defined $hash_base) {
4719 print " | " .
4720 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4721 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4722 "history");
4724 print " | " .
4725 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4726 file_name=>"$basedir$t->{'name'}")},
4727 "raw");
4728 print "</td>\n";
4730 } elsif ($t->{'type'} eq "tree") {
4731 print "<td class=\"list\">";
4732 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4733 file_name=>"$basedir$t->{'name'}",
4734 %base_key)},
4735 esc_path($t->{'name'}));
4736 print "</td>\n";
4737 print "<td class=\"link\">";
4738 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4739 file_name=>"$basedir$t->{'name'}",
4740 %base_key)},
4741 "tree");
4742 if (defined $hash_base) {
4743 print " | " .
4744 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4745 file_name=>"$basedir$t->{'name'}")},
4746 "history");
4748 print "</td>\n";
4749 } else {
4750 # unknown object: we can only present history for it
4751 # (this includes 'commit' object, i.e. submodule support)
4752 print "<td class=\"list\">" .
4753 esc_path($t->{'name'}) .
4754 "</td>\n";
4755 print "<td class=\"link\">";
4756 if (defined $hash_base) {
4757 print $cgi->a({-href => href(action=>"history",
4758 hash_base=>$hash_base,
4759 file_name=>"$basedir$t->{'name'}")},
4760 "history");
4762 print "</td>\n";
4766 ## ......................................................................
4767 ## functions printing large fragments of HTML
4769 # get pre-image filenames for merge (combined) diff
4770 sub fill_from_file_info {
4771 my ($diff, @parents) = @_;
4773 $diff->{'from_file'} = [ ];
4774 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4775 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4776 if ($diff->{'status'}[$i] eq 'R' ||
4777 $diff->{'status'}[$i] eq 'C') {
4778 $diff->{'from_file'}[$i] =
4779 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4783 return $diff;
4786 # is current raw difftree line of file deletion
4787 sub is_deleted {
4788 my $diffinfo = shift;
4790 return $diffinfo->{'to_id'} eq ('0' x 40);
4793 # does patch correspond to [previous] difftree raw line
4794 # $diffinfo - hashref of parsed raw diff format
4795 # $patchinfo - hashref of parsed patch diff format
4796 # (the same keys as in $diffinfo)
4797 sub is_patch_split {
4798 my ($diffinfo, $patchinfo) = @_;
4800 return defined $diffinfo && defined $patchinfo
4801 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4805 sub git_difftree_body {
4806 my ($difftree, $hash, @parents) = @_;
4807 my ($parent) = $parents[0];
4808 my $have_blame = gitweb_check_feature('blame');
4809 print "<div class=\"list_head\">\n";
4810 if ($#{$difftree} > 10) {
4811 print(($#{$difftree} + 1) . " files changed:\n");
4813 print "</div>\n";
4815 print "<table class=\"" .
4816 (@parents > 1 ? "combined " : "") .
4817 "diff_tree\">\n";
4819 # header only for combined diff in 'commitdiff' view
4820 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4821 if ($has_header) {
4822 # table header
4823 print "<thead><tr>\n" .
4824 "<th></th><th></th>\n"; # filename, patchN link
4825 for (my $i = 0; $i < @parents; $i++) {
4826 my $par = $parents[$i];
4827 print "<th>" .
4828 $cgi->a({-href => href(action=>"commitdiff",
4829 hash=>$hash, hash_parent=>$par),
4830 -title => 'commitdiff to parent number ' .
4831 ($i+1) . ': ' . substr($par,0,7)},
4832 $i+1) .
4833 "&nbsp;</th>\n";
4835 print "</tr></thead>\n<tbody>\n";
4838 my $alternate = 1;
4839 my $patchno = 0;
4840 foreach my $line (@{$difftree}) {
4841 my $diff = parsed_difftree_line($line);
4843 if ($alternate) {
4844 print "<tr class=\"dark\">\n";
4845 } else {
4846 print "<tr class=\"light\">\n";
4848 $alternate ^= 1;
4850 if (exists $diff->{'nparents'}) { # combined diff
4852 fill_from_file_info($diff, @parents)
4853 unless exists $diff->{'from_file'};
4855 if (!is_deleted($diff)) {
4856 # file exists in the result (child) commit
4857 print "<td>" .
4858 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4859 file_name=>$diff->{'to_file'},
4860 hash_base=>$hash),
4861 -class => "list"}, esc_path($diff->{'to_file'})) .
4862 "</td>\n";
4863 } else {
4864 print "<td>" .
4865 esc_path($diff->{'to_file'}) .
4866 "</td>\n";
4869 if ($action eq 'commitdiff') {
4870 # link to patch
4871 $patchno++;
4872 print "<td class=\"link\">" .
4873 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4874 "patch") .
4875 " | " .
4876 "</td>\n";
4879 my $has_history = 0;
4880 my $not_deleted = 0;
4881 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4882 my $hash_parent = $parents[$i];
4883 my $from_hash = $diff->{'from_id'}[$i];
4884 my $from_path = $diff->{'from_file'}[$i];
4885 my $status = $diff->{'status'}[$i];
4887 $has_history ||= ($status ne 'A');
4888 $not_deleted ||= ($status ne 'D');
4890 if ($status eq 'A') {
4891 print "<td class=\"link\" align=\"right\"> | </td>\n";
4892 } elsif ($status eq 'D') {
4893 print "<td class=\"link\">" .
4894 $cgi->a({-href => href(action=>"blob",
4895 hash_base=>$hash,
4896 hash=>$from_hash,
4897 file_name=>$from_path)},
4898 "blob" . ($i+1)) .
4899 " | </td>\n";
4900 } else {
4901 if ($diff->{'to_id'} eq $from_hash) {
4902 print "<td class=\"link nochange\">";
4903 } else {
4904 print "<td class=\"link\">";
4906 print $cgi->a({-href => href(action=>"blobdiff",
4907 hash=>$diff->{'to_id'},
4908 hash_parent=>$from_hash,
4909 hash_base=>$hash,
4910 hash_parent_base=>$hash_parent,
4911 file_name=>$diff->{'to_file'},
4912 file_parent=>$from_path)},
4913 "diff" . ($i+1)) .
4914 " | </td>\n";
4918 print "<td class=\"link\">";
4919 if ($not_deleted) {
4920 print $cgi->a({-href => href(action=>"blob",
4921 hash=>$diff->{'to_id'},
4922 file_name=>$diff->{'to_file'},
4923 hash_base=>$hash)},
4924 "blob");
4925 print " | " if ($has_history);
4927 if ($has_history) {
4928 print $cgi->a({-href => href(action=>"history",
4929 file_name=>$diff->{'to_file'},
4930 hash_base=>$hash)},
4931 "history");
4933 print "</td>\n";
4935 print "</tr>\n";
4936 next; # instead of 'else' clause, to avoid extra indent
4938 # else ordinary diff
4940 my ($to_mode_oct, $to_mode_str, $to_file_type);
4941 my ($from_mode_oct, $from_mode_str, $from_file_type);
4942 if ($diff->{'to_mode'} ne ('0' x 6)) {
4943 $to_mode_oct = oct $diff->{'to_mode'};
4944 if (S_ISREG($to_mode_oct)) { # only for regular file
4945 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4947 $to_file_type = file_type($diff->{'to_mode'});
4949 if ($diff->{'from_mode'} ne ('0' x 6)) {
4950 $from_mode_oct = oct $diff->{'from_mode'};
4951 if (S_ISREG($from_mode_oct)) { # only for regular file
4952 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4954 $from_file_type = file_type($diff->{'from_mode'});
4957 if ($diff->{'status'} eq "A") { # created
4958 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4959 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4960 $mode_chng .= "]</span>";
4961 print "<td>";
4962 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4963 hash_base=>$hash, file_name=>$diff->{'file'}),
4964 -class => "list"}, esc_path($diff->{'file'}));
4965 print "</td>\n";
4966 print "<td>$mode_chng</td>\n";
4967 print "<td class=\"link\">";
4968 if ($action eq 'commitdiff') {
4969 # link to patch
4970 $patchno++;
4971 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4972 "patch") .
4973 " | ";
4975 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4976 hash_base=>$hash, file_name=>$diff->{'file'})},
4977 "blob");
4978 print "</td>\n";
4980 } elsif ($diff->{'status'} eq "D") { # deleted
4981 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4982 print "<td>";
4983 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4984 hash_base=>$parent, file_name=>$diff->{'file'}),
4985 -class => "list"}, esc_path($diff->{'file'}));
4986 print "</td>\n";
4987 print "<td>$mode_chng</td>\n";
4988 print "<td class=\"link\">";
4989 if ($action eq 'commitdiff') {
4990 # link to patch
4991 $patchno++;
4992 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4993 "patch") .
4994 " | ";
4996 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4997 hash_base=>$parent, file_name=>$diff->{'file'})},
4998 "blob") . " | ";
4999 if ($have_blame) {
5000 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5001 file_name=>$diff->{'file'})},
5002 "blame") . " | ";
5004 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5005 file_name=>$diff->{'file'})},
5006 "history");
5007 print "</td>\n";
5009 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5010 my $mode_chnge = "";
5011 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5012 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5013 if ($from_file_type ne $to_file_type) {
5014 $mode_chnge .= " from $from_file_type to $to_file_type";
5016 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5017 if ($from_mode_str && $to_mode_str) {
5018 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5019 } elsif ($to_mode_str) {
5020 $mode_chnge .= " mode: $to_mode_str";
5023 $mode_chnge .= "]</span>\n";
5025 print "<td>";
5026 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5027 hash_base=>$hash, file_name=>$diff->{'file'}),
5028 -class => "list"}, esc_path($diff->{'file'}));
5029 print "</td>\n";
5030 print "<td>$mode_chnge</td>\n";
5031 print "<td class=\"link\">";
5032 if ($action eq 'commitdiff') {
5033 # link to patch
5034 $patchno++;
5035 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5036 "patch") .
5037 " | ";
5038 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5039 # "commit" view and modified file (not onlu mode changed)
5040 print $cgi->a({-href => href(action=>"blobdiff",
5041 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5042 hash_base=>$hash, hash_parent_base=>$parent,
5043 file_name=>$diff->{'file'})},
5044 "diff") .
5045 " | ";
5047 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5048 hash_base=>$hash, file_name=>$diff->{'file'})},
5049 "blob") . " | ";
5050 if ($have_blame) {
5051 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5052 file_name=>$diff->{'file'})},
5053 "blame") . " | ";
5055 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5056 file_name=>$diff->{'file'})},
5057 "history");
5058 print "</td>\n";
5060 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5061 my %status_name = ('R' => 'moved', 'C' => 'copied');
5062 my $nstatus = $status_name{$diff->{'status'}};
5063 my $mode_chng = "";
5064 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5065 # mode also for directories, so we cannot use $to_mode_str
5066 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5068 print "<td>" .
5069 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5070 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5071 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5072 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5073 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5074 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5075 -class => "list"}, esc_path($diff->{'from_file'})) .
5076 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5077 "<td class=\"link\">";
5078 if ($action eq 'commitdiff') {
5079 # link to patch
5080 $patchno++;
5081 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5082 "patch") .
5083 " | ";
5084 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5085 # "commit" view and modified file (not only pure rename or copy)
5086 print $cgi->a({-href => href(action=>"blobdiff",
5087 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5088 hash_base=>$hash, hash_parent_base=>$parent,
5089 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5090 "diff") .
5091 " | ";
5093 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5094 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5095 "blob") . " | ";
5096 if ($have_blame) {
5097 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5098 file_name=>$diff->{'to_file'})},
5099 "blame") . " | ";
5101 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5102 file_name=>$diff->{'to_file'})},
5103 "history");
5104 print "</td>\n";
5106 } # we should not encounter Unmerged (U) or Unknown (X) status
5107 print "</tr>\n";
5109 print "</tbody>" if $has_header;
5110 print "</table>\n";
5113 # Print context lines and then rem/add lines in a side-by-side manner.
5114 sub print_sidebyside_diff_lines {
5115 my ($ctx, $rem, $add) = @_;
5117 # print context block before add/rem block
5118 if (@$ctx) {
5119 print join '',
5120 '<div class="chunk_block ctx">',
5121 '<div class="old">',
5122 @$ctx,
5123 '</div>',
5124 '<div class="new">',
5125 @$ctx,
5126 '</div>',
5127 '</div>';
5130 if (!@$add) {
5131 # pure removal
5132 print join '',
5133 '<div class="chunk_block rem">',
5134 '<div class="old">',
5135 @$rem,
5136 '</div>',
5137 '</div>';
5138 } elsif (!@$rem) {
5139 # pure addition
5140 print join '',
5141 '<div class="chunk_block add">',
5142 '<div class="new">',
5143 @$add,
5144 '</div>',
5145 '</div>';
5146 } else {
5147 print join '',
5148 '<div class="chunk_block chg">',
5149 '<div class="old">',
5150 @$rem,
5151 '</div>',
5152 '<div class="new">',
5153 @$add,
5154 '</div>',
5155 '</div>';
5159 # Print context lines and then rem/add lines in inline manner.
5160 sub print_inline_diff_lines {
5161 my ($ctx, $rem, $add) = @_;
5163 print @$ctx, @$rem, @$add;
5166 # Format removed and added line, mark changed part and HTML-format them.
5167 # Implementation is based on contrib/diff-highlight
5168 sub format_rem_add_lines_pair {
5169 my ($rem, $add, $num_parents) = @_;
5171 # We need to untabify lines before split()'ing them;
5172 # otherwise offsets would be invalid.
5173 chomp $rem;
5174 chomp $add;
5175 $rem = untabify($rem);
5176 $add = untabify($add);
5178 my @rem = split(//, $rem);
5179 my @add = split(//, $add);
5180 my ($esc_rem, $esc_add);
5181 # Ignore leading +/- characters for each parent.
5182 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5183 my ($prefix_has_nonspace, $suffix_has_nonspace);
5185 my $shorter = (@rem < @add) ? @rem : @add;
5186 while ($prefix_len < $shorter) {
5187 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5189 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5190 $prefix_len++;
5193 while ($prefix_len + $suffix_len < $shorter) {
5194 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5196 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5197 $suffix_len++;
5200 # Mark lines that are different from each other, but have some common
5201 # part that isn't whitespace. If lines are completely different, don't
5202 # mark them because that would make output unreadable, especially if
5203 # diff consists of multiple lines.
5204 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5205 $esc_rem = esc_html_hl_regions($rem, 'marked',
5206 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5207 $esc_add = esc_html_hl_regions($add, 'marked',
5208 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5209 } else {
5210 $esc_rem = esc_html($rem, -nbsp=>1);
5211 $esc_add = esc_html($add, -nbsp=>1);
5214 return format_diff_line(\$esc_rem, 'rem'),
5215 format_diff_line(\$esc_add, 'add');
5218 # HTML-format diff context, removed and added lines.
5219 sub format_ctx_rem_add_lines {
5220 my ($ctx, $rem, $add, $num_parents) = @_;
5221 my (@new_ctx, @new_rem, @new_add);
5222 my $can_highlight = 0;
5223 my $is_combined = ($num_parents > 1);
5225 # Highlight if every removed line has a corresponding added line.
5226 if (@$add > 0 && @$add == @$rem) {
5227 $can_highlight = 1;
5229 # Highlight lines in combined diff only if the chunk contains
5230 # diff between the same version, e.g.
5232 # - a
5233 # - b
5234 # + c
5235 # + d
5237 # Otherwise the highlightling would be confusing.
5238 if ($is_combined) {
5239 for (my $i = 0; $i < @$add; $i++) {
5240 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5241 my $prefix_add = substr($add->[$i], 0, $num_parents);
5243 $prefix_rem =~ s/-/+/g;
5245 if ($prefix_rem ne $prefix_add) {
5246 $can_highlight = 0;
5247 last;
5253 if ($can_highlight) {
5254 for (my $i = 0; $i < @$add; $i++) {
5255 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5256 $rem->[$i], $add->[$i], $num_parents);
5257 push @new_rem, $line_rem;
5258 push @new_add, $line_add;
5260 } else {
5261 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5262 @new_add = map { format_diff_line($_, 'add') } @$add;
5265 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5267 return (\@new_ctx, \@new_rem, \@new_add);
5270 # Print context lines and then rem/add lines.
5271 sub print_diff_lines {
5272 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5273 my $is_combined = $num_parents > 1;
5275 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5276 $num_parents);
5278 if ($diff_style eq 'sidebyside' && !$is_combined) {
5279 print_sidebyside_diff_lines($ctx, $rem, $add);
5280 } else {
5281 # default 'inline' style and unknown styles
5282 print_inline_diff_lines($ctx, $rem, $add);
5286 sub print_diff_chunk {
5287 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5288 my (@ctx, @rem, @add);
5290 # The class of the previous line.
5291 my $prev_class = '';
5293 return unless @chunk;
5295 # incomplete last line might be among removed or added lines,
5296 # or both, or among context lines: find which
5297 for (my $i = 1; $i < @chunk; $i++) {
5298 if ($chunk[$i][0] eq 'incomplete') {
5299 $chunk[$i][0] = $chunk[$i-1][0];
5303 # guardian
5304 push @chunk, ["", ""];
5306 foreach my $line_info (@chunk) {
5307 my ($class, $line) = @$line_info;
5309 # print chunk headers
5310 if ($class && $class eq 'chunk_header') {
5311 print format_diff_line($line, $class, $from, $to);
5312 next;
5315 ## print from accumulator when have some add/rem lines or end
5316 # of chunk (flush context lines), or when have add and rem
5317 # lines and new block is reached (otherwise add/rem lines could
5318 # be reordered)
5319 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5320 (@rem && @add && $class ne $prev_class)) {
5321 print_diff_lines(\@ctx, \@rem, \@add,
5322 $diff_style, $num_parents);
5323 @ctx = @rem = @add = ();
5326 ## adding lines to accumulator
5327 # guardian value
5328 last unless $line;
5329 # rem, add or change
5330 if ($class eq 'rem') {
5331 push @rem, $line;
5332 } elsif ($class eq 'add') {
5333 push @add, $line;
5335 # context line
5336 if ($class eq 'ctx') {
5337 push @ctx, $line;
5340 $prev_class = $class;
5344 sub git_patchset_body {
5345 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5346 my ($hash_parent) = $hash_parents[0];
5348 my $is_combined = (@hash_parents > 1);
5349 my $patch_idx = 0;
5350 my $patch_number = 0;
5351 my $patch_line;
5352 my $diffinfo;
5353 my $to_name;
5354 my (%from, %to);
5355 my @chunk; # for side-by-side diff
5357 print "<div class=\"patchset\">\n";
5359 # skip to first patch
5360 while ($patch_line = <$fd>) {
5361 chomp $patch_line;
5363 last if ($patch_line =~ m/^diff /);
5366 PATCH:
5367 while ($patch_line) {
5369 # parse "git diff" header line
5370 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5371 # $1 is from_name, which we do not use
5372 $to_name = unquote($2);
5373 $to_name =~ s!^b/!!;
5374 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5375 # $1 is 'cc' or 'combined', which we do not use
5376 $to_name = unquote($2);
5377 } else {
5378 $to_name = undef;
5381 # check if current patch belong to current raw line
5382 # and parse raw git-diff line if needed
5383 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5384 # this is continuation of a split patch
5385 print "<div class=\"patch cont\">\n";
5386 } else {
5387 # advance raw git-diff output if needed
5388 $patch_idx++ if defined $diffinfo;
5390 # read and prepare patch information
5391 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5393 # compact combined diff output can have some patches skipped
5394 # find which patch (using pathname of result) we are at now;
5395 if ($is_combined) {
5396 while ($to_name ne $diffinfo->{'to_file'}) {
5397 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5398 format_diff_cc_simplified($diffinfo, @hash_parents) .
5399 "</div>\n"; # class="patch"
5401 $patch_idx++;
5402 $patch_number++;
5404 last if $patch_idx > $#$difftree;
5405 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5409 # modifies %from, %to hashes
5410 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5412 # this is first patch for raw difftree line with $patch_idx index
5413 # we index @$difftree array from 0, but number patches from 1
5414 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5417 # git diff header
5418 #assert($patch_line =~ m/^diff /) if DEBUG;
5419 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5420 $patch_number++;
5421 # print "git diff" header
5422 print format_git_diff_header_line($patch_line, $diffinfo,
5423 \%from, \%to);
5425 # print extended diff header
5426 print "<div class=\"diff extended_header\">\n";
5427 EXTENDED_HEADER:
5428 while ($patch_line = <$fd>) {
5429 chomp $patch_line;
5431 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5433 print format_extended_diff_header_line($patch_line, $diffinfo,
5434 \%from, \%to);
5436 print "</div>\n"; # class="diff extended_header"
5438 # from-file/to-file diff header
5439 if (! $patch_line) {
5440 print "</div>\n"; # class="patch"
5441 last PATCH;
5443 next PATCH if ($patch_line =~ m/^diff /);
5444 #assert($patch_line =~ m/^---/) if DEBUG;
5446 my $last_patch_line = $patch_line;
5447 $patch_line = <$fd>;
5448 chomp $patch_line;
5449 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5451 print format_diff_from_to_header($last_patch_line, $patch_line,
5452 $diffinfo, \%from, \%to,
5453 @hash_parents);
5455 # the patch itself
5456 LINE:
5457 while ($patch_line = <$fd>) {
5458 chomp $patch_line;
5460 next PATCH if ($patch_line =~ m/^diff /);
5462 my $class = diff_line_class($patch_line, \%from, \%to);
5464 if ($class eq 'chunk_header') {
5465 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5466 @chunk = ();
5469 push @chunk, [ $class, $patch_line ];
5472 } continue {
5473 if (@chunk) {
5474 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5475 @chunk = ();
5477 print "</div>\n"; # class="patch"
5480 # for compact combined (--cc) format, with chunk and patch simplification
5481 # the patchset might be empty, but there might be unprocessed raw lines
5482 for (++$patch_idx if $patch_number > 0;
5483 $patch_idx < @$difftree;
5484 ++$patch_idx) {
5485 # read and prepare patch information
5486 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5488 # generate anchor for "patch" links in difftree / whatchanged part
5489 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5490 format_diff_cc_simplified($diffinfo, @hash_parents) .
5491 "</div>\n"; # class="patch"
5493 $patch_number++;
5496 if ($patch_number == 0) {
5497 if (@hash_parents > 1) {
5498 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5499 } else {
5500 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5504 print "</div>\n"; # class="patchset"
5507 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5509 sub git_project_search_form {
5510 my ($searchtext, $search_use_regexp) = @_;
5512 my $limit = '';
5513 if ($project_filter) {
5514 $limit = " in '$project_filter/'";
5517 print "<div class=\"projsearch\">\n";
5518 print $cgi->startform(-method => 'get', -action => $my_uri) .
5519 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5520 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5521 if (defined $project_filter);
5522 print $cgi->textfield(-name => 's', -value => $searchtext,
5523 -title => "Search project by name and description$limit",
5524 -size => 60) . "\n" .
5525 "<span title=\"Extended regular expression\">" .
5526 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5527 -checked => $search_use_regexp) .
5528 "</span>\n" .
5529 $cgi->submit(-name => 'btnS', -value => 'Search') .
5530 $cgi->end_form() . "\n" .
5531 $cgi->a({-href => href(project => undef, searchtext => undef,
5532 project_filter => $project_filter)},
5533 esc_html("List all projects$limit")) . "<br />\n";
5534 print "</div>\n";
5537 # entry for given @keys needs filling if at least one of keys in list
5538 # is not present in %$project_info
5539 sub project_info_needs_filling {
5540 my ($project_info, @keys) = @_;
5542 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5543 foreach my $key (@keys) {
5544 if (!exists $project_info->{$key}) {
5545 return 1;
5548 return;
5551 # fills project list info (age, description, owner, category, forks, etc.)
5552 # for each project in the list, removing invalid projects from
5553 # returned list, or fill only specified info.
5555 # Invalid projects are removed from the returned list if and only if you
5556 # ask 'age' or 'age_string' to be filled, because they are the only fields
5557 # that run unconditionally git command that requires repository, and
5558 # therefore do always check if project repository is invalid.
5560 # USAGE:
5561 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5562 # ensures that 'descr_long' and 'ctags' fields are filled
5563 # * @project_list = fill_project_list_info(\@project_list)
5564 # ensures that all fields are filled (and invalid projects removed)
5566 # NOTE: modifies $projlist, but does not remove entries from it
5567 sub fill_project_list_info {
5568 my ($projlist, @wanted_keys) = @_;
5569 my @projects;
5570 my $filter_set = sub { return @_; };
5571 if (@wanted_keys) {
5572 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5573 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5576 my $show_ctags = gitweb_check_feature('ctags');
5577 PROJECT:
5578 foreach my $pr (@$projlist) {
5579 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5580 my (@activity) = git_get_last_activity($pr->{'path'});
5581 unless (@activity) {
5582 next PROJECT;
5584 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5586 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5587 my $descr = git_get_project_description($pr->{'path'}) || "";
5588 $descr = to_utf8($descr);
5589 $pr->{'descr_long'} = $descr;
5590 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5592 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5593 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5595 if ($show_ctags &&
5596 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5597 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5599 if ($projects_list_group_categories &&
5600 project_info_needs_filling($pr, $filter_set->('category'))) {
5601 my $cat = git_get_project_category($pr->{'path'}) ||
5602 $project_list_default_category;
5603 $pr->{'category'} = to_utf8($cat);
5606 push @projects, $pr;
5609 return @projects;
5612 sub sort_projects_list {
5613 my ($projlist, $order) = @_;
5614 my @projects;
5616 my %order_info = (
5617 project => { key => 'path', type => 'str' },
5618 descr => { key => 'descr_long', type => 'str' },
5619 owner => { key => 'owner', type => 'str' },
5620 age => { key => 'age', type => 'num' }
5622 my $oi = $order_info{$order};
5623 return @$projlist unless defined $oi;
5624 if ($oi->{'type'} eq 'str') {
5625 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @$projlist;
5626 } else {
5627 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @$projlist;
5630 return @projects;
5633 # returns a hash of categories, containing the list of project
5634 # belonging to each category
5635 sub build_projlist_by_category {
5636 my ($projlist, $from, $to) = @_;
5637 my %categories;
5639 $from = 0 unless defined $from;
5640 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5642 for (my $i = $from; $i <= $to; $i++) {
5643 my $pr = $projlist->[$i];
5644 push @{$categories{ $pr->{'category'} }}, $pr;
5647 return wantarray ? %categories : \%categories;
5650 # print 'sort by' <th> element, generating 'sort by $name' replay link
5651 # if that order is not selected
5652 sub print_sort_th {
5653 print format_sort_th(@_);
5656 sub format_sort_th {
5657 my ($name, $order, $header) = @_;
5658 my $sort_th = "";
5659 $header ||= ucfirst($name);
5661 if ($order eq $name) {
5662 $sort_th .= "<th>$header</th>\n";
5663 } else {
5664 $sort_th .= "<th>" .
5665 $cgi->a({-href => href(-replay=>1, order=>$name),
5666 -class => "header"}, $header) .
5667 "</th>\n";
5670 return $sort_th;
5673 sub git_project_list_rows {
5674 my ($projlist, $from, $to, $check_forks) = @_;
5676 $from = 0 unless defined $from;
5677 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5679 my $alternate = 1;
5680 for (my $i = $from; $i <= $to; $i++) {
5681 my $pr = $projlist->[$i];
5683 if ($alternate) {
5684 print "<tr class=\"dark\">\n";
5685 } else {
5686 print "<tr class=\"light\">\n";
5688 $alternate ^= 1;
5690 if ($check_forks) {
5691 print "<td>";
5692 if ($pr->{'forks'}) {
5693 my $nforks = scalar @{$pr->{'forks'}};
5694 if ($nforks > 0) {
5695 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5696 -title => "$nforks forks"}, "+");
5697 } else {
5698 print $cgi->span({-title => "$nforks forks"}, "+");
5701 print "</td>\n";
5703 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5704 -class => "list"},
5705 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5706 "</td>\n" .
5707 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5708 -class => "list",
5709 -title => $pr->{'descr_long'}},
5710 $search_regexp
5711 ? esc_html_match_hl_chopped($pr->{'descr_long'},
5712 $pr->{'descr'}, $search_regexp)
5713 : esc_html($pr->{'descr'})) .
5714 "</td>\n";
5715 unless ($omit_owner) {
5716 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5718 unless ($omit_age_column) {
5719 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5720 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5722 print"<td class=\"link\">" .
5723 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5724 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5725 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5726 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5727 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5728 "</td>\n" .
5729 "</tr>\n";
5733 sub git_project_list_body {
5734 # actually uses global variable $project
5735 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5736 my @projects = @$projlist;
5738 my $check_forks = gitweb_check_feature('forks');
5739 my $show_ctags = gitweb_check_feature('ctags');
5740 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5741 $check_forks = undef
5742 if ($tagfilter || $search_regexp);
5744 # filtering out forks before filling info allows to do less work
5745 @projects = filter_forks_from_projects_list(\@projects)
5746 if ($check_forks);
5747 # search_projects_list pre-fills required info
5748 @projects = search_projects_list(\@projects,
5749 'search_regexp' => $search_regexp,
5750 'tagfilter' => $tagfilter)
5751 if ($tagfilter || $search_regexp);
5752 # fill the rest
5753 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5754 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5755 push @all_fields, 'owner' unless($omit_owner);
5756 @projects = fill_project_list_info(\@projects, @all_fields);
5758 $order ||= $default_projects_order;
5759 $from = 0 unless defined $from;
5760 $to = $#projects if (!defined $to || $#projects < $to);
5762 # short circuit
5763 if ($from > $to) {
5764 print "<center>\n".
5765 "<b>No such projects found</b><br />\n".
5766 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5767 "</center>\n<br />\n";
5768 return;
5771 @projects = sort_projects_list(\@projects, $order);
5773 if ($show_ctags) {
5774 my $ctags = git_gather_all_ctags(\@projects);
5775 my $cloud = git_populate_project_tagcloud($ctags);
5776 print git_show_project_tagcloud($cloud, 64);
5779 print "<table class=\"project_list\">\n";
5780 unless ($no_header) {
5781 print "<tr>\n";
5782 if ($check_forks) {
5783 print "<th></th>\n";
5785 print_sort_th('project', $order, 'Project');
5786 print_sort_th('descr', $order, 'Description');
5787 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5788 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5789 print "<th></th>\n" . # for links
5790 "</tr>\n";
5793 if ($projects_list_group_categories) {
5794 # only display categories with projects in the $from-$to window
5795 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5796 my %categories = build_projlist_by_category(\@projects, $from, $to);
5797 foreach my $cat (sort keys %categories) {
5798 unless ($cat eq "") {
5799 print "<tr>\n";
5800 if ($check_forks) {
5801 print "<td></td>\n";
5803 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5804 print "</tr>\n";
5807 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5809 } else {
5810 git_project_list_rows(\@projects, $from, $to, $check_forks);
5813 if (defined $extra) {
5814 print "<tr>\n";
5815 if ($check_forks) {
5816 print "<td></td>\n";
5818 print "<td colspan=\"5\">$extra</td>\n" .
5819 "</tr>\n";
5821 print "</table>\n";
5824 sub git_log_body {
5825 # uses global variable $project
5826 my ($commitlist, $from, $to, $refs, $extra) = @_;
5828 $from = 0 unless defined $from;
5829 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5831 for (my $i = 0; $i <= $to; $i++) {
5832 my %co = %{$commitlist->[$i]};
5833 next if !%co;
5834 my $commit = $co{'id'};
5835 my $ref = format_ref_marker($refs, $commit);
5836 git_print_header_div('commit',
5837 "<span class=\"age\">$co{'age_string'}</span>" .
5838 esc_html($co{'title'}) . $ref,
5839 $commit);
5840 print "<div class=\"title_text\">\n" .
5841 "<div class=\"log_link\">\n" .
5842 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5843 " | " .
5844 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5845 " | " .
5846 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5847 "<br/>\n" .
5848 "</div>\n";
5849 git_print_authorship(\%co, -tag => 'span');
5850 print "<br/>\n</div>\n";
5852 print "<div class=\"log_body\">\n";
5853 git_print_log($co{'comment'}, -final_empty_line=> 1);
5854 print "</div>\n";
5856 if ($extra) {
5857 print "<div class=\"page_nav\">\n";
5858 print "$extra\n";
5859 print "</div>\n";
5863 sub git_shortlog_body {
5864 # uses global variable $project
5865 my ($commitlist, $from, $to, $refs, $extra) = @_;
5867 $from = 0 unless defined $from;
5868 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5870 print "<table class=\"shortlog\">\n";
5871 my $alternate = 1;
5872 for (my $i = $from; $i <= $to; $i++) {
5873 my %co = %{$commitlist->[$i]};
5874 my $commit = $co{'id'};
5875 my $ref = format_ref_marker($refs, $commit);
5876 if ($alternate) {
5877 print "<tr class=\"dark\">\n";
5878 } else {
5879 print "<tr class=\"light\">\n";
5881 $alternate ^= 1;
5882 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5883 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5884 format_author_html('td', \%co, 10) . "<td>";
5885 print format_subject_html($co{'title'}, $co{'title_short'},
5886 href(action=>"commit", hash=>$commit), $ref);
5887 print "</td>\n" .
5888 "<td class=\"link\">" .
5889 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5890 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5891 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5892 my $snapshot_links = format_snapshot_links($commit);
5893 if (defined $snapshot_links) {
5894 print " | " . $snapshot_links;
5896 print "</td>\n" .
5897 "</tr>\n";
5899 if (defined $extra) {
5900 print "<tr>\n" .
5901 "<td colspan=\"4\">$extra</td>\n" .
5902 "</tr>\n";
5904 print "</table>\n";
5907 sub git_history_body {
5908 # Warning: assumes constant type (blob or tree) during history
5909 my ($commitlist, $from, $to, $refs, $extra,
5910 $file_name, $file_hash, $ftype) = @_;
5912 $from = 0 unless defined $from;
5913 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5915 print "<table class=\"history\">\n";
5916 my $alternate = 1;
5917 for (my $i = $from; $i <= $to; $i++) {
5918 my %co = %{$commitlist->[$i]};
5919 if (!%co) {
5920 next;
5922 my $commit = $co{'id'};
5924 my $ref = format_ref_marker($refs, $commit);
5926 if ($alternate) {
5927 print "<tr class=\"dark\">\n";
5928 } else {
5929 print "<tr class=\"light\">\n";
5931 $alternate ^= 1;
5932 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5933 # shortlog: format_author_html('td', \%co, 10)
5934 format_author_html('td', \%co, 15, 3) . "<td>";
5935 # originally git_history used chop_str($co{'title'}, 50)
5936 print format_subject_html($co{'title'}, $co{'title_short'},
5937 href(action=>"commit", hash=>$commit), $ref);
5938 print "</td>\n" .
5939 "<td class=\"link\">" .
5940 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5941 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5943 if ($ftype eq 'blob') {
5944 my $blob_current = $file_hash;
5945 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5946 if (defined $blob_current && defined $blob_parent &&
5947 $blob_current ne $blob_parent) {
5948 print " | " .
5949 $cgi->a({-href => href(action=>"blobdiff",
5950 hash=>$blob_current, hash_parent=>$blob_parent,
5951 hash_base=>$hash_base, hash_parent_base=>$commit,
5952 file_name=>$file_name)},
5953 "diff to current");
5956 print "</td>\n" .
5957 "</tr>\n";
5959 if (defined $extra) {
5960 print "<tr>\n" .
5961 "<td colspan=\"4\">$extra</td>\n" .
5962 "</tr>\n";
5964 print "</table>\n";
5967 sub git_tags_body {
5968 # uses global variable $project
5969 my ($taglist, $from, $to, $extra) = @_;
5970 $from = 0 unless defined $from;
5971 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5973 print "<table class=\"tags\">\n";
5974 my $alternate = 1;
5975 for (my $i = $from; $i <= $to; $i++) {
5976 my $entry = $taglist->[$i];
5977 my %tag = %$entry;
5978 my $comment = $tag{'subject'};
5979 my $comment_short;
5980 if (defined $comment) {
5981 $comment_short = chop_str($comment, 30, 5);
5983 if ($alternate) {
5984 print "<tr class=\"dark\">\n";
5985 } else {
5986 print "<tr class=\"light\">\n";
5988 $alternate ^= 1;
5989 if (defined $tag{'age'}) {
5990 print "<td><i>$tag{'age'}</i></td>\n";
5991 } else {
5992 print "<td></td>\n";
5994 print "<td>" .
5995 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5996 -class => "list name"}, esc_html($tag{'name'})) .
5997 "</td>\n" .
5998 "<td>";
5999 if (defined $comment) {
6000 print format_subject_html($comment, $comment_short,
6001 href(action=>"tag", hash=>$tag{'id'}));
6003 print "</td>\n" .
6004 "<td class=\"selflink\">";
6005 if ($tag{'type'} eq "tag") {
6006 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6007 } else {
6008 print "&nbsp;";
6010 print "</td>\n" .
6011 "<td class=\"link\">" . " | " .
6012 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6013 if ($tag{'reftype'} eq "commit") {
6014 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6015 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6016 } elsif ($tag{'reftype'} eq "blob") {
6017 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6019 print "</td>\n" .
6020 "</tr>";
6022 if (defined $extra) {
6023 print "<tr>\n" .
6024 "<td colspan=\"5\">$extra</td>\n" .
6025 "</tr>\n";
6027 print "</table>\n";
6030 sub git_heads_body {
6031 # uses global variable $project
6032 my ($headlist, $head_at, $from, $to, $extra) = @_;
6033 $from = 0 unless defined $from;
6034 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6036 print "<table class=\"heads\">\n";
6037 my $alternate = 1;
6038 for (my $i = $from; $i <= $to; $i++) {
6039 my $entry = $headlist->[$i];
6040 my %ref = %$entry;
6041 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6042 if ($alternate) {
6043 print "<tr class=\"dark\">\n";
6044 } else {
6045 print "<tr class=\"light\">\n";
6047 $alternate ^= 1;
6048 print "<td><i>$ref{'age'}</i></td>\n" .
6049 ($curr ? "<td class=\"current_head\">" : "<td>") .
6050 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6051 -class => "list name"},esc_html($ref{'name'})) .
6052 "</td>\n" .
6053 "<td class=\"link\">" .
6054 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6055 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6056 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6057 "</td>\n" .
6058 "</tr>";
6060 if (defined $extra) {
6061 print "<tr>\n" .
6062 "<td colspan=\"3\">$extra</td>\n" .
6063 "</tr>\n";
6065 print "</table>\n";
6068 # Display a single remote block
6069 sub git_remote_block {
6070 my ($remote, $rdata, $limit, $head) = @_;
6072 my $heads = $rdata->{'heads'};
6073 my $fetch = $rdata->{'fetch'};
6074 my $push = $rdata->{'push'};
6076 my $urls_table = "<table class=\"projects_list\">\n" ;
6078 if (defined $fetch) {
6079 if ($fetch eq $push) {
6080 $urls_table .= format_repo_url("URL", $fetch);
6081 } else {
6082 $urls_table .= format_repo_url("Fetch URL", $fetch);
6083 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6085 } elsif (defined $push) {
6086 $urls_table .= format_repo_url("Push URL", $push);
6087 } else {
6088 $urls_table .= format_repo_url("", "No remote URL");
6091 $urls_table .= "</table>\n";
6093 my $dots;
6094 if (defined $limit && $limit < @$heads) {
6095 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6098 print $urls_table;
6099 git_heads_body($heads, $head, 0, $limit, $dots);
6102 # Display a list of remote names with the respective fetch and push URLs
6103 sub git_remotes_list {
6104 my ($remotedata, $limit) = @_;
6105 print "<table class=\"heads\">\n";
6106 my $alternate = 1;
6107 my @remotes = sort keys %$remotedata;
6109 my $limited = $limit && $limit < @remotes;
6111 $#remotes = $limit - 1 if $limited;
6113 while (my $remote = shift @remotes) {
6114 my $rdata = $remotedata->{$remote};
6115 my $fetch = $rdata->{'fetch'};
6116 my $push = $rdata->{'push'};
6117 if ($alternate) {
6118 print "<tr class=\"dark\">\n";
6119 } else {
6120 print "<tr class=\"light\">\n";
6122 $alternate ^= 1;
6123 print "<td>" .
6124 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6125 -class=> "list name"},esc_html($remote)) .
6126 "</td>";
6127 print "<td class=\"link\">" .
6128 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6129 " | " .
6130 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6131 "</td>";
6133 print "</tr>\n";
6136 if ($limited) {
6137 print "<tr>\n" .
6138 "<td colspan=\"3\">" .
6139 $cgi->a({-href => href(action=>"remotes")}, "...") .
6140 "</td>\n" . "</tr>\n";
6143 print "</table>";
6146 # Display remote heads grouped by remote, unless there are too many
6147 # remotes, in which case we only display the remote names
6148 sub git_remotes_body {
6149 my ($remotedata, $limit, $head) = @_;
6150 if ($limit and $limit < keys %$remotedata) {
6151 git_remotes_list($remotedata, $limit);
6152 } else {
6153 fill_remote_heads($remotedata);
6154 while (my ($remote, $rdata) = each %$remotedata) {
6155 git_print_section({-class=>"remote", -id=>$remote},
6156 ["remotes", $remote, $remote], sub {
6157 git_remote_block($remote, $rdata, $limit, $head);
6163 sub git_search_message {
6164 my %co = @_;
6166 my $greptype;
6167 if ($searchtype eq 'commit') {
6168 $greptype = "--grep=";
6169 } elsif ($searchtype eq 'author') {
6170 $greptype = "--author=";
6171 } elsif ($searchtype eq 'committer') {
6172 $greptype = "--committer=";
6174 $greptype .= $searchtext;
6175 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6176 $greptype, '--regexp-ignore-case',
6177 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6179 my $paging_nav = '';
6180 if ($page > 0) {
6181 $paging_nav .=
6182 $cgi->a({-href => href(-replay=>1, page=>undef)},
6183 "first") .
6184 " &sdot; " .
6185 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6186 -accesskey => "p", -title => "Alt-p"}, "prev");
6187 } else {
6188 $paging_nav .= "first &sdot; prev";
6190 my $next_link = '';
6191 if ($#commitlist >= 100) {
6192 $next_link =
6193 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6194 -accesskey => "n", -title => "Alt-n"}, "next");
6195 $paging_nav .= " &sdot; $next_link";
6196 } else {
6197 $paging_nav .= " &sdot; next";
6200 git_header_html();
6202 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6203 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6204 if ($page == 0 && !@commitlist) {
6205 print "<p>No match.</p>\n";
6206 } else {
6207 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6210 git_footer_html();
6213 sub git_search_changes {
6214 my %co = @_;
6216 local $/ = "\n";
6217 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6218 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6219 ($search_use_regexp ? '--pickaxe-regex' : ())
6220 or die_error(500, "Open git-log failed");
6222 git_header_html();
6224 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6225 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6227 print "<table class=\"pickaxe search\">\n";
6228 my $alternate = 1;
6229 undef %co;
6230 my @files;
6231 while (my $line = <$fd>) {
6232 chomp $line;
6233 next unless $line;
6235 my %set = parse_difftree_raw_line($line);
6236 if (defined $set{'commit'}) {
6237 # finish previous commit
6238 if (%co) {
6239 print "</td>\n" .
6240 "<td class=\"link\">" .
6241 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6242 "commit") .
6243 " | " .
6244 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6245 hash_base=>$co{'id'})},
6246 "tree") .
6247 "</td>\n" .
6248 "</tr>\n";
6251 if ($alternate) {
6252 print "<tr class=\"dark\">\n";
6253 } else {
6254 print "<tr class=\"light\">\n";
6256 $alternate ^= 1;
6257 %co = parse_commit($set{'commit'});
6258 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6259 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6260 "<td><i>$author</i></td>\n" .
6261 "<td>" .
6262 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6263 -class => "list subject"},
6264 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6265 } elsif (defined $set{'to_id'}) {
6266 next if ($set{'to_id'} =~ m/^0{40}$/);
6268 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6269 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6270 -class => "list"},
6271 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6272 "<br/>\n";
6275 close $fd;
6277 # finish last commit (warning: repetition!)
6278 if (%co) {
6279 print "</td>\n" .
6280 "<td class=\"link\">" .
6281 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6282 "commit") .
6283 " | " .
6284 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6285 hash_base=>$co{'id'})},
6286 "tree") .
6287 "</td>\n" .
6288 "</tr>\n";
6291 print "</table>\n";
6293 git_footer_html();
6296 sub git_search_files {
6297 my %co = @_;
6299 local $/ = "\n";
6300 open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6301 $search_use_regexp ? ('-E', '-i') : '-F',
6302 $searchtext, $co{'tree'}
6303 or die_error(500, "Open git-grep failed");
6305 git_header_html();
6307 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6308 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6310 print "<table class=\"grep_search\">\n";
6311 my $alternate = 1;
6312 my $matches = 0;
6313 my $lastfile = '';
6314 my $file_href;
6315 while (my $line = <$fd>) {
6316 chomp $line;
6317 my ($file, $lno, $ltext, $binary);
6318 last if ($matches++ > 1000);
6319 if ($line =~ /^Binary file (.+) matches$/) {
6320 $file = $1;
6321 $binary = 1;
6322 } else {
6323 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6324 $file =~ s/^$co{'tree'}://;
6326 if ($file ne $lastfile) {
6327 $lastfile and print "</td></tr>\n";
6328 if ($alternate++) {
6329 print "<tr class=\"dark\">\n";
6330 } else {
6331 print "<tr class=\"light\">\n";
6333 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6334 file_name=>$file);
6335 print "<td class=\"list\">".
6336 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6337 print "</td><td>\n";
6338 $lastfile = $file;
6340 if ($binary) {
6341 print "<div class=\"binary\">Binary file</div>\n";
6342 } else {
6343 $ltext = untabify($ltext);
6344 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6345 $ltext = esc_html($1, -nbsp=>1);
6346 $ltext .= '<span class="match">';
6347 $ltext .= esc_html($2, -nbsp=>1);
6348 $ltext .= '</span>';
6349 $ltext .= esc_html($3, -nbsp=>1);
6350 } else {
6351 $ltext = esc_html($ltext, -nbsp=>1);
6353 print "<div class=\"pre\">" .
6354 $cgi->a({-href => $file_href.'#l'.$lno,
6355 -class => "linenr"}, sprintf('%4i', $lno)) .
6356 ' ' . $ltext . "</div>\n";
6359 if ($lastfile) {
6360 print "</td></tr>\n";
6361 if ($matches > 1000) {
6362 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6364 } else {
6365 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6367 close $fd;
6369 print "</table>\n";
6371 git_footer_html();
6374 sub git_search_grep_body {
6375 my ($commitlist, $from, $to, $extra) = @_;
6376 $from = 0 unless defined $from;
6377 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6379 print "<table class=\"commit_search\">\n";
6380 my $alternate = 1;
6381 for (my $i = $from; $i <= $to; $i++) {
6382 my %co = %{$commitlist->[$i]};
6383 if (!%co) {
6384 next;
6386 my $commit = $co{'id'};
6387 if ($alternate) {
6388 print "<tr class=\"dark\">\n";
6389 } else {
6390 print "<tr class=\"light\">\n";
6392 $alternate ^= 1;
6393 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6394 format_author_html('td', \%co, 15, 5) .
6395 "<td>" .
6396 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6397 -class => "list subject"},
6398 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6399 my $comment = $co{'comment'};
6400 foreach my $line (@$comment) {
6401 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6402 my ($lead, $match, $trail) = ($1, $2, $3);
6403 $match = chop_str($match, 70, 5, 'center');
6404 my $contextlen = int((80 - length($match))/2);
6405 $contextlen = 30 if ($contextlen > 30);
6406 $lead = chop_str($lead, $contextlen, 10, 'left');
6407 $trail = chop_str($trail, $contextlen, 10, 'right');
6409 $lead = esc_html($lead);
6410 $match = esc_html($match);
6411 $trail = esc_html($trail);
6413 print "$lead<span class=\"match\">$match</span>$trail<br />";
6416 print "</td>\n" .
6417 "<td class=\"link\">" .
6418 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6419 " | " .
6420 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6421 " | " .
6422 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6423 print "</td>\n" .
6424 "</tr>\n";
6426 if (defined $extra) {
6427 print "<tr>\n" .
6428 "<td colspan=\"3\">$extra</td>\n" .
6429 "</tr>\n";
6431 print "</table>\n";
6434 ## ======================================================================
6435 ## ======================================================================
6436 ## actions
6438 sub git_project_list {
6439 my $order = $input_params{'order'};
6440 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6441 die_error(400, "Unknown order parameter");
6444 my @list = git_get_projects_list($project_filter, $strict_export);
6445 if (!@list) {
6446 die_error(404, "No projects found");
6449 git_header_html();
6450 if (defined $home_text && -f $home_text) {
6451 print "<div class=\"index_include\">\n";
6452 insert_file($home_text);
6453 print "</div>\n";
6456 git_project_search_form($searchtext, $search_use_regexp);
6457 git_project_list_body(\@list, $order);
6458 git_footer_html();
6461 sub git_forks {
6462 my $order = $input_params{'order'};
6463 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6464 die_error(400, "Unknown order parameter");
6467 my $filter = $project;
6468 $filter =~ s/\.git$//;
6469 my @list = git_get_projects_list($filter);
6470 if (!@list) {
6471 die_error(404, "No forks found");
6474 git_header_html();
6475 git_print_page_nav('','');
6476 git_print_header_div('summary', "$project forks");
6477 git_project_list_body(\@list, $order);
6478 git_footer_html();
6481 sub git_project_index {
6482 my @projects = git_get_projects_list($project_filter, $strict_export);
6483 if (!@projects) {
6484 die_error(404, "No projects found");
6487 print $cgi->header(
6488 -type => 'text/plain',
6489 -charset => 'utf-8',
6490 -content_disposition => 'inline; filename="index.aux"');
6492 foreach my $pr (@projects) {
6493 if (!exists $pr->{'owner'}) {
6494 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6497 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6498 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6499 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6500 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6501 $path =~ s/ /\+/g;
6502 $owner =~ s/ /\+/g;
6504 print "$path $owner\n";
6508 sub git_summary {
6509 my $descr = git_get_project_description($project) || "none";
6510 my %co = parse_commit("HEAD");
6511 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6512 my $head = $co{'id'};
6513 my $remote_heads = gitweb_check_feature('remote_heads');
6515 my $owner = git_get_project_owner($project);
6517 my $refs = git_get_references();
6518 # These get_*_list functions return one more to allow us to see if
6519 # there are more ...
6520 my @taglist = git_get_tags_list(16);
6521 my @headlist = git_get_heads_list(16);
6522 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6523 my @forklist;
6524 my $check_forks = gitweb_check_feature('forks');
6526 if ($check_forks) {
6527 # find forks of a project
6528 my $filter = $project;
6529 $filter =~ s/\.git$//;
6530 @forklist = git_get_projects_list($filter);
6531 # filter out forks of forks
6532 @forklist = filter_forks_from_projects_list(\@forklist)
6533 if (@forklist);
6536 git_header_html();
6537 git_print_page_nav('summary','', $head);
6539 print "<div class=\"title\">&nbsp;</div>\n";
6540 print "<table class=\"projects_list\">\n" .
6541 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6542 unless ($omit_owner) {
6543 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6545 if (defined $cd{'rfc2822'}) {
6546 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6547 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6550 # use per project git URL list in $projectroot/$project/cloneurl
6551 # or make project git URL from git base URL and project name
6552 my $url_tag = "URL";
6553 my @url_list = git_get_project_url_list($project);
6554 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6555 foreach my $git_url (@url_list) {
6556 next unless $git_url;
6557 print format_repo_url($url_tag, $git_url);
6558 $url_tag = "";
6561 # Tag cloud
6562 my $show_ctags = gitweb_check_feature('ctags');
6563 if ($show_ctags) {
6564 my $ctags = git_get_project_ctags($project);
6565 if (%$ctags) {
6566 # without ability to add tags, don't show if there are none
6567 my $cloud = git_populate_project_tagcloud($ctags);
6568 print "<tr id=\"metadata_ctags\">" .
6569 "<td>content tags</td>" .
6570 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6571 "</tr>\n";
6575 print "</table>\n";
6577 # If XSS prevention is on, we don't include README.html.
6578 # TODO: Allow a readme in some safe format.
6579 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6580 print "<div class=\"title\">readme</div>\n" .
6581 "<div class=\"readme\">\n";
6582 insert_file("$projectroot/$project/README.html");
6583 print "\n</div>\n"; # class="readme"
6586 # we need to request one more than 16 (0..15) to check if
6587 # those 16 are all
6588 my @commitlist = $head ? parse_commits($head, 17) : ();
6589 if (@commitlist) {
6590 git_print_header_div('shortlog');
6591 git_shortlog_body(\@commitlist, 0, 15, $refs,
6592 $#commitlist <= 15 ? undef :
6593 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6596 if (@taglist) {
6597 git_print_header_div('tags');
6598 git_tags_body(\@taglist, 0, 15,
6599 $#taglist <= 15 ? undef :
6600 $cgi->a({-href => href(action=>"tags")}, "..."));
6603 if (@headlist) {
6604 git_print_header_div('heads');
6605 git_heads_body(\@headlist, $head, 0, 15,
6606 $#headlist <= 15 ? undef :
6607 $cgi->a({-href => href(action=>"heads")}, "..."));
6610 if (%remotedata) {
6611 git_print_header_div('remotes');
6612 git_remotes_body(\%remotedata, 15, $head);
6615 if (@forklist) {
6616 git_print_header_div('forks');
6617 git_project_list_body(\@forklist, 'age', 0, 15,
6618 $#forklist <= 15 ? undef :
6619 $cgi->a({-href => href(action=>"forks")}, "..."),
6620 'no_header');
6623 git_footer_html();
6626 sub git_tag {
6627 my %tag = parse_tag($hash);
6629 if (! %tag) {
6630 die_error(404, "Unknown tag object");
6633 my $head = git_get_head_hash($project);
6634 git_header_html();
6635 git_print_page_nav('','', $head,undef,$head);
6636 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6637 print "<div class=\"title_text\">\n" .
6638 "<table class=\"object_header\">\n" .
6639 "<tr>\n" .
6640 "<td>object</td>\n" .
6641 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6642 $tag{'object'}) . "</td>\n" .
6643 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6644 $tag{'type'}) . "</td>\n" .
6645 "</tr>\n";
6646 if (defined($tag{'author'})) {
6647 git_print_authorship_rows(\%tag, 'author');
6649 print "</table>\n\n" .
6650 "</div>\n";
6651 print "<div class=\"page_body\">";
6652 my $comment = $tag{'comment'};
6653 foreach my $line (@$comment) {
6654 chomp $line;
6655 print esc_html($line, -nbsp=>1) . "<br/>\n";
6657 print "</div>\n";
6658 git_footer_html();
6661 sub git_blame_common {
6662 my $format = shift || 'porcelain';
6663 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6664 $format = 'incremental';
6665 $action = 'blame_incremental'; # for page title etc
6668 # permissions
6669 gitweb_check_feature('blame')
6670 or die_error(403, "Blame view not allowed");
6672 # error checking
6673 die_error(400, "No file name given") unless $file_name;
6674 $hash_base ||= git_get_head_hash($project);
6675 die_error(404, "Couldn't find base commit") unless $hash_base;
6676 my %co = parse_commit($hash_base)
6677 or die_error(404, "Commit not found");
6678 my $ftype = "blob";
6679 if (!defined $hash) {
6680 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6681 or die_error(404, "Error looking up file");
6682 } else {
6683 $ftype = git_get_type($hash);
6684 if ($ftype !~ "blob") {
6685 die_error(400, "Object is not a blob");
6689 my $fd;
6690 if ($format eq 'incremental') {
6691 # get file contents (as base)
6692 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6693 or die_error(500, "Open git-cat-file failed");
6694 } elsif ($format eq 'data') {
6695 # run git-blame --incremental
6696 open $fd, "-|", git_cmd(), "blame", "--incremental",
6697 $hash_base, "--", $file_name
6698 or die_error(500, "Open git-blame --incremental failed");
6699 } else {
6700 # run git-blame --porcelain
6701 open $fd, "-|", git_cmd(), "blame", '-p',
6702 $hash_base, '--', $file_name
6703 or die_error(500, "Open git-blame --porcelain failed");
6706 # incremental blame data returns early
6707 if ($format eq 'data') {
6708 print $cgi->header(
6709 -type=>"text/plain", -charset => "utf-8",
6710 -status=> "200 OK");
6711 local $| = 1; # output autoflush
6712 while (my $line = <$fd>) {
6713 print to_utf8($line);
6715 close $fd
6716 or print "ERROR $!\n";
6718 print 'END';
6719 if (defined $t0 && gitweb_check_feature('timed')) {
6720 print ' '.
6721 tv_interval($t0, [ gettimeofday() ]).
6722 ' '.$number_of_git_cmds;
6724 print "\n";
6726 return;
6729 # page header
6730 git_header_html();
6731 my $formats_nav =
6732 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6733 "blob") .
6734 " | ";
6735 if ($format eq 'incremental') {
6736 $formats_nav .=
6737 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6738 "blame") . " (non-incremental)";
6739 } else {
6740 $formats_nav .=
6741 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6742 "blame") . " (incremental)";
6744 $formats_nav .=
6745 " | " .
6746 $cgi->a({-href => href(action=>"history", -replay=>1)},
6747 "history") .
6748 " | " .
6749 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6750 "HEAD");
6751 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6752 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6753 git_print_page_path($file_name, $ftype, $hash_base);
6755 # page body
6756 if ($format eq 'incremental') {
6757 print "<noscript>\n<div class=\"error\"><center><b>\n".
6758 "This page requires JavaScript to run.\n Use ".
6759 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6760 'this page').
6761 " instead.\n".
6762 "</b></center></div>\n</noscript>\n";
6764 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6767 print qq!<div class="page_body">\n!;
6768 print qq!<div id="progress_info">... / ...</div>\n!
6769 if ($format eq 'incremental');
6770 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6771 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6772 qq!<thead>\n!.
6773 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6774 qq!</thead>\n!.
6775 qq!<tbody>\n!;
6777 my @rev_color = qw(light dark);
6778 my $num_colors = scalar(@rev_color);
6779 my $current_color = 0;
6781 if ($format eq 'incremental') {
6782 my $color_class = $rev_color[$current_color];
6784 #contents of a file
6785 my $linenr = 0;
6786 LINE:
6787 while (my $line = <$fd>) {
6788 chomp $line;
6789 $linenr++;
6791 print qq!<tr id="l$linenr" class="$color_class">!.
6792 qq!<td class="sha1"><a href=""> </a></td>!.
6793 qq!<td class="linenr">!.
6794 qq!<a class="linenr" href="">$linenr</a></td>!;
6795 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6796 print qq!</tr>\n!;
6799 } else { # porcelain, i.e. ordinary blame
6800 my %metainfo = (); # saves information about commits
6802 # blame data
6803 LINE:
6804 while (my $line = <$fd>) {
6805 chomp $line;
6806 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6807 # no <lines in group> for subsequent lines in group of lines
6808 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6809 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6810 if (!exists $metainfo{$full_rev}) {
6811 $metainfo{$full_rev} = { 'nprevious' => 0 };
6813 my $meta = $metainfo{$full_rev};
6814 my $data;
6815 while ($data = <$fd>) {
6816 chomp $data;
6817 last if ($data =~ s/^\t//); # contents of line
6818 if ($data =~ /^(\S+)(?: (.*))?$/) {
6819 $meta->{$1} = $2 unless exists $meta->{$1};
6821 if ($data =~ /^previous /) {
6822 $meta->{'nprevious'}++;
6825 my $short_rev = substr($full_rev, 0, 8);
6826 my $author = $meta->{'author'};
6827 my %date =
6828 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6829 my $date = $date{'iso-tz'};
6830 if ($group_size) {
6831 $current_color = ($current_color + 1) % $num_colors;
6833 my $tr_class = $rev_color[$current_color];
6834 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6835 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6836 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6837 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6838 if ($group_size) {
6839 print "<td class=\"sha1\"";
6840 print " title=\"". esc_html($author) . ", $date\"";
6841 print " rowspan=\"$group_size\"" if ($group_size > 1);
6842 print ">";
6843 print $cgi->a({-href => href(action=>"commit",
6844 hash=>$full_rev,
6845 file_name=>$file_name)},
6846 esc_html($short_rev));
6847 if ($group_size >= 2) {
6848 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6849 if (@author_initials) {
6850 print "<br />" .
6851 esc_html(join('', @author_initials));
6852 # or join('.', ...)
6855 print "</td>\n";
6857 # 'previous' <sha1 of parent commit> <filename at commit>
6858 if (exists $meta->{'previous'} &&
6859 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6860 $meta->{'parent'} = $1;
6861 $meta->{'file_parent'} = unquote($2);
6863 my $linenr_commit =
6864 exists($meta->{'parent'}) ?
6865 $meta->{'parent'} : $full_rev;
6866 my $linenr_filename =
6867 exists($meta->{'file_parent'}) ?
6868 $meta->{'file_parent'} : unquote($meta->{'filename'});
6869 my $blamed = href(action => 'blame',
6870 file_name => $linenr_filename,
6871 hash_base => $linenr_commit);
6872 print "<td class=\"linenr\">";
6873 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6874 -class => "linenr" },
6875 esc_html($lineno));
6876 print "</td>";
6877 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6878 print "</tr>\n";
6879 } # end while
6883 # footer
6884 print "</tbody>\n".
6885 "</table>\n"; # class="blame"
6886 print "</div>\n"; # class="blame_body"
6887 close $fd
6888 or print "Reading blob failed\n";
6890 git_footer_html();
6893 sub git_blame {
6894 git_blame_common();
6897 sub git_blame_incremental {
6898 git_blame_common('incremental');
6901 sub git_blame_data {
6902 git_blame_common('data');
6905 sub git_tags {
6906 my $head = git_get_head_hash($project);
6907 git_header_html();
6908 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6909 git_print_header_div('summary', $project);
6911 my @tagslist = git_get_tags_list();
6912 if (@tagslist) {
6913 git_tags_body(\@tagslist);
6915 git_footer_html();
6918 sub git_heads {
6919 my $head = git_get_head_hash($project);
6920 git_header_html();
6921 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6922 git_print_header_div('summary', $project);
6924 my @headslist = git_get_heads_list();
6925 if (@headslist) {
6926 git_heads_body(\@headslist, $head);
6928 git_footer_html();
6931 # used both for single remote view and for list of all the remotes
6932 sub git_remotes {
6933 gitweb_check_feature('remote_heads')
6934 or die_error(403, "Remote heads view is disabled");
6936 my $head = git_get_head_hash($project);
6937 my $remote = $input_params{'hash'};
6939 my $remotedata = git_get_remotes_list($remote);
6940 die_error(500, "Unable to get remote information") unless defined $remotedata;
6942 unless (%$remotedata) {
6943 die_error(404, defined $remote ?
6944 "Remote $remote not found" :
6945 "No remotes found");
6948 git_header_html(undef, undef, -action_extra => $remote);
6949 git_print_page_nav('', '', $head, undef, $head,
6950 format_ref_views($remote ? '' : 'remotes'));
6952 fill_remote_heads($remotedata);
6953 if (defined $remote) {
6954 git_print_header_div('remotes', "$remote remote for $project");
6955 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6956 } else {
6957 git_print_header_div('summary', "$project remotes");
6958 git_remotes_body($remotedata, undef, $head);
6961 git_footer_html();
6964 sub git_blob_plain {
6965 my $type = shift;
6966 my $expires;
6968 if (!defined $hash) {
6969 if (defined $file_name) {
6970 my $base = $hash_base || git_get_head_hash($project);
6971 $hash = git_get_hash_by_path($base, $file_name, "blob")
6972 or die_error(404, "Cannot find file");
6973 } else {
6974 die_error(400, "No file name defined");
6976 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6977 # blobs defined by non-textual hash id's can be cached
6978 $expires = "+1d";
6981 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6982 or die_error(500, "Open git-cat-file blob '$hash' failed");
6984 # content-type (can include charset)
6985 $type = blob_contenttype($fd, $file_name, $type);
6987 # "save as" filename, even when no $file_name is given
6988 my $save_as = "$hash";
6989 if (defined $file_name) {
6990 $save_as = $file_name;
6991 } elsif ($type =~ m/^text\//) {
6992 $save_as .= '.txt';
6995 # With XSS prevention on, blobs of all types except a few known safe
6996 # ones are served with "Content-Disposition: attachment" to make sure
6997 # they don't run in our security domain. For certain image types,
6998 # blob view writes an <img> tag referring to blob_plain view, and we
6999 # want to be sure not to break that by serving the image as an
7000 # attachment (though Firefox 3 doesn't seem to care).
7001 my $sandbox = $prevent_xss &&
7002 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7004 # serve text/* as text/plain
7005 if ($prevent_xss &&
7006 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7007 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7008 my $rest = $1;
7009 $rest = defined $rest ? $rest : '';
7010 $type = "text/plain$rest";
7013 print $cgi->header(
7014 -type => $type,
7015 -expires => $expires,
7016 -content_disposition =>
7017 ($sandbox ? 'attachment' : 'inline')
7018 . '; filename="' . $save_as . '"');
7019 local $/ = undef;
7020 binmode STDOUT, ':raw';
7021 print <$fd>;
7022 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7023 close $fd;
7026 sub git_blob {
7027 my $expires;
7029 if (!defined $hash) {
7030 if (defined $file_name) {
7031 my $base = $hash_base || git_get_head_hash($project);
7032 $hash = git_get_hash_by_path($base, $file_name, "blob")
7033 or die_error(404, "Cannot find file");
7034 } else {
7035 die_error(400, "No file name defined");
7037 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7038 # blobs defined by non-textual hash id's can be cached
7039 $expires = "+1d";
7042 my $have_blame = gitweb_check_feature('blame');
7043 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7044 or die_error(500, "Couldn't cat $file_name, $hash");
7045 my $mimetype = blob_mimetype($fd, $file_name);
7046 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7047 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7048 close $fd;
7049 return git_blob_plain($mimetype);
7051 # we can have blame only for text/* mimetype
7052 $have_blame &&= ($mimetype =~ m!^text/!);
7054 my $highlight = gitweb_check_feature('highlight');
7055 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
7056 $fd = run_highlighter($fd, $highlight, $syntax)
7057 if $syntax;
7059 git_header_html(undef, $expires);
7060 my $formats_nav = '';
7061 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7062 if (defined $file_name) {
7063 if ($have_blame) {
7064 $formats_nav .=
7065 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7066 "blame") .
7067 " | ";
7069 $formats_nav .=
7070 $cgi->a({-href => href(action=>"history", -replay=>1)},
7071 "history") .
7072 " | " .
7073 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7074 "raw") .
7075 " | " .
7076 $cgi->a({-href => href(action=>"blob",
7077 hash_base=>"HEAD", file_name=>$file_name)},
7078 "HEAD");
7079 } else {
7080 $formats_nav .=
7081 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7082 "raw");
7084 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7085 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7086 } else {
7087 print "<div class=\"page_nav\">\n" .
7088 "<br/><br/></div>\n" .
7089 "<div class=\"title\">".esc_html($hash)."</div>\n";
7091 git_print_page_path($file_name, "blob", $hash_base);
7092 print "<div class=\"page_body\">\n";
7093 if ($mimetype =~ m!^image/!) {
7094 print qq!<img type="!.esc_attr($mimetype).qq!"!;
7095 if ($file_name) {
7096 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7098 print qq! src="! .
7099 href(action=>"blob_plain", hash=>$hash,
7100 hash_base=>$hash_base, file_name=>$file_name) .
7101 qq!" />\n!;
7102 } else {
7103 my $nr;
7104 while (my $line = <$fd>) {
7105 chomp $line;
7106 $nr++;
7107 $line = untabify($line);
7108 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7109 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7110 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
7113 close $fd
7114 or print "Reading blob failed.\n";
7115 print "</div>";
7116 git_footer_html();
7119 sub git_tree {
7120 if (!defined $hash_base) {
7121 $hash_base = "HEAD";
7123 if (!defined $hash) {
7124 if (defined $file_name) {
7125 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7126 } else {
7127 $hash = $hash_base;
7130 die_error(404, "No such tree") unless defined($hash);
7132 my $show_sizes = gitweb_check_feature('show-sizes');
7133 my $have_blame = gitweb_check_feature('blame');
7135 my @entries = ();
7137 local $/ = "\0";
7138 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7139 ($show_sizes ? '-l' : ()), @extra_options, $hash
7140 or die_error(500, "Open git-ls-tree failed");
7141 @entries = map { chomp; $_ } <$fd>;
7142 close $fd
7143 or die_error(404, "Reading tree failed");
7146 my $refs = git_get_references();
7147 my $ref = format_ref_marker($refs, $hash_base);
7148 git_header_html();
7149 my $basedir = '';
7150 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7151 my @views_nav = ();
7152 if (defined $file_name) {
7153 push @views_nav,
7154 $cgi->a({-href => href(action=>"history", -replay=>1)},
7155 "history"),
7156 $cgi->a({-href => href(action=>"tree",
7157 hash_base=>"HEAD", file_name=>$file_name)},
7158 "HEAD"),
7160 my $snapshot_links = format_snapshot_links($hash);
7161 if (defined $snapshot_links) {
7162 # FIXME: Should be available when we have no hash base as well.
7163 push @views_nav, $snapshot_links;
7165 git_print_page_nav('tree','', $hash_base, undef, undef,
7166 join(' | ', @views_nav));
7167 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7168 } else {
7169 undef $hash_base;
7170 print "<div class=\"page_nav\">\n";
7171 print "<br/><br/></div>\n";
7172 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7174 if (defined $file_name) {
7175 $basedir = $file_name;
7176 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7177 $basedir .= '/';
7179 git_print_page_path($file_name, 'tree', $hash_base);
7181 print "<div class=\"page_body\">\n";
7182 print "<table class=\"tree\">\n";
7183 my $alternate = 1;
7184 # '..' (top directory) link if possible
7185 if (defined $hash_base &&
7186 defined $file_name && $file_name =~ m![^/]+$!) {
7187 if ($alternate) {
7188 print "<tr class=\"dark\">\n";
7189 } else {
7190 print "<tr class=\"light\">\n";
7192 $alternate ^= 1;
7194 my $up = $file_name;
7195 $up =~ s!/?[^/]+$!!;
7196 undef $up unless $up;
7197 # based on git_print_tree_entry
7198 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7199 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7200 print '<td class="list">';
7201 print $cgi->a({-href => href(action=>"tree",
7202 hash_base=>$hash_base,
7203 file_name=>$up)},
7204 "..");
7205 print "</td>\n";
7206 print "<td class=\"link\"></td>\n";
7208 print "</tr>\n";
7210 foreach my $line (@entries) {
7211 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7213 if ($alternate) {
7214 print "<tr class=\"dark\">\n";
7215 } else {
7216 print "<tr class=\"light\">\n";
7218 $alternate ^= 1;
7220 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7222 print "</tr>\n";
7224 print "</table>\n" .
7225 "</div>";
7226 git_footer_html();
7229 sub snapshot_name {
7230 my ($project, $hash) = @_;
7232 # path/to/project.git -> project
7233 # path/to/project/.git -> project
7234 my $name = to_utf8($project);
7235 $name =~ s,([^/])/*\.git$,$1,;
7236 $name = basename($name);
7237 # sanitize name
7238 $name =~ s/[[:cntrl:]]/?/g;
7240 my $ver = $hash;
7241 if ($hash =~ /^[0-9a-fA-F]+$/) {
7242 # shorten SHA-1 hash
7243 my $full_hash = git_get_full_hash($project, $hash);
7244 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7245 $ver = git_get_short_hash($project, $hash);
7247 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7248 # tags don't need shortened SHA-1 hash
7249 $ver = $1;
7250 } else {
7251 # branches and other need shortened SHA-1 hash
7252 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
7253 $ver = $1;
7255 $ver .= '-' . git_get_short_hash($project, $hash);
7257 # in case of hierarchical branch names
7258 $ver =~ s!/!.!g;
7260 # name = project-version_string
7261 $name = "$name-$ver";
7263 return wantarray ? ($name, $name) : $name;
7266 sub exit_if_unmodified_since {
7267 my ($latest_epoch) = @_;
7268 our $cgi;
7270 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7271 if (defined $if_modified) {
7272 my $since;
7273 if (eval { require HTTP::Date; 1; }) {
7274 $since = HTTP::Date::str2time($if_modified);
7275 } elsif (eval { require Time::ParseDate; 1; }) {
7276 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7278 if (defined $since && $latest_epoch <= $since) {
7279 my %latest_date = parse_date($latest_epoch);
7280 print $cgi->header(
7281 -last_modified => $latest_date{'rfc2822'},
7282 -status => '304 Not Modified');
7283 goto DONE_GITWEB;
7288 sub git_snapshot {
7289 my $format = $input_params{'snapshot_format'};
7290 if (!@snapshot_fmts) {
7291 die_error(403, "Snapshots not allowed");
7293 # default to first supported snapshot format
7294 $format ||= $snapshot_fmts[0];
7295 if ($format !~ m/^[a-z0-9]+$/) {
7296 die_error(400, "Invalid snapshot format parameter");
7297 } elsif (!exists($known_snapshot_formats{$format})) {
7298 die_error(400, "Unknown snapshot format");
7299 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7300 die_error(403, "Snapshot format not allowed");
7301 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7302 die_error(403, "Unsupported snapshot format");
7305 my $type = git_get_type("$hash^{}");
7306 if (!$type) {
7307 die_error(404, 'Object does not exist');
7308 } elsif ($type eq 'blob') {
7309 die_error(400, 'Object is not a tree-ish');
7312 my ($name, $prefix) = snapshot_name($project, $hash);
7313 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7315 my %co = parse_commit($hash);
7316 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7318 my $cmd = quote_command(
7319 git_cmd(), 'archive',
7320 "--format=$known_snapshot_formats{$format}{'format'}",
7321 "--prefix=$prefix/", $hash);
7322 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7323 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7326 $filename =~ s/(["\\])/\\$1/g;
7327 my %latest_date;
7328 if (%co) {
7329 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7332 print $cgi->header(
7333 -type => $known_snapshot_formats{$format}{'type'},
7334 -content_disposition => 'inline; filename="' . $filename . '"',
7335 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7336 -status => '200 OK');
7338 open my $fd, "-|", $cmd
7339 or die_error(500, "Execute git-archive failed");
7340 binmode STDOUT, ':raw';
7341 print <$fd>;
7342 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7343 close $fd;
7346 sub git_log_generic {
7347 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7349 my $head = git_get_head_hash($project);
7350 if (!defined $base) {
7351 $base = $head;
7353 if (!defined $page) {
7354 $page = 0;
7356 my $refs = git_get_references();
7358 my $commit_hash = $base;
7359 if (defined $parent) {
7360 $commit_hash = "$parent..$base";
7362 my @commitlist =
7363 parse_commits($commit_hash, 101, (100 * $page),
7364 defined $file_name ? ($file_name, "--full-history") : ());
7366 my $ftype;
7367 if (!defined $file_hash && defined $file_name) {
7368 # some commits could have deleted file in question,
7369 # and not have it in tree, but one of them has to have it
7370 for (my $i = 0; $i < @commitlist; $i++) {
7371 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7372 last if defined $file_hash;
7375 if (defined $file_hash) {
7376 $ftype = git_get_type($file_hash);
7378 if (defined $file_name && !defined $ftype) {
7379 die_error(500, "Unknown type of object");
7381 my %co;
7382 if (defined $file_name) {
7383 %co = parse_commit($base)
7384 or die_error(404, "Unknown commit object");
7388 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7389 my $next_link = '';
7390 if ($#commitlist >= 100) {
7391 $next_link =
7392 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7393 -accesskey => "n", -title => "Alt-n"}, "next");
7395 my $patch_max = gitweb_get_feature('patches');
7396 if ($patch_max && !defined $file_name) {
7397 if ($patch_max < 0 || @commitlist <= $patch_max) {
7398 $paging_nav .= " &sdot; " .
7399 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7400 "patches");
7404 git_header_html();
7405 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7406 if (defined $file_name) {
7407 git_print_header_div('commit', esc_html($co{'title'}), $base);
7408 } else {
7409 git_print_header_div('summary', $project)
7411 git_print_page_path($file_name, $ftype, $hash_base)
7412 if (defined $file_name);
7414 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7415 $file_name, $file_hash, $ftype);
7417 git_footer_html();
7420 sub git_log {
7421 git_log_generic('log', \&git_log_body,
7422 $hash, $hash_parent);
7425 sub git_commit {
7426 $hash ||= $hash_base || "HEAD";
7427 my %co = parse_commit($hash)
7428 or die_error(404, "Unknown commit object");
7430 my $parent = $co{'parent'};
7431 my $parents = $co{'parents'}; # listref
7433 # we need to prepare $formats_nav before any parameter munging
7434 my $formats_nav;
7435 if (!defined $parent) {
7436 # --root commitdiff
7437 $formats_nav .= '(initial)';
7438 } elsif (@$parents == 1) {
7439 # single parent commit
7440 $formats_nav .=
7441 '(parent: ' .
7442 $cgi->a({-href => href(action=>"commit",
7443 hash=>$parent)},
7444 esc_html(substr($parent, 0, 7))) .
7445 ')';
7446 } else {
7447 # merge commit
7448 $formats_nav .=
7449 '(merge: ' .
7450 join(' ', map {
7451 $cgi->a({-href => href(action=>"commit",
7452 hash=>$_)},
7453 esc_html(substr($_, 0, 7)));
7454 } @$parents ) .
7455 ')';
7457 if (gitweb_check_feature('patches') && @$parents <= 1) {
7458 $formats_nav .= " | " .
7459 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7460 "patch");
7463 if (!defined $parent) {
7464 $parent = "--root";
7466 my @difftree;
7467 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7468 @diff_opts,
7469 (@$parents <= 1 ? $parent : '-c'),
7470 $hash, "--"
7471 or die_error(500, "Open git-diff-tree failed");
7472 @difftree = map { chomp; $_ } <$fd>;
7473 close $fd or die_error(404, "Reading git-diff-tree failed");
7475 # non-textual hash id's can be cached
7476 my $expires;
7477 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7478 $expires = "+1d";
7480 my $refs = git_get_references();
7481 my $ref = format_ref_marker($refs, $co{'id'});
7483 git_header_html(undef, $expires);
7484 git_print_page_nav('commit', '',
7485 $hash, $co{'tree'}, $hash,
7486 $formats_nav);
7488 if (defined $co{'parent'}) {
7489 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7490 } else {
7491 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7493 print "<div class=\"title_text\">\n" .
7494 "<table class=\"object_header\">\n";
7495 git_print_authorship_rows(\%co);
7496 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7497 print "<tr>" .
7498 "<td>tree</td>" .
7499 "<td class=\"sha1\">" .
7500 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7501 class => "list"}, $co{'tree'}) .
7502 "</td>" .
7503 "<td class=\"link\">" .
7504 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7505 "tree");
7506 my $snapshot_links = format_snapshot_links($hash);
7507 if (defined $snapshot_links) {
7508 print " | " . $snapshot_links;
7510 print "</td>" .
7511 "</tr>\n";
7513 foreach my $par (@$parents) {
7514 print "<tr>" .
7515 "<td>parent</td>" .
7516 "<td class=\"sha1\">" .
7517 $cgi->a({-href => href(action=>"commit", hash=>$par),
7518 class => "list"}, $par) .
7519 "</td>" .
7520 "<td class=\"link\">" .
7521 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7522 " | " .
7523 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7524 "</td>" .
7525 "</tr>\n";
7527 print "</table>".
7528 "</div>\n";
7530 print "<div class=\"page_body\">\n";
7531 git_print_log($co{'comment'});
7532 print "</div>\n";
7534 git_difftree_body(\@difftree, $hash, @$parents);
7536 git_footer_html();
7539 sub git_object {
7540 # object is defined by:
7541 # - hash or hash_base alone
7542 # - hash_base and file_name
7543 my $type;
7545 # - hash or hash_base alone
7546 if ($hash || ($hash_base && !defined $file_name)) {
7547 my $object_id = $hash || $hash_base;
7549 open my $fd, "-|", quote_command(
7550 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7551 or die_error(404, "Object does not exist");
7552 $type = <$fd>;
7553 chomp $type;
7554 close $fd
7555 or die_error(404, "Object does not exist");
7557 # - hash_base and file_name
7558 } elsif ($hash_base && defined $file_name) {
7559 $file_name =~ s,/+$,,;
7561 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7562 or die_error(404, "Base object does not exist");
7564 # here errors should not hapen
7565 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7566 or die_error(500, "Open git-ls-tree failed");
7567 my $line = <$fd>;
7568 close $fd;
7570 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7571 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7572 die_error(404, "File or directory for given base does not exist");
7574 $type = $2;
7575 $hash = $3;
7576 } else {
7577 die_error(400, "Not enough information to find object");
7580 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7581 hash=>$hash, hash_base=>$hash_base,
7582 file_name=>$file_name),
7583 -status => '302 Found');
7586 sub git_blobdiff {
7587 my $format = shift || 'html';
7588 my $diff_style = $input_params{'diff_style'} || 'inline';
7590 my $fd;
7591 my @difftree;
7592 my %diffinfo;
7593 my $expires;
7595 # preparing $fd and %diffinfo for git_patchset_body
7596 # new style URI
7597 if (defined $hash_base && defined $hash_parent_base) {
7598 if (defined $file_name) {
7599 # read raw output
7600 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7601 $hash_parent_base, $hash_base,
7602 "--", (defined $file_parent ? $file_parent : ()), $file_name
7603 or die_error(500, "Open git-diff-tree failed");
7604 @difftree = map { chomp; $_ } <$fd>;
7605 close $fd
7606 or die_error(404, "Reading git-diff-tree failed");
7607 @difftree
7608 or die_error(404, "Blob diff not found");
7610 } elsif (defined $hash &&
7611 $hash =~ /[0-9a-fA-F]{40}/) {
7612 # try to find filename from $hash
7614 # read filtered raw output
7615 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7616 $hash_parent_base, $hash_base, "--"
7617 or die_error(500, "Open git-diff-tree failed");
7618 @difftree =
7619 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7620 # $hash == to_id
7621 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7622 map { chomp; $_ } <$fd>;
7623 close $fd
7624 or die_error(404, "Reading git-diff-tree failed");
7625 @difftree
7626 or die_error(404, "Blob diff not found");
7628 } else {
7629 die_error(400, "Missing one of the blob diff parameters");
7632 if (@difftree > 1) {
7633 die_error(400, "Ambiguous blob diff specification");
7636 %diffinfo = parse_difftree_raw_line($difftree[0]);
7637 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7638 $file_name ||= $diffinfo{'to_file'};
7640 $hash_parent ||= $diffinfo{'from_id'};
7641 $hash ||= $diffinfo{'to_id'};
7643 # non-textual hash id's can be cached
7644 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7645 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7646 $expires = '+1d';
7649 # open patch output
7650 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7651 '-p', ($format eq 'html' ? "--full-index" : ()),
7652 $hash_parent_base, $hash_base,
7653 "--", (defined $file_parent ? $file_parent : ()), $file_name
7654 or die_error(500, "Open git-diff-tree failed");
7657 # old/legacy style URI -- not generated anymore since 1.4.3.
7658 if (!%diffinfo) {
7659 die_error('404 Not Found', "Missing one of the blob diff parameters")
7662 # header
7663 if ($format eq 'html') {
7664 my $formats_nav =
7665 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7666 "raw");
7667 $formats_nav .= diff_style_nav($diff_style);
7668 git_header_html(undef, $expires);
7669 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7670 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7671 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7672 } else {
7673 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7674 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7676 if (defined $file_name) {
7677 git_print_page_path($file_name, "blob", $hash_base);
7678 } else {
7679 print "<div class=\"page_path\"></div>\n";
7682 } elsif ($format eq 'plain') {
7683 print $cgi->header(
7684 -type => 'text/plain',
7685 -charset => 'utf-8',
7686 -expires => $expires,
7687 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7689 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7691 } else {
7692 die_error(400, "Unknown blobdiff format");
7695 # patch
7696 if ($format eq 'html') {
7697 print "<div class=\"page_body\">\n";
7699 git_patchset_body($fd, $diff_style,
7700 [ \%diffinfo ], $hash_base, $hash_parent_base);
7701 close $fd;
7703 print "</div>\n"; # class="page_body"
7704 git_footer_html();
7706 } else {
7707 while (my $line = <$fd>) {
7708 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7709 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7711 print $line;
7713 last if $line =~ m!^\+\+\+!;
7715 local $/ = undef;
7716 print <$fd>;
7717 close $fd;
7721 sub git_blobdiff_plain {
7722 git_blobdiff('plain');
7725 # assumes that it is added as later part of already existing navigation,
7726 # so it returns "| foo | bar" rather than just "foo | bar"
7727 sub diff_style_nav {
7728 my ($diff_style, $is_combined) = @_;
7729 $diff_style ||= 'inline';
7731 return "" if ($is_combined);
7733 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7734 my %styles = @styles;
7735 @styles =
7736 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7738 return join '',
7739 map { " | ".$_ }
7740 map {
7741 $_ eq $diff_style ? $styles{$_} :
7742 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7743 } @styles;
7746 sub git_commitdiff {
7747 my %params = @_;
7748 my $format = $params{-format} || 'html';
7749 my $diff_style = $input_params{'diff_style'} || 'inline';
7751 my ($patch_max) = gitweb_get_feature('patches');
7752 if ($format eq 'patch') {
7753 die_error(403, "Patch view not allowed") unless $patch_max;
7756 $hash ||= $hash_base || "HEAD";
7757 my %co = parse_commit($hash)
7758 or die_error(404, "Unknown commit object");
7760 # choose format for commitdiff for merge
7761 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7762 $hash_parent = '--cc';
7764 # we need to prepare $formats_nav before almost any parameter munging
7765 my $formats_nav;
7766 if ($format eq 'html') {
7767 $formats_nav =
7768 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7769 "raw");
7770 if ($patch_max && @{$co{'parents'}} <= 1) {
7771 $formats_nav .= " | " .
7772 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7773 "patch");
7775 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7777 if (defined $hash_parent &&
7778 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7779 # commitdiff with two commits given
7780 my $hash_parent_short = $hash_parent;
7781 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7782 $hash_parent_short = substr($hash_parent, 0, 7);
7784 $formats_nav .=
7785 ' (from';
7786 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7787 if ($co{'parents'}[$i] eq $hash_parent) {
7788 $formats_nav .= ' parent ' . ($i+1);
7789 last;
7792 $formats_nav .= ': ' .
7793 $cgi->a({-href => href(-replay=>1,
7794 hash=>$hash_parent, hash_base=>undef)},
7795 esc_html($hash_parent_short)) .
7796 ')';
7797 } elsif (!$co{'parent'}) {
7798 # --root commitdiff
7799 $formats_nav .= ' (initial)';
7800 } elsif (scalar @{$co{'parents'}} == 1) {
7801 # single parent commit
7802 $formats_nav .=
7803 ' (parent: ' .
7804 $cgi->a({-href => href(-replay=>1,
7805 hash=>$co{'parent'}, hash_base=>undef)},
7806 esc_html(substr($co{'parent'}, 0, 7))) .
7807 ')';
7808 } else {
7809 # merge commit
7810 if ($hash_parent eq '--cc') {
7811 $formats_nav .= ' | ' .
7812 $cgi->a({-href => href(-replay=>1,
7813 hash=>$hash, hash_parent=>'-c')},
7814 'combined');
7815 } else { # $hash_parent eq '-c'
7816 $formats_nav .= ' | ' .
7817 $cgi->a({-href => href(-replay=>1,
7818 hash=>$hash, hash_parent=>'--cc')},
7819 'compact');
7821 $formats_nav .=
7822 ' (merge: ' .
7823 join(' ', map {
7824 $cgi->a({-href => href(-replay=>1,
7825 hash=>$_, hash_base=>undef)},
7826 esc_html(substr($_, 0, 7)));
7827 } @{$co{'parents'}} ) .
7828 ')';
7832 my $hash_parent_param = $hash_parent;
7833 if (!defined $hash_parent_param) {
7834 # --cc for multiple parents, --root for parentless
7835 $hash_parent_param =
7836 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7839 # read commitdiff
7840 my $fd;
7841 my @difftree;
7842 if ($format eq 'html') {
7843 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7844 "--no-commit-id", "--patch-with-raw", "--full-index",
7845 $hash_parent_param, $hash, "--"
7846 or die_error(500, "Open git-diff-tree failed");
7848 while (my $line = <$fd>) {
7849 chomp $line;
7850 # empty line ends raw part of diff-tree output
7851 last unless $line;
7852 push @difftree, scalar parse_difftree_raw_line($line);
7855 } elsif ($format eq 'plain') {
7856 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7857 '-p', $hash_parent_param, $hash, "--"
7858 or die_error(500, "Open git-diff-tree failed");
7859 } elsif ($format eq 'patch') {
7860 # For commit ranges, we limit the output to the number of
7861 # patches specified in the 'patches' feature.
7862 # For single commits, we limit the output to a single patch,
7863 # diverging from the git-format-patch default.
7864 my @commit_spec = ();
7865 if ($hash_parent) {
7866 if ($patch_max > 0) {
7867 push @commit_spec, "-$patch_max";
7869 push @commit_spec, '-n', "$hash_parent..$hash";
7870 } else {
7871 if ($params{-single}) {
7872 push @commit_spec, '-1';
7873 } else {
7874 if ($patch_max > 0) {
7875 push @commit_spec, "-$patch_max";
7877 push @commit_spec, "-n";
7879 push @commit_spec, '--root', $hash;
7881 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7882 '--encoding=utf8', '--stdout', @commit_spec
7883 or die_error(500, "Open git-format-patch failed");
7884 } else {
7885 die_error(400, "Unknown commitdiff format");
7888 # non-textual hash id's can be cached
7889 my $expires;
7890 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7891 $expires = "+1d";
7894 # write commit message
7895 if ($format eq 'html') {
7896 my $refs = git_get_references();
7897 my $ref = format_ref_marker($refs, $co{'id'});
7899 git_header_html(undef, $expires);
7900 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7901 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7902 print "<div class=\"title_text\">\n" .
7903 "<table class=\"object_header\">\n";
7904 git_print_authorship_rows(\%co);
7905 print "</table>".
7906 "</div>\n";
7907 print "<div class=\"page_body\">\n";
7908 if (@{$co{'comment'}} > 1) {
7909 print "<div class=\"log\">\n";
7910 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7911 print "</div>\n"; # class="log"
7914 } elsif ($format eq 'plain') {
7915 my $refs = git_get_references("tags");
7916 my $tagname = git_get_rev_name_tags($hash);
7917 my $filename = basename($project) . "-$hash.patch";
7919 print $cgi->header(
7920 -type => 'text/plain',
7921 -charset => 'utf-8',
7922 -expires => $expires,
7923 -content_disposition => 'inline; filename="' . "$filename" . '"');
7924 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7925 print "From: " . to_utf8($co{'author'}) . "\n";
7926 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7927 print "Subject: " . to_utf8($co{'title'}) . "\n";
7929 print "X-Git-Tag: $tagname\n" if $tagname;
7930 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7932 foreach my $line (@{$co{'comment'}}) {
7933 print to_utf8($line) . "\n";
7935 print "---\n\n";
7936 } elsif ($format eq 'patch') {
7937 my $filename = basename($project) . "-$hash.patch";
7939 print $cgi->header(
7940 -type => 'text/plain',
7941 -charset => 'utf-8',
7942 -expires => $expires,
7943 -content_disposition => 'inline; filename="' . "$filename" . '"');
7946 # write patch
7947 if ($format eq 'html') {
7948 my $use_parents = !defined $hash_parent ||
7949 $hash_parent eq '-c' || $hash_parent eq '--cc';
7950 git_difftree_body(\@difftree, $hash,
7951 $use_parents ? @{$co{'parents'}} : $hash_parent);
7952 print "<br/>\n";
7954 git_patchset_body($fd, $diff_style,
7955 \@difftree, $hash,
7956 $use_parents ? @{$co{'parents'}} : $hash_parent);
7957 close $fd;
7958 print "</div>\n"; # class="page_body"
7959 git_footer_html();
7961 } elsif ($format eq 'plain') {
7962 local $/ = undef;
7963 print <$fd>;
7964 close $fd
7965 or print "Reading git-diff-tree failed\n";
7966 } elsif ($format eq 'patch') {
7967 local $/ = undef;
7968 print <$fd>;
7969 close $fd
7970 or print "Reading git-format-patch failed\n";
7974 sub git_commitdiff_plain {
7975 git_commitdiff(-format => 'plain');
7978 # format-patch-style patches
7979 sub git_patch {
7980 git_commitdiff(-format => 'patch', -single => 1);
7983 sub git_patches {
7984 git_commitdiff(-format => 'patch');
7987 sub git_history {
7988 git_log_generic('history', \&git_history_body,
7989 $hash_base, $hash_parent_base,
7990 $file_name, $hash);
7993 sub git_search {
7994 $searchtype ||= 'commit';
7996 # check if appropriate features are enabled
7997 gitweb_check_feature('search')
7998 or die_error(403, "Search is disabled");
7999 if ($searchtype eq 'pickaxe') {
8000 # pickaxe may take all resources of your box and run for several minutes
8001 # with every query - so decide by yourself how public you make this feature
8002 gitweb_check_feature('pickaxe')
8003 or die_error(403, "Pickaxe search is disabled");
8005 if ($searchtype eq 'grep') {
8006 # grep search might be potentially CPU-intensive, too
8007 gitweb_check_feature('grep')
8008 or die_error(403, "Grep search is disabled");
8011 if (!defined $searchtext) {
8012 die_error(400, "Text field is empty");
8014 if (!defined $hash) {
8015 $hash = git_get_head_hash($project);
8017 my %co = parse_commit($hash);
8018 if (!%co) {
8019 die_error(404, "Unknown commit object");
8021 if (!defined $page) {
8022 $page = 0;
8025 if ($searchtype eq 'commit' ||
8026 $searchtype eq 'author' ||
8027 $searchtype eq 'committer') {
8028 git_search_message(%co);
8029 } elsif ($searchtype eq 'pickaxe') {
8030 git_search_changes(%co);
8031 } elsif ($searchtype eq 'grep') {
8032 git_search_files(%co);
8033 } else {
8034 die_error(400, "Unknown search type");
8038 sub git_search_help {
8039 git_header_html();
8040 git_print_page_nav('','', $hash,$hash,$hash);
8041 print <<EOT;
8042 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8043 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8044 the pattern entered is recognized as the POSIX extended
8045 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8046 insensitive).</p>
8047 <dl>
8048 <dt><b>commit</b></dt>
8049 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8051 my $have_grep = gitweb_check_feature('grep');
8052 if ($have_grep) {
8053 print <<EOT;
8054 <dt><b>grep</b></dt>
8055 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8056 a different one) are searched for the given pattern. On large trees, this search can take
8057 a while and put some strain on the server, so please use it with some consideration. Note that
8058 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8059 case-sensitive.</dd>
8062 print <<EOT;
8063 <dt><b>author</b></dt>
8064 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8065 <dt><b>committer</b></dt>
8066 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8068 my $have_pickaxe = gitweb_check_feature('pickaxe');
8069 if ($have_pickaxe) {
8070 print <<EOT;
8071 <dt><b>pickaxe</b></dt>
8072 <dd>All commits that caused the string to appear or disappear from any file (changes that
8073 added, removed or "modified" the string) will be listed. This search can take a while and
8074 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8075 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8078 print "</dl>\n";
8079 git_footer_html();
8082 sub git_shortlog {
8083 git_log_generic('shortlog', \&git_shortlog_body,
8084 $hash, $hash_parent);
8087 ## ......................................................................
8088 ## feeds (RSS, Atom; OPML)
8090 sub git_feed {
8091 my $format = shift || 'atom';
8092 my $have_blame = gitweb_check_feature('blame');
8094 # Atom: http://www.atomenabled.org/developers/syndication/
8095 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8096 if ($format ne 'rss' && $format ne 'atom') {
8097 die_error(400, "Unknown web feed format");
8100 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8101 my $head = $hash || 'HEAD';
8102 my @commitlist = parse_commits($head, 150, 0, $file_name);
8104 my %latest_commit;
8105 my %latest_date;
8106 my $content_type = "application/$format+xml";
8107 if (defined $cgi->http('HTTP_ACCEPT') &&
8108 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8109 # browser (feed reader) prefers text/xml
8110 $content_type = 'text/xml';
8112 if (defined($commitlist[0])) {
8113 %latest_commit = %{$commitlist[0]};
8114 my $latest_epoch = $latest_commit{'committer_epoch'};
8115 exit_if_unmodified_since($latest_epoch);
8116 %latest_date = parse_date($latest_epoch, $latest_commit{'comitter_tz'});
8118 print $cgi->header(
8119 -type => $content_type,
8120 -charset => 'utf-8',
8121 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8122 -status => '200 OK');
8124 # Optimization: skip generating the body if client asks only
8125 # for Last-Modified date.
8126 return if ($cgi->request_method() eq 'HEAD');
8128 # header variables
8129 my $title = "$site_name - $project/$action";
8130 my $feed_type = 'log';
8131 if (defined $hash) {
8132 $title .= " - '$hash'";
8133 $feed_type = 'branch log';
8134 if (defined $file_name) {
8135 $title .= " :: $file_name";
8136 $feed_type = 'history';
8138 } elsif (defined $file_name) {
8139 $title .= " - $file_name";
8140 $feed_type = 'history';
8142 $title .= " $feed_type";
8143 my $descr = git_get_project_description($project);
8144 if (defined $descr) {
8145 $descr = esc_html($descr);
8146 } else {
8147 $descr = "$project " .
8148 ($format eq 'rss' ? 'RSS' : 'Atom') .
8149 " feed";
8151 my $owner = git_get_project_owner($project);
8152 $owner = esc_html($owner);
8154 #header
8155 my $alt_url;
8156 if (defined $file_name) {
8157 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8158 } elsif (defined $hash) {
8159 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8160 } else {
8161 $alt_url = href(-full=>1, action=>"summary");
8163 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8164 if ($format eq 'rss') {
8165 print <<XML;
8166 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8167 <channel>
8169 print "<title>$title</title>\n" .
8170 "<link>$alt_url</link>\n" .
8171 "<description>$descr</description>\n" .
8172 "<language>en</language>\n" .
8173 # project owner is responsible for 'editorial' content
8174 "<managingEditor>$owner</managingEditor>\n";
8175 if (defined $logo || defined $favicon) {
8176 # prefer the logo to the favicon, since RSS
8177 # doesn't allow both
8178 my $img = esc_url($logo || $favicon);
8179 print "<image>\n" .
8180 "<url>$img</url>\n" .
8181 "<title>$title</title>\n" .
8182 "<link>$alt_url</link>\n" .
8183 "</image>\n";
8185 if (%latest_date) {
8186 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8187 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8189 print "<generator>gitweb v.$version/$git_version</generator>\n";
8190 } elsif ($format eq 'atom') {
8191 print <<XML;
8192 <feed xmlns="http://www.w3.org/2005/Atom">
8194 print "<title>$title</title>\n" .
8195 "<subtitle>$descr</subtitle>\n" .
8196 '<link rel="alternate" type="text/html" href="' .
8197 $alt_url . '" />' . "\n" .
8198 '<link rel="self" type="' . $content_type . '" href="' .
8199 $cgi->self_url() . '" />' . "\n" .
8200 "<id>" . href(-full=>1) . "</id>\n" .
8201 # use project owner for feed author
8202 "<author><name>$owner</name></author>\n";
8203 if (defined $favicon) {
8204 print "<icon>" . esc_url($favicon) . "</icon>\n";
8206 if (defined $logo) {
8207 # not twice as wide as tall: 72 x 27 pixels
8208 print "<logo>" . esc_url($logo) . "</logo>\n";
8210 if (! %latest_date) {
8211 # dummy date to keep the feed valid until commits trickle in:
8212 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8213 } else {
8214 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8216 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8219 # contents
8220 for (my $i = 0; $i <= $#commitlist; $i++) {
8221 my %co = %{$commitlist[$i]};
8222 my $commit = $co{'id'};
8223 # we read 150, we always show 30 and the ones more recent than 48 hours
8224 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8225 last;
8227 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8229 # get list of changed files
8230 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8231 $co{'parent'} || "--root",
8232 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8233 or next;
8234 my @difftree = map { chomp; $_ } <$fd>;
8235 close $fd
8236 or next;
8238 # print element (entry, item)
8239 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8240 if ($format eq 'rss') {
8241 print "<item>\n" .
8242 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8243 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8244 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8245 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8246 "<link>$co_url</link>\n" .
8247 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8248 "<content:encoded>" .
8249 "<![CDATA[\n";
8250 } elsif ($format eq 'atom') {
8251 print "<entry>\n" .
8252 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8253 "<updated>$cd{'iso-8601'}</updated>\n" .
8254 "<author>\n" .
8255 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8256 if ($co{'author_email'}) {
8257 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8259 print "</author>\n" .
8260 # use committer for contributor
8261 "<contributor>\n" .
8262 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8263 if ($co{'committer_email'}) {
8264 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8266 print "</contributor>\n" .
8267 "<published>$cd{'iso-8601'}</published>\n" .
8268 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8269 "<id>$co_url</id>\n" .
8270 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8271 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8273 my $comment = $co{'comment'};
8274 print "<pre>\n";
8275 foreach my $line (@$comment) {
8276 $line = esc_html($line);
8277 print "$line\n";
8279 print "</pre><ul>\n";
8280 foreach my $difftree_line (@difftree) {
8281 my %difftree = parse_difftree_raw_line($difftree_line);
8282 next if !$difftree{'from_id'};
8284 my $file = $difftree{'file'} || $difftree{'to_file'};
8286 print "<li>" .
8287 "[" .
8288 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8289 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8290 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8291 file_name=>$file, file_parent=>$difftree{'from_file'}),
8292 -title => "diff"}, 'D');
8293 if ($have_blame) {
8294 print $cgi->a({-href => href(-full=>1, action=>"blame",
8295 file_name=>$file, hash_base=>$commit),
8296 -title => "blame"}, 'B');
8298 # if this is not a feed of a file history
8299 if (!defined $file_name || $file_name ne $file) {
8300 print $cgi->a({-href => href(-full=>1, action=>"history",
8301 file_name=>$file, hash=>$commit),
8302 -title => "history"}, 'H');
8304 $file = esc_path($file);
8305 print "] ".
8306 "$file</li>\n";
8308 if ($format eq 'rss') {
8309 print "</ul>]]>\n" .
8310 "</content:encoded>\n" .
8311 "</item>\n";
8312 } elsif ($format eq 'atom') {
8313 print "</ul>\n</div>\n" .
8314 "</content>\n" .
8315 "</entry>\n";
8319 # end of feed
8320 if ($format eq 'rss') {
8321 print "</channel>\n</rss>\n";
8322 } elsif ($format eq 'atom') {
8323 print "</feed>\n";
8327 sub git_rss {
8328 git_feed('rss');
8331 sub git_atom {
8332 git_feed('atom');
8335 sub git_opml {
8336 my @list = git_get_projects_list($project_filter, $strict_export);
8337 if (!@list) {
8338 die_error(404, "No projects found");
8341 print $cgi->header(
8342 -type => 'text/xml',
8343 -charset => 'utf-8',
8344 -content_disposition => 'inline; filename="opml.xml"');
8346 my $title = esc_html($site_name);
8347 my $filter = " within subdirectory ";
8348 if (defined $project_filter) {
8349 $filter .= esc_html($project_filter);
8350 } else {
8351 $filter = "";
8353 print <<XML;
8354 <?xml version="1.0" encoding="utf-8"?>
8355 <opml version="1.0">
8356 <head>
8357 <title>$title OPML Export$filter</title>
8358 </head>
8359 <body>
8360 <outline text="git RSS feeds">
8363 foreach my $pr (@list) {
8364 my %proj = %$pr;
8365 my $head = git_get_head_hash($proj{'path'});
8366 if (!defined $head) {
8367 next;
8369 $git_dir = "$projectroot/$proj{'path'}";
8370 my %co = parse_commit($head);
8371 if (!%co) {
8372 next;
8375 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8376 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8377 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8378 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8380 print <<XML;
8381 </outline>
8382 </body>
8383 </opml>