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
13 use CGI
qw(:standard :escapeHTML -nosticky);
14 use CGI
::Util
qw(unescape);
15 use CGI
::Carp
qw(fatalsToBrowser set_message);
19 use File
::Basename
qw(basename);
20 use Time
::HiRes
qw(gettimeofday tv_interval);
21 binmode STDOUT
, ':utf8';
23 if (!defined($CGI::VERSION
) || $CGI::VERSION
< 4.08) {
24 eval 'sub CGI::multi_param { CGI::param(@_) }'
27 our $t0 = [ gettimeofday
() ];
28 our $number_of_git_cmds = 0;
31 CGI
->compile() if $ENV{'MOD_PERL'};
34 our $version = "2.8.1";
36 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
40 our $my_url = $cgi->url();
41 our $my_uri = $cgi->url(-absolute
=> 1);
43 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
44 # needed and used only for URLs with nonempty PATH_INFO
45 our $base_url = $my_url;
47 # When the script is used as DirectoryIndex, the URL does not contain the name
48 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
49 # have to do it ourselves. We make $path_info global because it's also used
52 # Another issue with the script being the DirectoryIndex is that the resulting
53 # $my_url data is not the full script URL: this is good, because we want
54 # generated links to keep implying the script name if it wasn't explicitly
55 # indicated in the URL we're handling, but it means that $my_url cannot be used
57 # Therefore, if we needed to strip PATH_INFO, then we know that we have
58 # to build the base URL ourselves:
59 our $path_info = decode_utf8
($ENV{"PATH_INFO"});
61 # $path_info has already been URL-decoded by the web server, but
62 # $my_url and $my_uri have not. URL-decode them so we can properly
64 $my_url = unescape
($my_url);
65 $my_uri = unescape
($my_uri);
66 if ($my_url =~ s
,\Q
$path_info\E
$,, &&
67 $my_uri =~ s
,\Q
$path_info\E
$,, &&
68 defined $ENV{'SCRIPT_NAME'}) {
69 $base_url = $cgi->url(-base
=> 1) . $ENV{'SCRIPT_NAME'};
73 # target of the home link on top of all pages
74 our $home_link = $my_uri || "/";
77 # core git executable to use
78 # this can just be "git" if your webserver has a sensible PATH
79 our $GIT = "/usr/bin/git";
81 # absolute fs-path which will be prepended to the project path
82 #our $projectroot = "/pub/scm";
83 our $projectroot = "/pub/git";
85 # fs traversing limit for getting project list
86 # the number is relative to the projectroot
87 our $project_maxdepth = 2007;
89 # string of the home link on top of all pages
90 our $home_link_str = "projects";
92 # extra breadcrumbs preceding the home link
93 our @extra_breadcrumbs = ();
95 # name of your site or organization to appear in page titles
96 # replace this with something more descriptive for clearer bookmarks
98 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
100 # html snippet to include in the <head> section of each page
101 our $site_html_head_string = "";
102 # filename of html text to include at top of each page
103 our $site_header = "";
104 # html text to include at home page
105 our $home_text = "indextext.html";
106 # filename of html text to include at bottom of each page
107 our $site_footer = "";
110 our @stylesheets = ("static/gitweb.css");
111 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
112 our $stylesheet = undef;
113 # URI of GIT logo (72x27 size)
114 our $logo = "static/git-logo.png";
115 # URI of GIT favicon, assumed to be image/png type
116 our $favicon = "static/git-favicon.png";
117 # URI of gitweb.js (JavaScript code for gitweb)
118 our $javascript = "static/gitweb.js";
120 # URI and label (title) of GIT logo link
121 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
122 #our $logo_label = "git documentation";
123 our $logo_url = "http://git-scm.com/";
124 our $logo_label = "git homepage";
126 # source of projects list
127 our $projects_list = "";
129 # the width (in characters) of the projects list "Description" column
130 our $projects_list_description_width = 25;
132 # group projects by category on the projects list
133 # (enabled if this variable evaluates to true)
134 our $projects_list_group_categories = 0;
136 # default category if none specified
137 # (leave the empty string for no category)
138 our $project_list_default_category = "";
140 # default order of projects list
141 # valid values are none, project, descr, owner, and age
142 our $default_projects_order = "project";
144 # show repository only if this file exists
145 # (only effective if this variable evaluates to true)
148 # don't generate age column on the projects list page
149 our $omit_age_column = 0;
151 # don't generate information about owners of repositories
154 # show repository only if this subroutine returns true
155 # when given the path to the project, for example:
156 # sub { return -e "$_[0]/git-daemon-export-ok"; }
157 our $export_auth_hook = undef;
159 # only allow viewing of repositories also shown on the overview page
160 our $strict_export = "";
162 # list of git base URLs used for URL to where fetch project from,
163 # i.e. full URL is "$git_base_url/$project"
164 our @git_base_url_list = grep { $_ ne '' } ("");
166 # default blob_plain mimetype and default charset for text/plain blob
167 our $default_blob_plain_mimetype = 'text/plain';
168 our $default_text_plain_charset = undef;
170 # file to use for guessing MIME types before trying /etc/mime.types
171 # (relative to the current git repository)
172 our $mimetypes_file = undef;
174 # assume this charset if line contains non-UTF-8 characters;
175 # it should be valid encoding (see Encoding::Supported(3pm) for list),
176 # for which encoding all byte sequences are valid, for example
177 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
178 # could be even 'utf-8' for the old behavior)
179 our $fallback_encoding = 'latin1';
181 # rename detection options for git-diff and git-diff-tree
182 # - default is '-M', with the cost proportional to
183 # (number of removed files) * (number of new files).
184 # - more costly is '-C' (which implies '-M'), with the cost proportional to
185 # (number of changed files + number of removed files) * (number of new files)
186 # - even more costly is '-C', '--find-copies-harder' with cost
187 # (number of files in the original tree) * (number of new files)
188 # - one might want to include '-B' option, e.g. '-B', '-M'
189 our @diff_opts = ('-M'); # taken from git_commit
191 # Disables features that would allow repository owners to inject script into
193 our $prevent_xss = 0;
195 # Path to the highlight executable to use (must be the one from
196 # http://www.andre-simon.de due to assumptions about parameters and output).
197 # Useful if highlight is not installed on your webserver's PATH.
198 # [Default: highlight]
199 our $highlight_bin = "highlight";
201 our $highlight_force = 0;
203 # information about snapshot formats that gitweb is capable of serving
204 our %known_snapshot_formats = (
206 # 'display' => display name,
207 # 'type' => mime type,
208 # 'suffix' => filename suffix,
209 # 'format' => --format for git-archive,
210 # 'compressor' => [compressor command and arguments]
211 # (array reference, optional)
212 # 'disabled' => boolean (optional)}
215 'display' => 'tar.gz',
216 'type' => 'application/x-gzip',
217 'suffix' => '.tar.gz',
219 'compressor' => ['gzip', '-n']},
222 'display' => 'tar.bz2',
223 'type' => 'application/x-bzip2',
224 'suffix' => '.tar.bz2',
226 'compressor' => ['bzip2']},
229 'display' => 'tar.xz',
230 'type' => 'application/x-xz',
231 'suffix' => '.tar.xz',
233 'compressor' => ['xz'],
238 'type' => 'application/x-zip',
243 # Aliases so we understand old gitweb.snapshot values in repository
245 our %known_snapshot_format_aliases = (
250 # backward compatibility: legacy gitweb config support
251 'x-gzip' => undef, 'gz' => undef,
252 'x-bzip2' => undef, 'bz2' => undef,
253 'x-zip' => undef, '' => undef,
256 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
257 # are changed, it may be appropriate to change these values too via
264 # Used to set the maximum load that we will still respond to gitweb queries.
265 # If server load exceed this value then return "503 server busy" error.
266 # If gitweb cannot determined server load, it is taken to be 0.
267 # Leave it undefined (or set to 'undef') to turn off load checking.
270 # configuration for 'highlight' (http://www.andre-simon.de/)
272 our %highlight_basename = (
275 'SConstruct' => 'py', # SCons equivalent of Makefile
276 'Makefile' => 'make',
279 our %highlight_ext = (
280 # main extensions, defining name of syntax;
281 # see files in /usr/share/highlight/langDefs/ directory
282 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
283 # alternate extensions, see /etc/highlight/filetypes.conf
284 (map { $_ => 'c' } qw(c h)),
285 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
286 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
287 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
288 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
289 (map { $_ => 'make'} qw(make mak mk)),
290 (map { $_ => 'xml' } qw(xml xhtml html htm)),
293 # You define site-wide feature defaults here; override them with
294 # $GITWEB_CONFIG as necessary.
297 # 'sub' => feature-sub (subroutine),
298 # 'override' => allow-override (boolean),
299 # 'default' => [ default options...] (array reference)}
301 # if feature is overridable (it means that allow-override has true value),
302 # then feature-sub will be called with default options as parameters;
303 # return value of feature-sub indicates if to enable specified feature
305 # if there is no 'sub' key (no feature-sub), then feature cannot be
308 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
309 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
312 # Enable the 'blame' blob view, showing the last commit that modified
313 # each line in the file. This can be very CPU-intensive.
315 # To enable system wide have in $GITWEB_CONFIG
316 # $feature{'blame'}{'default'} = [1];
317 # To have project specific config enable override in $GITWEB_CONFIG
318 # $feature{'blame'}{'override'} = 1;
319 # and in project config gitweb.blame = 0|1;
321 'sub' => sub { feature_bool
('blame', @_) },
325 # Enable the 'snapshot' link, providing a compressed archive of any
326 # tree. This can potentially generate high traffic if you have large
329 # Value is a list of formats defined in %known_snapshot_formats that
331 # To disable system wide have in $GITWEB_CONFIG
332 # $feature{'snapshot'}{'default'} = [];
333 # To have project specific config enable override in $GITWEB_CONFIG
334 # $feature{'snapshot'}{'override'} = 1;
335 # and in project config, a comma-separated list of formats or "none"
336 # to disable. Example: gitweb.snapshot = tbz2,zip;
338 'sub' => \
&feature_snapshot
,
340 'default' => ['tgz']},
342 # Enable text search, which will list the commits which match author,
343 # committer or commit text to a given string. Enabled by default.
344 # Project specific override is not supported.
346 # Note that this controls all search features, which means that if
347 # it is disabled, then 'grep' and 'pickaxe' search would also be
353 # Enable grep search, which will list the files in currently selected
354 # tree containing the given string. Enabled by default. This can be
355 # potentially CPU-intensive, of course.
356 # Note that you need to have 'search' feature enabled too.
358 # To enable system wide have in $GITWEB_CONFIG
359 # $feature{'grep'}{'default'} = [1];
360 # To have project specific config enable override in $GITWEB_CONFIG
361 # $feature{'grep'}{'override'} = 1;
362 # and in project config gitweb.grep = 0|1;
364 'sub' => sub { feature_bool
('grep', @_) },
368 # Enable the pickaxe search, which will list the commits that modified
369 # a given string in a file. This can be practical and quite faster
370 # alternative to 'blame', but still potentially CPU-intensive.
371 # Note that you need to have 'search' feature enabled too.
373 # To enable system wide have in $GITWEB_CONFIG
374 # $feature{'pickaxe'}{'default'} = [1];
375 # To have project specific config enable override in $GITWEB_CONFIG
376 # $feature{'pickaxe'}{'override'} = 1;
377 # and in project config gitweb.pickaxe = 0|1;
379 'sub' => sub { feature_bool
('pickaxe', @_) },
383 # Enable showing size of blobs in a 'tree' view, in a separate
384 # column, similar to what 'ls -l' does. This cost a bit of IO.
386 # To disable system wide have in $GITWEB_CONFIG
387 # $feature{'show-sizes'}{'default'} = [0];
388 # To have project specific config enable override in $GITWEB_CONFIG
389 # $feature{'show-sizes'}{'override'} = 1;
390 # and in project config gitweb.showsizes = 0|1;
392 'sub' => sub { feature_bool
('showsizes', @_) },
396 # Make gitweb use an alternative format of the URLs which can be
397 # more readable and natural-looking: project name is embedded
398 # directly in the path and the query string contains other
399 # auxiliary information. All gitweb installations recognize
400 # URL in either format; this configures in which formats gitweb
403 # To enable system wide have in $GITWEB_CONFIG
404 # $feature{'pathinfo'}{'default'} = [1];
405 # Project specific override is not supported.
407 # Note that you will need to change the default location of CSS,
408 # favicon, logo and possibly other files to an absolute URL. Also,
409 # if gitweb.cgi serves as your indexfile, you will need to force
410 # $my_uri to contain the script name in your $GITWEB_CONFIG.
415 # Make gitweb consider projects in project root subdirectories
416 # to be forks of existing projects. Given project $projname.git,
417 # projects matching $projname/*.git will not be shown in the main
418 # projects list, instead a '+' mark will be added to $projname
419 # there and a 'forks' view will be enabled for the project, listing
420 # all the forks. If project list is taken from a file, forks have
421 # to be listed after the main project.
423 # To enable system wide have in $GITWEB_CONFIG
424 # $feature{'forks'}{'default'} = [1];
425 # Project specific override is not supported.
430 # Insert custom links to the action bar of all project pages.
431 # This enables you mainly to link to third-party scripts integrating
432 # into gitweb; e.g. git-browser for graphical history representation
433 # or custom web-based repository administration interface.
435 # The 'default' value consists of a list of triplets in the form
436 # (label, link, position) where position is the label after which
437 # to insert the link and link is a format string where %n expands
438 # to the project name, %f to the project path within the filesystem,
439 # %h to the current hash (h gitweb parameter) and %b to the current
440 # hash base (hb gitweb parameter); %% expands to %.
442 # To enable system wide have in $GITWEB_CONFIG e.g.
443 # $feature{'actions'}{'default'} = [('graphiclog',
444 # '/git-browser/by-commit.html?r=%n', 'summary')];
445 # Project specific override is not supported.
450 # Allow gitweb scan project content tags of project repository,
451 # and display the popular Web 2.0-ish "tag cloud" near the projects
452 # list. Note that this is something COMPLETELY different from the
455 # gitweb by itself can show existing tags, but it does not handle
456 # tagging itself; you need to do it externally, outside gitweb.
457 # The format is described in git_get_project_ctags() subroutine.
458 # You may want to install the HTML::TagCloud Perl module to get
459 # a pretty tag cloud instead of just a list of tags.
461 # To enable system wide have in $GITWEB_CONFIG
462 # $feature{'ctags'}{'default'} = [1];
463 # Project specific override is not supported.
465 # In the future whether ctags editing is enabled might depend
466 # on the value, but using 1 should always mean no editing of ctags.
471 # The maximum number of patches in a patchset generated in patch
472 # view. Set this to 0 or undef to disable patch view, or to a
473 # negative number to remove any limit.
475 # To disable system wide have in $GITWEB_CONFIG
476 # $feature{'patches'}{'default'} = [0];
477 # To have project specific config enable override in $GITWEB_CONFIG
478 # $feature{'patches'}{'override'} = 1;
479 # and in project config gitweb.patches = 0|n;
480 # where n is the maximum number of patches allowed in a patchset.
482 'sub' => \
&feature_patches
,
486 # Avatar support. When this feature is enabled, views such as
487 # shortlog or commit will display an avatar associated with
488 # the email of the committer(s) and/or author(s).
490 # Currently available providers are gravatar and picon.
491 # If an unknown provider is specified, the feature is disabled.
493 # Gravatar depends on Digest::MD5.
494 # Picon currently relies on the indiana.edu database.
496 # To enable system wide have in $GITWEB_CONFIG
497 # $feature{'avatar'}{'default'} = ['<provider>'];
498 # where <provider> is either gravatar or picon.
499 # To have project specific config enable override in $GITWEB_CONFIG
500 # $feature{'avatar'}{'override'} = 1;
501 # and in project config gitweb.avatar = <provider>;
503 'sub' => \
&feature_avatar
,
507 # Enable displaying how much time and how many git commands
508 # it took to generate and display page. Disabled by default.
509 # Project specific override is not supported.
514 # Enable turning some links into links to actions which require
515 # JavaScript to run (like 'blame_incremental'). Not enabled by
516 # default. Project specific override is currently not supported.
517 'javascript-actions' => {
521 # Enable and configure ability to change common timezone for dates
522 # in gitweb output via JavaScript. Enabled by default.
523 # Project specific override is not supported.
524 'javascript-timezone' => {
527 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
528 # or undef to turn off this feature
529 'gitweb_tz', # name of cookie where to store selected timezone
530 'datetime', # CSS class used to mark up dates for manipulation
533 # Syntax highlighting support. This is based on Daniel Svensson's
534 # and Sham Chukoury's work in gitweb-xmms2.git.
535 # It requires the 'highlight' program present in $PATH,
536 # and therefore is disabled by default.
538 # To enable system wide have in $GITWEB_CONFIG
539 # $feature{'highlight'}{'default'} = [1];
542 'sub' => sub { feature_bool
('highlight', @_) },
546 # Enable displaying of remote heads in the heads list
548 # To enable system wide have in $GITWEB_CONFIG
549 # $feature{'remote_heads'}{'default'} = [1];
550 # To have project specific config enable override in $GITWEB_CONFIG
551 # $feature{'remote_heads'}{'override'} = 1;
552 # and in project config gitweb.remoteheads = 0|1;
554 'sub' => sub { feature_bool
('remote_heads', @_) },
558 # Enable showing branches under other refs in addition to heads
560 # To set system wide extra branch refs have in $GITWEB_CONFIG
561 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
562 # To have project specific config enable override in $GITWEB_CONFIG
563 # $feature{'extra-branch-refs'}{'override'} = 1;
564 # and in project config gitweb.extrabranchrefs = dirs of choice
565 # Every directory is separated with whitespace.
567 'extra-branch-refs' => {
568 'sub' => \
&feature_extra_branch_refs
,
573 sub gitweb_get_feature
{
575 return unless exists $feature{$name};
576 my ($sub, $override, @defaults) = (
577 $feature{$name}{'sub'},
578 $feature{$name}{'override'},
579 @
{$feature{$name}{'default'}});
580 # project specific override is possible only if we have project
581 our $git_dir; # global variable, declared later
582 if (!$override || !defined $git_dir) {
586 warn "feature $name is not overridable";
589 return $sub->(@defaults);
592 # A wrapper to check if a given feature is enabled.
593 # With this, you can say
595 # my $bool_feat = gitweb_check_feature('bool_feat');
596 # gitweb_check_feature('bool_feat') or somecode;
600 # my ($bool_feat) = gitweb_get_feature('bool_feat');
601 # (gitweb_get_feature('bool_feat'))[0] or somecode;
603 sub gitweb_check_feature
{
604 return (gitweb_get_feature
(@_))[0];
610 my ($val) = git_get_project_config
($key, '--bool');
614 } elsif ($val eq 'true') {
616 } elsif ($val eq 'false') {
621 sub feature_snapshot
{
624 my ($val) = git_get_project_config
('snapshot');
627 @fmts = ($val eq 'none' ?
() : split /\s*[,\s]\s*/, $val);
633 sub feature_patches
{
634 my @val = (git_get_project_config
('patches', '--int'));
644 my @val = (git_get_project_config
('avatar'));
646 return @val ?
@val : @_;
649 sub feature_extra_branch_refs
{
650 my (@branch_refs) = @_;
651 my $values = git_get_project_config
('extrabranchrefs');
654 $values = config_to_multi
($values);
656 foreach my $value (@
{$values}) {
657 push @branch_refs, split /\s+/, $value;
664 # checking HEAD file with -e is fragile if the repository was
665 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
667 sub check_head_link
{
669 my $headfile = "$dir/HEAD";
670 return ((-e
$headfile) ||
671 (-l
$headfile && readlink($headfile) =~ /^refs\/heads\
//));
674 sub check_export_ok
{
676 return (check_head_link
($dir) &&
677 (!$export_ok || -e
"$dir/$export_ok") &&
678 (!$export_auth_hook || $export_auth_hook->($dir)));
681 # process alternate names for backward compatibility
682 # filter out unsupported (unknown) snapshot formats
683 sub filter_snapshot_fmts
{
687 exists $known_snapshot_format_aliases{$_} ?
688 $known_snapshot_format_aliases{$_} : $_} @fmts;
690 exists $known_snapshot_formats{$_} &&
691 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
694 sub filter_and_validate_refs
{
696 my %unique_refs = ();
698 foreach my $ref (@refs) {
699 die_error
(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format
($ref));
700 # 'heads' are added implicitly in get_branch_refs().
701 $unique_refs{$ref} = 1 if ($ref ne 'heads');
703 return sort keys %unique_refs;
706 # If it is set to code reference, it is code that it is to be run once per
707 # request, allowing updating configurations that change with each request,
708 # while running other code in config file only once.
710 # Otherwise, if it is false then gitweb would process config file only once;
711 # if it is true then gitweb config would be run for each request.
712 our $per_request_config = 1;
714 # read and parse gitweb config file given by its parameter.
715 # returns true on success, false on recoverable error, allowing
716 # to chain this subroutine, using first file that exists.
717 # dies on errors during parsing config file, as it is unrecoverable.
718 sub read_config_file
{
719 my $filename = shift;
720 return unless defined $filename;
721 # die if there are errors parsing config file
730 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
731 sub evaluate_gitweb_config
{
732 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "gitweb_config.perl";
733 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "/etc/gitweb.conf";
734 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "/etc/gitweb-common.conf";
736 # Protect against duplications of file names, to not read config twice.
737 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
738 # there possibility of duplication of filename there doesn't matter.
739 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
740 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
742 # Common system-wide settings for convenience.
743 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
744 read_config_file
($GITWEB_CONFIG_COMMON);
746 # Use first config file that exists. This means use the per-instance
747 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
748 read_config_file
($GITWEB_CONFIG) and return;
749 read_config_file
($GITWEB_CONFIG_SYSTEM);
752 # Get loadavg of system, to compare against $maxload.
753 # Currently it requires '/proc/loadavg' present to get loadavg;
754 # if it is not present it returns 0, which means no load checking.
756 if( -e
'/proc/loadavg' ){
757 open my $fd, '<', '/proc/loadavg'
759 my @load = split(/\s+/, scalar <$fd>);
762 # The first three columns measure CPU and IO utilization of the last one,
763 # five, and 10 minute periods. The fourth column shows the number of
764 # currently running processes and the total number of processes in the m/n
765 # format. The last column displays the last process ID used.
766 return $load[0] || 0;
768 # additional checks for load average should go here for things that don't export
774 # version of the core git binary
776 sub evaluate_git_version
{
777 our $git_version = qx("$GIT" --version
) =~ m/git version (.*)$/ ?
$1 : "unknown";
778 $number_of_git_cmds++;
782 if (defined $maxload && get_loadavg
() > $maxload) {
783 die_error
(503, "The load average on the server is too high");
787 # ======================================================================
788 # input validation and dispatch
790 # input parameters can be collected from a variety of sources (presently, CGI
791 # and PATH_INFO), so we define an %input_params hash that collects them all
792 # together during validation: this allows subsequent uses (e.g. href()) to be
793 # agnostic of the parameter origin
795 our %input_params = ();
797 # input parameters are stored with the long parameter name as key. This will
798 # also be used in the href subroutine to convert parameters to their CGI
799 # equivalent, and since the href() usage is the most frequent one, we store
800 # the name -> CGI key mapping here, instead of the reverse.
802 # XXX: Warning: If you touch this, check the search form for updating,
805 our @cgi_param_mapping = (
813 hash_parent_base
=> "hpb",
818 snapshot_format
=> "sf",
819 extra_options
=> "opt",
820 search_use_regexp
=> "sr",
823 project_filter
=> "pf",
824 # this must be last entry (for manipulation from JavaScript)
827 our %cgi_param_mapping = @cgi_param_mapping;
829 # we will also need to know the possible actions, for validation
831 "blame" => \
&git_blame
,
832 "blame_incremental" => \
&git_blame_incremental
,
833 "blame_data" => \
&git_blame_data
,
834 "blobdiff" => \
&git_blobdiff
,
835 "blobdiff_plain" => \
&git_blobdiff_plain
,
836 "blob" => \
&git_blob
,
837 "blob_plain" => \
&git_blob_plain
,
838 "commitdiff" => \
&git_commitdiff
,
839 "commitdiff_plain" => \
&git_commitdiff_plain
,
840 "commit" => \
&git_commit
,
841 "forks" => \
&git_forks
,
842 "heads" => \
&git_heads
,
843 "history" => \
&git_history
,
845 "patch" => \
&git_patch
,
846 "patches" => \
&git_patches
,
847 "remotes" => \
&git_remotes
,
849 "atom" => \
&git_atom
,
850 "search" => \
&git_search
,
851 "search_help" => \
&git_search_help
,
852 "shortlog" => \
&git_shortlog
,
853 "summary" => \
&git_summary
,
855 "tags" => \
&git_tags
,
856 "tree" => \
&git_tree
,
857 "snapshot" => \
&git_snapshot
,
858 "object" => \
&git_object
,
859 # those below don't need $project
860 "opml" => \
&git_opml
,
861 "project_list" => \
&git_project_list
,
862 "project_index" => \
&git_project_index
,
865 # finally, we have the hash of allowed extra_options for the commands that
867 our %allowed_options = (
868 "--no-merges" => [ qw(rss atom log shortlog history) ],
871 # fill %input_params with the CGI parameters. All values except for 'opt'
872 # should be single values, but opt can be an array. We should probably
873 # build an array of parameters that can be multi-valued, but since for the time
874 # being it's only this one, we just single it out
875 sub evaluate_query_params
{
878 while (my ($name, $symbol) = each %cgi_param_mapping) {
879 if ($symbol eq 'opt') {
880 $input_params{$name} = [ map { decode_utf8
($_) } $cgi->multi_param($symbol) ];
882 $input_params{$name} = decode_utf8
($cgi->param($symbol));
887 # now read PATH_INFO and update the parameter list for missing parameters
888 sub evaluate_path_info
{
889 return if defined $input_params{'project'};
890 return if !$path_info;
891 $path_info =~ s
,^/+,,;
892 return if !$path_info;
894 # find which part of PATH_INFO is project
895 my $project = $path_info;
897 while ($project && !check_head_link
("$projectroot/$project")) {
898 $project =~ s
,/*[^/]*$,,;
900 return unless $project;
901 $input_params{'project'} = $project;
903 # do not change any parameters if an action is given using the query string
904 return if $input_params{'action'};
905 $path_info =~ s
,^\Q
$project\E
/*,,;
907 # next, check if we have an action
908 my $action = $path_info;
910 if (exists $actions{$action}) {
911 $path_info =~ s
,^$action/*,,;
912 $input_params{'action'} = $action;
915 # list of actions that want hash_base instead of hash, but can have no
916 # pathname (f) parameter
922 # we want to catch, among others
923 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
924 my ($parentrefname, $parentpathname, $refname, $pathname) =
925 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
927 # first, analyze the 'current' part
928 if (defined $pathname) {
929 # we got "branch:filename" or "branch:dir/"
930 # we could use git_get_type(branch:pathname), but:
931 # - it needs $git_dir
932 # - it does a git() call
933 # - the convention of terminating directories with a slash
934 # makes it superfluous
935 # - embedding the action in the PATH_INFO would make it even
937 $pathname =~ s
,^/+,,;
938 if (!$pathname || substr($pathname, -1) eq "/") {
939 $input_params{'action'} ||= "tree";
942 # the default action depends on whether we had parent info
944 if ($parentrefname) {
945 $input_params{'action'} ||= "blobdiff_plain";
947 $input_params{'action'} ||= "blob_plain";
950 $input_params{'hash_base'} ||= $refname;
951 $input_params{'file_name'} ||= $pathname;
952 } elsif (defined $refname) {
953 # we got "branch". In this case we have to choose if we have to
954 # set hash or hash_base.
956 # Most of the actions without a pathname only want hash to be
957 # set, except for the ones specified in @wants_base that want
958 # hash_base instead. It should also be noted that hand-crafted
959 # links having 'history' as an action and no pathname or hash
960 # set will fail, but that happens regardless of PATH_INFO.
961 if (defined $parentrefname) {
962 # if there is parent let the default be 'shortlog' action
963 # (for http://git.example.com/repo.git/A..B links); if there
964 # is no parent, dispatch will detect type of object and set
965 # action appropriately if required (if action is not set)
966 $input_params{'action'} ||= "shortlog";
968 if ($input_params{'action'} &&
969 grep { $_ eq $input_params{'action'} } @wants_base) {
970 $input_params{'hash_base'} ||= $refname;
972 $input_params{'hash'} ||= $refname;
976 # next, handle the 'parent' part, if present
977 if (defined $parentrefname) {
978 # a missing pathspec defaults to the 'current' filename, allowing e.g.
979 # someproject/blobdiff/oldrev..newrev:/filename
980 if ($parentpathname) {
981 $parentpathname =~ s
,^/+,,;
982 $parentpathname =~ s
,/$,,;
983 $input_params{'file_parent'} ||= $parentpathname;
985 $input_params{'file_parent'} ||= $input_params{'file_name'};
987 # we assume that hash_parent_base is wanted if a path was specified,
988 # or if the action wants hash_base instead of hash
989 if (defined $input_params{'file_parent'} ||
990 grep { $_ eq $input_params{'action'} } @wants_base) {
991 $input_params{'hash_parent_base'} ||= $parentrefname;
993 $input_params{'hash_parent'} ||= $parentrefname;
997 # for the snapshot action, we allow URLs in the form
998 # $project/snapshot/$hash.ext
999 # where .ext determines the snapshot and gets removed from the
1000 # passed $refname to provide the $hash.
1002 # To be able to tell that $refname includes the format extension, we
1003 # require the following two conditions to be satisfied:
1004 # - the hash input parameter MUST have been set from the $refname part
1005 # of the URL (i.e. they must be equal)
1006 # - the snapshot format MUST NOT have been defined already (e.g. from
1008 # It's also useless to try any matching unless $refname has a dot,
1009 # so we check for that too
1010 if (defined $input_params{'action'} &&
1011 $input_params{'action'} eq 'snapshot' &&
1012 defined $refname && index($refname, '.') != -1 &&
1013 $refname eq $input_params{'hash'} &&
1014 !defined $input_params{'snapshot_format'}) {
1015 # We loop over the known snapshot formats, checking for
1016 # extensions. Allowed extensions are both the defined suffix
1017 # (which includes the initial dot already) and the snapshot
1018 # format key itself, with a prepended dot
1019 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1020 my $hash = $refname;
1021 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1025 # a valid suffix was found, so set the snapshot format
1026 # and reset the hash parameter
1027 $input_params{'snapshot_format'} = $fmt;
1028 $input_params{'hash'} = $hash;
1029 # we also set the format suffix to the one requested
1030 # in the URL: this way a request for e.g. .tgz returns
1031 # a .tgz instead of a .tar.gz
1032 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1038 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1039 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1040 $searchtext, $search_regexp, $project_filter);
1041 sub evaluate_and_validate_params
{
1042 our $action = $input_params{'action'};
1043 if (defined $action) {
1044 if (!is_valid_action
($action)) {
1045 die_error
(400, "Invalid action parameter");
1049 # parameters which are pathnames
1050 our $project = $input_params{'project'};
1051 if (defined $project) {
1052 if (!is_valid_project
($project)) {
1054 die_error
(404, "No such project");
1058 our $project_filter = $input_params{'project_filter'};
1059 if (defined $project_filter) {
1060 if (!is_valid_pathname
($project_filter)) {
1061 die_error
(404, "Invalid project_filter parameter");
1065 our $file_name = $input_params{'file_name'};
1066 if (defined $file_name) {
1067 if (!is_valid_pathname
($file_name)) {
1068 die_error
(400, "Invalid file parameter");
1072 our $file_parent = $input_params{'file_parent'};
1073 if (defined $file_parent) {
1074 if (!is_valid_pathname
($file_parent)) {
1075 die_error
(400, "Invalid file parent parameter");
1079 # parameters which are refnames
1080 our $hash = $input_params{'hash'};
1081 if (defined $hash) {
1082 if (!is_valid_refname
($hash)) {
1083 die_error
(400, "Invalid hash parameter");
1087 our $hash_parent = $input_params{'hash_parent'};
1088 if (defined $hash_parent) {
1089 if (!is_valid_refname
($hash_parent)) {
1090 die_error
(400, "Invalid hash parent parameter");
1094 our $hash_base = $input_params{'hash_base'};
1095 if (defined $hash_base) {
1096 if (!is_valid_refname
($hash_base)) {
1097 die_error
(400, "Invalid hash base parameter");
1101 our @extra_options = @
{$input_params{'extra_options'}};
1102 # @extra_options is always defined, since it can only be (currently) set from
1103 # CGI, and $cgi->param() returns the empty array in array context if the param
1105 foreach my $opt (@extra_options) {
1106 if (not exists $allowed_options{$opt}) {
1107 die_error
(400, "Invalid option parameter");
1109 if (not grep(/^$action$/, @
{$allowed_options{$opt}})) {
1110 die_error
(400, "Invalid option parameter for this action");
1114 our $hash_parent_base = $input_params{'hash_parent_base'};
1115 if (defined $hash_parent_base) {
1116 if (!is_valid_refname
($hash_parent_base)) {
1117 die_error
(400, "Invalid hash parent base parameter");
1122 our $page = $input_params{'page'};
1123 if (defined $page) {
1124 if ($page =~ m/[^0-9]/) {
1125 die_error
(400, "Invalid page parameter");
1129 our $searchtype = $input_params{'searchtype'};
1130 if (defined $searchtype) {
1131 if ($searchtype =~ m/[^a-z]/) {
1132 die_error
(400, "Invalid searchtype parameter");
1136 our $search_use_regexp = $input_params{'search_use_regexp'};
1138 our $searchtext = $input_params{'searchtext'};
1139 our $search_regexp = undef;
1140 if (defined $searchtext) {
1141 if (length($searchtext) < 2) {
1142 die_error
(403, "At least two characters are required for search parameter");
1144 if ($search_use_regexp) {
1145 $search_regexp = $searchtext;
1146 if (!eval { qr/$search_regexp/; 1; }) {
1147 (my $error = $@
) =~ s/ at \S+ line \d+.*\n?//;
1148 die_error
(400, "Invalid search regexp '$search_regexp'",
1152 $search_regexp = quotemeta $searchtext;
1157 # path to the current git repository
1159 sub evaluate_git_dir
{
1160 our $git_dir = "$projectroot/$project" if $project;
1163 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1164 sub configure_gitweb_features
{
1165 # list of supported snapshot formats
1166 our @snapshot_fmts = gitweb_get_feature
('snapshot');
1167 @snapshot_fmts = filter_snapshot_fmts
(@snapshot_fmts);
1169 # check that the avatar feature is set to a known provider name,
1170 # and for each provider check if the dependencies are satisfied.
1171 # if the provider name is invalid or the dependencies are not met,
1172 # reset $git_avatar to the empty string.
1173 our ($git_avatar) = gitweb_get_feature
('avatar');
1174 if ($git_avatar eq 'gravatar') {
1175 $git_avatar = '' unless (eval { require Digest
::MD5
; 1; });
1176 } elsif ($git_avatar eq 'picon') {
1182 our @extra_branch_refs = gitweb_get_feature
('extra-branch-refs');
1183 @extra_branch_refs = filter_and_validate_refs
(@extra_branch_refs);
1186 sub get_branch_refs
{
1187 return ('heads', @extra_branch_refs);
1190 # custom error handler: 'die <message>' is Internal Server Error
1191 sub handle_errors_html
{
1192 my $msg = shift; # it is already HTML escaped
1194 # to avoid infinite loop where error occurs in die_error,
1195 # change handler to default handler, disabling handle_errors_html
1196 set_message
("Error occurred when inside die_error:\n$msg");
1198 # you cannot jump out of die_error when called as error handler;
1199 # the subroutine set via CGI::Carp::set_message is called _after_
1200 # HTTP headers are already written, so it cannot write them itself
1201 die_error
(undef, undef, $msg, -error_handler
=> 1, -no_http_header
=> 1);
1203 set_message
(\
&handle_errors_html
);
1207 if (!defined $action) {
1208 if (defined $hash) {
1209 $action = git_get_type
($hash);
1210 $action or die_error
(404, "Object does not exist");
1211 } elsif (defined $hash_base && defined $file_name) {
1212 $action = git_get_type
("$hash_base:$file_name");
1213 $action or die_error
(404, "File or directory does not exist");
1214 } elsif (defined $project) {
1215 $action = 'summary';
1217 $action = 'project_list';
1220 if (!defined($actions{$action})) {
1221 die_error
(400, "Unknown action");
1223 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1225 die_error
(400, "Project needed");
1227 $actions{$action}->();
1231 our $t0 = [ gettimeofday
() ]
1233 our $number_of_git_cmds = 0;
1236 our $first_request = 1;
1241 if ($first_request) {
1242 evaluate_gitweb_config
();
1243 evaluate_git_version
();
1245 if ($per_request_config) {
1246 if (ref($per_request_config) eq 'CODE') {
1247 $per_request_config->();
1248 } elsif (!$first_request) {
1249 evaluate_gitweb_config
();
1254 # $projectroot and $projects_list might be set in gitweb config file
1255 $projects_list ||= $projectroot;
1257 evaluate_query_params
();
1258 evaluate_path_info
();
1259 evaluate_and_validate_params
();
1262 configure_gitweb_features
();
1267 our $is_last_request = sub { 1 };
1268 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1271 sub configure_as_fcgi
{
1273 our $CGI = 'CGI::Fast';
1275 my $request_number = 0;
1276 # let each child service 100 requests
1277 our $is_last_request = sub { ++$request_number > 100 };
1280 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__
;
1282 if $script_name =~ /\.fcgi$/;
1284 return unless (@ARGV);
1286 require Getopt
::Long
;
1287 Getopt
::Long
::GetOptions
(
1288 'fastcgi|fcgi|f' => \
&configure_as_fcgi
,
1289 'nproc|n=i' => sub {
1290 my ($arg, $val) = @_;
1291 return unless eval { require FCGI
::ProcManager
; 1; };
1292 my $proc_manager = FCGI
::ProcManager
->new({
1293 n_processes
=> $val,
1295 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1296 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1297 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1306 $pre_listen_hook->()
1307 if $pre_listen_hook;
1310 while ($cgi = $CGI->new()) {
1311 $pre_dispatch_hook->()
1312 if $pre_dispatch_hook;
1316 $post_dispatch_hook->()
1317 if $post_dispatch_hook;
1320 last REQUEST
if ($is_last_request->());
1329 if (defined caller) {
1330 # wrapped in a subroutine processing requests,
1331 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1334 # pure CGI script, serving single request
1338 ## ======================================================================
1341 # possible values of extra options
1342 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1343 # -replay => 1 - start from a current view (replay with modifications)
1344 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1345 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1348 # default is to use -absolute url() i.e. $my_uri
1349 my $href = $params{-full
} ?
$my_url : $my_uri;
1351 # implicit -replay, must be first of implicit params
1352 $params{-replay
} = 1 if (keys %params == 1 && $params{-anchor
});
1354 $params{'project'} = $project unless exists $params{'project'};
1356 if ($params{-replay
}) {
1357 while (my ($name, $symbol) = each %cgi_param_mapping) {
1358 if (!exists $params{$name}) {
1359 $params{$name} = $input_params{$name};
1364 my $use_pathinfo = gitweb_check_feature
('pathinfo');
1365 if (defined $params{'project'} &&
1366 (exists $params{-path_info
} ?
$params{-path_info
} : $use_pathinfo)) {
1367 # try to put as many parameters as possible in PATH_INFO:
1370 # - hash_parent or hash_parent_base:/file_parent
1371 # - hash or hash_base:/filename
1372 # - the snapshot_format as an appropriate suffix
1374 # When the script is the root DirectoryIndex for the domain,
1375 # $href here would be something like http://gitweb.example.com/
1376 # Thus, we strip any trailing / from $href, to spare us double
1377 # slashes in the final URL
1380 # Then add the project name, if present
1381 $href .= "/".esc_path_info
($params{'project'});
1382 delete $params{'project'};
1384 # since we destructively absorb parameters, we keep this
1385 # boolean that remembers if we're handling a snapshot
1386 my $is_snapshot = $params{'action'} eq 'snapshot';
1388 # Summary just uses the project path URL, any other action is
1390 if (defined $params{'action'}) {
1391 $href .= "/".esc_path_info
($params{'action'})
1392 unless $params{'action'} eq 'summary';
1393 delete $params{'action'};
1396 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1397 # stripping nonexistent or useless pieces
1398 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1399 || $params{'hash_parent'} || $params{'hash'});
1400 if (defined $params{'hash_base'}) {
1401 if (defined $params{'hash_parent_base'}) {
1402 $href .= esc_path_info
($params{'hash_parent_base'});
1403 # skip the file_parent if it's the same as the file_name
1404 if (defined $params{'file_parent'}) {
1405 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1406 delete $params{'file_parent'};
1407 } elsif ($params{'file_parent'} !~ /\.\./) {
1408 $href .= ":/".esc_path_info
($params{'file_parent'});
1409 delete $params{'file_parent'};
1413 delete $params{'hash_parent'};
1414 delete $params{'hash_parent_base'};
1415 } elsif (defined $params{'hash_parent'}) {
1416 $href .= esc_path_info
($params{'hash_parent'}). "..";
1417 delete $params{'hash_parent'};
1420 $href .= esc_path_info
($params{'hash_base'});
1421 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1422 $href .= ":/".esc_path_info
($params{'file_name'});
1423 delete $params{'file_name'};
1425 delete $params{'hash'};
1426 delete $params{'hash_base'};
1427 } elsif (defined $params{'hash'}) {
1428 $href .= esc_path_info
($params{'hash'});
1429 delete $params{'hash'};
1432 # If the action was a snapshot, we can absorb the
1433 # snapshot_format parameter too
1435 my $fmt = $params{'snapshot_format'};
1436 # snapshot_format should always be defined when href()
1437 # is called, but just in case some code forgets, we
1438 # fall back to the default
1439 $fmt ||= $snapshot_fmts[0];
1440 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1441 delete $params{'snapshot_format'};
1445 # now encode the parameters explicitly
1447 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1448 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1449 if (defined $params{$name}) {
1450 if (ref($params{$name}) eq "ARRAY") {
1451 foreach my $par (@
{$params{$name}}) {
1452 push @result, $symbol . "=" . esc_param
($par);
1455 push @result, $symbol . "=" . esc_param
($params{$name});
1459 $href .= "?" . join(';', @result) if scalar @result;
1461 # final transformation: trailing spaces must be escaped (URI-encoded)
1462 $href =~ s/(\s+)$/CGI::escape($1)/e;
1464 if ($params{-anchor
}) {
1465 $href .= "#".esc_param
($params{-anchor
});
1472 ## ======================================================================
1473 ## validation, quoting/unquoting and escaping
1475 sub is_valid_action
{
1477 return undef unless exists $actions{$input};
1481 sub is_valid_project
{
1484 return unless defined $input;
1485 if (!is_valid_pathname
($input) ||
1486 !(-d
"$projectroot/$input") ||
1487 !check_export_ok
("$projectroot/$input") ||
1488 ($strict_export && !project_in_list
($input))) {
1495 sub is_valid_pathname
{
1498 return undef unless defined $input;
1499 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1500 # at the beginning, at the end, and between slashes.
1501 # also this catches doubled slashes
1502 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1505 # no null characters
1506 if ($input =~ m!\0!) {
1512 sub is_valid_ref_format
{
1515 return undef unless defined $input;
1516 # restrictions on ref name according to git-check-ref-format
1517 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1523 sub is_valid_refname
{
1526 return undef unless defined $input;
1527 # textual hashes are O.K.
1528 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1531 # it must be correct pathname
1532 is_valid_pathname
($input) or return undef;
1533 # check git-check-ref-format restrictions
1534 is_valid_ref_format
($input) or return undef;
1538 # decode sequences of octets in utf8 into Perl's internal form,
1539 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1540 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1543 return undef unless defined $str;
1545 if (utf8
::is_utf8
($str) || utf8
::decode
($str)) {
1548 return decode
($fallback_encoding, $str, Encode
::FB_DEFAULT
);
1552 # quote unsafe chars, but keep the slash, even when it's not
1553 # correct, but quoted slashes look too horrible in bookmarks
1556 return undef unless defined $str;
1557 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI
::escape
($1)/eg
;
1562 # the quoting rules for path_info fragment are slightly different
1565 return undef unless defined $str;
1567 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1568 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI
::escape
($1)/eg
;
1573 # quote unsafe chars in whole URL, so some characters cannot be quoted
1576 return undef unless defined $str;
1577 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI
::escape
($1)/eg
;
1582 # quote unsafe characters in HTML attributes
1585 # for XHTML conformance escaping '"' to '"' is not enough
1586 return esc_html
(@_);
1589 # replace invalid utf8 character with SUBSTITUTION sequence
1594 return undef unless defined $str;
1596 $str = to_utf8
($str);
1597 $str = $cgi->escapeHTML($str);
1598 if ($opts{'-nbsp'}) {
1599 $str =~ s/ / /g;
1601 $str =~ s
|([[:cntrl
:]])|(($1 ne "\t") ? quot_cec
($1) : $1)|eg
;
1605 # quote control characters and escape filename to HTML
1610 return undef unless defined $str;
1612 $str = to_utf8
($str);
1613 $str = $cgi->escapeHTML($str);
1614 if ($opts{'-nbsp'}) {
1615 $str =~ s/ / /g;
1617 $str =~ s
|([[:cntrl
:]])|quot_cec
($1)|eg
;
1621 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1625 return undef unless defined $str;
1627 $str = to_utf8
($str);
1628 $str =~ s
|([[:cntrl
:]])|(index("\t\n\r", $1) != -1 ?
$1 : quot_cec
($1))|eg
;
1632 # Make control characters "printable", using character escape codes (CEC)
1636 my %es = ( # character escape codes, aka escape sequences
1637 "\t" => '\t', # tab (HT)
1638 "\n" => '\n', # line feed (LF)
1639 "\r" => '\r', # carrige return (CR)
1640 "\f" => '\f', # form feed (FF)
1641 "\b" => '\b', # backspace (BS)
1642 "\a" => '\a', # alarm (bell) (BEL)
1643 "\e" => '\e', # escape (ESC)
1644 "\013" => '\v', # vertical tab (VT)
1645 "\000" => '\0', # nul character (NUL)
1647 my $chr = ( (exists $es{$cntrl})
1649 : sprintf('\%2x', ord($cntrl)) );
1650 if ($opts{-nohtml
}) {
1653 return "<span class=\"cntrl\">$chr</span>";
1657 # Alternatively use unicode control pictures codepoints,
1658 # Unicode "printable representation" (PR)
1663 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1664 if ($opts{-nohtml
}) {
1667 return "<span class=\"cntrl\">$chr</span>";
1671 # git may return quoted and escaped filenames
1677 my %es = ( # character escape codes, aka escape sequences
1678 't' => "\t", # tab (HT, TAB)
1679 'n' => "\n", # newline (NL)
1680 'r' => "\r", # return (CR)
1681 'f' => "\f", # form feed (FF)
1682 'b' => "\b", # backspace (BS)
1683 'a' => "\a", # alarm (bell) (BEL)
1684 'e' => "\e", # escape (ESC)
1685 'v' => "\013", # vertical tab (VT)
1688 if ($seq =~ m/^[0-7]{1,3}$/) {
1689 # octal char sequence
1690 return chr(oct($seq));
1691 } elsif (exists $es{$seq}) {
1692 # C escape sequence, aka character escape code
1695 # quoted ordinary character
1699 if ($str =~ m/^"(.*)"$/) {
1702 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1707 # escape tabs (convert tabs to spaces)
1711 while ((my $pos = index($line, "\t")) != -1) {
1712 if (my $count = (8 - ($pos % 8))) {
1713 my $spaces = ' ' x
$count;
1714 $line =~ s/\t/$spaces/;
1721 sub project_in_list
{
1722 my $project = shift;
1723 my @list = git_get_projects_list
();
1724 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1727 ## ----------------------------------------------------------------------
1728 ## HTML aware string manipulation
1730 # Try to chop given string on a word boundary between position
1731 # $len and $len+$add_len. If there is no word boundary there,
1732 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1733 # (marking chopped part) would be longer than given string.
1737 my $add_len = shift || 10;
1738 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1740 # Make sure perl knows it is utf8 encoded so we don't
1741 # cut in the middle of a utf8 multibyte char.
1742 $str = to_utf8
($str);
1744 # allow only $len chars, but don't cut a word if it would fit in $add_len
1745 # if it doesn't fit, cut it if it's still longer than the dots we would add
1746 # remove chopped character entities entirely
1748 # when chopping in the middle, distribute $len into left and right part
1749 # return early if chopping wouldn't make string shorter
1750 if ($where eq 'center') {
1751 return $str if ($len + 5 >= length($str)); # filler is length 5
1754 return $str if ($len + 4 >= length($str)); # filler is length 4
1757 # regexps: ending and beginning with word part up to $add_len
1758 my $endre = qr/.{$len}\w{0,$add_len}/;
1759 my $begre = qr/\w{0,$add_len}.{$len}/;
1761 if ($where eq 'left') {
1762 $str =~ m/^(.*?)($begre)$/;
1763 my ($lead, $body) = ($1, $2);
1764 if (length($lead) > 4) {
1767 return "$lead$body";
1769 } elsif ($where eq 'center') {
1770 $str =~ m/^($endre)(.*)$/;
1771 my ($left, $str) = ($1, $2);
1772 $str =~ m/^(.*?)($begre)$/;
1773 my ($mid, $right) = ($1, $2);
1774 if (length($mid) > 5) {
1777 return "$left$mid$right";
1780 $str =~ m/^($endre)(.*)$/;
1783 if (length($tail) > 4) {
1786 return "$body$tail";
1790 # takes the same arguments as chop_str, but also wraps a <span> around the
1791 # result with a title attribute if it does get chopped. Additionally, the
1792 # string is HTML-escaped.
1793 sub chop_and_escape_str
{
1796 my $chopped = chop_str
(@_);
1797 $str = to_utf8
($str);
1798 if ($chopped eq $str) {
1799 return esc_html
($chopped);
1801 $str =~ s/[[:cntrl:]]/?/g;
1802 return $cgi->span({-title
=>$str}, esc_html
($chopped));
1806 # Highlight selected fragments of string, using given CSS class,
1807 # and escape HTML. It is assumed that fragments do not overlap.
1808 # Regions are passed as list of pairs (array references).
1810 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1811 # '<span class="mark">foo</span>bar'
1812 sub esc_html_hl_regions
{
1813 my ($str, $css_class, @sel) = @_;
1814 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1815 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1816 return esc_html
($str, %opts) unless @sel;
1822 my ($begin, $end) = @
$s;
1824 # Don't create empty <span> elements.
1825 next if $end <= $begin;
1827 my $escaped = esc_html
(substr($str, $begin, $end - $begin),
1830 $out .= esc_html
(substr($str, $pos, $begin - $pos), %opts)
1831 if ($begin - $pos > 0);
1832 $out .= $cgi->span({-class => $css_class}, $escaped);
1836 $out .= esc_html
(substr($str, $pos), %opts)
1837 if ($pos < length($str));
1842 # return positions of beginning and end of each match
1844 my ($str, $regexp) = @_;
1845 return unless (defined $str && defined $regexp);
1848 while ($str =~ /$regexp/g) {
1849 push @matches, [$-[0], $+[0]];
1854 # highlight match (if any), and escape HTML
1855 sub esc_html_match_hl
{
1856 my ($str, $regexp) = @_;
1857 return esc_html
($str) unless defined $regexp;
1859 my @matches = matchpos_list
($str, $regexp);
1860 return esc_html
($str) unless @matches;
1862 return esc_html_hl_regions
($str, 'match', @matches);
1866 # highlight match (if any) of shortened string, and escape HTML
1867 sub esc_html_match_hl_chopped
{
1868 my ($str, $chopped, $regexp) = @_;
1869 return esc_html_match_hl
($str, $regexp) unless defined $chopped;
1871 my @matches = matchpos_list
($str, $regexp);
1872 return esc_html
($chopped) unless @matches;
1874 # filter matches so that we mark chopped string
1875 my $tail = "... "; # see chop_str
1876 unless ($chopped =~ s/\Q$tail\E$//) {
1879 my $chop_len = length($chopped);
1880 my $tail_len = length($tail);
1883 for my $m (@matches) {
1884 if ($m->[0] > $chop_len) {
1885 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1887 } elsif ($m->[1] > $chop_len) {
1888 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1894 return esc_html_hl_regions
($chopped . $tail, 'match', @filtered);
1897 ## ----------------------------------------------------------------------
1898 ## functions returning short strings
1900 # CSS class for given age value (in seconds)
1904 if (!defined $age) {
1906 } elsif ($age < 60*60*2) {
1908 } elsif ($age < 60*60*24*2) {
1915 # convert age in seconds to "nn units ago" string
1920 if ($age > 60*60*24*365*2) {
1921 $age_str = (int $age/60/60/24/365);
1922 $age_str .= " years ago";
1923 } elsif ($age > 60*60*24*(365/12)*2) {
1924 $age_str = int $age/60/60/24/(365/12);
1925 $age_str .= " months ago";
1926 } elsif ($age > 60*60*24*7*2) {
1927 $age_str = int $age/60/60/24/7;
1928 $age_str .= " weeks ago";
1929 } elsif ($age > 60*60*24*2) {
1930 $age_str = int $age/60/60/24;
1931 $age_str .= " days ago";
1932 } elsif ($age > 60*60*2) {
1933 $age_str = int $age/60/60;
1934 $age_str .= " hours ago";
1935 } elsif ($age > 60*2) {
1936 $age_str = int $age/60;
1937 $age_str .= " min ago";
1938 } elsif ($age > 2) {
1939 $age_str = int $age;
1940 $age_str .= " sec ago";
1942 $age_str .= " right now";
1948 S_IFINVALID
=> 0030000,
1949 S_IFGITLINK
=> 0160000,
1952 # submodule/subproject, a commit object reference
1956 return (($mode & S_IFMT
) == S_IFGITLINK
)
1959 # convert file mode in octal to symbolic file mode string
1961 my $mode = oct shift;
1963 if (S_ISGITLINK
($mode)) {
1964 return 'm---------';
1965 } elsif (S_ISDIR
($mode & S_IFMT
)) {
1966 return 'drwxr-xr-x';
1967 } elsif (S_ISLNK
($mode)) {
1968 return 'lrwxrwxrwx';
1969 } elsif (S_ISREG
($mode)) {
1970 # git cares only about the executable bit
1971 if ($mode & S_IXUSR
) {
1972 return '-rwxr-xr-x';
1974 return '-rw-r--r--';
1977 return '----------';
1981 # convert file mode in octal to file type string
1985 if ($mode !~ m/^[0-7]+$/) {
1991 if (S_ISGITLINK
($mode)) {
1993 } elsif (S_ISDIR
($mode & S_IFMT
)) {
1995 } elsif (S_ISLNK
($mode)) {
1997 } elsif (S_ISREG
($mode)) {
2004 # convert file mode in octal to file type description string
2005 sub file_type_long
{
2008 if ($mode !~ m/^[0-7]+$/) {
2014 if (S_ISGITLINK
($mode)) {
2016 } elsif (S_ISDIR
($mode & S_IFMT
)) {
2018 } elsif (S_ISLNK
($mode)) {
2020 } elsif (S_ISREG
($mode)) {
2021 if ($mode & S_IXUSR
) {
2022 return "executable";
2032 ## ----------------------------------------------------------------------
2033 ## functions returning short HTML fragments, or transforming HTML fragments
2034 ## which don't belong to other sections
2036 # format line of commit message.
2037 sub format_log_line_html
{
2040 $line = esc_html
($line, -nbsp
=>1);
2041 $line =~ s
{\b([0-9a
-fA
-F
]{8,40})\b}{
2042 $cgi->a({-href
=> href
(action
=>"object", hash
=>$1),
2043 -class => "text"}, $1);
2049 # format marker of refs pointing to given object
2051 # the destination action is chosen based on object type and current context:
2052 # - for annotated tags, we choose the tag view unless it's the current view
2053 # already, in which case we go to shortlog view
2054 # - for other refs, we keep the current view if we're in history, shortlog or
2055 # log view, and select shortlog otherwise
2056 sub format_ref_marker
{
2057 my ($refs, $id) = @_;
2060 if (defined $refs->{$id}) {
2061 foreach my $ref (@
{$refs->{$id}}) {
2062 # this code exploits the fact that non-lightweight tags are the
2063 # only indirect objects, and that they are the only objects for which
2064 # we want to use tag instead of shortlog as action
2065 my ($type, $name) = qw();
2066 my $indirect = ($ref =~ s/\^\{\}$//);
2067 # e.g. tags/v2.6.11 or heads/next
2068 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2077 $class .= " indirect" if $indirect;
2079 my $dest_action = "shortlog";
2082 $dest_action = "tag" unless $action eq "tag";
2083 } elsif ($action =~ /^(history|(short)?log)$/) {
2084 $dest_action = $action;
2088 $dest .= "refs/" unless $ref =~ m
!^refs
/!;
2091 my $link = $cgi->a({
2093 action
=>$dest_action,
2097 $markers .= " <span class=\"".esc_attr
($class)."\" title=\"".esc_attr
($ref)."\">" .
2103 return ' <span class="refs">'. $markers . '</span>';
2109 # format, perhaps shortened and with markers, title line
2110 sub format_subject_html
{
2111 my ($long, $short, $href, $extra) = @_;
2112 $extra = '' unless defined($extra);
2114 if (length($short) < length($long)) {
2115 $long =~ s/[[:cntrl:]]/?/g;
2116 return $cgi->a({-href
=> $href, -class => "list subject",
2117 -title
=> to_utf8
($long)},
2118 esc_html
($short)) . $extra;
2120 return $cgi->a({-href
=> $href, -class => "list subject"},
2121 esc_html
($long)) . $extra;
2125 # Rather than recomputing the url for an email multiple times, we cache it
2126 # after the first hit. This gives a visible benefit in views where the avatar
2127 # for the same email is used repeatedly (e.g. shortlog).
2128 # The cache is shared by all avatar engines (currently gravatar only), which
2129 # are free to use it as preferred. Since only one avatar engine is used for any
2130 # given page, there's no risk for cache conflicts.
2131 our %avatar_cache = ();
2133 # Compute the picon url for a given email, by using the picon search service over at
2134 # http://www.cs.indiana.edu/picons/search.html
2136 my $email = lc shift;
2137 if (!$avatar_cache{$email}) {
2138 my ($user, $domain) = split('@', $email);
2139 $avatar_cache{$email} =
2140 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2142 "users+domains+unknown/up/single";
2144 return $avatar_cache{$email};
2147 # Compute the gravatar url for a given email, if it's not in the cache already.
2148 # Gravatar stores only the part of the URL before the size, since that's the
2149 # one computationally more expensive. This also allows reuse of the cache for
2150 # different sizes (for this particular engine).
2152 my $email = lc shift;
2154 $avatar_cache{$email} ||=
2155 "//www.gravatar.com/avatar/" .
2156 Digest
::MD5
::md5_hex
($email) . "?s=";
2157 return $avatar_cache{$email} . $size;
2160 # Insert an avatar for the given $email at the given $size if the feature
2162 sub git_get_avatar
{
2163 my ($email, %opts) = @_;
2164 my $pre_white = ($opts{-pad_before
} ?
" " : "");
2165 my $post_white = ($opts{-pad_after
} ?
" " : "");
2166 $opts{-size
} ||= 'default';
2167 my $size = $avatar_size{$opts{-size
}} || $avatar_size{'default'};
2169 if ($git_avatar eq 'gravatar') {
2170 $url = gravatar_url
($email, $size);
2171 } elsif ($git_avatar eq 'picon') {
2172 $url = picon_url
($email);
2174 # Other providers can be added by extending the if chain, defining $url
2175 # as needed. If no variant puts something in $url, we assume avatars
2176 # are completely disabled/unavailable.
2179 "<img width=\"$size\" " .
2180 "class=\"avatar\" " .
2181 "src=\"".esc_url
($url)."\" " .
2189 sub format_search_author
{
2190 my ($author, $searchtype, $displaytext) = @_;
2191 my $have_search = gitweb_check_feature
('search');
2195 if ($searchtype eq 'author') {
2196 $performed = "authored";
2197 } elsif ($searchtype eq 'committer') {
2198 $performed = "committed";
2201 return $cgi->a({-href
=> href
(action
=>"search", hash
=>$hash,
2202 searchtext
=>$author,
2203 searchtype
=>$searchtype), class=>"list",
2204 title
=>"Search for commits $performed by $author"},
2208 return $displaytext;
2212 # format the author name of the given commit with the given tag
2213 # the author name is chopped and escaped according to the other
2214 # optional parameters (see chop_str).
2215 sub format_author_html
{
2218 my $author = chop_and_escape_str
($co->{'author_name'}, @_);
2219 return "<$tag class=\"author\">" .
2220 format_search_author
($co->{'author_name'}, "author",
2221 git_get_avatar
($co->{'author_email'}, -pad_after
=> 1) .
2226 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2227 sub format_git_diff_header_line
{
2229 my $diffinfo = shift;
2230 my ($from, $to) = @_;
2232 if ($diffinfo->{'nparents'}) {
2234 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2235 if ($to->{'href'}) {
2236 $line .= $cgi->a({-href
=> $to->{'href'}, -class => "path"},
2237 esc_path
($to->{'file'}));
2238 } else { # file was deleted (no href)
2239 $line .= esc_path
($to->{'file'});
2243 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2244 if ($from->{'href'}) {
2245 $line .= $cgi->a({-href
=> $from->{'href'}, -class => "path"},
2246 'a/' . esc_path
($from->{'file'}));
2247 } else { # file was added (no href)
2248 $line .= 'a/' . esc_path
($from->{'file'});
2251 if ($to->{'href'}) {
2252 $line .= $cgi->a({-href
=> $to->{'href'}, -class => "path"},
2253 'b/' . esc_path
($to->{'file'}));
2254 } else { # file was deleted
2255 $line .= 'b/' . esc_path
($to->{'file'});
2259 return "<div class=\"diff header\">$line</div>\n";
2262 # format extended diff header line, before patch itself
2263 sub format_extended_diff_header_line
{
2265 my $diffinfo = shift;
2266 my ($from, $to) = @_;
2269 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2270 $line .= $cgi->a({-href
=>$from->{'href'}, -class=>"path"},
2271 esc_path
($from->{'file'}));
2273 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2274 $line .= $cgi->a({-href
=>$to->{'href'}, -class=>"path"},
2275 esc_path
($to->{'file'}));
2277 # match single <mode>
2278 if ($line =~ m/\s(\d{6})$/) {
2279 $line .= '<span class="info"> (' .
2280 file_type_long
($1) .
2284 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2285 # can match only for combined diff
2287 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2288 if ($from->{'href'}[$i]) {
2289 $line .= $cgi->a({-href
=>$from->{'href'}[$i],
2291 substr($diffinfo->{'from_id'}[$i],0,7));
2296 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2299 if ($to->{'href'}) {
2300 $line .= $cgi->a({-href
=>$to->{'href'}, -class=>"hash"},
2301 substr($diffinfo->{'to_id'},0,7));
2306 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2307 # can match only for ordinary diff
2308 my ($from_link, $to_link);
2309 if ($from->{'href'}) {
2310 $from_link = $cgi->a({-href
=>$from->{'href'}, -class=>"hash"},
2311 substr($diffinfo->{'from_id'},0,7));
2313 $from_link = '0' x
7;
2315 if ($to->{'href'}) {
2316 $to_link = $cgi->a({-href
=>$to->{'href'}, -class=>"hash"},
2317 substr($diffinfo->{'to_id'},0,7));
2321 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2322 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2325 return $line . "<br/>\n";
2328 # format from-file/to-file diff header
2329 sub format_diff_from_to_header
{
2330 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2335 #assert($line =~ m/^---/) if DEBUG;
2336 # no extra formatting for "^--- /dev/null"
2337 if (! $diffinfo->{'nparents'}) {
2338 # ordinary (single parent) diff
2339 if ($line =~ m!^--- "?a/!) {
2340 if ($from->{'href'}) {
2342 $cgi->a({-href
=>$from->{'href'}, -class=>"path"},
2343 esc_path
($from->{'file'}));
2346 esc_path
($from->{'file'});
2349 $result .= qq!<div
class="diff from_file">$line</div
>\n!;
2352 # combined diff (merge commit)
2353 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2354 if ($from->{'href'}[$i]) {
2356 $cgi->a({-href
=>href
(action
=>"blobdiff",
2357 hash_parent
=>$diffinfo->{'from_id'}[$i],
2358 hash_parent_base
=>$parents[$i],
2359 file_parent
=>$from->{'file'}[$i],
2360 hash
=>$diffinfo->{'to_id'},
2362 file_name
=>$to->{'file'}),
2364 -title
=>"diff" . ($i+1)},
2367 $cgi->a({-href
=>$from->{'href'}[$i], -class=>"path"},
2368 esc_path
($from->{'file'}[$i]));
2370 $line = '--- /dev/null';
2372 $result .= qq!<div
class="diff from_file">$line</div
>\n!;
2377 #assert($line =~ m/^\+\+\+/) if DEBUG;
2378 # no extra formatting for "^+++ /dev/null"
2379 if ($line =~ m!^\+\+\+ "?b/!) {
2380 if ($to->{'href'}) {
2382 $cgi->a({-href
=>$to->{'href'}, -class=>"path"},
2383 esc_path
($to->{'file'}));
2386 esc_path
($to->{'file'});
2389 $result .= qq!<div
class="diff to_file">$line</div
>\n!;
2394 # create note for patch simplified by combined diff
2395 sub format_diff_cc_simplified
{
2396 my ($diffinfo, @parents) = @_;
2399 $result .= "<div class=\"diff header\">" .
2401 if (!is_deleted
($diffinfo)) {
2402 $result .= $cgi->a({-href
=> href
(action
=>"blob",
2404 hash
=>$diffinfo->{'to_id'},
2405 file_name
=>$diffinfo->{'to_file'}),
2407 esc_path
($diffinfo->{'to_file'}));
2409 $result .= esc_path
($diffinfo->{'to_file'});
2411 $result .= "</div>\n" . # class="diff header"
2412 "<div class=\"diff nodifferences\">" .
2414 "</div>\n"; # class="diff nodifferences"
2419 sub diff_line_class
{
2420 my ($line, $from, $to) = @_;
2425 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2426 $num_sign = scalar @
{$from->{'href'}};
2429 my @diff_line_classifier = (
2430 { regexp
=> qr/^\@\@{$num_sign} /, class => "chunk_header"},
2431 { regexp
=> qr/^\\/, class => "incomplete" },
2432 { regexp
=> qr/^ {$num_sign}/, class => "ctx" },
2433 # classifier for context must come before classifier add/rem,
2434 # or we would have to use more complicated regexp, for example
2435 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2436 { regexp
=> qr/^[+ ]{$num_sign}/, class => "add" },
2437 { regexp
=> qr/^[- ]{$num_sign}/, class => "rem" },
2439 for my $clsfy (@diff_line_classifier) {
2440 return $clsfy->{'class'}
2441 if ($line =~ $clsfy->{'regexp'});
2448 # assumes that $from and $to are defined and correctly filled,
2449 # and that $line holds a line of chunk header for unified diff
2450 sub format_unidiff_chunk_header
{
2451 my ($line, $from, $to) = @_;
2453 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2454 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2456 $from_lines = 0 unless defined $from_lines;
2457 $to_lines = 0 unless defined $to_lines;
2459 if ($from->{'href'}) {
2460 $from_text = $cgi->a({-href
=>"$from->{'href'}#l$from_start",
2461 -class=>"list"}, $from_text);
2463 if ($to->{'href'}) {
2464 $to_text = $cgi->a({-href
=>"$to->{'href'}#l$to_start",
2465 -class=>"list"}, $to_text);
2467 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2468 "<span class=\"section\">" . esc_html
($section, -nbsp
=>1) . "</span>";
2472 # assumes that $from and $to are defined and correctly filled,
2473 # and that $line holds a line of chunk header for combined diff
2474 sub format_cc_diff_chunk_header
{
2475 my ($line, $from, $to) = @_;
2477 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2478 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2480 @from_text = split(' ', $ranges);
2481 for (my $i = 0; $i < @from_text; ++$i) {
2482 ($from_start[$i], $from_nlines[$i]) =
2483 (split(',', substr($from_text[$i], 1)), 0);
2486 $to_text = pop @from_text;
2487 $to_start = pop @from_start;
2488 $to_nlines = pop @from_nlines;
2490 $line = "<span class=\"chunk_info\">$prefix ";
2491 for (my $i = 0; $i < @from_text; ++$i) {
2492 if ($from->{'href'}[$i]) {
2493 $line .= $cgi->a({-href
=>"$from->{'href'}[$i]#l$from_start[$i]",
2494 -class=>"list"}, $from_text[$i]);
2496 $line .= $from_text[$i];
2500 if ($to->{'href'}) {
2501 $line .= $cgi->a({-href
=>"$to->{'href'}#l$to_start",
2502 -class=>"list"}, $to_text);
2506 $line .= " $prefix</span>" .
2507 "<span class=\"section\">" . esc_html
($section, -nbsp
=>1) . "</span>";
2511 # process patch (diff) line (not to be used for diff headers),
2512 # returning HTML-formatted (but not wrapped) line.
2513 # If the line is passed as a reference, it is treated as HTML and not
2515 sub format_diff_line
{
2516 my ($line, $diff_class, $from, $to) = @_;
2522 $line = untabify
($line);
2524 if ($from && $to && $line =~ m/^\@{2} /) {
2525 $line = format_unidiff_chunk_header
($line, $from, $to);
2526 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2527 $line = format_cc_diff_chunk_header
($line, $from, $to);
2529 $line = esc_html
($line, -nbsp
=>1);
2533 my $diff_classes = "diff";
2534 $diff_classes .= " $diff_class" if ($diff_class);
2535 $line = "<div class=\"$diff_classes\">$line</div>\n";
2540 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2541 # linked. Pass the hash of the tree/commit to snapshot.
2542 sub format_snapshot_links
{
2544 my $num_fmts = @snapshot_fmts;
2545 if ($num_fmts > 1) {
2546 # A parenthesized list of links bearing format names.
2547 # e.g. "snapshot (_tar.gz_ _zip_)"
2548 return "snapshot (" . join(' ', map
2555 }, $known_snapshot_formats{$_}{'display'})
2556 , @snapshot_fmts) . ")";
2557 } elsif ($num_fmts == 1) {
2558 # A single "snapshot" link whose tooltip bears the format name.
2560 my ($fmt) = @snapshot_fmts;
2566 snapshot_format
=>$fmt
2568 -title
=> "in format: $known_snapshot_formats{$fmt}{'display'}"
2570 } else { # $num_fmts == 0
2575 ## ......................................................................
2576 ## functions returning values to be passed, perhaps after some
2577 ## transformation, to other functions; e.g. returning arguments to href()
2579 # returns hash to be passed to href to generate gitweb URL
2580 # in -title key it returns description of link
2582 my $format = shift || 'Atom';
2583 my %res = (action
=> lc($format));
2584 my $matched_ref = 0;
2586 # feed links are possible only for project views
2587 return unless (defined $project);
2588 # some views should link to OPML, or to generic project feed,
2589 # or don't have specific feed yet (so they should use generic)
2590 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2593 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2594 # (fullname) to differentiate from tag links; this also makes
2595 # possible to detect branch links
2596 for my $ref (get_branch_refs
()) {
2597 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2598 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2600 $matched_ref = $ref;
2604 # find log type for feed description (title)
2606 if (defined $file_name) {
2607 $type = "history of $file_name";
2608 $type .= "/" if ($action eq 'tree');
2609 $type .= " on '$branch'" if (defined $branch);
2611 $type = "log of $branch" if (defined $branch);
2614 $res{-title
} = $type;
2615 $res{'hash'} = (defined $branch ?
"refs/$matched_ref/$branch" : undef);
2616 $res{'file_name'} = $file_name;
2621 ## ----------------------------------------------------------------------
2622 ## git utility subroutines, invoking git commands
2624 # returns path to the core git executable and the --git-dir parameter as list
2626 $number_of_git_cmds++;
2627 return $GIT, '--git-dir='.$git_dir;
2630 # quote the given arguments for passing them to the shell
2631 # quote_command("command", "arg 1", "arg with ' and ! characters")
2632 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2633 # Try to avoid using this function wherever possible.
2636 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2639 # get HEAD ref of given project as hash
2640 sub git_get_head_hash
{
2641 return git_get_full_hash
(shift, 'HEAD');
2644 sub git_get_full_hash
{
2645 return git_get_hash
(@_);
2648 sub git_get_short_hash
{
2649 return git_get_hash
(@_, '--short=7');
2653 my ($project, $hash, @options) = @_;
2654 my $o_git_dir = $git_dir;
2656 $git_dir = "$projectroot/$project";
2657 if (open my $fd, '-|', git_cmd
(), 'rev-parse',
2658 '--verify', '-q', @options, $hash) {
2660 chomp $retval if defined $retval;
2663 if (defined $o_git_dir) {
2664 $git_dir = $o_git_dir;
2669 # get type of given object
2673 open my $fd, "-|", git_cmd
(), "cat-file", '-t', $hash or return;
2675 close $fd or return;
2680 # repository configuration
2681 our $config_file = '';
2684 # store multiple values for single key as anonymous array reference
2685 # single values stored directly in the hash, not as [ <value> ]
2686 sub hash_set_multi
{
2687 my ($hash, $key, $value) = @_;
2689 if (!exists $hash->{$key}) {
2690 $hash->{$key} = $value;
2691 } elsif (!ref $hash->{$key}) {
2692 $hash->{$key} = [ $hash->{$key}, $value ];
2694 push @
{$hash->{$key}}, $value;
2698 # return hash of git project configuration
2699 # optionally limited to some section, e.g. 'gitweb'
2700 sub git_parse_project_config
{
2701 my $section_regexp = shift;
2706 open my $fh, "-|", git_cmd
(), "config", '-z', '-l',
2709 while (my $keyval = <$fh>) {
2711 my ($key, $value) = split(/\n/, $keyval, 2);
2713 hash_set_multi
(\
%config, $key, $value)
2714 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2721 # convert config value to boolean: 'true' or 'false'
2722 # no value, number > 0, 'true' and 'yes' values are true
2723 # rest of values are treated as false (never as error)
2724 sub config_to_bool
{
2727 return 1 if !defined $val; # section.key
2729 # strip leading and trailing whitespace
2733 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2734 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2737 # convert config value to simple decimal number
2738 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2739 # to be multiplied by 1024, 1048576, or 1073741824
2743 # strip leading and trailing whitespace
2747 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2749 # unknown unit is treated as 1
2750 return $num * ($unit eq 'g' ?
1073741824 :
2751 $unit eq 'm' ?
1048576 :
2752 $unit eq 'k' ?
1024 : 1);
2757 # convert config value to array reference, if needed
2758 sub config_to_multi
{
2761 return ref($val) ?
$val : (defined($val) ?
[ $val ] : []);
2764 sub git_get_project_config
{
2765 my ($key, $type) = @_;
2767 return unless defined $git_dir;
2770 return unless ($key);
2771 # only subsection, if exists, is case sensitive,
2772 # and not lowercased by 'git config -z -l'
2773 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2775 $key = join(".", lc($hi), $mi, lc($lo));
2776 return if ($lo =~ /\W/ || $hi =~ /\W/);
2780 return if ($key =~ /\W/);
2782 $key =~ s/^gitweb\.//;
2785 if (defined $type) {
2788 unless ($type eq 'bool' || $type eq 'int');
2792 if (!defined $config_file ||
2793 $config_file ne "$git_dir/config") {
2794 %config = git_parse_project_config
('gitweb');
2795 $config_file = "$git_dir/config";
2798 # check if config variable (key) exists
2799 return unless exists $config{"gitweb.$key"};
2802 if (!defined $type) {
2803 return $config{"gitweb.$key"};
2804 } elsif ($type eq 'bool') {
2805 # backward compatibility: 'git config --bool' returns true/false
2806 return config_to_bool
($config{"gitweb.$key"}) ?
'true' : 'false';
2807 } elsif ($type eq 'int') {
2808 return config_to_int
($config{"gitweb.$key"});
2810 return $config{"gitweb.$key"};
2813 # get hash of given path at given ref
2814 sub git_get_hash_by_path
{
2816 my $path = shift || return undef;
2821 open my $fd, "-|", git_cmd
(), "ls-tree", $base, "--", $path
2822 or die_error
(500, "Open git-ls-tree failed");
2824 close $fd or return undef;
2826 if (!defined $line) {
2827 # there is no tree or hash given by $path at $base
2831 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2832 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2833 if (defined $type && $type ne $2) {
2834 # type doesn't match
2840 # get path of entry with given hash at given tree-ish (ref)
2841 # used to get 'from' filename for combined diff (merge commit) for renames
2842 sub git_get_path_by_hash
{
2843 my $base = shift || return;
2844 my $hash = shift || return;
2848 open my $fd, "-|", git_cmd
(), "ls-tree", '-r', '-t', '-z', $base
2850 while (my $line = <$fd>) {
2853 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2854 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2855 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2864 ## ......................................................................
2865 ## git utility functions, directly accessing git repository
2867 # get the value of config variable either from file named as the variable
2868 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2869 # configuration variable in the repository config file.
2870 sub git_get_file_or_project_config
{
2871 my ($path, $name) = @_;
2873 $git_dir = "$projectroot/$path";
2874 open my $fd, '<', "$git_dir/$name"
2875 or return git_get_project_config
($name);
2878 if (defined $conf) {
2884 sub git_get_project_description
{
2886 return git_get_file_or_project_config
($path, 'description');
2889 sub git_get_project_category
{
2891 return git_get_file_or_project_config
($path, 'category');
2895 # supported formats:
2896 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2897 # - if its contents is a number, use it as tag weight,
2898 # - otherwise add a tag with weight 1
2899 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2900 # the same value multiple times increases tag weight
2901 # * `gitweb.ctag' multi-valued repo config variable
2902 sub git_get_project_ctags
{
2903 my $project = shift;
2906 $git_dir = "$projectroot/$project";
2907 if (opendir my $dh, "$git_dir/ctags") {
2908 my @files = grep { -f
$_ } map { "$git_dir/ctags/$_" } readdir($dh);
2909 foreach my $tagfile (@files) {
2910 open my $ct, '<', $tagfile
2916 (my $ctag = $tagfile) =~ s
#.*/##;
2917 if ($val =~ /^\d+$/) {
2918 $ctags->{$ctag} = $val;
2920 $ctags->{$ctag} = 1;
2925 } elsif (open my $fh, '<', "$git_dir/ctags") {
2926 while (my $line = <$fh>) {
2928 $ctags->{$line}++ if $line;
2933 my $taglist = config_to_multi
(git_get_project_config
('ctag'));
2934 foreach my $tag (@
$taglist) {
2942 # return hash, where keys are content tags ('ctags'),
2943 # and values are sum of weights of given tag in every project
2944 sub git_gather_all_ctags
{
2945 my $projects = shift;
2948 foreach my $p (@
$projects) {
2949 foreach my $ct (keys %{$p->{'ctags'}}) {
2950 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2957 sub git_populate_project_tagcloud
{
2960 # First, merge different-cased tags; tags vote on casing
2962 foreach (keys %$ctags) {
2963 $ctags_lc{lc $_}->{count
} += $ctags->{$_};
2964 if (not $ctags_lc{lc $_}->{topcount
}
2965 or $ctags_lc{lc $_}->{topcount
} < $ctags->{$_}) {
2966 $ctags_lc{lc $_}->{topcount
} = $ctags->{$_};
2967 $ctags_lc{lc $_}->{topname
} = $_;
2972 my $matched = $input_params{'ctag'};
2973 if (eval { require HTML
::TagCloud
; 1; }) {
2974 $cloud = HTML
::TagCloud
->new;
2975 foreach my $ctag (sort keys %ctags_lc) {
2976 # Pad the title with spaces so that the cloud looks
2978 my $title = esc_html
($ctags_lc{$ctag}->{topname
});
2979 $title =~ s/ / /g;
2980 $title =~ s/^/ /g;
2981 $title =~ s/$/ /g;
2982 if (defined $matched && $matched eq $ctag) {
2983 $title = qq(<span
class="match">$title</span
>);
2985 $cloud->add($title, href
(project
=>undef, ctag
=>$ctag),
2986 $ctags_lc{$ctag}->{count
});
2990 foreach my $ctag (keys %ctags_lc) {
2991 my $title = esc_html
($ctags_lc{$ctag}->{topname
}, -nbsp
=>1);
2992 if (defined $matched && $matched eq $ctag) {
2993 $title = qq(<span
class="match">$title</span
>);
2995 $cloud->{$ctag}{count
} = $ctags_lc{$ctag}->{count
};
2996 $cloud->{$ctag}{ctag
} =
2997 $cgi->a({-href
=>href
(project
=>undef, ctag
=>$ctag)}, $title);
3003 sub git_show_project_tagcloud
{
3004 my ($cloud, $count) = @_;
3005 if (ref $cloud eq 'HTML::TagCloud') {
3006 return $cloud->html_and_css($count);
3008 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3010 '<div id="htmltagcloud"'.($project ?
'' : ' align="center"').'>' .
3012 $cloud->{$_}->{'ctag'}
3013 } splice(@tags, 0, $count)) .
3018 sub git_get_project_url_list
{
3021 $git_dir = "$projectroot/$path";
3022 open my $fd, '<', "$git_dir/cloneurl"
3023 or return wantarray ?
3024 @
{ config_to_multi
(git_get_project_config
('url')) } :
3025 config_to_multi
(git_get_project_config
('url'));
3026 my @git_project_url_list = map { chomp; $_ } <$fd>;
3029 return wantarray ?
@git_project_url_list : \
@git_project_url_list;
3032 sub git_get_projects_list
{
3033 my $filter = shift || '';
3034 my $paranoid = shift;
3037 if (-d
$projects_list) {
3038 # search in directory
3039 my $dir = $projects_list;
3040 # remove the trailing "/"
3042 my $pfxlen = length("$dir");
3043 my $pfxdepth = ($dir =~ tr!/!!);
3044 # when filtering, search only given subdirectory
3045 if ($filter && !$paranoid) {
3051 follow_fast
=> 1, # follow symbolic links
3052 follow_skip
=> 2, # ignore duplicates
3053 dangling_symlinks
=> 0, # ignore dangling symlinks, silently
3056 our $project_maxdepth;
3058 # skip project-list toplevel, if we get it.
3059 return if (m!^[/.]$!);
3060 # only directories can be git repositories
3061 return unless (-d
$_);
3062 # don't traverse too deep (Find is super slow on os x)
3063 # $project_maxdepth excludes depth of $projectroot
3064 if (($File::Find
::name
=~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3065 $File::Find
::prune
= 1;
3069 my $path = substr($File::Find
::name
, $pfxlen + 1);
3070 # paranoidly only filter here
3071 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3074 # we check related file in $projectroot
3075 if (check_export_ok
("$projectroot/$path")) {
3076 push @list, { path
=> $path };
3077 $File::Find
::prune
= 1;
3082 } elsif (-f
$projects_list) {
3083 # read from file(url-encoded):
3084 # 'git%2Fgit.git Linus+Torvalds'
3085 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3086 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3087 open my $fd, '<', $projects_list or return;
3089 while (my $line = <$fd>) {
3091 my ($path, $owner) = split ' ', $line;
3092 $path = unescape
($path);
3093 $owner = unescape
($owner);
3094 if (!defined $path) {
3097 # if $filter is rpovided, check if $path begins with $filter
3098 if ($filter && $path !~ m!^\Q$filter\E/!) {
3101 if (check_export_ok
("$projectroot/$path")) {
3106 $pr->{'owner'} = to_utf8
($owner);
3116 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3117 # as side effects it sets 'forks' field to list of forks for forked projects
3118 sub filter_forks_from_projects_list
{
3119 my $projects = shift;
3121 my %trie; # prefix tree of directories (path components)
3122 # generate trie out of those directories that might contain forks
3123 foreach my $pr (@
$projects) {
3124 my $path = $pr->{'path'};
3125 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3126 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3127 next unless ($path); # skip '.git' repository: tests, git-instaweb
3128 next unless (-d
"$projectroot/$path"); # containing directory exists
3129 $pr->{'forks'} = []; # there can be 0 or more forks of project
3132 my @dirs = split('/', $path);
3133 # walk the trie, until either runs out of components or out of trie
3135 while (scalar @dirs &&
3136 exists($ref->{$dirs[0]})) {
3137 $ref = $ref->{shift @dirs};
3139 # create rest of trie structure from rest of components
3140 foreach my $dir (@dirs) {
3141 $ref = $ref->{$dir} = {};
3143 # create end marker, store $pr as a data
3144 $ref->{''} = $pr if (!exists $ref->{''});
3147 # filter out forks, by finding shortest prefix match for paths
3150 foreach my $pr (@
$projects) {
3154 foreach my $dir (split('/', $pr->{'path'})) {
3155 if (exists $ref->{''}) {
3156 # found [shortest] prefix, is a fork - skip it
3157 push @
{$ref->{''}{'forks'}}, $pr;
3160 if (!exists $ref->{$dir}) {
3161 # not in trie, cannot have prefix, not a fork
3162 push @filtered, $pr;
3165 # If the dir is there, we just walk one step down the trie.
3166 $ref = $ref->{$dir};
3168 # we ran out of trie
3169 # (shouldn't happen: it's either no match, or end marker)
3170 push @filtered, $pr;
3176 # note: fill_project_list_info must be run first,
3177 # for 'descr_long' and 'ctags' to be filled
3178 sub search_projects_list
{
3179 my ($projlist, %opts) = @_;
3180 my $tagfilter = $opts{'tagfilter'};
3181 my $search_re = $opts{'search_regexp'};
3184 unless ($tagfilter || $search_re);
3186 # searching projects require filling to be run before it;
3187 fill_project_list_info
($projlist,
3188 $tagfilter ?
'ctags' : (),
3189 $search_re ?
('path', 'descr') : ());
3192 foreach my $pr (@
$projlist) {
3195 next unless ref($pr->{'ctags'}) eq 'HASH';
3197 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3202 $pr->{'path'} =~ /$search_re/ ||
3203 $pr->{'descr_long'} =~ /$search_re/;
3206 push @projects, $pr;
3212 our $gitweb_project_owner = undef;
3213 sub git_get_project_list_from_file
{
3215 return if (defined $gitweb_project_owner);
3217 $gitweb_project_owner = {};
3218 # read from file (url-encoded):
3219 # 'git%2Fgit.git Linus+Torvalds'
3220 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3221 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3222 if (-f
$projects_list) {
3223 open(my $fd, '<', $projects_list);
3224 while (my $line = <$fd>) {
3226 my ($pr, $ow) = split ' ', $line;
3227 $pr = unescape
($pr);
3228 $ow = unescape
($ow);
3229 $gitweb_project_owner->{$pr} = to_utf8
($ow);
3235 sub git_get_project_owner
{
3236 my $project = shift;
3239 return undef unless $project;
3240 $git_dir = "$projectroot/$project";
3242 if (!defined $gitweb_project_owner) {
3243 git_get_project_list_from_file
();
3246 if (exists $gitweb_project_owner->{$project}) {
3247 $owner = $gitweb_project_owner->{$project};
3249 if (!defined $owner){
3250 $owner = git_get_project_config
('owner');
3252 if (!defined $owner) {
3253 $owner = get_file_owner
("$git_dir");
3259 sub git_get_last_activity
{
3263 $git_dir = "$projectroot/$path";
3264 open($fd, "-|", git_cmd
(), 'for-each-ref',
3265 '--format=%(committer)',
3266 '--sort=-committerdate',
3268 map { "refs/$_" } get_branch_refs
()) or return;
3269 my $most_recent = <$fd>;
3270 close $fd or return;
3271 if (defined $most_recent &&
3272 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3274 my $age = time - $timestamp;
3275 return ($age, age_string
($age));
3277 return (undef, undef);
3280 # Implementation note: when a single remote is wanted, we cannot use 'git
3281 # remote show -n' because that command always work (assuming it's a remote URL
3282 # if it's not defined), and we cannot use 'git remote show' because that would
3283 # try to make a network roundtrip. So the only way to find if that particular
3284 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3285 # and when we find what we want.
3286 sub git_get_remotes_list
{
3290 open my $fd, '-|' , git_cmd
(), 'remote', '-v';
3292 while (my $remote = <$fd>) {
3294 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3295 next if $wanted and not $remote eq $wanted;
3296 my ($url, $key) = ($1, $2);
3298 $remotes{$remote} ||= { 'heads' => () };
3299 $remotes{$remote}{$key} = $url;
3301 close $fd or return;
3302 return wantarray ?
%remotes : \
%remotes;
3305 # Takes a hash of remotes as first parameter and fills it by adding the
3306 # available remote heads for each of the indicated remotes.
3307 sub fill_remote_heads
{
3308 my $remotes = shift;
3309 my @heads = map { "remotes/$_" } keys %$remotes;
3310 my @remoteheads = git_get_heads_list
(undef, @heads);
3311 foreach my $remote (keys %$remotes) {
3312 $remotes->{$remote}{'heads'} = [ grep {
3313 $_->{'name'} =~ s!^$remote/!!
3318 sub git_get_references
{
3319 my $type = shift || "";
3321 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3322 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3323 open my $fd, "-|", git_cmd
(), "show-ref", "--dereference",
3324 ($type ?
("--", "refs/$type") : ()) # use -- <pattern> if $type
3327 while (my $line = <$fd>) {
3329 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3330 if (defined $refs{$1}) {
3331 push @
{$refs{$1}}, $2;
3337 close $fd or return;
3341 sub git_get_rev_name_tags
{
3342 my $hash = shift || return undef;
3344 open my $fd, "-|", git_cmd
(), "name-rev", "--tags", $hash
3346 my $name_rev = <$fd>;
3349 if ($name_rev =~ m
|^$hash tags
/(.*)$|) {
3352 # catches also '$hash undefined' output
3357 ## ----------------------------------------------------------------------
3358 ## parse to hash functions
3362 my $tz = shift || "-0000";
3365 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3366 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3367 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3368 $date{'hour'} = $hour;
3369 $date{'minute'} = $min;
3370 $date{'mday'} = $mday;
3371 $date{'day'} = $days[$wday];
3372 $date{'month'} = $months[$mon];
3373 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3374 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3375 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3376 $mday, $months[$mon], $hour ,$min;
3377 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3378 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3380 my ($tz_sign, $tz_hour, $tz_min) =
3381 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3382 $tz_sign = ($tz_sign eq '-' ?
-1 : +1);
3383 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3384 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3385 $date{'hour_local'} = $hour;
3386 $date{'minute_local'} = $min;
3387 $date{'tz_local'} = $tz;
3388 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3389 1900+$year, $mon+1, $mday,
3390 $hour, $min, $sec, $tz);
3399 open my $fd, "-|", git_cmd
(), "cat-file", "tag", $tag_id or return;
3400 $tag{'id'} = $tag_id;
3401 while (my $line = <$fd>) {
3403 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3404 $tag{'object'} = $1;
3405 } elsif ($line =~ m/^type (.+)$/) {
3407 } elsif ($line =~ m/^tag (.+)$/) {
3409 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3410 $tag{'author'} = $1;
3411 $tag{'author_epoch'} = $2;
3412 $tag{'author_tz'} = $3;
3413 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3414 $tag{'author_name'} = $1;
3415 $tag{'author_email'} = $2;
3417 $tag{'author_name'} = $tag{'author'};
3419 } elsif ($line =~ m/--BEGIN/) {
3420 push @comment, $line;
3422 } elsif ($line eq "") {
3426 push @comment, <$fd>;
3427 $tag{'comment'} = \
@comment;
3428 close $fd or return;
3429 if (!defined $tag{'name'}) {
3435 sub parse_commit_text
{
3436 my ($commit_text, $withparents) = @_;
3437 my @commit_lines = split '\n', $commit_text;
3440 pop @commit_lines; # Remove '\0'
3442 if (! @commit_lines) {
3446 my $header = shift @commit_lines;
3447 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3450 ($co{'id'}, my @parents) = split ' ', $header;
3451 while (my $line = shift @commit_lines) {
3452 last if $line eq "\n";
3453 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3455 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3457 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3458 $co{'author'} = to_utf8
($1);
3459 $co{'author_epoch'} = $2;
3460 $co{'author_tz'} = $3;
3461 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3462 $co{'author_name'} = $1;
3463 $co{'author_email'} = $2;
3465 $co{'author_name'} = $co{'author'};
3467 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3468 $co{'committer'} = to_utf8
($1);
3469 $co{'committer_epoch'} = $2;
3470 $co{'committer_tz'} = $3;
3471 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3472 $co{'committer_name'} = $1;
3473 $co{'committer_email'} = $2;
3475 $co{'committer_name'} = $co{'committer'};
3479 if (!defined $co{'tree'}) {
3482 $co{'parents'} = \
@parents;
3483 $co{'parent'} = $parents[0];
3485 foreach my $title (@commit_lines) {
3488 $co{'title'} = chop_str
($title, 80, 5);
3489 # remove leading stuff of merges to make the interesting part visible
3490 if (length($title) > 50) {
3491 $title =~ s/^Automatic //;
3492 $title =~ s/^merge (of|with) /Merge ... /i;
3493 if (length($title) > 50) {
3494 $title =~ s/(http|rsync):\/\///;
3496 if (length($title) > 50) {
3497 $title =~ s/(master|www|rsync)\.//;
3499 if (length($title) > 50) {
3500 $title =~ s/kernel.org:?//;
3502 if (length($title) > 50) {
3503 $title =~ s/\/pub\/scm//;
3506 $co{'title_short'} = chop_str
($title, 50, 5);
3510 if (! defined $co{'title'} || $co{'title'} eq "") {
3511 $co{'title'} = $co{'title_short'} = '(no commit message)';
3513 # remove added spaces
3514 foreach my $line (@commit_lines) {
3517 $co{'comment'} = \
@commit_lines;
3519 my $age = time - $co{'committer_epoch'};
3521 $co{'age_string'} = age_string
($age);
3522 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3523 if ($age > 60*60*24*7*2) {
3524 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3525 $co{'age_string_age'} = $co{'age_string'};
3527 $co{'age_string_date'} = $co{'age_string'};
3528 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3534 my ($commit_id) = @_;
3539 open my $fd, "-|", git_cmd
(), "rev-list",
3545 or die_error
(500, "Open git-rev-list failed");
3546 %co = parse_commit_text
(<$fd>, 1);
3553 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3561 open my $fd, "-|", git_cmd
(), "rev-list",
3564 ("--max-count=" . $maxcount),
3565 ("--skip=" . $skip),
3569 ($filename ?
($filename) : ())
3570 or die_error
(500, "Open git-rev-list failed");
3571 while (my $line = <$fd>) {
3572 my %co = parse_commit_text
($line);
3577 return wantarray ?
@cos : \
@cos;
3580 # parse line of git-diff-tree "raw" output
3581 sub parse_difftree_raw_line
{
3585 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3586 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3587 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3588 $res{'from_mode'} = $1;
3589 $res{'to_mode'} = $2;
3590 $res{'from_id'} = $3;
3592 $res{'status'} = $5;
3593 $res{'similarity'} = $6;
3594 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3595 ($res{'from_file'}, $res{'to_file'}) = map { unquote
($_) } split("\t", $7);
3597 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote
($7);
3600 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3601 # combined diff (for merge commit)
3602 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3603 $res{'nparents'} = length($1);
3604 $res{'from_mode'} = [ split(' ', $2) ];
3605 $res{'to_mode'} = pop @
{$res{'from_mode'}};
3606 $res{'from_id'} = [ split(' ', $3) ];
3607 $res{'to_id'} = pop @
{$res{'from_id'}};
3608 $res{'status'} = [ split('', $4) ];
3609 $res{'to_file'} = unquote
($5);
3611 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3612 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3613 $res{'commit'} = $1;
3616 return wantarray ?
%res : \
%res;
3619 # wrapper: return parsed line of git-diff-tree "raw" output
3620 # (the argument might be raw line, or parsed info)
3621 sub parsed_difftree_line
{
3622 my $line_or_ref = shift;
3624 if (ref($line_or_ref) eq "HASH") {
3625 # pre-parsed (or generated by hand)
3626 return $line_or_ref;
3628 return parse_difftree_raw_line
($line_or_ref);
3632 # parse line of git-ls-tree output
3633 sub parse_ls_tree_line
{
3639 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3640 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3649 $res{'name'} = unquote
($5);
3652 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3653 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3661 $res{'name'} = unquote
($4);
3665 return wantarray ?
%res : \
%res;
3668 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3669 sub parse_from_to_diffinfo
{
3670 my ($diffinfo, $from, $to, @parents) = @_;
3672 if ($diffinfo->{'nparents'}) {
3674 $from->{'file'} = [];
3675 $from->{'href'} = [];
3676 fill_from_file_info
($diffinfo, @parents)
3677 unless exists $diffinfo->{'from_file'};
3678 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3679 $from->{'file'}[$i] =
3680 defined $diffinfo->{'from_file'}[$i] ?
3681 $diffinfo->{'from_file'}[$i] :
3682 $diffinfo->{'to_file'};
3683 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3684 $from->{'href'}[$i] = href
(action
=>"blob",
3685 hash_base
=>$parents[$i],
3686 hash
=>$diffinfo->{'from_id'}[$i],
3687 file_name
=>$from->{'file'}[$i]);
3689 $from->{'href'}[$i] = undef;
3693 # ordinary (not combined) diff
3694 $from->{'file'} = $diffinfo->{'from_file'};
3695 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3696 $from->{'href'} = href
(action
=>"blob", hash_base
=>$hash_parent,
3697 hash
=>$diffinfo->{'from_id'},
3698 file_name
=>$from->{'file'});
3700 delete $from->{'href'};
3704 $to->{'file'} = $diffinfo->{'to_file'};
3705 if (!is_deleted
($diffinfo)) { # file exists in result
3706 $to->{'href'} = href
(action
=>"blob", hash_base
=>$hash,
3707 hash
=>$diffinfo->{'to_id'},
3708 file_name
=>$to->{'file'});
3710 delete $to->{'href'};
3714 ## ......................................................................
3715 ## parse to array of hashes functions
3717 sub git_get_heads_list
{
3718 my ($limit, @classes) = @_;
3719 @classes = get_branch_refs
() unless @classes;
3720 my @patterns = map { "refs/$_" } @classes;
3723 open my $fd, '-|', git_cmd
(), 'for-each-ref',
3724 ($limit ?
'--count='.($limit+1) : ()), '--sort=-committerdate',
3725 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3728 while (my $line = <$fd>) {
3732 my ($refinfo, $committerinfo) = split(/\0/, $line);
3733 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3734 my ($committer, $epoch, $tz) =
3735 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3736 $ref_item{'fullname'} = $name;
3737 my $strip_refs = join '|', map { quotemeta } get_branch_refs
();
3738 $name =~ s!^refs/($strip_refs|remotes)/!!;
3739 $ref_item{'name'} = $name;
3740 # for refs neither in 'heads' nor 'remotes' we want to
3741 # show their ref dir
3742 my $ref_dir = (defined $1) ?
$1 : '';
3743 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3744 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3747 $ref_item{'id'} = $hash;
3748 $ref_item{'title'} = $title || '(no commit message)';
3749 $ref_item{'epoch'} = $epoch;
3751 $ref_item{'age'} = age_string
(time - $ref_item{'epoch'});
3753 $ref_item{'age'} = "unknown";
3756 push @headslist, \
%ref_item;
3760 return wantarray ?
@headslist : \
@headslist;
3763 sub git_get_tags_list
{
3767 open my $fd, '-|', git_cmd
(), 'for-each-ref',
3768 ($limit ?
'--count='.($limit+1) : ()), '--sort=-creatordate',
3769 '--format=%(objectname) %(objecttype) %(refname) '.
3770 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3773 while (my $line = <$fd>) {
3777 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3778 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3779 my ($creator, $epoch, $tz) =
3780 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3781 $ref_item{'fullname'} = $name;
3782 $name =~ s!^refs/tags/!!;
3784 $ref_item{'type'} = $type;
3785 $ref_item{'id'} = $id;
3786 $ref_item{'name'} = $name;
3787 if ($type eq "tag") {
3788 $ref_item{'subject'} = $title;
3789 $ref_item{'reftype'} = $reftype;
3790 $ref_item{'refid'} = $refid;
3792 $ref_item{'reftype'} = $type;
3793 $ref_item{'refid'} = $id;
3796 if ($type eq "tag" || $type eq "commit") {
3797 $ref_item{'epoch'} = $epoch;
3799 $ref_item{'age'} = age_string
(time - $ref_item{'epoch'});
3801 $ref_item{'age'} = "unknown";
3805 push @tagslist, \
%ref_item;
3809 return wantarray ?
@tagslist : \
@tagslist;
3812 ## ----------------------------------------------------------------------
3813 ## filesystem-related functions
3815 sub get_file_owner
{
3818 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3819 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3820 if (!defined $gcos) {
3824 $owner =~ s/[,;].*$//;
3825 return to_utf8
($owner);
3828 # assume that file exists
3830 my $filename = shift;
3832 open my $fd, '<', $filename;
3833 print map { to_utf8
($_) } <$fd>;
3837 ## ......................................................................
3838 ## mimetype related functions
3840 sub mimetype_guess_file
{
3841 my $filename = shift;
3842 my $mimemap = shift;
3843 -r
$mimemap or return undef;
3846 open(my $mh, '<', $mimemap) or return undef;
3848 next if m/^#/; # skip comments
3849 my ($mimetype, @exts) = split(/\s+/);
3850 foreach my $ext (@exts) {
3851 $mimemap{$ext} = $mimetype;
3856 $filename =~ /\.([^.]*)$/;
3857 return $mimemap{$1};
3860 sub mimetype_guess
{
3861 my $filename = shift;
3863 $filename =~ /\./ or return undef;
3865 if ($mimetypes_file) {
3866 my $file = $mimetypes_file;
3867 if ($file !~ m!^/!) { # if it is relative path
3868 # it is relative to project
3869 $file = "$projectroot/$project/$file";
3871 $mime = mimetype_guess_file
($filename, $file);
3873 $mime ||= mimetype_guess_file
($filename, '/etc/mime.types');
3879 my $filename = shift;
3882 my $mime = mimetype_guess
($filename);
3883 $mime and return $mime;
3887 return $default_blob_plain_mimetype unless $fd;
3890 return 'text/plain';
3891 } elsif (! $filename) {
3892 return 'application/octet-stream';
3893 } elsif ($filename =~ m/\.png$/i) {
3895 } elsif ($filename =~ m/\.gif$/i) {
3897 } elsif ($filename =~ m/\.jpe?g$/i) {
3898 return 'image/jpeg';
3900 return 'application/octet-stream';
3904 sub blob_contenttype
{
3905 my ($fd, $file_name, $type) = @_;
3907 $type ||= blob_mimetype
($fd, $file_name);
3908 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3909 $type .= "; charset=$default_text_plain_charset";
3915 # guess file syntax for syntax highlighting; return undef if no highlighting
3916 # the name of syntax can (in the future) depend on syntax highlighter used
3917 sub guess_file_syntax
{
3918 my ($highlight, $mimetype, $file_name) = @_;
3919 return undef unless ($highlight && defined $file_name);
3920 my $basename = basename
($file_name, '.in');
3921 return $highlight_basename{$basename}
3922 if exists $highlight_basename{$basename};
3924 $basename =~ /\.([^.]*)$/;
3925 my $ext = $1 or return undef;
3926 return $highlight_ext{$ext}
3927 if exists $highlight_ext{$ext};
3932 # run highlighter and return FD of its output,
3933 # or return original FD if no highlighting
3934 sub run_highlighter
{
3935 my ($fd, $highlight, $syntax) = @_;
3936 return $fd unless ($highlight && (defined $syntax || $highlight_force));
3939 my $syntax_arg = "--syntax $syntax";
3940 if ($highlight_force) {
3941 $syntax_arg = "--force"
3943 open $fd, quote_command
(git_cmd
(), "cat-file", "blob", $hash)." | ".
3944 quote_command
($^X
, '-CO', '-MEncode=decode,FB_DEFAULT', '-pse',
3945 '$_ = decode($fe, $_, FB_DEFAULT) if !utf8::decode($_);',
3946 '--', "-fe=$fallback_encoding")." | ".
3947 quote_command
($highlight_bin).
3948 " --replace-tabs=8 --fragment $syntax_arg |"
3949 or die_error
(500, "Couldn't open file or run syntax highlighter");
3953 ## ======================================================================
3954 ## functions printing HTML: header, footer, error page
3956 sub get_page_title
{
3957 my $title = to_utf8
($site_name);
3959 unless (defined $project) {
3960 if (defined $project_filter) {
3961 $title .= " - projects in '" . esc_path
($project_filter) . "'";
3965 $title .= " - " . to_utf8
($project);
3967 return $title unless (defined $action);
3968 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3970 return $title unless (defined $file_name);
3971 $title .= " - " . esc_path
($file_name);
3972 if ($action eq "tree" && $file_name !~ m
|/$|) {
3979 sub get_content_type_html
{
3980 # require explicit support from the UA if we are to send the page as
3981 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3982 # we have to do this because MSIE sometimes globs '*/*', pretending to
3983 # support xhtml+xml but choking when it gets what it asked for.
3984 if (defined $cgi->http('HTTP_ACCEPT') &&
3985 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\
+xml
(,|;|\s
|$)/ &&
3986 $cgi->Accept('application/xhtml+xml') != 0) {
3987 return 'application/xhtml+xml';
3993 sub print_feed_meta
{
3994 if (defined $project) {
3995 my %href_params = get_feed_info
();
3996 if (!exists $href_params{'-title'}) {
3997 $href_params{'-title'} = 'log';
4000 foreach my $format (qw(RSS Atom)) {
4001 my $type = lc($format);
4003 '-rel' => 'alternate',
4004 '-title' => esc_attr
("$project - $href_params{'-title'} - $format feed"),
4005 '-type' => "application/$type+xml"
4008 $href_params{'extra_options'} = undef;
4009 $href_params{'action'} = $type;
4010 $link_attr{'-href'} = href
(%href_params);
4012 "rel=\"$link_attr{'-rel'}\" ".
4013 "title=\"$link_attr{'-title'}\" ".
4014 "href=\"$link_attr{'-href'}\" ".
4015 "type=\"$link_attr{'-type'}\" ".
4018 $href_params{'extra_options'} = '--no-merges';
4019 $link_attr{'-href'} = href
(%href_params);
4020 $link_attr{'-title'} .= ' (no merges)';
4022 "rel=\"$link_attr{'-rel'}\" ".
4023 "title=\"$link_attr{'-title'}\" ".
4024 "href=\"$link_attr{'-href'}\" ".
4025 "type=\"$link_attr{'-type'}\" ".
4030 printf('<link rel="alternate" title="%s projects list" '.
4031 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4032 esc_attr
($site_name), href
(project
=>undef, action
=>"project_index"));
4033 printf('<link rel="alternate" title="%s projects feeds" '.
4034 'href="%s" type="text/x-opml" />'."\n",
4035 esc_attr
($site_name), href
(project
=>undef, action
=>"opml"));
4039 sub print_header_links
{
4042 # print out each stylesheet that exist, providing backwards capability
4043 # for those people who defined $stylesheet in a config file
4044 if (defined $stylesheet) {
4045 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
4047 foreach my $stylesheet (@stylesheets) {
4048 next unless $stylesheet;
4049 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
4053 if ($status eq '200 OK');
4054 if (defined $favicon) {
4055 print qq(<link rel
="shortcut icon" href
=").esc_url($favicon).qq(" type
="image/png" />\n);
4059 sub print_nav_breadcrumbs_path
{
4060 my $dirprefix = undef;
4061 while (my $part = shift) {
4062 $dirprefix .= "/" if defined $dirprefix;
4063 $dirprefix .= $part;
4064 print $cgi->a({-href
=> href
(project
=> undef,
4065 project_filter
=> $dirprefix,
4066 action
=> "project_list")},
4067 esc_html
($part)) . " / ";
4071 sub print_nav_breadcrumbs
{
4074 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4075 print $cgi->a({-href
=> esc_url
($crumb->[1])}, $crumb->[0]) . " / ";
4077 if (defined $project) {
4078 my @dirname = split '/', $project;
4079 my $projectbasename = pop @dirname;
4080 print_nav_breadcrumbs_path
(@dirname);
4081 print $cgi->a({-href
=> href
(action
=>"summary")}, esc_html
($projectbasename));
4082 if (defined $action) {
4083 my $action_print = $action ;
4084 if (defined $opts{-action_extra
}) {
4085 $action_print = $cgi->a({-href
=> href
(action
=>$action)},
4088 print " / $action_print";
4090 if (defined $opts{-action_extra
}) {
4091 print " / $opts{-action_extra}";
4094 } elsif (defined $project_filter) {
4095 print_nav_breadcrumbs_path
(split '/', $project_filter);
4099 sub print_search_form
{
4100 if (!defined $searchtext) {
4104 if (defined $hash_base) {
4105 $search_hash = $hash_base;
4106 } elsif (defined $hash) {
4107 $search_hash = $hash;
4109 $search_hash = "HEAD";
4111 my $action = $my_uri;
4112 my $use_pathinfo = gitweb_check_feature
('pathinfo');
4113 if ($use_pathinfo) {
4114 $action .= "/".esc_url
($project);
4116 print $cgi->start_form(-method
=> "get", -action
=> $action) .
4117 "<div class=\"search\">\n" .
4119 $cgi->input({-name
=>"p", -value
=>$project, -type
=>"hidden"}) . "\n") .
4120 $cgi->input({-name
=>"a", -value
=>"search", -type
=>"hidden"}) . "\n" .
4121 $cgi->input({-name
=>"h", -value
=>$search_hash, -type
=>"hidden"}) . "\n" .
4122 $cgi->popup_menu(-name
=> 'st', -default => 'commit',
4123 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4124 " " . $cgi->a({-href
=> href
(action
=>"search_help"),
4125 -title
=> "search help" }, "?") . " search:\n",
4126 $cgi->textfield(-name
=> "s", -value
=> $searchtext, -override
=> 1) . "\n" .
4127 "<span title=\"Extended regular expression\">" .
4128 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
4129 -checked
=> $search_use_regexp) .
4132 $cgi->end_form() . "\n";
4135 sub git_header_html
{
4136 my $status = shift || "200 OK";
4137 my $expires = shift;
4140 my $title = get_page_title
();
4141 my $content_type = get_content_type_html
();
4142 print $cgi->header(-type
=>$content_type, -charset
=> 'utf-8',
4143 -status
=> $status, -expires
=> $expires)
4144 unless ($opts{'-no_http_header'});
4145 my $mod_perl_version = $ENV{'MOD_PERL'} ?
" $ENV{'MOD_PERL'}" : '';
4147 <?xml version="1.0" encoding="utf-8"?>
4148 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4149 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4150 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4151 <!-- git core binaries version $git_version -->
4153 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4154 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4155 <meta name="robots" content="index, nofollow"/>
4156 <title>$title</title>
4158 # the stylesheet, favicon etc urls won't work correctly with path_info
4159 # unless we set the appropriate base URL
4160 if ($ENV{'PATH_INFO'}) {
4161 print "<base href=\"".esc_url
($base_url)."\" />\n";
4163 print_header_links
($status);
4165 if (defined $site_html_head_string) {
4166 print to_utf8
($site_html_head_string);
4172 if (defined $site_header && -f
$site_header) {
4173 insert_file
($site_header);
4176 print "<div class=\"page_header\">\n";
4177 if (defined $logo) {
4178 print $cgi->a({-href
=> esc_url
($logo_url),
4179 -title
=> $logo_label},
4180 $cgi->img({-src
=> esc_url
($logo),
4181 -width
=> 72, -height
=> 27,
4183 -class => "logo"}));
4185 print_nav_breadcrumbs
(%opts);
4188 my $have_search = gitweb_check_feature
('search');
4189 if (defined $project && $have_search) {
4190 print_search_form
();
4194 sub git_footer_html
{
4195 my $feed_class = 'rss_logo';
4197 print "<div class=\"page_footer\">\n";
4198 if (defined $project) {
4199 my $descr = git_get_project_description
($project);
4200 if (defined $descr) {
4201 print "<div class=\"page_footer_text\">" . esc_html
($descr) . "</div>\n";
4204 my %href_params = get_feed_info
();
4205 if (!%href_params) {
4206 $feed_class .= ' generic';
4208 $href_params{'-title'} ||= 'log';
4210 foreach my $format (qw(RSS Atom)) {
4211 $href_params{'action'} = lc($format);
4212 print $cgi->a({-href
=> href
(%href_params),
4213 -title
=> "$href_params{'-title'} $format feed",
4214 -class => $feed_class}, $format)."\n";
4218 print $cgi->a({-href
=> href
(project
=>undef, action
=>"opml",
4219 project_filter
=> $project_filter),
4220 -class => $feed_class}, "OPML") . " ";
4221 print $cgi->a({-href
=> href
(project
=>undef, action
=>"project_index",
4222 project_filter
=> $project_filter),
4223 -class => $feed_class}, "TXT") . "\n";
4225 print "</div>\n"; # class="page_footer"
4227 if (defined $t0 && gitweb_check_feature
('timed')) {
4228 print "<div id=\"generating_info\">\n";
4229 print 'This page took '.
4230 '<span id="generating_time" class="time_span">'.
4231 tv_interval
($t0, [ gettimeofday
() ]).
4234 '<span id="generating_cmd">'.
4235 $number_of_git_cmds.
4236 '</span> git commands '.
4238 print "</div>\n"; # class="page_footer"
4241 if (defined $site_footer && -f
$site_footer) {
4242 insert_file
($site_footer);
4245 print qq!<script type
="text/javascript" src
="!.esc_url($javascript).qq!"></script
>\n!;
4246 if (defined $action &&
4247 $action eq 'blame_incremental') {
4248 print qq!<script type
="text/javascript">\n!.
4249 qq!startBlame
("!. href(action=>"blame_data
", -replay=>1) .qq!",\n!.
4250 qq! "!. href() .qq!");\n!.
4253 my ($jstimezone, $tz_cookie, $datetime_class) =
4254 gitweb_get_feature
('javascript-timezone');
4256 print qq!<script type
="text/javascript">\n!.
4257 qq!window
.onload
= function
() {\n!;
4258 if (gitweb_check_feature
('javascript-actions')) {
4259 print qq! fixLinks
();\n!;
4261 if ($jstimezone && $tz_cookie && $datetime_class) {
4262 print qq! var tz_cookie
= { name
: '$tz_cookie', expires
: 14, path
: '/' };\n!. # in days
4263 qq! onloadTZSetup
('$jstimezone', tz_cookie
, '$datetime_class');\n!;
4273 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4274 # Example: die_error(404, 'Hash not found')
4275 # By convention, use the following status codes (as defined in RFC 2616):
4276 # 400: Invalid or missing CGI parameters, or
4277 # requested object exists but has wrong type.
4278 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4279 # this server or project.
4280 # 404: Requested object/revision/project doesn't exist.
4281 # 500: The server isn't configured properly, or
4282 # an internal error occurred (e.g. failed assertions caused by bugs), or
4283 # an unknown error occurred (e.g. the git binary died unexpectedly).
4284 # 503: The server is currently unavailable (because it is overloaded,
4285 # or down for maintenance). Generally, this is a temporary state.
4287 my $status = shift || 500;
4288 my $error = esc_html
(shift) || "Internal Server Error";
4292 my %http_responses = (
4293 400 => '400 Bad Request',
4294 403 => '403 Forbidden',
4295 404 => '404 Not Found',
4296 500 => '500 Internal Server Error',
4297 503 => '503 Service Unavailable',
4299 git_header_html
($http_responses{$status}, undef, %opts);
4301 <div class="page_body">
4306 if (defined $extra) {
4314 unless ($opts{'-error_handler'});
4317 ## ----------------------------------------------------------------------
4318 ## functions printing or outputting HTML: navigation
4320 sub git_print_page_nav
{
4321 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4322 $extra = '' if !defined $extra; # pager or formats
4324 my @navs = qw(summary shortlog log commit commitdiff tree);
4326 @navs = grep { $_ ne $suppress } @navs;
4329 my %arg = map { $_ => {action
=>$_} } @navs;
4330 if (defined $head) {
4331 for (qw(commit commitdiff)) {
4332 $arg{$_}{'hash'} = $head;
4334 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4335 for (qw(shortlog log)) {
4336 $arg{$_}{'hash'} = $head;
4341 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4342 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4344 my @actions = gitweb_get_feature
('actions');
4347 'n' => $project, # project name
4348 'f' => $git_dir, # project path within filesystem
4349 'h' => $treehead || '', # current hash ('h' parameter)
4350 'b' => $treebase || '', # hash base ('hb' parameter)
4353 my ($label, $link, $pos) = splice(@actions,0,3);
4355 @navs = map { $_ eq $pos ?
($_, $label) : $_ } @navs;
4357 $link =~ s/%([%nfhb])/$repl{$1}/g;
4358 $arg{$label}{'_href'} = $link;
4361 print "<div class=\"page_nav\">\n" .
4363 map { $_ eq $current ?
4364 $_ : $cgi->a({-href
=> ($arg{$_}{_href
} ?
$arg{$_}{_href
} : href
(%{$arg{$_}}))}, "$_")
4366 print "<br/>\n$extra<br/>\n" .
4370 # returns a submenu for the nagivation of the refs views (tags, heads,
4371 # remotes) with the current view disabled and the remotes view only
4372 # available if the feature is enabled
4373 sub format_ref_views
{
4375 my @ref_views = qw{tags heads
};
4376 push @ref_views, 'remotes' if gitweb_check_feature
('remote_heads');
4377 return join " | ", map {
4378 $_ eq $current ?
$_ :
4379 $cgi->a({-href
=> href
(action
=>$_)}, $_)
4383 sub format_paging_nav
{
4384 my ($action, $page, $has_next_link) = @_;
4390 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)}, "first") .
4392 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
4393 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
4395 $paging_nav .= "first ⋅ prev";
4398 if ($has_next_link) {
4399 $paging_nav .= " ⋅ " .
4400 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
4401 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
4403 $paging_nav .= " ⋅ next";
4409 ## ......................................................................
4410 ## functions printing or outputting HTML: div
4412 sub git_print_header_div
{
4413 my ($action, $title, $hash, $hash_base) = @_;
4416 $args{'action'} = $action;
4417 $args{'hash'} = $hash if $hash;
4418 $args{'hash_base'} = $hash_base if $hash_base;
4420 print "<div class=\"header\">\n" .
4421 $cgi->a({-href
=> href
(%args), -class => "title"},
4422 $title ?
$title : $action) .
4426 sub format_repo_url
{
4427 my ($name, $url) = @_;
4428 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4431 # Group output by placing it in a DIV element and adding a header.
4432 # Options for start_div() can be provided by passing a hash reference as the
4433 # first parameter to the function.
4434 # Options to git_print_header_div() can be provided by passing an array
4435 # reference. This must follow the options to start_div if they are present.
4436 # The content can be a scalar, which is output as-is, a scalar reference, which
4437 # is output after html escaping, an IO handle passed either as *handle or
4438 # *handle{IO}, or a function reference. In the latter case all following
4439 # parameters will be taken as argument to the content function call.
4440 sub git_print_section
{
4441 my ($div_args, $header_args, $content);
4443 if (ref($arg) eq 'HASH') {
4447 if (ref($arg) eq 'ARRAY') {
4448 $header_args = $arg;
4453 print $cgi->start_div($div_args);
4454 git_print_header_div
(@
$header_args);
4456 if (ref($content) eq 'CODE') {
4458 } elsif (ref($content) eq 'SCALAR') {
4459 print esc_html
($$content);
4460 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4462 } elsif (!ref($content) && defined($content)) {
4466 print $cgi->end_div;
4469 sub format_timestamp_html
{
4471 my $strtime = $date->{'rfc2822'};
4473 my (undef, undef, $datetime_class) =
4474 gitweb_get_feature
('javascript-timezone');
4475 if ($datetime_class) {
4476 $strtime = qq!<span
class="$datetime_class">$strtime</span
>!;
4479 my $localtime_format = '(%02d:%02d %s)';
4480 if ($date->{'hour_local'} < 6) {
4481 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4484 sprintf($localtime_format,
4485 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4490 # Outputs the author name and date in long form
4491 sub git_print_authorship
{
4494 my $tag = $opts{-tag
} || 'div';
4495 my $author = $co->{'author_name'};
4497 my %ad = parse_date
($co->{'author_epoch'}, $co->{'author_tz'});
4498 print "<$tag class=\"author_date\">" .
4499 format_search_author
($author, "author", esc_html
($author)) .
4500 " [".format_timestamp_html
(\
%ad)."]".
4501 git_get_avatar
($co->{'author_email'}, -pad_before
=> 1) .
4505 # Outputs table rows containing the full author or committer information,
4506 # in the format expected for 'commit' view (& similar).
4507 # Parameters are a commit hash reference, followed by the list of people
4508 # to output information for. If the list is empty it defaults to both
4509 # author and committer.
4510 sub git_print_authorship_rows
{
4512 # too bad we can't use @people = @_ || ('author', 'committer')
4514 @people = ('author', 'committer') unless @people;
4515 foreach my $who (@people) {
4516 my %wd = parse_date
($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4517 print "<tr><td>$who</td><td>" .
4518 format_search_author
($co->{"${who}_name"}, $who,
4519 esc_html
($co->{"${who}_name"})) . " " .
4520 format_search_author
($co->{"${who}_email"}, $who,
4521 esc_html
("<" . $co->{"${who}_email"} . ">")) .
4522 "</td><td rowspan=\"2\">" .
4523 git_get_avatar
($co->{"${who}_email"}, -size
=> 'double') .
4527 format_timestamp_html
(\
%wd) .
4533 sub git_print_page_path
{
4539 print "<div class=\"page_path\">";
4540 print $cgi->a({-href
=> href
(action
=>"tree", hash_base
=>$hb),
4541 -title
=> 'tree root'}, to_utf8
("[$project]"));
4543 if (defined $name) {
4544 my @dirname = split '/', $name;
4545 my $basename = pop @dirname;
4548 foreach my $dir (@dirname) {
4549 $fullname .= ($fullname ?
'/' : '') . $dir;
4550 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$fullname,
4552 -title
=> $fullname}, esc_path
($dir));
4555 if (defined $type && $type eq 'blob') {
4556 print $cgi->a({-href
=> href
(action
=>"blob_plain", file_name
=>$file_name,
4558 -title
=> $name}, esc_path
($basename));
4559 } elsif (defined $type && $type eq 'tree') {
4560 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$file_name,
4562 -title
=> $name}, esc_path
($basename));
4565 print esc_path
($basename);
4568 print "<br/></div>\n";
4575 if ($opts{'-remove_title'}) {
4576 # remove title, i.e. first line of log
4579 # remove leading empty lines
4580 while (defined $log->[0] && $log->[0] eq "") {
4585 my $skip_blank_line = 0;
4586 foreach my $line (@
$log) {
4587 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4588 if (! $opts{'-remove_signoff'}) {
4589 print "<span class=\"signoff\">" . esc_html
($line) . "</span><br/>\n";
4590 $skip_blank_line = 1;
4595 if ($line =~ m
,\s
*([a
-z
]*link): (https?
://\S
+),i
) {
4596 if (! $opts{'-remove_signoff'}) {
4597 print "<span class=\"signoff\">" . esc_html
($1) . ": " .
4598 "<a href=\"" . esc_html
($2) . "\">" . esc_html
($2) . "</a>" .
4600 $skip_blank_line = 1;
4605 # print only one empty line
4606 # do not print empty line after signoff
4608 next if ($skip_blank_line);
4609 $skip_blank_line = 1;
4611 $skip_blank_line = 0;
4614 print format_log_line_html
($line) . "<br/>\n";
4617 if ($opts{'-final_empty_line'}) {
4618 # end with single empty line
4619 print "<br/>\n" unless $skip_blank_line;
4623 # return link target (what link points to)
4624 sub git_get_link_target
{
4629 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
4633 $link_target = <$fd>;
4638 return $link_target;
4641 # given link target, and the directory (basedir) the link is in,
4642 # return target of link relative to top directory (top tree);
4643 # return undef if it is not possible (including absolute links).
4644 sub normalize_link_target
{
4645 my ($link_target, $basedir) = @_;
4647 # absolute symlinks (beginning with '/') cannot be normalized
4648 return if (substr($link_target, 0, 1) eq '/');
4650 # normalize link target to path from top (root) tree (dir)
4653 $path = $basedir . '/' . $link_target;
4655 # we are in top (root) tree (dir)
4656 $path = $link_target;
4659 # remove //, /./, and /../
4661 foreach my $part (split('/', $path)) {
4662 # discard '.' and ''
4663 next if (!$part || $part eq '.');
4665 if ($part eq '..') {
4669 # link leads outside repository (outside top dir)
4673 push @path_parts, $part;
4676 $path = join('/', @path_parts);
4681 # print tree entry (row of git_tree), but without encompassing <tr> element
4682 sub git_print_tree_entry
{
4683 my ($t, $basedir, $hash_base, $have_blame) = @_;
4686 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4688 # The format of a table row is: mode list link. Where mode is
4689 # the mode of the entry, list is the name of the entry, an href,
4690 # and link is the action links of the entry.
4692 print "<td class=\"mode\">" . mode_str
($t->{'mode'}) . "</td>\n";
4693 if (exists $t->{'size'}) {
4694 print "<td class=\"size\">$t->{'size'}</td>\n";
4696 if ($t->{'type'} eq "blob") {
4697 print "<td class=\"list\">" .
4698 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4699 file_name
=>"$basedir$t->{'name'}", %base_key),
4700 -class => "list"}, esc_path
($t->{'name'}));
4701 if (S_ISLNK
(oct $t->{'mode'})) {
4702 my $link_target = git_get_link_target
($t->{'hash'});
4704 my $norm_target = normalize_link_target
($link_target, $basedir);
4705 if (defined $norm_target) {
4707 $cgi->a({-href
=> href
(action
=>"object", hash_base
=>$hash_base,
4708 file_name
=>$norm_target),
4709 -title
=> $norm_target}, esc_path
($link_target));
4711 print " -> " . esc_path
($link_target);
4716 print "<td class=\"link\">";
4717 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4718 file_name
=>"$basedir$t->{'name'}", %base_key)},
4722 $cgi->a({-href
=> href
(action
=>"blame", hash
=>$t->{'hash'},
4723 file_name
=>"$basedir$t->{'name'}", %base_key)},
4726 if (defined $hash_base) {
4728 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4729 hash
=>$t->{'hash'}, file_name
=>"$basedir$t->{'name'}")},
4733 $cgi->a({-href
=> href
(action
=>"blob_plain", hash_base
=>$hash_base,
4734 file_name
=>"$basedir$t->{'name'}")},
4738 } elsif ($t->{'type'} eq "tree") {
4739 print "<td class=\"list\">";
4740 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4741 file_name
=>"$basedir$t->{'name'}",
4743 esc_path
($t->{'name'}));
4745 print "<td class=\"link\">";
4746 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4747 file_name
=>"$basedir$t->{'name'}",
4750 if (defined $hash_base) {
4752 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4753 file_name
=>"$basedir$t->{'name'}")},
4758 # unknown object: we can only present history for it
4759 # (this includes 'commit' object, i.e. submodule support)
4760 print "<td class=\"list\">" .
4761 esc_path
($t->{'name'}) .
4763 print "<td class=\"link\">";
4764 if (defined $hash_base) {
4765 print $cgi->a({-href
=> href
(action
=>"history",
4766 hash_base
=>$hash_base,
4767 file_name
=>"$basedir$t->{'name'}")},
4774 ## ......................................................................
4775 ## functions printing large fragments of HTML
4777 # get pre-image filenames for merge (combined) diff
4778 sub fill_from_file_info
{
4779 my ($diff, @parents) = @_;
4781 $diff->{'from_file'} = [ ];
4782 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4783 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4784 if ($diff->{'status'}[$i] eq 'R' ||
4785 $diff->{'status'}[$i] eq 'C') {
4786 $diff->{'from_file'}[$i] =
4787 git_get_path_by_hash
($parents[$i], $diff->{'from_id'}[$i]);
4794 # is current raw difftree line of file deletion
4796 my $diffinfo = shift;
4798 return $diffinfo->{'to_id'} eq ('0' x
40);
4801 # does patch correspond to [previous] difftree raw line
4802 # $diffinfo - hashref of parsed raw diff format
4803 # $patchinfo - hashref of parsed patch diff format
4804 # (the same keys as in $diffinfo)
4805 sub is_patch_split
{
4806 my ($diffinfo, $patchinfo) = @_;
4808 return defined $diffinfo && defined $patchinfo
4809 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4813 sub git_difftree_body
{
4814 my ($difftree, $hash, @parents) = @_;
4815 my ($parent) = $parents[0];
4816 my $have_blame = gitweb_check_feature
('blame');
4817 print "<div class=\"list_head\">\n";
4818 if ($#{$difftree} > 10) {
4819 print(($#{$difftree} + 1) . " files changed:\n");
4823 print "<table class=\"" .
4824 (@parents > 1 ?
"combined " : "") .
4827 # header only for combined diff in 'commitdiff' view
4828 my $has_header = @
$difftree && @parents > 1 && $action eq 'commitdiff';
4831 print "<thead><tr>\n" .
4832 "<th></th><th></th>\n"; # filename, patchN link
4833 for (my $i = 0; $i < @parents; $i++) {
4834 my $par = $parents[$i];
4836 $cgi->a({-href
=> href
(action
=>"commitdiff",
4837 hash
=>$hash, hash_parent
=>$par),
4838 -title
=> 'commitdiff to parent number ' .
4839 ($i+1) . ': ' . substr($par,0,7)},
4843 print "</tr></thead>\n<tbody>\n";
4848 foreach my $line (@
{$difftree}) {
4849 my $diff = parsed_difftree_line
($line);
4852 print "<tr class=\"dark\">\n";
4854 print "<tr class=\"light\">\n";
4858 if (exists $diff->{'nparents'}) { # combined diff
4860 fill_from_file_info
($diff, @parents)
4861 unless exists $diff->{'from_file'};
4863 if (!is_deleted
($diff)) {
4864 # file exists in the result (child) commit
4866 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4867 file_name
=>$diff->{'to_file'},
4869 -class => "list"}, esc_path
($diff->{'to_file'})) .
4873 esc_path
($diff->{'to_file'}) .
4877 if ($action eq 'commitdiff') {
4880 print "<td class=\"link\">" .
4881 $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4887 my $has_history = 0;
4888 my $not_deleted = 0;
4889 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4890 my $hash_parent = $parents[$i];
4891 my $from_hash = $diff->{'from_id'}[$i];
4892 my $from_path = $diff->{'from_file'}[$i];
4893 my $status = $diff->{'status'}[$i];
4895 $has_history ||= ($status ne 'A');
4896 $not_deleted ||= ($status ne 'D');
4898 if ($status eq 'A') {
4899 print "<td class=\"link\" align=\"right\"> | </td>\n";
4900 } elsif ($status eq 'D') {
4901 print "<td class=\"link\">" .
4902 $cgi->a({-href
=> href
(action
=>"blob",
4905 file_name
=>$from_path)},
4909 if ($diff->{'to_id'} eq $from_hash) {
4910 print "<td class=\"link nochange\">";
4912 print "<td class=\"link\">";
4914 print $cgi->a({-href
=> href
(action
=>"blobdiff",
4915 hash
=>$diff->{'to_id'},
4916 hash_parent
=>$from_hash,
4918 hash_parent_base
=>$hash_parent,
4919 file_name
=>$diff->{'to_file'},
4920 file_parent
=>$from_path)},
4926 print "<td class=\"link\">";
4928 print $cgi->a({-href
=> href
(action
=>"blob",
4929 hash
=>$diff->{'to_id'},
4930 file_name
=>$diff->{'to_file'},
4933 print " | " if ($has_history);
4936 print $cgi->a({-href
=> href
(action
=>"history",
4937 file_name
=>$diff->{'to_file'},
4944 next; # instead of 'else' clause, to avoid extra indent
4946 # else ordinary diff
4948 my ($to_mode_oct, $to_mode_str, $to_file_type);
4949 my ($from_mode_oct, $from_mode_str, $from_file_type);
4950 if ($diff->{'to_mode'} ne ('0' x
6)) {
4951 $to_mode_oct = oct $diff->{'to_mode'};
4952 if (S_ISREG
($to_mode_oct)) { # only for regular file
4953 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4955 $to_file_type = file_type
($diff->{'to_mode'});
4957 if ($diff->{'from_mode'} ne ('0' x
6)) {
4958 $from_mode_oct = oct $diff->{'from_mode'};
4959 if (S_ISREG
($from_mode_oct)) { # only for regular file
4960 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4962 $from_file_type = file_type
($diff->{'from_mode'});
4965 if ($diff->{'status'} eq "A") { # created
4966 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4967 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4968 $mode_chng .= "]</span>";
4970 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4971 hash_base
=>$hash, file_name
=>$diff->{'file'}),
4972 -class => "list"}, esc_path
($diff->{'file'}));
4974 print "<td>$mode_chng</td>\n";
4975 print "<td class=\"link\">";
4976 if ($action eq 'commitdiff') {
4979 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4983 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4984 hash_base
=>$hash, file_name
=>$diff->{'file'})},
4988 } elsif ($diff->{'status'} eq "D") { # deleted
4989 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4991 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
4992 hash_base
=>$parent, file_name
=>$diff->{'file'}),
4993 -class => "list"}, esc_path
($diff->{'file'}));
4995 print "<td>$mode_chng</td>\n";
4996 print "<td class=\"link\">";
4997 if ($action eq 'commitdiff') {
5000 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5004 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
5005 hash_base
=>$parent, file_name
=>$diff->{'file'})},
5008 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$parent,
5009 file_name
=>$diff->{'file'})},
5012 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$parent,
5013 file_name
=>$diff->{'file'})},
5017 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5018 my $mode_chnge = "";
5019 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5020 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5021 if ($from_file_type ne $to_file_type) {
5022 $mode_chnge .= " from $from_file_type to $to_file_type";
5024 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5025 if ($from_mode_str && $to_mode_str) {
5026 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5027 } elsif ($to_mode_str) {
5028 $mode_chnge .= " mode: $to_mode_str";
5031 $mode_chnge .= "]</span>\n";
5034 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5035 hash_base
=>$hash, file_name
=>$diff->{'file'}),
5036 -class => "list"}, esc_path
($diff->{'file'}));
5038 print "<td>$mode_chnge</td>\n";
5039 print "<td class=\"link\">";
5040 if ($action eq 'commitdiff') {
5043 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5046 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5047 # "commit" view and modified file (not onlu mode changed)
5048 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5049 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5050 hash_base
=>$hash, hash_parent_base
=>$parent,
5051 file_name
=>$diff->{'file'})},
5055 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5056 hash_base
=>$hash, file_name
=>$diff->{'file'})},
5059 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5060 file_name
=>$diff->{'file'})},
5063 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5064 file_name
=>$diff->{'file'})},
5068 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5069 my %status_name = ('R' => 'moved', 'C' => 'copied');
5070 my $nstatus = $status_name{$diff->{'status'}};
5072 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5073 # mode also for directories, so we cannot use $to_mode_str
5074 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5077 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$hash,
5078 hash
=>$diff->{'to_id'}, file_name
=>$diff->{'to_file'}),
5079 -class => "list"}, esc_path
($diff->{'to_file'})) . "</td>\n" .
5080 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5081 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$parent,
5082 hash
=>$diff->{'from_id'}, file_name
=>$diff->{'from_file'}),
5083 -class => "list"}, esc_path
($diff->{'from_file'})) .
5084 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5085 "<td class=\"link\">";
5086 if ($action eq 'commitdiff') {
5089 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5092 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5093 # "commit" view and modified file (not only pure rename or copy)
5094 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5095 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5096 hash_base
=>$hash, hash_parent_base
=>$parent,
5097 file_name
=>$diff->{'to_file'}, file_parent
=>$diff->{'from_file'})},
5101 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5102 hash_base
=>$parent, file_name
=>$diff->{'to_file'})},
5105 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5106 file_name
=>$diff->{'to_file'})},
5109 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5110 file_name
=>$diff->{'to_file'})},
5114 } # we should not encounter Unmerged (U) or Unknown (X) status
5117 print "</tbody>" if $has_header;
5121 # Print context lines and then rem/add lines in a side-by-side manner.
5122 sub print_sidebyside_diff_lines
{
5123 my ($ctx, $rem, $add) = @_;
5125 # print context block before add/rem block
5128 '<div class="chunk_block ctx">',
5129 '<div class="old">',
5132 '<div class="new">',
5141 '<div class="chunk_block rem">',
5142 '<div class="old">',
5149 '<div class="chunk_block add">',
5150 '<div class="new">',
5156 '<div class="chunk_block chg">',
5157 '<div class="old">',
5160 '<div class="new">',
5167 # Print context lines and then rem/add lines in inline manner.
5168 sub print_inline_diff_lines
{
5169 my ($ctx, $rem, $add) = @_;
5171 print @
$ctx, @
$rem, @
$add;
5174 # Format removed and added line, mark changed part and HTML-format them.
5175 # Implementation is based on contrib/diff-highlight
5176 sub format_rem_add_lines_pair
{
5177 my ($rem, $add, $num_parents) = @_;
5179 # We need to untabify lines before split()'ing them;
5180 # otherwise offsets would be invalid.
5183 $rem = untabify
($rem);
5184 $add = untabify
($add);
5186 my @rem = split(//, $rem);
5187 my @add = split(//, $add);
5188 my ($esc_rem, $esc_add);
5189 # Ignore leading +/- characters for each parent.
5190 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5191 my ($prefix_has_nonspace, $suffix_has_nonspace);
5193 my $shorter = (@rem < @add) ?
@rem : @add;
5194 while ($prefix_len < $shorter) {
5195 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5197 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5201 while ($prefix_len + $suffix_len < $shorter) {
5202 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5204 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5208 # Mark lines that are different from each other, but have some common
5209 # part that isn't whitespace. If lines are completely different, don't
5210 # mark them because that would make output unreadable, especially if
5211 # diff consists of multiple lines.
5212 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5213 $esc_rem = esc_html_hl_regions
($rem, 'marked',
5214 [$prefix_len, @rem - $suffix_len], -nbsp
=>1);
5215 $esc_add = esc_html_hl_regions
($add, 'marked',
5216 [$prefix_len, @add - $suffix_len], -nbsp
=>1);
5218 $esc_rem = esc_html
($rem, -nbsp
=>1);
5219 $esc_add = esc_html
($add, -nbsp
=>1);
5222 return format_diff_line
(\
$esc_rem, 'rem'),
5223 format_diff_line
(\
$esc_add, 'add');
5226 # HTML-format diff context, removed and added lines.
5227 sub format_ctx_rem_add_lines
{
5228 my ($ctx, $rem, $add, $num_parents) = @_;
5229 my (@new_ctx, @new_rem, @new_add);
5230 my $can_highlight = 0;
5231 my $is_combined = ($num_parents > 1);
5233 # Highlight if every removed line has a corresponding added line.
5234 if (@
$add > 0 && @
$add == @
$rem) {
5237 # Highlight lines in combined diff only if the chunk contains
5238 # diff between the same version, e.g.
5245 # Otherwise the highlightling would be confusing.
5247 for (my $i = 0; $i < @
$add; $i++) {
5248 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5249 my $prefix_add = substr($add->[$i], 0, $num_parents);
5251 $prefix_rem =~ s/-/+/g;
5253 if ($prefix_rem ne $prefix_add) {
5261 if ($can_highlight) {
5262 for (my $i = 0; $i < @
$add; $i++) {
5263 my ($line_rem, $line_add) = format_rem_add_lines_pair
(
5264 $rem->[$i], $add->[$i], $num_parents);
5265 push @new_rem, $line_rem;
5266 push @new_add, $line_add;
5269 @new_rem = map { format_diff_line
($_, 'rem') } @
$rem;
5270 @new_add = map { format_diff_line
($_, 'add') } @
$add;
5273 @new_ctx = map { format_diff_line
($_, 'ctx') } @
$ctx;
5275 return (\
@new_ctx, \
@new_rem, \
@new_add);
5278 # Print context lines and then rem/add lines.
5279 sub print_diff_lines
{
5280 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5281 my $is_combined = $num_parents > 1;
5283 ($ctx, $rem, $add) = format_ctx_rem_add_lines
($ctx, $rem, $add,
5286 if ($diff_style eq 'sidebyside' && !$is_combined) {
5287 print_sidebyside_diff_lines
($ctx, $rem, $add);
5289 # default 'inline' style and unknown styles
5290 print_inline_diff_lines
($ctx, $rem, $add);
5294 sub print_diff_chunk
{
5295 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5296 my (@ctx, @rem, @add);
5298 # The class of the previous line.
5299 my $prev_class = '';
5301 return unless @chunk;
5303 # incomplete last line might be among removed or added lines,
5304 # or both, or among context lines: find which
5305 for (my $i = 1; $i < @chunk; $i++) {
5306 if ($chunk[$i][0] eq 'incomplete') {
5307 $chunk[$i][0] = $chunk[$i-1][0];
5312 push @chunk, ["", ""];
5314 foreach my $line_info (@chunk) {
5315 my ($class, $line) = @
$line_info;
5317 # print chunk headers
5318 if ($class && $class eq 'chunk_header') {
5319 print format_diff_line
($line, $class, $from, $to);
5323 ## print from accumulator when have some add/rem lines or end
5324 # of chunk (flush context lines), or when have add and rem
5325 # lines and new block is reached (otherwise add/rem lines could
5327 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5328 (@rem && @add && $class ne $prev_class)) {
5329 print_diff_lines
(\
@ctx, \
@rem, \
@add,
5330 $diff_style, $num_parents);
5331 @ctx = @rem = @add = ();
5334 ## adding lines to accumulator
5337 # rem, add or change
5338 if ($class eq 'rem') {
5340 } elsif ($class eq 'add') {
5344 if ($class eq 'ctx') {
5348 $prev_class = $class;
5352 sub git_patchset_body
{
5353 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5354 my ($hash_parent) = $hash_parents[0];
5356 my $is_combined = (@hash_parents > 1);
5358 my $patch_number = 0;
5363 my @chunk; # for side-by-side diff
5365 print "<div class=\"patchset\">\n";
5367 # skip to first patch
5368 while ($patch_line = <$fd>) {
5371 last if ($patch_line =~ m/^diff /);
5375 while ($patch_line) {
5377 # parse "git diff" header line
5378 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5379 # $1 is from_name, which we do not use
5380 $to_name = unquote
($2);
5381 $to_name =~ s!^b/!!;
5382 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5383 # $1 is 'cc' or 'combined', which we do not use
5384 $to_name = unquote
($2);
5389 # check if current patch belong to current raw line
5390 # and parse raw git-diff line if needed
5391 if (is_patch_split
($diffinfo, { 'to_file' => $to_name })) {
5392 # this is continuation of a split patch
5393 print "<div class=\"patch cont\">\n";
5395 # advance raw git-diff output if needed
5396 $patch_idx++ if defined $diffinfo;
5398 # read and prepare patch information
5399 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5401 # compact combined diff output can have some patches skipped
5402 # find which patch (using pathname of result) we are at now;
5404 while ($to_name ne $diffinfo->{'to_file'}) {
5405 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5406 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5407 "</div>\n"; # class="patch"
5412 last if $patch_idx > $#$difftree;
5413 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5417 # modifies %from, %to hashes
5418 parse_from_to_diffinfo
($diffinfo, \
%from, \
%to, @hash_parents);
5420 # this is first patch for raw difftree line with $patch_idx index
5421 # we index @$difftree array from 0, but number patches from 1
5422 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5426 #assert($patch_line =~ m/^diff /) if DEBUG;
5427 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5429 # print "git diff" header
5430 print format_git_diff_header_line
($patch_line, $diffinfo,
5433 # print extended diff header
5434 print "<div class=\"diff extended_header\">\n";
5436 while ($patch_line = <$fd>) {
5439 last EXTENDED_HEADER
if ($patch_line =~ m/^--- |^diff /);
5441 print format_extended_diff_header_line
($patch_line, $diffinfo,
5444 print "</div>\n"; # class="diff extended_header"
5446 # from-file/to-file diff header
5447 if (! $patch_line) {
5448 print "</div>\n"; # class="patch"
5451 next PATCH
if ($patch_line =~ m/^diff /);
5452 #assert($patch_line =~ m/^---/) if DEBUG;
5454 my $last_patch_line = $patch_line;
5455 $patch_line = <$fd>;
5457 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5459 print format_diff_from_to_header
($last_patch_line, $patch_line,
5460 $diffinfo, \
%from, \
%to,
5465 while ($patch_line = <$fd>) {
5468 next PATCH
if ($patch_line =~ m/^diff /);
5470 my $class = diff_line_class
($patch_line, \
%from, \
%to);
5472 if ($class eq 'chunk_header') {
5473 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5477 push @chunk, [ $class, $patch_line ];
5482 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5485 print "</div>\n"; # class="patch"
5488 # for compact combined (--cc) format, with chunk and patch simplification
5489 # the patchset might be empty, but there might be unprocessed raw lines
5490 for (++$patch_idx if $patch_number > 0;
5491 $patch_idx < @
$difftree;
5493 # read and prepare patch information
5494 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5496 # generate anchor for "patch" links in difftree / whatchanged part
5497 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5498 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5499 "</div>\n"; # class="patch"
5504 if ($patch_number == 0) {
5505 if (@hash_parents > 1) {
5506 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5508 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5512 print "</div>\n"; # class="patchset"
5515 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5517 sub git_project_search_form
{
5518 my ($searchtext, $search_use_regexp) = @_;
5521 if ($project_filter) {
5522 $limit = " in '$project_filter/'";
5525 print "<div class=\"projsearch\">\n";
5526 print $cgi->start_form(-method
=> 'get', -action
=> $my_uri) .
5527 $cgi->hidden(-name
=> 'a', -value
=> 'project_list') . "\n";
5528 print $cgi->hidden(-name
=> 'pf', -value
=> $project_filter). "\n"
5529 if (defined $project_filter);
5530 print $cgi->textfield(-name
=> 's', -value
=> $searchtext,
5531 -title
=> "Search project by name and description$limit",
5532 -size
=> 60) . "\n" .
5533 "<span title=\"Extended regular expression\">" .
5534 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
5535 -checked
=> $search_use_regexp) .
5537 $cgi->submit(-name
=> 'btnS', -value
=> 'Search') .
5538 $cgi->end_form() . "\n" .
5539 $cgi->a({-href
=> href
(project
=> undef, searchtext
=> undef,
5540 project_filter
=> $project_filter)},
5541 esc_html
("List all projects$limit")) . "<br />\n";
5545 # entry for given @keys needs filling if at least one of keys in list
5546 # is not present in %$project_info
5547 sub project_info_needs_filling
{
5548 my ($project_info, @keys) = @_;
5550 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5551 foreach my $key (@keys) {
5552 if (!exists $project_info->{$key}) {
5559 # fills project list info (age, description, owner, category, forks, etc.)
5560 # for each project in the list, removing invalid projects from
5561 # returned list, or fill only specified info.
5563 # Invalid projects are removed from the returned list if and only if you
5564 # ask 'age' or 'age_string' to be filled, because they are the only fields
5565 # that run unconditionally git command that requires repository, and
5566 # therefore do always check if project repository is invalid.
5569 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5570 # ensures that 'descr_long' and 'ctags' fields are filled
5571 # * @project_list = fill_project_list_info(\@project_list)
5572 # ensures that all fields are filled (and invalid projects removed)
5574 # NOTE: modifies $projlist, but does not remove entries from it
5575 sub fill_project_list_info
{
5576 my ($projlist, @wanted_keys) = @_;
5578 my $filter_set = sub { return @_; };
5580 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5581 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5584 my $show_ctags = gitweb_check_feature
('ctags');
5586 foreach my $pr (@
$projlist) {
5587 if (project_info_needs_filling
($pr, $filter_set->('age', 'age_string'))) {
5588 my (@activity) = git_get_last_activity
($pr->{'path'});
5589 unless (@activity) {
5592 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5594 if (project_info_needs_filling
($pr, $filter_set->('descr', 'descr_long'))) {
5595 my $descr = git_get_project_description
($pr->{'path'}) || "";
5596 $descr = to_utf8
($descr);
5597 $pr->{'descr_long'} = $descr;
5598 $pr->{'descr'} = chop_str
($descr, $projects_list_description_width, 5);
5600 if (project_info_needs_filling
($pr, $filter_set->('owner'))) {
5601 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}") || "";
5604 project_info_needs_filling
($pr, $filter_set->('ctags'))) {
5605 $pr->{'ctags'} = git_get_project_ctags
($pr->{'path'});
5607 if ($projects_list_group_categories &&
5608 project_info_needs_filling
($pr, $filter_set->('category'))) {
5609 my $cat = git_get_project_category
($pr->{'path'}) ||
5610 $project_list_default_category;
5611 $pr->{'category'} = to_utf8
($cat);
5614 push @projects, $pr;
5620 sub sort_projects_list
{
5621 my ($projlist, $order) = @_;
5625 return sub { $a->{$key} cmp $b->{$key} };
5628 sub order_num_then_undef
{
5631 defined $a->{$key} ?
5632 (defined $b->{$key} ?
$a->{$key} <=> $b->{$key} : -1) :
5633 (defined $b->{$key} ?
1 : 0)
5638 project
=> order_str
('path'),
5639 descr
=> order_str
('descr_long'),
5640 owner
=> order_str
('owner'),
5641 age
=> order_num_then_undef
('age'),
5644 my $ordering = $orderings{$order};
5645 return defined $ordering ?
sort $ordering @
$projlist : @
$projlist;
5648 # returns a hash of categories, containing the list of project
5649 # belonging to each category
5650 sub build_projlist_by_category
{
5651 my ($projlist, $from, $to) = @_;
5654 $from = 0 unless defined $from;
5655 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5657 for (my $i = $from; $i <= $to; $i++) {
5658 my $pr = $projlist->[$i];
5659 push @
{$categories{ $pr->{'category'} }}, $pr;
5662 return wantarray ?
%categories : \
%categories;
5665 # print 'sort by' <th> element, generating 'sort by $name' replay link
5666 # if that order is not selected
5668 print format_sort_th
(@_);
5671 sub format_sort_th
{
5672 my ($name, $order, $header) = @_;
5674 $header ||= ucfirst($name);
5676 if ($order eq $name) {
5677 $sort_th .= "<th>$header</th>\n";
5679 $sort_th .= "<th>" .
5680 $cgi->a({-href
=> href
(-replay
=>1, order
=>$name),
5681 -class => "header"}, $header) .
5688 sub git_project_list_rows
{
5689 my ($projlist, $from, $to, $check_forks) = @_;
5691 $from = 0 unless defined $from;
5692 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5695 for (my $i = $from; $i <= $to; $i++) {
5696 my $pr = $projlist->[$i];
5699 print "<tr class=\"dark\">\n";
5701 print "<tr class=\"light\">\n";
5707 if ($pr->{'forks'}) {
5708 my $nforks = scalar @
{$pr->{'forks'}};
5710 print $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks"),
5711 -title
=> "$nforks forks"}, "+");
5713 print $cgi->span({-title
=> "$nforks forks"}, "+");
5718 print "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5720 esc_html_match_hl
($pr->{'path'}, $search_regexp)) .
5722 "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5724 -title
=> $pr->{'descr_long'}},
5726 ? esc_html_match_hl_chopped
($pr->{'descr_long'},
5727 $pr->{'descr'}, $search_regexp)
5728 : esc_html
($pr->{'descr'})) .
5730 unless ($omit_owner) {
5731 print "<td><i>" . chop_and_escape_str
($pr->{'owner'}, 15) . "</i></td>\n";
5733 unless ($omit_age_column) {
5734 print "<td class=\"". age_class
($pr->{'age'}) . "\">" .
5735 (defined $pr->{'age_string'} ?
$pr->{'age_string'} : "No commits") . "</td>\n";
5737 print"<td class=\"link\">" .
5738 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary")}, "summary") . " | " .
5739 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"shortlog")}, "shortlog") . " | " .
5740 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"log")}, "log") . " | " .
5741 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"tree")}, "tree") .
5742 ($pr->{'forks'} ?
" | " . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks")}, "forks") : '') .
5748 sub git_project_list_body
{
5749 # actually uses global variable $project
5750 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5751 my @projects = @
$projlist;
5753 my $check_forks = gitweb_check_feature
('forks');
5754 my $show_ctags = gitweb_check_feature
('ctags');
5755 my $tagfilter = $show_ctags ?
$input_params{'ctag'} : undef;
5756 $check_forks = undef
5757 if ($tagfilter || $search_regexp);
5759 # filtering out forks before filling info allows to do less work
5760 @projects = filter_forks_from_projects_list
(\
@projects)
5762 # search_projects_list pre-fills required info
5763 @projects = search_projects_list
(\
@projects,
5764 'search_regexp' => $search_regexp,
5765 'tagfilter' => $tagfilter)
5766 if ($tagfilter || $search_regexp);
5768 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5769 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5770 push @all_fields, 'owner' unless($omit_owner);
5771 @projects = fill_project_list_info
(\
@projects, @all_fields);
5773 $order ||= $default_projects_order;
5774 $from = 0 unless defined $from;
5775 $to = $#projects if (!defined $to || $#projects < $to);
5780 "<b>No such projects found</b><br />\n".
5781 "Click ".$cgi->a({-href
=>href
(project
=>undef)},"here")." to view all projects<br />\n".
5782 "</center>\n<br />\n";
5786 @projects = sort_projects_list
(\
@projects, $order);
5789 my $ctags = git_gather_all_ctags
(\
@projects);
5790 my $cloud = git_populate_project_tagcloud
($ctags);
5791 print git_show_project_tagcloud
($cloud, 64);
5794 print "<table class=\"project_list\">\n";
5795 unless ($no_header) {
5798 print "<th></th>\n";
5800 print_sort_th
('project', $order, 'Project');
5801 print_sort_th
('descr', $order, 'Description');
5802 print_sort_th
('owner', $order, 'Owner') unless $omit_owner;
5803 print_sort_th
('age', $order, 'Last Change') unless $omit_age_column;
5804 print "<th></th>\n" . # for links
5808 if ($projects_list_group_categories) {
5809 # only display categories with projects in the $from-$to window
5810 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5811 my %categories = build_projlist_by_category
(\
@projects, $from, $to);
5812 foreach my $cat (sort keys %categories) {
5813 unless ($cat eq "") {
5816 print "<td></td>\n";
5818 print "<td class=\"category\" colspan=\"5\">".esc_html
($cat)."</td>\n";
5822 git_project_list_rows
($categories{$cat}, undef, undef, $check_forks);
5825 git_project_list_rows
(\
@projects, $from, $to, $check_forks);
5828 if (defined $extra) {
5831 print "<td></td>\n";
5833 print "<td colspan=\"5\">$extra</td>\n" .
5840 # uses global variable $project
5841 my ($commitlist, $from, $to, $refs, $extra) = @_;
5843 $from = 0 unless defined $from;
5844 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5846 for (my $i = 0; $i <= $to; $i++) {
5847 my %co = %{$commitlist->[$i]};
5849 my $commit = $co{'id'};
5850 my $ref = format_ref_marker
($refs, $commit);
5851 git_print_header_div
('commit',
5852 "<span class=\"age\">$co{'age_string'}</span>" .
5853 esc_html
($co{'title'}) . $ref,
5855 print "<div class=\"title_text\">\n" .
5856 "<div class=\"log_link\">\n" .
5857 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") .
5859 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") .
5861 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree") .
5864 git_print_authorship
(\
%co, -tag
=> 'span');
5865 print "<br/>\n</div>\n";
5867 print "<div class=\"log_body\">\n";
5868 git_print_log
($co{'comment'}, -final_empty_line
=> 1);
5872 print "<div class=\"page_nav\">\n";
5878 sub git_shortlog_body
{
5879 # uses global variable $project
5880 my ($commitlist, $from, $to, $refs, $extra) = @_;
5882 $from = 0 unless defined $from;
5883 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5885 print "<table class=\"shortlog\">\n";
5887 for (my $i = $from; $i <= $to; $i++) {
5888 my %co = %{$commitlist->[$i]};
5889 my $commit = $co{'id'};
5890 my $ref = format_ref_marker
($refs, $commit);
5892 print "<tr class=\"dark\">\n";
5894 print "<tr class=\"light\">\n";
5897 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5898 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5899 format_author_html
('td', \
%co, 10) . "<td>";
5900 print format_subject_html
($co{'title'}, $co{'title_short'},
5901 href
(action
=>"commit", hash
=>$commit), $ref);
5903 "<td class=\"link\">" .
5904 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") . " | " .
5905 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") . " | " .
5906 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree");
5907 my $snapshot_links = format_snapshot_links
($commit);
5908 if (defined $snapshot_links) {
5909 print " | " . $snapshot_links;
5914 if (defined $extra) {
5916 "<td colspan=\"4\">$extra</td>\n" .
5922 sub git_history_body
{
5923 # Warning: assumes constant type (blob or tree) during history
5924 my ($commitlist, $from, $to, $refs, $extra,
5925 $file_name, $file_hash, $ftype) = @_;
5927 $from = 0 unless defined $from;
5928 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5930 print "<table class=\"history\">\n";
5932 for (my $i = $from; $i <= $to; $i++) {
5933 my %co = %{$commitlist->[$i]};
5937 my $commit = $co{'id'};
5939 my $ref = format_ref_marker
($refs, $commit);
5942 print "<tr class=\"dark\">\n";
5944 print "<tr class=\"light\">\n";
5947 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5948 # shortlog: format_author_html('td', \%co, 10)
5949 format_author_html
('td', \
%co, 15, 3) . "<td>";
5950 # originally git_history used chop_str($co{'title'}, 50)
5951 print format_subject_html
($co{'title'}, $co{'title_short'},
5952 href
(action
=>"commit", hash
=>$commit), $ref);
5954 "<td class=\"link\">" .
5955 $cgi->a({-href
=> href
(action
=>$ftype, hash_base
=>$commit, file_name
=>$file_name)}, $ftype) . " | " .
5956 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff");
5958 if ($ftype eq 'blob') {
5959 my $blob_current = $file_hash;
5960 my $blob_parent = git_get_hash_by_path
($commit, $file_name);
5961 if (defined $blob_current && defined $blob_parent &&
5962 $blob_current ne $blob_parent) {
5964 $cgi->a({-href
=> href
(action
=>"blobdiff",
5965 hash
=>$blob_current, hash_parent
=>$blob_parent,
5966 hash_base
=>$hash_base, hash_parent_base
=>$commit,
5967 file_name
=>$file_name)},
5974 if (defined $extra) {
5976 "<td colspan=\"4\">$extra</td>\n" .
5983 # uses global variable $project
5984 my ($taglist, $from, $to, $extra) = @_;
5985 $from = 0 unless defined $from;
5986 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5988 print "<table class=\"tags\">\n";
5990 for (my $i = $from; $i <= $to; $i++) {
5991 my $entry = $taglist->[$i];
5993 my $comment = $tag{'subject'};
5995 if (defined $comment) {
5996 $comment_short = chop_str
($comment, 30, 5);
5999 print "<tr class=\"dark\">\n";
6001 print "<tr class=\"light\">\n";
6004 if (defined $tag{'age'}) {
6005 print "<td><i>$tag{'age'}</i></td>\n";
6007 print "<td></td>\n";
6010 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'}),
6011 -class => "list name"}, esc_html
($tag{'name'})) .
6014 if (defined $comment) {
6015 print format_subject_html
($comment, $comment_short,
6016 href
(action
=>"tag", hash
=>$tag{'id'}));
6019 "<td class=\"selflink\">";
6020 if ($tag{'type'} eq "tag") {
6021 print $cgi->a({-href
=> href
(action
=>"tag", hash
=>$tag{'id'})}, "tag");
6026 "<td class=\"link\">" . " | " .
6027 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'})}, $tag{'reftype'});
6028 if ($tag{'reftype'} eq "commit") {
6029 print " | " . $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$tag{'fullname'})}, "shortlog") .
6030 " | " . $cgi->a({-href
=> href
(action
=>"log", hash
=>$tag{'fullname'})}, "log");
6031 } elsif ($tag{'reftype'} eq "blob") {
6032 print " | " . $cgi->a({-href
=> href
(action
=>"blob_plain", hash
=>$tag{'refid'})}, "raw");
6037 if (defined $extra) {
6039 "<td colspan=\"5\">$extra</td>\n" .
6045 sub git_heads_body
{
6046 # uses global variable $project
6047 my ($headlist, $head_at, $from, $to, $extra) = @_;
6048 $from = 0 unless defined $from;
6049 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6051 print "<table class=\"heads\">\n";
6053 for (my $i = $from; $i <= $to; $i++) {
6054 my $entry = $headlist->[$i];
6056 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6058 print "<tr class=\"dark\">\n";
6060 print "<tr class=\"light\">\n";
6063 print "<td><i>$ref{'age'}</i></td>\n" .
6064 ($curr ?
"<td class=\"current_head\">" : "<td>") .
6065 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'}),
6066 -class => "list name"},esc_html
($ref{'name'})) .
6068 "<td class=\"link\">" .
6069 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'})}, "shortlog") . " | " .
6070 $cgi->a({-href
=> href
(action
=>"log", hash
=>$ref{'fullname'})}, "log") . " | " .
6071 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$ref{'fullname'}, hash_base
=>$ref{'fullname'})}, "tree") .
6075 if (defined $extra) {
6077 "<td colspan=\"3\">$extra</td>\n" .
6083 # Display a single remote block
6084 sub git_remote_block
{
6085 my ($remote, $rdata, $limit, $head) = @_;
6087 my $heads = $rdata->{'heads'};
6088 my $fetch = $rdata->{'fetch'};
6089 my $push = $rdata->{'push'};
6091 my $urls_table = "<table class=\"projects_list\">\n" ;
6093 if (defined $fetch) {
6094 if ($fetch eq $push) {
6095 $urls_table .= format_repo_url
("URL", $fetch);
6097 $urls_table .= format_repo_url
("Fetch URL", $fetch);
6098 $urls_table .= format_repo_url
("Push URL", $push) if defined $push;
6100 } elsif (defined $push) {
6101 $urls_table .= format_repo_url
("Push URL", $push);
6103 $urls_table .= format_repo_url
("", "No remote URL");
6106 $urls_table .= "</table>\n";
6109 if (defined $limit && $limit < @
$heads) {
6110 $dots = $cgi->a({-href
=> href
(action
=>"remotes", hash
=>$remote)}, "...");
6114 git_heads_body
($heads, $head, 0, $limit, $dots);
6117 # Display a list of remote names with the respective fetch and push URLs
6118 sub git_remotes_list
{
6119 my ($remotedata, $limit) = @_;
6120 print "<table class=\"heads\">\n";
6122 my @remotes = sort keys %$remotedata;
6124 my $limited = $limit && $limit < @remotes;
6126 $#remotes = $limit - 1 if $limited;
6128 while (my $remote = shift @remotes) {
6129 my $rdata = $remotedata->{$remote};
6130 my $fetch = $rdata->{'fetch'};
6131 my $push = $rdata->{'push'};
6133 print "<tr class=\"dark\">\n";
6135 print "<tr class=\"light\">\n";
6139 $cgi->a({-href
=> href
(action
=>'remotes', hash
=>$remote),
6140 -class=> "list name"},esc_html
($remote)) .
6142 print "<td class=\"link\">" .
6143 (defined $fetch ?
$cgi->a({-href
=> $fetch}, "fetch") : "fetch") .
6145 (defined $push ?
$cgi->a({-href
=> $push}, "push") : "push") .
6153 "<td colspan=\"3\">" .
6154 $cgi->a({-href
=> href
(action
=>"remotes")}, "...") .
6155 "</td>\n" . "</tr>\n";
6161 # Display remote heads grouped by remote, unless there are too many
6162 # remotes, in which case we only display the remote names
6163 sub git_remotes_body
{
6164 my ($remotedata, $limit, $head) = @_;
6165 if ($limit and $limit < keys %$remotedata) {
6166 git_remotes_list
($remotedata, $limit);
6168 fill_remote_heads
($remotedata);
6169 while (my ($remote, $rdata) = each %$remotedata) {
6170 git_print_section
({-class=>"remote", -id
=>$remote},
6171 ["remotes", $remote, $remote], sub {
6172 git_remote_block
($remote, $rdata, $limit, $head);
6178 sub git_search_message
{
6182 if ($searchtype eq 'commit') {
6183 $greptype = "--grep=";
6184 } elsif ($searchtype eq 'author') {
6185 $greptype = "--author=";
6186 } elsif ($searchtype eq 'committer') {
6187 $greptype = "--committer=";
6189 $greptype .= $searchtext;
6190 my @commitlist = parse_commits
($hash, 101, (100 * $page), undef,
6191 $greptype, '--regexp-ignore-case',
6192 $search_use_regexp ?
'--extended-regexp' : '--fixed-strings');
6194 my $paging_nav = '';
6197 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)},
6200 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
6201 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
6203 $paging_nav .= "first ⋅ prev";
6206 if ($#commitlist >= 100) {
6208 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
6209 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
6210 $paging_nav .= " ⋅ $next_link";
6212 $paging_nav .= " ⋅ next";
6217 git_print_page_nav
('','', $hash,$co{'tree'},$hash, $paging_nav);
6218 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6219 if ($page == 0 && !@commitlist) {
6220 print "<p>No match.</p>\n";
6222 git_search_grep_body
(\
@commitlist, 0, 99, $next_link);
6228 sub git_search_changes
{
6232 open my $fd, '-|', git_cmd
(), '--no-pager', 'log', @diff_opts,
6233 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6234 ($search_use_regexp ?
'--pickaxe-regex' : ())
6235 or die_error
(500, "Open git-log failed");
6239 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6240 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6242 print "<table class=\"pickaxe search\">\n";
6246 while (my $line = <$fd>) {
6250 my %set = parse_difftree_raw_line
($line);
6251 if (defined $set{'commit'}) {
6252 # finish previous commit
6255 "<td class=\"link\">" .
6256 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6259 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6260 hash_base
=>$co{'id'})},
6267 print "<tr class=\"dark\">\n";
6269 print "<tr class=\"light\">\n";
6272 %co = parse_commit
($set{'commit'});
6273 my $author = chop_and_escape_str
($co{'author_name'}, 15, 5);
6274 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6275 "<td><i>$author</i></td>\n" .
6277 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6278 -class => "list subject"},
6279 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6280 } elsif (defined $set{'to_id'}) {
6281 next if ($set{'to_id'} =~ m/^0{40}$/);
6283 print $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$co{'id'},
6284 hash
=>$set{'to_id'}, file_name
=>$set{'to_file'}),
6286 "<span class=\"match\">" . esc_path
($set{'file'}) . "</span>") .
6292 # finish last commit (warning: repetition!)
6295 "<td class=\"link\">" .
6296 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6299 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6300 hash_base
=>$co{'id'})},
6311 sub git_search_files
{
6315 open my $fd, "-|", git_cmd
(), 'grep', '-n', '-z',
6316 $search_use_regexp ?
('-E', '-i') : '-F',
6317 $searchtext, $co{'tree'}
6318 or die_error
(500, "Open git-grep failed");
6322 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6323 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6325 print "<table class=\"grep_search\">\n";
6330 while (my $line = <$fd>) {
6332 my ($file, $lno, $ltext, $binary);
6333 last if ($matches++ > 1000);
6334 if ($line =~ /^Binary file (.+) matches$/) {
6338 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6339 $file =~ s/^$co{'tree'}://;
6341 if ($file ne $lastfile) {
6342 $lastfile and print "</td></tr>\n";
6344 print "<tr class=\"dark\">\n";
6346 print "<tr class=\"light\">\n";
6348 $file_href = href
(action
=>"blob", hash_base
=>$co{'id'},
6350 print "<td class=\"list\">".
6351 $cgi->a({-href
=> $file_href, -class => "list"}, esc_path
($file));
6352 print "</td><td>\n";
6356 print "<div class=\"binary\">Binary file</div>\n";
6358 $ltext = untabify
($ltext);
6359 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6360 $ltext = esc_html
($1, -nbsp
=>1);
6361 $ltext .= '<span class="match">';
6362 $ltext .= esc_html
($2, -nbsp
=>1);
6363 $ltext .= '</span>';
6364 $ltext .= esc_html
($3, -nbsp
=>1);
6366 $ltext = esc_html
($ltext, -nbsp
=>1);
6368 print "<div class=\"pre\">" .
6369 $cgi->a({-href
=> $file_href.'#l'.$lno,
6370 -class => "linenr"}, sprintf('%4i', $lno)) .
6371 ' ' . $ltext . "</div>\n";
6375 print "</td></tr>\n";
6376 if ($matches > 1000) {
6377 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6380 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6389 sub git_search_grep_body
{
6390 my ($commitlist, $from, $to, $extra) = @_;
6391 $from = 0 unless defined $from;
6392 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6394 print "<table class=\"commit_search\">\n";
6396 for (my $i = $from; $i <= $to; $i++) {
6397 my %co = %{$commitlist->[$i]};
6401 my $commit = $co{'id'};
6403 print "<tr class=\"dark\">\n";
6405 print "<tr class=\"light\">\n";
6408 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6409 format_author_html
('td', \
%co, 15, 5) .
6411 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6412 -class => "list subject"},
6413 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6414 my $comment = $co{'comment'};
6415 foreach my $line (@
$comment) {
6416 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6417 my ($lead, $match, $trail) = ($1, $2, $3);
6418 $match = chop_str
($match, 70, 5, 'center');
6419 my $contextlen = int((80 - length($match))/2);
6420 $contextlen = 30 if ($contextlen > 30);
6421 $lead = chop_str
($lead, $contextlen, 10, 'left');
6422 $trail = chop_str
($trail, $contextlen, 10, 'right');
6424 $lead = esc_html
($lead);
6425 $match = esc_html
($match);
6426 $trail = esc_html
($trail);
6428 print "$lead<span class=\"match\">$match</span>$trail<br />";
6432 "<td class=\"link\">" .
6433 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})}, "commit") .
6435 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$co{'id'})}, "commitdiff") .
6437 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$co{'id'})}, "tree");
6441 if (defined $extra) {
6443 "<td colspan=\"3\">$extra</td>\n" .
6449 ## ======================================================================
6450 ## ======================================================================
6453 sub git_project_list
{
6454 my $order = $input_params{'order'};
6455 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6456 die_error
(400, "Unknown order parameter");
6459 my @list = git_get_projects_list
($project_filter, $strict_export);
6461 die_error
(404, "No projects found");
6465 if (defined $home_text && -f
$home_text) {
6466 print "<div class=\"index_include\">\n";
6467 insert_file
($home_text);
6471 git_project_search_form
($searchtext, $search_use_regexp);
6472 git_project_list_body
(\
@list, $order);
6477 my $order = $input_params{'order'};
6478 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6479 die_error
(400, "Unknown order parameter");
6482 my $filter = $project;
6483 $filter =~ s/\.git$//;
6484 my @list = git_get_projects_list
($filter);
6486 die_error
(404, "No forks found");
6490 git_print_page_nav
('','');
6491 git_print_header_div
('summary', "$project forks");
6492 git_project_list_body
(\
@list, $order);
6496 sub git_project_index
{
6497 my @projects = git_get_projects_list
($project_filter, $strict_export);
6499 die_error
(404, "No projects found");
6503 -type
=> 'text/plain',
6504 -charset
=> 'utf-8',
6505 -content_disposition
=> 'inline; filename="index.aux"');
6507 foreach my $pr (@projects) {
6508 if (!exists $pr->{'owner'}) {
6509 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}");
6512 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6513 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6514 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6515 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6519 print "$path $owner\n";
6524 my $descr = git_get_project_description
($project) || "none";
6525 my %co = parse_commit
("HEAD");
6526 my %cd = %co ? parse_date
($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6527 my $head = $co{'id'};
6528 my $remote_heads = gitweb_check_feature
('remote_heads');
6530 my $owner = git_get_project_owner
($project);
6532 my $refs = git_get_references
();
6533 # These get_*_list functions return one more to allow us to see if
6534 # there are more ...
6535 my @taglist = git_get_tags_list
(16);
6536 my @headlist = git_get_heads_list
(16);
6537 my %remotedata = $remote_heads ? git_get_remotes_list
() : ();
6539 my $check_forks = gitweb_check_feature
('forks');
6542 # find forks of a project
6543 my $filter = $project;
6544 $filter =~ s/\.git$//;
6545 @forklist = git_get_projects_list
($filter);
6546 # filter out forks of forks
6547 @forklist = filter_forks_from_projects_list
(\
@forklist)
6552 git_print_page_nav
('summary','', $head);
6554 print "<div class=\"title\"> </div>\n";
6555 print "<table class=\"projects_list\">\n" .
6556 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html
($descr) . "</td></tr>\n";
6557 if ($owner and not $omit_owner) {
6558 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html
($owner) . "</td></tr>\n";
6560 if (defined $cd{'rfc2822'}) {
6561 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6562 "<td>".format_timestamp_html
(\
%cd)."</td></tr>\n";
6565 # use per project git URL list in $projectroot/$project/cloneurl
6566 # or make project git URL from git base URL and project name
6567 my $url_tag = "URL";
6568 my @url_list = git_get_project_url_list
($project);
6569 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6570 foreach my $git_url (@url_list) {
6571 next unless $git_url;
6572 print format_repo_url
($url_tag, $git_url);
6577 my $show_ctags = gitweb_check_feature
('ctags');
6579 my $ctags = git_get_project_ctags
($project);
6581 # without ability to add tags, don't show if there are none
6582 my $cloud = git_populate_project_tagcloud
($ctags);
6583 print "<tr id=\"metadata_ctags\">" .
6584 "<td>content tags</td>" .
6585 "<td>".git_show_project_tagcloud
($cloud, 48)."</td>" .
6592 # If XSS prevention is on, we don't include README.html.
6593 # TODO: Allow a readme in some safe format.
6594 if (!$prevent_xss && -s
"$projectroot/$project/README.html") {
6595 print "<div class=\"title\">readme</div>\n" .
6596 "<div class=\"readme\">\n";
6597 insert_file
("$projectroot/$project/README.html");
6598 print "\n</div>\n"; # class="readme"
6601 # we need to request one more than 16 (0..15) to check if
6603 my @commitlist = $head ? parse_commits
($head, 17) : ();
6605 git_print_header_div
('shortlog');
6606 git_shortlog_body
(\
@commitlist, 0, 15, $refs,
6607 $#commitlist <= 15 ?
undef :
6608 $cgi->a({-href
=> href
(action
=>"shortlog")}, "..."));
6612 git_print_header_div
('tags');
6613 git_tags_body
(\
@taglist, 0, 15,
6614 $#taglist <= 15 ?
undef :
6615 $cgi->a({-href
=> href
(action
=>"tags")}, "..."));
6619 git_print_header_div
('heads');
6620 git_heads_body
(\
@headlist, $head, 0, 15,
6621 $#headlist <= 15 ?
undef :
6622 $cgi->a({-href
=> href
(action
=>"heads")}, "..."));
6626 git_print_header_div
('remotes');
6627 git_remotes_body
(\
%remotedata, 15, $head);
6631 git_print_header_div
('forks');
6632 git_project_list_body
(\
@forklist, 'age', 0, 15,
6633 $#forklist <= 15 ?
undef :
6634 $cgi->a({-href
=> href
(action
=>"forks")}, "..."),
6642 my %tag = parse_tag
($hash);
6645 die_error
(404, "Unknown tag object");
6648 my $head = git_get_head_hash
($project);
6650 git_print_page_nav
('','', $head,undef,$head);
6651 git_print_header_div
('commit', esc_html
($tag{'name'}), $hash);
6652 print "<div class=\"title_text\">\n" .
6653 "<table class=\"object_header\">\n" .
6655 "<td>object</td>\n" .
6656 "<td>" . $cgi->a({-class => "list", -href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6657 $tag{'object'}) . "</td>\n" .
6658 "<td class=\"link\">" . $cgi->a({-href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6659 $tag{'type'}) . "</td>\n" .
6661 if (defined($tag{'author'})) {
6662 git_print_authorship_rows
(\
%tag, 'author');
6664 print "</table>\n\n" .
6666 print "<div class=\"page_body\">";
6667 my $comment = $tag{'comment'};
6668 foreach my $line (@
$comment) {
6670 print esc_html
($line, -nbsp
=>1) . "<br/>\n";
6676 sub git_blame_common
{
6677 my $format = shift || 'porcelain';
6678 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6679 $format = 'incremental';
6680 $action = 'blame_incremental'; # for page title etc
6684 gitweb_check_feature
('blame')
6685 or die_error
(403, "Blame view not allowed");
6688 die_error
(400, "No file name given") unless $file_name;
6689 $hash_base ||= git_get_head_hash
($project);
6690 die_error
(404, "Couldn't find base commit") unless $hash_base;
6691 my %co = parse_commit
($hash_base)
6692 or die_error
(404, "Commit not found");
6694 if (!defined $hash) {
6695 $hash = git_get_hash_by_path
($hash_base, $file_name, "blob")
6696 or die_error
(404, "Error looking up file");
6698 $ftype = git_get_type
($hash);
6699 if ($ftype !~ "blob") {
6700 die_error
(400, "Object is not a blob");
6705 if ($format eq 'incremental') {
6706 # get file contents (as base)
6707 open $fd, "-|", git_cmd
(), 'cat-file', 'blob', $hash
6708 or die_error
(500, "Open git-cat-file failed");
6709 } elsif ($format eq 'data') {
6710 # run git-blame --incremental
6711 open $fd, "-|", git_cmd
(), "blame", "--incremental",
6712 $hash_base, "--", $file_name
6713 or die_error
(500, "Open git-blame --incremental failed");
6715 # run git-blame --porcelain
6716 open $fd, "-|", git_cmd
(), "blame", '-p',
6717 $hash_base, '--', $file_name
6718 or die_error
(500, "Open git-blame --porcelain failed");
6720 binmode $fd, ':utf8';
6722 # incremental blame data returns early
6723 if ($format eq 'data') {
6725 -type
=>"text/plain", -charset
=> "utf-8",
6726 -status
=> "200 OK");
6727 local $| = 1; # output autoflush
6728 while (my $line = <$fd>) {
6729 print to_utf8
($line);
6732 or print "ERROR $!\n";
6735 if (defined $t0 && gitweb_check_feature
('timed')) {
6737 tv_interval
($t0, [ gettimeofday
() ]).
6738 ' '.$number_of_git_cmds;
6748 $cgi->a({-href
=> href
(action
=>"blob", -replay
=>1)},
6751 if ($format eq 'incremental') {
6753 $cgi->a({-href
=> href
(action
=>"blame", javascript
=>0, -replay
=>1)},
6754 "blame") . " (non-incremental)";
6757 $cgi->a({-href
=> href
(action
=>"blame_incremental", -replay
=>1)},
6758 "blame") . " (incremental)";
6762 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
6765 $cgi->a({-href
=> href
(action
=>$action, file_name
=>$file_name)},
6767 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6768 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
6769 git_print_page_path
($file_name, $ftype, $hash_base);
6772 if ($format eq 'incremental') {
6773 print "<noscript>\n<div class=\"error\"><center><b>\n".
6774 "This page requires JavaScript to run.\n Use ".
6775 $cgi->a({-href
=> href
(action
=>'blame',javascript
=>0,-replay
=>1)},
6778 "</b></center></div>\n</noscript>\n";
6780 print qq!<div id
="progress_bar" style
="width: 100%; background-color: yellow"></div
>\n!;
6783 print qq!<div
class="page_body">\n!;
6784 print qq!<div id
="progress_info">... / ...</div
>\n!
6785 if ($format eq 'incremental');
6786 print qq!<table id
="blame_table" class="blame" width
="100%">\n!.
6787 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6789 qq!<tr
><th
>Commit
</th><th>Line</th
><th
>Data
</th></tr
>\n!.
6793 my @rev_color = qw(light dark);
6794 my $num_colors = scalar(@rev_color);
6795 my $current_color = 0;
6797 if ($format eq 'incremental') {
6798 my $color_class = $rev_color[$current_color];
6803 while (my $line = <$fd>) {
6807 print qq!<tr id
="l$linenr" class="$color_class">!.
6808 qq!<td
class="sha1"><a href
=""> </a></td
>!.
6809 qq!<td
class="linenr">!.
6810 qq!<a
class="linenr" href
="">$linenr</a></td
>!;
6811 print qq!<td
class="pre">! . esc_html
($line) . "</td>\n";
6815 } else { # porcelain, i.e. ordinary blame
6816 my %metainfo = (); # saves information about commits
6820 while (my $line = <$fd>) {
6822 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6823 # no <lines in group> for subsequent lines in group of lines
6824 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6825 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6826 if (!exists $metainfo{$full_rev}) {
6827 $metainfo{$full_rev} = { 'nprevious' => 0 };
6829 my $meta = $metainfo{$full_rev};
6831 while ($data = <$fd>) {
6833 last if ($data =~ s/^\t//); # contents of line
6834 if ($data =~ /^(\S+)(?: (.*))?$/) {
6835 $meta->{$1} = $2 unless exists $meta->{$1};
6837 if ($data =~ /^previous /) {
6838 $meta->{'nprevious'}++;
6841 my $short_rev = substr($full_rev, 0, 8);
6842 my $author = $meta->{'author'};
6844 parse_date
($meta->{'author-time'}, $meta->{'author-tz'});
6845 my $date = $date{'iso-tz'};
6847 $current_color = ($current_color + 1) % $num_colors;
6849 my $tr_class = $rev_color[$current_color];
6850 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6851 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6852 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6853 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6855 print "<td class=\"sha1\"";
6856 print " title=\"". esc_html
($author) . ", $date\"";
6857 print " rowspan=\"$group_size\"" if ($group_size > 1);
6859 print $cgi->a({-href
=> href
(action
=>"commit",
6861 file_name
=>$file_name)},
6862 esc_html
($short_rev));
6863 if ($group_size >= 2) {
6864 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6865 if (@author_initials) {
6867 esc_html
(join('', @author_initials));
6873 # 'previous' <sha1 of parent commit> <filename at commit>
6874 if (exists $meta->{'previous'} &&
6875 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6876 $meta->{'parent'} = $1;
6877 $meta->{'file_parent'} = unquote
($2);
6880 exists($meta->{'parent'}) ?
6881 $meta->{'parent'} : $full_rev;
6882 my $linenr_filename =
6883 exists($meta->{'file_parent'}) ?
6884 $meta->{'file_parent'} : unquote
($meta->{'filename'});
6885 my $blamed = href
(action
=> 'blame',
6886 file_name
=> $linenr_filename,
6887 hash_base
=> $linenr_commit);
6888 print "<td class=\"linenr\">";
6889 print $cgi->a({ -href
=> "$blamed#l$orig_lineno",
6890 -class => "linenr" },
6893 print "<td class=\"pre\">" . esc_html
($data) . "</td>\n";
6901 "</table>\n"; # class="blame"
6902 print "</div>\n"; # class="blame_body"
6904 or print "Reading blob failed\n";
6913 sub git_blame_incremental
{
6914 git_blame_common
('incremental');
6917 sub git_blame_data
{
6918 git_blame_common
('data');
6922 my $head = git_get_head_hash
($project);
6924 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('tags'));
6925 git_print_header_div
('summary', $project);
6927 my @tagslist = git_get_tags_list
();
6929 git_tags_body
(\
@tagslist);
6935 my $head = git_get_head_hash
($project);
6937 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('heads'));
6938 git_print_header_div
('summary', $project);
6940 my @headslist = git_get_heads_list
();
6942 git_heads_body
(\
@headslist, $head);
6947 # used both for single remote view and for list of all the remotes
6949 gitweb_check_feature
('remote_heads')
6950 or die_error
(403, "Remote heads view is disabled");
6952 my $head = git_get_head_hash
($project);
6953 my $remote = $input_params{'hash'};
6955 my $remotedata = git_get_remotes_list
($remote);
6956 die_error
(500, "Unable to get remote information") unless defined $remotedata;
6958 unless (%$remotedata) {
6959 die_error
(404, defined $remote ?
6960 "Remote $remote not found" :
6961 "No remotes found");
6964 git_header_html
(undef, undef, -action_extra
=> $remote);
6965 git_print_page_nav
('', '', $head, undef, $head,
6966 format_ref_views
($remote ?
'' : 'remotes'));
6968 fill_remote_heads
($remotedata);
6969 if (defined $remote) {
6970 git_print_header_div
('remotes', "$remote remote for $project");
6971 git_remote_block
($remote, $remotedata->{$remote}, undef, $head);
6973 git_print_header_div
('summary', "$project remotes");
6974 git_remotes_body
($remotedata, undef, $head);
6980 sub git_blob_plain
{
6984 if (!defined $hash) {
6985 if (defined $file_name) {
6986 my $base = $hash_base || git_get_head_hash
($project);
6987 $hash = git_get_hash_by_path
($base, $file_name, "blob")
6988 or die_error
(404, "Cannot find file");
6990 die_error
(400, "No file name defined");
6992 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6993 # blobs defined by non-textual hash id's can be cached
6997 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
6998 or die_error
(500, "Open git-cat-file blob '$hash' failed");
7000 # content-type (can include charset)
7001 $type = blob_contenttype
($fd, $file_name, $type);
7003 # "save as" filename, even when no $file_name is given
7004 my $save_as = "$hash";
7005 if (defined $file_name) {
7006 $save_as = $file_name;
7007 } elsif ($type =~ m/^text\//) {
7011 # With XSS prevention on, blobs of all types except a few known safe
7012 # ones are served with "Content-Disposition: attachment" to make sure
7013 # they don't run in our security domain. For certain image types,
7014 # blob view writes an <img> tag referring to blob_plain view, and we
7015 # want to be sure not to break that by serving the image as an
7016 # attachment (though Firefox 3 doesn't seem to care).
7017 my $sandbox = $prevent_xss &&
7018 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7020 # serve text/* as text/plain
7022 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7023 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T
$fd))) {
7025 $rest = defined $rest ?
$rest : '';
7026 $type = "text/plain$rest";
7031 -expires
=> $expires,
7032 -content_disposition
=>
7033 ($sandbox ?
'attachment' : 'inline')
7034 . '; filename="' . $save_as . '"');
7036 binmode STDOUT
, ':raw';
7038 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7045 if (!defined $hash) {
7046 if (defined $file_name) {
7047 my $base = $hash_base || git_get_head_hash
($project);
7048 $hash = git_get_hash_by_path
($base, $file_name, "blob")
7049 or die_error
(404, "Cannot find file");
7051 die_error
(400, "No file name defined");
7053 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7054 # blobs defined by non-textual hash id's can be cached
7058 my $have_blame = gitweb_check_feature
('blame');
7059 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
7060 or die_error
(500, "Couldn't cat $file_name, $hash");
7061 my $mimetype = blob_mimetype
($fd, $file_name);
7062 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7063 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B
$fd) {
7065 return git_blob_plain
($mimetype);
7067 # we can have blame only for text/* mimetype
7068 $have_blame &&= ($mimetype =~ m!^text/!);
7070 my $highlight = gitweb_check_feature
('highlight');
7071 my $syntax = guess_file_syntax
($highlight, $mimetype, $file_name);
7072 $fd = run_highlighter
($fd, $highlight, $syntax);
7074 git_header_html
(undef, $expires);
7075 my $formats_nav = '';
7076 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7077 if (defined $file_name) {
7080 $cgi->a({-href
=> href
(action
=>"blame", -replay
=>1)},
7085 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7088 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7091 $cgi->a({-href
=> href
(action
=>"blob",
7092 hash_base
=>"HEAD", file_name
=>$file_name)},
7096 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7099 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7100 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7102 print "<div class=\"page_nav\">\n" .
7103 "<br/><br/></div>\n" .
7104 "<div class=\"title\">".esc_html
($hash)."</div>\n";
7106 git_print_page_path
($file_name, "blob", $hash_base);
7107 print "<div class=\"page_body\">\n";
7108 if ($mimetype =~ m!^image/!) {
7109 print qq!<img
class="blob" type
="!.esc_attr($mimetype).qq!"!;
7111 print qq! alt
="!.esc_attr($file_name).qq!" title
="!.esc_attr($file_name).qq!"!;
7114 href(action=>"blob_plain
", hash=>$hash,
7115 hash_base=>$hash_base, file_name=>$file_name) .
7119 while (my $line = <$fd>) {
7122 $line = untabify
($line);
7123 printf qq!<div
class="pre"><a id
="l%i" href
="%s#l%i" class="linenr">%4i</a> %s</div
>\n!,
7124 $nr, esc_attr
(href
(-replay
=> 1)), $nr, $nr,
7125 ($syntax || $highlight_force) ? sanitize
($line) : esc_html
($line, -nbsp
=>1);
7129 or print "Reading blob failed.\n";
7135 if (!defined $hash_base) {
7136 $hash_base = "HEAD";
7138 if (!defined $hash) {
7139 if (defined $file_name) {
7140 $hash = git_get_hash_by_path
($hash_base, $file_name, "tree");
7145 die_error
(404, "No such tree") unless defined($hash);
7147 my $show_sizes = gitweb_check_feature
('show-sizes');
7148 my $have_blame = gitweb_check_feature
('blame');
7153 open my $fd, "-|", git_cmd
(), "ls-tree", '-z',
7154 ($show_sizes ?
'-l' : ()), @extra_options, $hash
7155 or die_error
(500, "Open git-ls-tree failed");
7156 @entries = map { chomp; $_ } <$fd>;
7158 or die_error
(404, "Reading tree failed");
7161 my $refs = git_get_references
();
7162 my $ref = format_ref_marker
($refs, $hash_base);
7165 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7167 if (defined $file_name) {
7169 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7171 $cgi->a({-href
=> href
(action
=>"tree",
7172 hash_base
=>"HEAD", file_name
=>$file_name)},
7175 my $snapshot_links = format_snapshot_links
($hash);
7176 if (defined $snapshot_links) {
7177 # FIXME: Should be available when we have no hash base as well.
7178 push @views_nav, $snapshot_links;
7180 git_print_page_nav
('tree','', $hash_base, undef, undef,
7181 join(' | ', @views_nav));
7182 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash_base);
7185 print "<div class=\"page_nav\">\n";
7186 print "<br/><br/></div>\n";
7187 print "<div class=\"title\">".esc_html
($hash)."</div>\n";
7189 if (defined $file_name) {
7190 $basedir = $file_name;
7191 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7194 git_print_page_path
($file_name, 'tree', $hash_base);
7196 print "<div class=\"page_body\">\n";
7197 print "<table class=\"tree\">\n";
7199 # '..' (top directory) link if possible
7200 if (defined $hash_base &&
7201 defined $file_name && $file_name =~ m![^/]+$!) {
7203 print "<tr class=\"dark\">\n";
7205 print "<tr class=\"light\">\n";
7209 my $up = $file_name;
7210 $up =~ s!/?[^/]+$!!;
7211 undef $up unless $up;
7212 # based on git_print_tree_entry
7213 print '<td class="mode">' . mode_str
('040000') . "</td>\n";
7214 print '<td class="size"> </td>'."\n" if $show_sizes;
7215 print '<td class="list">';
7216 print $cgi->a({-href
=> href
(action
=>"tree",
7217 hash_base
=>$hash_base,
7221 print "<td class=\"link\"></td>\n";
7225 foreach my $line (@entries) {
7226 my %t = parse_ls_tree_line
($line, -z
=> 1, -l
=> $show_sizes);
7229 print "<tr class=\"dark\">\n";
7231 print "<tr class=\"light\">\n";
7235 git_print_tree_entry
(\
%t, $basedir, $hash_base, $have_blame);
7239 print "</table>\n" .
7244 sub sanitize_for_filename
{
7248 $name =~ s/[^[:alnum:]_.-]//g;
7254 my ($project, $hash) = @_;
7256 # path/to/project.git -> project
7257 # path/to/project/.git -> project
7258 my $name = to_utf8
($project);
7259 $name =~ s
,([^/])/*\
.git
$,$1,;
7260 $name = sanitize_for_filename
(basename
($name));
7263 if ($hash =~ /^[0-9a-fA-F]+$/) {
7264 # shorten SHA-1 hash
7265 my $full_hash = git_get_full_hash
($project, $hash);
7266 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7267 $ver = git_get_short_hash
($project, $hash);
7269 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7270 # tags don't need shortened SHA-1 hash
7273 # branches and other need shortened SHA-1 hash
7274 my $strip_refs = join '|', map { quotemeta } get_branch_refs
();
7275 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7276 my $ref_dir = (defined $1) ?
$1 : '';
7279 $ref_dir = sanitize_for_filename
($ref_dir);
7280 # for refs neither in heads nor remotes we want to
7281 # add a ref dir to archive name
7282 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7283 $ver = $ref_dir . '-' . $ver;
7286 $ver .= '-' . git_get_short_hash
($project, $hash);
7288 # special case of sanitization for filename - we change
7289 # slashes to dots instead of dashes
7290 # in case of hierarchical branch names
7292 $ver =~ s/[^[:alnum:]_.-]//g;
7294 # name = project-version_string
7295 $name = "$name-$ver";
7297 return wantarray ?
($name, $name) : $name;
7300 sub exit_if_unmodified_since
{
7301 my ($latest_epoch) = @_;
7304 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7305 if (defined $if_modified) {
7307 if (eval { require HTTP
::Date
; 1; }) {
7308 $since = HTTP
::Date
::str2time
($if_modified);
7309 } elsif (eval { require Time
::ParseDate
; 1; }) {
7310 $since = Time
::ParseDate
::parsedate
($if_modified, GMT
=> 1);
7312 if (defined $since && $latest_epoch <= $since) {
7313 my %latest_date = parse_date
($latest_epoch);
7315 -last_modified
=> $latest_date{'rfc2822'},
7316 -status
=> '304 Not Modified');
7323 my $format = $input_params{'snapshot_format'};
7324 if (!@snapshot_fmts) {
7325 die_error
(403, "Snapshots not allowed");
7327 # default to first supported snapshot format
7328 $format ||= $snapshot_fmts[0];
7329 if ($format !~ m/^[a-z0-9]+$/) {
7330 die_error
(400, "Invalid snapshot format parameter");
7331 } elsif (!exists($known_snapshot_formats{$format})) {
7332 die_error
(400, "Unknown snapshot format");
7333 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7334 die_error
(403, "Snapshot format not allowed");
7335 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7336 die_error
(403, "Unsupported snapshot format");
7339 my $type = git_get_type
("$hash^{}");
7341 die_error
(404, 'Object does not exist');
7342 } elsif ($type eq 'blob') {
7343 die_error
(400, 'Object is not a tree-ish');
7346 my ($name, $prefix) = snapshot_name
($project, $hash);
7347 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7349 my %co = parse_commit
($hash);
7350 exit_if_unmodified_since
($co{'committer_epoch'}) if %co;
7352 my $cmd = quote_command
(
7353 git_cmd
(), 'archive',
7354 "--format=$known_snapshot_formats{$format}{'format'}",
7355 "--prefix=$prefix/", $hash);
7356 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7357 $cmd .= ' | ' . quote_command
(@
{$known_snapshot_formats{$format}{'compressor'}});
7360 $filename =~ s/(["\\])/\\$1/g;
7363 %latest_date = parse_date
($co{'committer_epoch'}, $co{'committer_tz'});
7367 -type
=> $known_snapshot_formats{$format}{'type'},
7368 -content_disposition
=> 'inline; filename="' . $filename . '"',
7369 %co ?
(-last_modified
=> $latest_date{'rfc2822'}) : (),
7370 -status
=> '200 OK');
7372 open my $fd, "-|", $cmd
7373 or die_error
(500, "Execute git-archive failed");
7374 binmode STDOUT
, ':raw';
7376 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7380 sub git_log_generic
{
7381 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7383 my $head = git_get_head_hash
($project);
7384 if (!defined $base) {
7387 if (!defined $page) {
7390 my $refs = git_get_references
();
7392 my $commit_hash = $base;
7393 if (defined $parent) {
7394 $commit_hash = "$parent..$base";
7397 parse_commits
($commit_hash, 101, (100 * $page),
7398 defined $file_name ?
($file_name, "--full-history") : ());
7401 if (!defined $file_hash && defined $file_name) {
7402 # some commits could have deleted file in question,
7403 # and not have it in tree, but one of them has to have it
7404 for (my $i = 0; $i < @commitlist; $i++) {
7405 $file_hash = git_get_hash_by_path
($commitlist[$i]{'id'}, $file_name);
7406 last if defined $file_hash;
7409 if (defined $file_hash) {
7410 $ftype = git_get_type
($file_hash);
7412 if (defined $file_name && !defined $ftype) {
7413 die_error
(500, "Unknown type of object");
7416 if (defined $file_name) {
7417 %co = parse_commit
($base)
7418 or die_error
(404, "Unknown commit object");
7422 my $paging_nav = format_paging_nav
($fmt_name, $page, $#commitlist >= 100);
7424 if ($#commitlist >= 100) {
7426 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
7427 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
7429 my $patch_max = gitweb_get_feature
('patches');
7430 if ($patch_max && !defined $file_name) {
7431 if ($patch_max < 0 || @commitlist <= $patch_max) {
7432 $paging_nav .= " ⋅ " .
7433 $cgi->a({-href
=> href
(action
=>"patches", -replay
=>1)},
7439 git_print_page_nav
($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7440 if (defined $file_name) {
7441 git_print_header_div
('commit', esc_html
($co{'title'}), $base);
7443 git_print_header_div
('summary', $project)
7445 git_print_page_path
($file_name, $ftype, $hash_base)
7446 if (defined $file_name);
7448 $body_subr->(\
@commitlist, 0, 99, $refs, $next_link,
7449 $file_name, $file_hash, $ftype);
7455 git_log_generic
('log', \
&git_log_body
,
7456 $hash, $hash_parent);
7460 $hash ||= $hash_base || "HEAD";
7461 my %co = parse_commit
($hash)
7462 or die_error
(404, "Unknown commit object");
7464 my $parent = $co{'parent'};
7465 my $parents = $co{'parents'}; # listref
7467 # we need to prepare $formats_nav before any parameter munging
7469 if (!defined $parent) {
7471 $formats_nav .= '(initial)';
7472 } elsif (@
$parents == 1) {
7473 # single parent commit
7476 $cgi->a({-href
=> href
(action
=>"commit",
7478 esc_html
(substr($parent, 0, 7))) .
7485 $cgi->a({-href
=> href
(action
=>"commit",
7487 esc_html
(substr($_, 0, 7)));
7491 if (gitweb_check_feature
('patches') && @
$parents <= 1) {
7492 $formats_nav .= " | " .
7493 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7497 if (!defined $parent) {
7501 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', "--no-commit-id",
7503 (@
$parents <= 1 ?
$parent : '-c'),
7505 or die_error
(500, "Open git-diff-tree failed");
7506 @difftree = map { chomp; $_ } <$fd>;
7507 close $fd or die_error
(404, "Reading git-diff-tree failed");
7509 # non-textual hash id's can be cached
7511 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7514 my $refs = git_get_references
();
7515 my $ref = format_ref_marker
($refs, $co{'id'});
7517 git_header_html
(undef, $expires);
7518 git_print_page_nav
('commit', '',
7519 $hash, $co{'tree'}, $hash,
7522 if (defined $co{'parent'}) {
7523 git_print_header_div
('commitdiff', esc_html
($co{'title'}) . $ref, $hash);
7525 git_print_header_div
('tree', esc_html
($co{'title'}) . $ref, $co{'tree'}, $hash);
7527 print "<div class=\"title_text\">\n" .
7528 "<table class=\"object_header\">\n";
7529 git_print_authorship_rows
(\
%co);
7530 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7533 "<td class=\"sha1\">" .
7534 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash),
7535 class => "list"}, $co{'tree'}) .
7537 "<td class=\"link\">" .
7538 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash)},
7540 my $snapshot_links = format_snapshot_links
($hash);
7541 if (defined $snapshot_links) {
7542 print " | " . $snapshot_links;
7547 foreach my $par (@
$parents) {
7550 "<td class=\"sha1\">" .
7551 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par),
7552 class => "list"}, $par) .
7554 "<td class=\"link\">" .
7555 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par)}, "commit") .
7557 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$hash, hash_parent
=>$par)}, "diff") .
7564 print "<div class=\"page_body\">\n";
7565 git_print_log
($co{'comment'});
7568 git_difftree_body
(\
@difftree, $hash, @
$parents);
7574 # object is defined by:
7575 # - hash or hash_base alone
7576 # - hash_base and file_name
7579 # - hash or hash_base alone
7580 if ($hash || ($hash_base && !defined $file_name)) {
7581 my $object_id = $hash || $hash_base;
7583 open my $fd, "-|", quote_command
(
7584 git_cmd
(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7585 or die_error
(404, "Object does not exist");
7587 defined $type && chomp $type;
7589 or die_error
(404, "Object does not exist");
7591 # - hash_base and file_name
7592 } elsif ($hash_base && defined $file_name) {
7593 $file_name =~ s
,/+$,,;
7595 system(git_cmd
(), "cat-file", '-e', $hash_base) == 0
7596 or die_error
(404, "Base object does not exist");
7598 # here errors should not happen
7599 open my $fd, "-|", git_cmd
(), "ls-tree", $hash_base, "--", $file_name
7600 or die_error
(500, "Open git-ls-tree failed");
7604 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7605 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7606 die_error
(404, "File or directory for given base does not exist");
7611 die_error
(400, "Not enough information to find object");
7614 print $cgi->redirect(-uri
=> href
(action
=>$type, -full
=>1,
7615 hash
=>$hash, hash_base
=>$hash_base,
7616 file_name
=>$file_name),
7617 -status
=> '302 Found');
7621 my $format = shift || 'html';
7622 my $diff_style = $input_params{'diff_style'} || 'inline';
7629 # preparing $fd and %diffinfo for git_patchset_body
7631 if (defined $hash_base && defined $hash_parent_base) {
7632 if (defined $file_name) {
7634 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7635 $hash_parent_base, $hash_base,
7636 "--", (defined $file_parent ?
$file_parent : ()), $file_name
7637 or die_error
(500, "Open git-diff-tree failed");
7638 @difftree = map { chomp; $_ } <$fd>;
7640 or die_error
(404, "Reading git-diff-tree failed");
7642 or die_error
(404, "Blob diff not found");
7644 } elsif (defined $hash &&
7645 $hash =~ /[0-9a-fA-F]{40}/) {
7646 # try to find filename from $hash
7648 # read filtered raw output
7649 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7650 $hash_parent_base, $hash_base, "--"
7651 or die_error
(500, "Open git-diff-tree failed");
7653 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7655 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7656 map { chomp; $_ } <$fd>;
7658 or die_error
(404, "Reading git-diff-tree failed");
7660 or die_error
(404, "Blob diff not found");
7663 die_error
(400, "Missing one of the blob diff parameters");
7666 if (@difftree > 1) {
7667 die_error
(400, "Ambiguous blob diff specification");
7670 %diffinfo = parse_difftree_raw_line
($difftree[0]);
7671 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7672 $file_name ||= $diffinfo{'to_file'};
7674 $hash_parent ||= $diffinfo{'from_id'};
7675 $hash ||= $diffinfo{'to_id'};
7677 # non-textual hash id's can be cached
7678 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7679 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7684 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7685 '-p', ($format eq 'html' ?
"--full-index" : ()),
7686 $hash_parent_base, $hash_base,
7687 "--", (defined $file_parent ?
$file_parent : ()), $file_name
7688 or die_error
(500, "Open git-diff-tree failed");
7691 # old/legacy style URI -- not generated anymore since 1.4.3.
7693 die_error
('404 Not Found', "Missing one of the blob diff parameters")
7697 if ($format eq 'html') {
7699 $cgi->a({-href
=> href
(action
=>"blobdiff_plain", -replay
=>1)},
7701 $formats_nav .= diff_style_nav
($diff_style);
7702 git_header_html
(undef, $expires);
7703 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7704 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7705 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7707 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7708 print "<div class=\"title\">".esc_html
("$hash vs $hash_parent")."</div>\n";
7710 if (defined $file_name) {
7711 git_print_page_path
($file_name, "blob", $hash_base);
7713 print "<div class=\"page_path\"></div>\n";
7716 } elsif ($format eq 'plain') {
7718 -type
=> 'text/plain',
7719 -charset
=> 'utf-8',
7720 -expires
=> $expires,
7721 -content_disposition
=> 'inline; filename="' . "$file_name" . '.patch"');
7723 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7726 die_error
(400, "Unknown blobdiff format");
7730 if ($format eq 'html') {
7731 print "<div class=\"page_body\">\n";
7733 git_patchset_body
($fd, $diff_style,
7734 [ \
%diffinfo ], $hash_base, $hash_parent_base);
7737 print "</div>\n"; # class="page_body"
7741 while (my $line = <$fd>) {
7742 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7743 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7747 last if $line =~ m!^\+\+\+!;
7755 sub git_blobdiff_plain
{
7756 git_blobdiff
('plain');
7759 # assumes that it is added as later part of already existing navigation,
7760 # so it returns "| foo | bar" rather than just "foo | bar"
7761 sub diff_style_nav
{
7762 my ($diff_style, $is_combined) = @_;
7763 $diff_style ||= 'inline';
7765 return "" if ($is_combined);
7767 my @styles = (inline
=> 'inline', 'sidebyside' => 'side by side');
7768 my %styles = @styles;
7770 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7775 $_ eq $diff_style ?
$styles{$_} :
7776 $cgi->a({-href
=> href
(-replay
=>1, diff_style
=> $_)}, $styles{$_})
7780 sub git_commitdiff
{
7782 my $format = $params{-format
} || 'html';
7783 my $diff_style = $input_params{'diff_style'} || 'inline';
7785 my ($patch_max) = gitweb_get_feature
('patches');
7786 if ($format eq 'patch') {
7787 die_error
(403, "Patch view not allowed") unless $patch_max;
7790 $hash ||= $hash_base || "HEAD";
7791 my %co = parse_commit
($hash)
7792 or die_error
(404, "Unknown commit object");
7794 # choose format for commitdiff for merge
7795 if (! defined $hash_parent && @
{$co{'parents'}} > 1) {
7796 $hash_parent = '--cc';
7798 # we need to prepare $formats_nav before almost any parameter munging
7800 if ($format eq 'html') {
7802 $cgi->a({-href
=> href
(action
=>"commitdiff_plain", -replay
=>1)},
7804 if ($patch_max && @
{$co{'parents'}} <= 1) {
7805 $formats_nav .= " | " .
7806 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7809 $formats_nav .= diff_style_nav
($diff_style, @
{$co{'parents'}} > 1);
7811 if (defined $hash_parent &&
7812 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7813 # commitdiff with two commits given
7814 my $hash_parent_short = $hash_parent;
7815 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7816 $hash_parent_short = substr($hash_parent, 0, 7);
7820 for (my $i = 0; $i < @
{$co{'parents'}}; $i++) {
7821 if ($co{'parents'}[$i] eq $hash_parent) {
7822 $formats_nav .= ' parent ' . ($i+1);
7826 $formats_nav .= ': ' .
7827 $cgi->a({-href
=> href
(-replay
=>1,
7828 hash
=>$hash_parent, hash_base
=>undef)},
7829 esc_html
($hash_parent_short)) .
7831 } elsif (!$co{'parent'}) {
7833 $formats_nav .= ' (initial)';
7834 } elsif (scalar @
{$co{'parents'}} == 1) {
7835 # single parent commit
7838 $cgi->a({-href
=> href
(-replay
=>1,
7839 hash
=>$co{'parent'}, hash_base
=>undef)},
7840 esc_html
(substr($co{'parent'}, 0, 7))) .
7844 if ($hash_parent eq '--cc') {
7845 $formats_nav .= ' | ' .
7846 $cgi->a({-href
=> href
(-replay
=>1,
7847 hash
=>$hash, hash_parent
=>'-c')},
7849 } else { # $hash_parent eq '-c'
7850 $formats_nav .= ' | ' .
7851 $cgi->a({-href
=> href
(-replay
=>1,
7852 hash
=>$hash, hash_parent
=>'--cc')},
7858 $cgi->a({-href
=> href
(-replay
=>1,
7859 hash
=>$_, hash_base
=>undef)},
7860 esc_html
(substr($_, 0, 7)));
7861 } @
{$co{'parents'}} ) .
7866 my $hash_parent_param = $hash_parent;
7867 if (!defined $hash_parent_param) {
7868 # --cc for multiple parents, --root for parentless
7869 $hash_parent_param =
7870 @
{$co{'parents'}} > 1 ?
'--cc' : $co{'parent'} || '--root';
7876 if ($format eq 'html') {
7877 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7878 "--no-commit-id", "--patch-with-raw", "--full-index",
7879 $hash_parent_param, $hash, "--"
7880 or die_error
(500, "Open git-diff-tree failed");
7882 while (my $line = <$fd>) {
7884 # empty line ends raw part of diff-tree output
7886 push @difftree, scalar parse_difftree_raw_line
($line);
7889 } elsif ($format eq 'plain') {
7890 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7891 '-p', $hash_parent_param, $hash, "--"
7892 or die_error
(500, "Open git-diff-tree failed");
7893 } elsif ($format eq 'patch') {
7894 # For commit ranges, we limit the output to the number of
7895 # patches specified in the 'patches' feature.
7896 # For single commits, we limit the output to a single patch,
7897 # diverging from the git-format-patch default.
7898 my @commit_spec = ();
7900 if ($patch_max > 0) {
7901 push @commit_spec, "-$patch_max";
7903 push @commit_spec, '-n', "$hash_parent..$hash";
7905 if ($params{-single
}) {
7906 push @commit_spec, '-1';
7908 if ($patch_max > 0) {
7909 push @commit_spec, "-$patch_max";
7911 push @commit_spec, "-n";
7913 push @commit_spec, '--root', $hash;
7915 open $fd, "-|", git_cmd
(), "format-patch", @diff_opts,
7916 '--encoding=utf8', '--stdout', @commit_spec
7917 or die_error
(500, "Open git-format-patch failed");
7919 die_error
(400, "Unknown commitdiff format");
7922 # non-textual hash id's can be cached
7924 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7928 # write commit message
7929 if ($format eq 'html') {
7930 my $refs = git_get_references
();
7931 my $ref = format_ref_marker
($refs, $co{'id'});
7933 git_header_html
(undef, $expires);
7934 git_print_page_nav
('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7935 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash);
7936 print "<div class=\"title_text\">\n" .
7937 "<table class=\"object_header\">\n";
7938 git_print_authorship_rows
(\
%co);
7941 print "<div class=\"page_body\">\n";
7942 if (@
{$co{'comment'}} > 1) {
7943 print "<div class=\"log\">\n";
7944 git_print_log
($co{'comment'}, -final_empty_line
=> 1, -remove_title
=> 1);
7945 print "</div>\n"; # class="log"
7948 } elsif ($format eq 'plain') {
7949 my $refs = git_get_references
("tags");
7950 my $tagname = git_get_rev_name_tags
($hash);
7951 my $filename = basename
($project) . "-$hash.patch";
7954 -type
=> 'text/plain',
7955 -charset
=> 'utf-8',
7956 -expires
=> $expires,
7957 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
7958 my %ad = parse_date
($co{'author_epoch'}, $co{'author_tz'});
7959 print "From: " . to_utf8
($co{'author'}) . "\n";
7960 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7961 print "Subject: " . to_utf8
($co{'title'}) . "\n";
7963 print "X-Git-Tag: $tagname\n" if $tagname;
7964 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7966 foreach my $line (@
{$co{'comment'}}) {
7967 print to_utf8
($line) . "\n";
7970 } elsif ($format eq 'patch') {
7971 my $filename = basename
($project) . "-$hash.patch";
7974 -type
=> 'text/plain',
7975 -charset
=> 'utf-8',
7976 -expires
=> $expires,
7977 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
7981 if ($format eq 'html') {
7982 my $use_parents = !defined $hash_parent ||
7983 $hash_parent eq '-c' || $hash_parent eq '--cc';
7984 git_difftree_body
(\
@difftree, $hash,
7985 $use_parents ? @
{$co{'parents'}} : $hash_parent);
7988 git_patchset_body
($fd, $diff_style,
7990 $use_parents ? @
{$co{'parents'}} : $hash_parent);
7992 print "</div>\n"; # class="page_body"
7995 } elsif ($format eq 'plain') {
7999 or print "Reading git-diff-tree failed\n";
8000 } elsif ($format eq 'patch') {
8004 or print "Reading git-format-patch failed\n";
8008 sub git_commitdiff_plain
{
8009 git_commitdiff
(-format
=> 'plain');
8012 # format-patch-style patches
8014 git_commitdiff
(-format
=> 'patch', -single
=> 1);
8018 git_commitdiff
(-format
=> 'patch');
8022 git_log_generic
('history', \
&git_history_body
,
8023 $hash_base, $hash_parent_base,
8028 $searchtype ||= 'commit';
8030 # check if appropriate features are enabled
8031 gitweb_check_feature
('search')
8032 or die_error
(403, "Search is disabled");
8033 if ($searchtype eq 'pickaxe') {
8034 # pickaxe may take all resources of your box and run for several minutes
8035 # with every query - so decide by yourself how public you make this feature
8036 gitweb_check_feature
('pickaxe')
8037 or die_error
(403, "Pickaxe search is disabled");
8039 if ($searchtype eq 'grep') {
8040 # grep search might be potentially CPU-intensive, too
8041 gitweb_check_feature
('grep')
8042 or die_error
(403, "Grep search is disabled");
8045 if (!defined $searchtext) {
8046 die_error
(400, "Text field is empty");
8048 if (!defined $hash) {
8049 $hash = git_get_head_hash
($project);
8051 my %co = parse_commit
($hash);
8053 die_error
(404, "Unknown commit object");
8055 if (!defined $page) {
8059 if ($searchtype eq 'commit' ||
8060 $searchtype eq 'author' ||
8061 $searchtype eq 'committer') {
8062 git_search_message
(%co);
8063 } elsif ($searchtype eq 'pickaxe') {
8064 git_search_changes
(%co);
8065 } elsif ($searchtype eq 'grep') {
8066 git_search_files
(%co);
8068 die_error
(400, "Unknown search type");
8072 sub git_search_help
{
8074 git_print_page_nav
('','', $hash,$hash,$hash);
8076 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8077 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8078 the pattern entered is recognized as the POSIX extended
8079 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8082 <dt><b>commit</b></dt>
8083 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8085 my $have_grep = gitweb_check_feature
('grep');
8088 <dt><b>grep</b></dt>
8089 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8090 a different one) are searched for the given pattern. On large trees, this search can take
8091 a while and put some strain on the server, so please use it with some consideration. Note that
8092 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8093 case-sensitive.</dd>
8097 <dt><b>author</b></dt>
8098 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8099 <dt><b>committer</b></dt>
8100 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8102 my $have_pickaxe = gitweb_check_feature
('pickaxe');
8103 if ($have_pickaxe) {
8105 <dt><b>pickaxe</b></dt>
8106 <dd>All commits that caused the string to appear or disappear from any file (changes that
8107 added, removed or "modified" the string) will be listed. This search can take a while and
8108 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8109 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8117 git_log_generic
('shortlog', \
&git_shortlog_body
,
8118 $hash, $hash_parent);
8121 ## ......................................................................
8122 ## feeds (RSS, Atom; OPML)
8125 my $format = shift || 'atom';
8126 my $have_blame = gitweb_check_feature
('blame');
8128 # Atom: http://www.atomenabled.org/developers/syndication/
8129 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8130 if ($format ne 'rss' && $format ne 'atom') {
8131 die_error
(400, "Unknown web feed format");
8134 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8135 my $head = $hash || 'HEAD';
8136 my @commitlist = parse_commits
($head, 150, 0, $file_name);
8140 my $content_type = "application/$format+xml";
8141 if (defined $cgi->http('HTTP_ACCEPT') &&
8142 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8143 # browser (feed reader) prefers text/xml
8144 $content_type = 'text/xml';
8146 if (defined($commitlist[0])) {
8147 %latest_commit = %{$commitlist[0]};
8148 my $latest_epoch = $latest_commit{'committer_epoch'};
8149 exit_if_unmodified_since
($latest_epoch);
8150 %latest_date = parse_date
($latest_epoch, $latest_commit{'committer_tz'});
8153 -type
=> $content_type,
8154 -charset
=> 'utf-8',
8155 %latest_date ?
(-last_modified
=> $latest_date{'rfc2822'}) : (),
8156 -status
=> '200 OK');
8158 # Optimization: skip generating the body if client asks only
8159 # for Last-Modified date.
8160 return if ($cgi->request_method() eq 'HEAD');
8163 my $title = "$site_name - $project/$action";
8164 my $feed_type = 'log';
8165 if (defined $hash) {
8166 $title .= " - '$hash'";
8167 $feed_type = 'branch log';
8168 if (defined $file_name) {
8169 $title .= " :: $file_name";
8170 $feed_type = 'history';
8172 } elsif (defined $file_name) {
8173 $title .= " - $file_name";
8174 $feed_type = 'history';
8176 $title .= " $feed_type";
8177 $title = esc_html
($title);
8178 my $descr = git_get_project_description
($project);
8179 if (defined $descr) {
8180 $descr = esc_html
($descr);
8182 $descr = "$project " .
8183 ($format eq 'rss' ?
'RSS' : 'Atom') .
8186 my $owner = git_get_project_owner
($project);
8187 $owner = esc_html
($owner);
8191 if (defined $file_name) {
8192 $alt_url = href
(-full
=>1, action
=>"history", hash
=>$hash, file_name
=>$file_name);
8193 } elsif (defined $hash) {
8194 $alt_url = href
(-full
=>1, action
=>"log", hash
=>$hash);
8196 $alt_url = href
(-full
=>1, action
=>"summary");
8198 print qq!<?xml version
="1.0" encoding
="utf-8"?
>\n!;
8199 if ($format eq 'rss') {
8201 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8204 print "<title>$title</title>\n" .
8205 "<link>$alt_url</link>\n" .
8206 "<description>$descr</description>\n" .
8207 "<language>en</language>\n" .
8208 # project owner is responsible for 'editorial' content
8209 "<managingEditor>$owner</managingEditor>\n";
8210 if (defined $logo || defined $favicon) {
8211 # prefer the logo to the favicon, since RSS
8212 # doesn't allow both
8213 my $img = esc_url
($logo || $favicon);
8215 "<url>$img</url>\n" .
8216 "<title>$title</title>\n" .
8217 "<link>$alt_url</link>\n" .
8221 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8222 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8224 print "<generator>gitweb v.$version/$git_version</generator>\n";
8225 } elsif ($format eq 'atom') {
8227 <feed xmlns="http://www.w3.org/2005/Atom">
8229 print "<title>$title</title>\n" .
8230 "<subtitle>$descr</subtitle>\n" .
8231 '<link rel="alternate" type="text/html" href="' .
8232 $alt_url . '" />' . "\n" .
8233 '<link rel="self" type="' . $content_type . '" href="' .
8234 $cgi->self_url() . '" />' . "\n" .
8235 "<id>" . href
(-full
=>1) . "</id>\n" .
8236 # use project owner for feed author
8237 "<author><name>$owner</name></author>\n";
8238 if (defined $favicon) {
8239 print "<icon>" . esc_url
($favicon) . "</icon>\n";
8241 if (defined $logo) {
8242 # not twice as wide as tall: 72 x 27 pixels
8243 print "<logo>" . esc_url
($logo) . "</logo>\n";
8245 if (! %latest_date) {
8246 # dummy date to keep the feed valid until commits trickle in:
8247 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8249 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8251 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8255 for (my $i = 0; $i <= $#commitlist; $i++) {
8256 my %co = %{$commitlist[$i]};
8257 my $commit = $co{'id'};
8258 # we read 150, we always show 30 and the ones more recent than 48 hours
8259 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8262 my %cd = parse_date
($co{'author_epoch'}, $co{'author_tz'});
8264 # get list of changed files
8265 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
8266 $co{'parent'} || "--root",
8267 $co{'id'}, "--", (defined $file_name ?
$file_name : ())
8269 my @difftree = map { chomp; $_ } <$fd>;
8273 # print element (entry, item)
8274 my $co_url = href
(-full
=>1, action
=>"commitdiff", hash
=>$commit);
8275 if ($format eq 'rss') {
8277 "<title>" . esc_html
($co{'title'}) . "</title>\n" .
8278 "<author>" . esc_html
($co{'author'}) . "</author>\n" .
8279 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8280 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8281 "<link>$co_url</link>\n" .
8282 "<description>" . esc_html
($co{'title'}) . "</description>\n" .
8283 "<content:encoded>" .
8285 } elsif ($format eq 'atom') {
8287 "<title type=\"html\">" . esc_html
($co{'title'}) . "</title>\n" .
8288 "<updated>$cd{'iso-8601'}</updated>\n" .
8290 " <name>" . esc_html
($co{'author_name'}) . "</name>\n";
8291 if ($co{'author_email'}) {
8292 print " <email>" . esc_html
($co{'author_email'}) . "</email>\n";
8294 print "</author>\n" .
8295 # use committer for contributor
8297 " <name>" . esc_html
($co{'committer_name'}) . "</name>\n";
8298 if ($co{'committer_email'}) {
8299 print " <email>" . esc_html
($co{'committer_email'}) . "</email>\n";
8301 print "</contributor>\n" .
8302 "<published>$cd{'iso-8601'}</published>\n" .
8303 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8304 "<id>$co_url</id>\n" .
8305 "<content type=\"xhtml\" xml:base=\"" . esc_url
($my_url) . "\">\n" .
8306 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8308 my $comment = $co{'comment'};
8310 foreach my $line (@
$comment) {
8311 $line = esc_html
($line);
8314 print "</pre><ul>\n";
8315 foreach my $difftree_line (@difftree) {
8316 my %difftree = parse_difftree_raw_line
($difftree_line);
8317 next if !$difftree{'from_id'};
8319 my $file = $difftree{'file'} || $difftree{'to_file'};
8323 $cgi->a({-href
=> href
(-full
=>1, action
=>"blobdiff",
8324 hash
=>$difftree{'to_id'}, hash_parent
=>$difftree{'from_id'},
8325 hash_base
=>$co{'id'}, hash_parent_base
=>$co{'parent'},
8326 file_name
=>$file, file_parent
=>$difftree{'from_file'}),
8327 -title
=> "diff"}, 'D');
8329 print $cgi->a({-href
=> href
(-full
=>1, action
=>"blame",
8330 file_name
=>$file, hash_base
=>$commit),
8331 -title
=> "blame"}, 'B');
8333 # if this is not a feed of a file history
8334 if (!defined $file_name || $file_name ne $file) {
8335 print $cgi->a({-href
=> href
(-full
=>1, action
=>"history",
8336 file_name
=>$file, hash
=>$commit),
8337 -title
=> "history"}, 'H');
8339 $file = esc_path
($file);
8343 if ($format eq 'rss') {
8344 print "</ul>]]>\n" .
8345 "</content:encoded>\n" .
8347 } elsif ($format eq 'atom') {
8348 print "</ul>\n</div>\n" .
8355 if ($format eq 'rss') {
8356 print "</channel>\n</rss>\n";
8357 } elsif ($format eq 'atom') {
8371 my @list = git_get_projects_list
($project_filter, $strict_export);
8373 die_error
(404, "No projects found");
8377 -type
=> 'text/xml',
8378 -charset
=> 'utf-8',
8379 -content_disposition
=> 'inline; filename="opml.xml"');
8381 my $title = esc_html
($site_name);
8382 my $filter = " within subdirectory ";
8383 if (defined $project_filter) {
8384 $filter .= esc_html
($project_filter);
8389 <?xml version="1.0" encoding="utf-8"?>
8390 <opml version="1.0">
8392 <title>$title OPML Export$filter</title>
8395 <outline text="git RSS feeds">
8398 foreach my $pr (@list) {
8400 my $head = git_get_head_hash
($proj{'path'});
8401 if (!defined $head) {
8404 $git_dir = "$projectroot/$proj{'path'}";
8405 my %co = parse_commit
($head);
8410 my $path = esc_html
(chop_str
($proj{'path'}, 25, 5));
8411 my $rss = href
('project' => $proj{'path'}, 'action' => 'rss', -full
=> 1);
8412 my $html = href
('project' => $proj{'path'}, 'action' => 'summary', -full
=> 1);
8413 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";