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 # handle ACL in file access tests
14 use filetest
'access';
15 use CGI
qw(:standard :escapeHTML -nosticky);
16 use CGI
::Util
qw(unescape);
17 use CGI
::Carp
qw(fatalsToBrowser set_message);
21 use File
::Basename
qw(basename);
22 use Time
::HiRes
qw(gettimeofday tv_interval);
23 use Digest
::MD5
qw(md5_hex);
25 binmode STDOUT
, ':utf8';
27 if (!defined($CGI::VERSION
) || $CGI::VERSION
< 4.08) {
28 eval 'sub CGI::multi_param { CGI::param(@_) }'
31 our $t0 = [ gettimeofday
() ];
32 our $number_of_git_cmds = 0;
35 CGI-
>compile() if $ENV{'MOD_PERL'};
38 our $version = "++GIT_VERSION++";
40 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
44 our $my_url = $cgi->url();
45 our $my_uri = $cgi->url(-absolute
=> 1);
47 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
48 # needed and used only for URLs with nonempty PATH_INFO
49 our $base_url = $my_url;
51 # When the script is used as DirectoryIndex, the URL does not contain the name
52 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
53 # have to do it ourselves. We make $path_info global because it's also used
56 # Another issue with the script being the DirectoryIndex is that the resulting
57 # $my_url data is not the full script URL: this is good, because we want
58 # generated links to keep implying the script name if it wasn't explicitly
59 # indicated in the URL we're handling, but it means that $my_url cannot be used
61 # Therefore, if we needed to strip PATH_INFO, then we know that we have
62 # to build the base URL ourselves:
63 our $path_info = decode_utf8
($ENV{"PATH_INFO"});
65 # $path_info has already been URL-decoded by the web server, but
66 # $my_url and $my_uri have not. URL-decode them so we can properly
68 $my_url = unescape
($my_url);
69 $my_uri = unescape
($my_uri);
70 if ($my_url =~ s
,\Q
$path_info\E
$,, &&
71 $my_uri =~ s
,\Q
$path_info\E
$,, &&
72 defined $ENV{'SCRIPT_NAME'}) {
73 $base_url = $cgi->url(-base
=> 1) . $ENV{'SCRIPT_NAME'};
77 # target of the home link on top of all pages
78 our $home_link = $my_uri || "/";
81 # core git executable to use
82 # this can just be "git" if your webserver has a sensible PATH
83 our $GIT = "++GIT_BINDIR++/git";
85 # absolute fs-path which will be prepended to the project path
86 #our $projectroot = "/pub/scm";
87 our $projectroot = "++GITWEB_PROJECTROOT++";
89 # fs traversing limit for getting project list
90 # the number is relative to the projectroot
91 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
93 # string of the home link on top of all pages
94 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
96 # extra breadcrumbs preceding the home link
97 our @extra_breadcrumbs = ();
99 # name of your site or organization to appear in page titles
100 # replace this with something more descriptive for clearer bookmarks
101 our $site_name = "++GITWEB_SITENAME++"
102 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
104 # html snippet to include in the <head> section of each page
105 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
106 # filename of html text to include at top of each page
107 our $site_header = "++GITWEB_SITE_HEADER++";
108 # html text to include at home page
109 our $home_text = "++GITWEB_HOMETEXT++";
110 # filename of html text to include at bottom of each page
111 our $site_footer = "++GITWEB_SITE_FOOTER++";
114 our @stylesheets = ("++GITWEB_CSS++");
115 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
116 our $stylesheet = undef;
118 # URI of GIT logo (72x27 size)
119 our $logo = "++GITWEB_LOGO++";
120 # URI of GIT favicon, assumed to be image/png type
121 our $favicon = "++GITWEB_FAVICON++";
122 # URI of gitweb.js (JavaScript code for gitweb)
123 our $javascript = "++GITWEB_JS++";
125 # URI and label (title) of GIT logo link
126 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
127 #our $logo_label = "git documentation";
128 our $logo_url = "http://git-scm.com/";
129 our $logo_label = "git homepage";
131 # source of projects list
132 our $projects_list = "++GITWEB_LIST++";
134 # the width (in characters) of the projects list "Description" column
135 our $projects_list_description_width = 25;
137 # group projects by category on the projects list
138 # (enabled if this variable evaluates to true)
139 our $projects_list_group_categories = 0;
141 # default category if none specified
142 # (leave the empty string for no category)
143 our $project_list_default_category = "";
145 # default order of projects list
146 # valid values are none, project, descr, owner, and age
147 our $default_projects_order = "project";
149 # show repository only if this file exists
150 # (only effective if this variable evaluates to true)
151 our $export_ok = "++GITWEB_EXPORT_OK++";
153 # don't generate age column on the projects list page
154 our $omit_age_column = 0;
156 # don't generate information about owners of repositories
159 # show repository only if this subroutine returns true
160 # when given the path to the project, for example:
161 # sub { return -e "$_[0]/git-daemon-export-ok"; }
162 our $export_auth_hook = undef;
164 # only allow viewing of repositories also shown on the overview page
165 our $strict_export = "++GITWEB_STRICT_EXPORT++";
167 # list of git base URLs used for URL to where fetch project from,
168 # i.e. full URL is "$git_base_url/$project"
169 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
171 # default blob_plain mimetype and default charset for text/plain blob
172 our $default_blob_plain_mimetype = 'text/plain';
173 our $default_text_plain_charset = undef;
175 # file to use for guessing MIME types before trying /etc/mime.types
176 # (relative to the current git repository)
177 our $mimetypes_file = undef;
179 # assume this charset if line contains non-UTF-8 characters;
180 # it should be valid encoding (see Encoding::Supported(3pm) for list),
181 # for which encoding all byte sequences are valid, for example
182 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
183 # could be even 'utf-8' for the old behavior)
184 our $fallback_encoding = 'latin1';
186 # rename detection options for git-diff and git-diff-tree
187 # - default is '-M', with the cost proportional to
188 # (number of removed files) * (number of new files).
189 # - more costly is '-C' (which implies '-M'), with the cost proportional to
190 # (number of changed files + number of removed files) * (number of new files)
191 # - even more costly is '-C', '--find-copies-harder' with cost
192 # (number of files in the original tree) * (number of new files)
193 # - one might want to include '-B' option, e.g. '-B', '-M'
194 our @diff_opts = ('-M'); # taken from git_commit
196 # Disables features that would allow repository owners to inject script into
198 our $prevent_xss = 0;
200 # Path to the highlight executable to use (must be the one from
201 # http://www.andre-simon.de due to assumptions about parameters and output).
202 # Useful if highlight is not installed on your webserver's PATH.
203 # [Default: highlight]
204 our $highlight_bin = "++HIGHLIGHT_BIN++";
206 # information about snapshot formats that gitweb is capable of serving
207 our %known_snapshot_formats = (
209 # 'display' => display name,
210 # 'type' => mime type,
211 # 'suffix' => filename suffix,
212 # 'format' => --format for git-archive,
213 # 'compressor' => [compressor command and arguments]
214 # (array reference, optional)
215 # 'disabled' => boolean (optional)}
218 'display' => 'tar.gz',
219 'type' => 'application/x-gzip',
220 'suffix' => '.tar.gz',
222 'compressor' => ['gzip', '-n']},
225 'display' => 'tar.bz2',
226 'type' => 'application/x-bzip2',
227 'suffix' => '.tar.bz2',
229 'compressor' => ['bzip2']},
232 'display' => 'tar.xz',
233 'type' => 'application/x-xz',
234 'suffix' => '.tar.xz',
236 'compressor' => ['xz'],
241 'type' => 'application/x-zip',
246 # Aliases so we understand old gitweb.snapshot values in repository
248 our %known_snapshot_format_aliases = (
253 # backward compatibility: legacy gitweb config support
254 'x-gzip' => undef, 'gz' => undef,
255 'x-bzip2' => undef, 'bz2' => undef,
256 'x-zip' => undef, '' => undef,
259 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
260 # are changed, it may be appropriate to change these values too via
267 # Used to set the maximum load that we will still respond to gitweb queries.
268 # If server load exceed this value then return "503 server busy" error.
269 # If gitweb cannot determined server load, it is taken to be 0.
270 # Leave it undefined (or set to 'undef') to turn off load checking.
273 # configuration for 'highlight' (http://www.andre-simon.de/)
275 our %highlight_basename = (
278 'SConstruct' => 'py', # SCons equivalent of Makefile
279 'Makefile' => 'make',
282 our %highlight_ext = (
283 # main extensions, defining name of syntax;
284 # see files in /usr/share/highlight/langDefs/ directory
285 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
286 # alternate extensions, see /etc/highlight/filetypes.conf
287 (map { $_ => 'c' } qw(c h)),
288 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
289 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
290 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
291 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
292 (map { $_ => 'make'} qw(make mak mk)),
293 (map { $_ => 'xml' } qw(xml xhtml html htm)),
296 # You define site-wide feature defaults here; override them with
297 # $GITWEB_CONFIG as necessary.
300 # 'sub' => feature-sub (subroutine),
301 # 'override' => allow-override (boolean),
302 # 'default' => [ default options...] (array reference)}
304 # if feature is overridable (it means that allow-override has true value),
305 # then feature-sub will be called with default options as parameters;
306 # return value of feature-sub indicates if to enable specified feature
308 # if there is no 'sub' key (no feature-sub), then feature cannot be
311 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
312 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
315 # Enable the 'blame' blob view, showing the last commit that modified
316 # each line in the file. This can be very CPU-intensive.
318 # To enable system wide have in $GITWEB_CONFIG
319 # $feature{'blame'}{'default'} = [1];
320 # To have project specific config enable override in $GITWEB_CONFIG
321 # $feature{'blame'}{'override'} = 1;
322 # and in project config gitweb.blame = 0|1;
324 'sub' => sub { feature_bool
('blame', @_) },
328 # Enable the 'snapshot' link, providing a compressed archive of any
329 # tree. This can potentially generate high traffic if you have large
332 # Value is a list of formats defined in %known_snapshot_formats that
334 # To disable system wide have in $GITWEB_CONFIG
335 # $feature{'snapshot'}{'default'} = [];
336 # To have project specific config enable override in $GITWEB_CONFIG
337 # $feature{'snapshot'}{'override'} = 1;
338 # and in project config, a comma-separated list of formats or "none"
339 # to disable. Example: gitweb.snapshot = tbz2,zip;
341 'sub' => \
&feature_snapshot
,
343 'default' => ['tgz']},
345 # Enable text search, which will list the commits which match author,
346 # committer or commit text to a given string. Enabled by default.
347 # Project specific override is not supported.
349 # Note that this controls all search features, which means that if
350 # it is disabled, then 'grep' and 'pickaxe' search would also be
356 # Enable grep search, which will list the files in currently selected
357 # tree containing the given string. Enabled by default. This can be
358 # potentially CPU-intensive, of course.
359 # Note that you need to have 'search' feature enabled too.
361 # To enable system wide have in $GITWEB_CONFIG
362 # $feature{'grep'}{'default'} = [1];
363 # To have project specific config enable override in $GITWEB_CONFIG
364 # $feature{'grep'}{'override'} = 1;
365 # and in project config gitweb.grep = 0|1;
367 'sub' => sub { feature_bool
('grep', @_) },
371 # Enable the pickaxe search, which will list the commits that modified
372 # a given string in a file. This can be practical and quite faster
373 # alternative to 'blame', but still potentially CPU-intensive.
374 # Note that you need to have 'search' feature enabled too.
376 # To enable system wide have in $GITWEB_CONFIG
377 # $feature{'pickaxe'}{'default'} = [1];
378 # To have project specific config enable override in $GITWEB_CONFIG
379 # $feature{'pickaxe'}{'override'} = 1;
380 # and in project config gitweb.pickaxe = 0|1;
382 'sub' => sub { feature_bool
('pickaxe', @_) },
386 # Enable showing size of blobs in a 'tree' view, in a separate
387 # column, similar to what 'ls -l' does. This cost a bit of IO.
389 # To disable system wide have in $GITWEB_CONFIG
390 # $feature{'show-sizes'}{'default'} = [0];
391 # To have project specific config enable override in $GITWEB_CONFIG
392 # $feature{'show-sizes'}{'override'} = 1;
393 # and in project config gitweb.showsizes = 0|1;
395 'sub' => sub { feature_bool
('showsizes', @_) },
399 # Make gitweb use an alternative format of the URLs which can be
400 # more readable and natural-looking: project name is embedded
401 # directly in the path and the query string contains other
402 # auxiliary information. All gitweb installations recognize
403 # URL in either format; this configures in which formats gitweb
406 # To enable system wide have in $GITWEB_CONFIG
407 # $feature{'pathinfo'}{'default'} = [1];
408 # Project specific override is not supported.
410 # Note that you will need to change the default location of CSS,
411 # favicon, logo and possibly other files to an absolute URL. Also,
412 # if gitweb.cgi serves as your indexfile, you will need to force
413 # $my_uri to contain the script name in your $GITWEB_CONFIG.
418 # Make gitweb consider projects in project root subdirectories
419 # to be forks of existing projects. Given project $projname.git,
420 # projects matching $projname/*.git will not be shown in the main
421 # projects list, instead a '+' mark will be added to $projname
422 # there and a 'forks' view will be enabled for the project, listing
423 # all the forks. If project list is taken from a file, forks have
424 # to be listed after the main project.
426 # To enable system wide have in $GITWEB_CONFIG
427 # $feature{'forks'}{'default'} = [1];
428 # Project specific override is not supported.
433 # Insert custom links to the action bar of all project pages.
434 # This enables you mainly to link to third-party scripts integrating
435 # into gitweb; e.g. git-browser for graphical history representation
436 # or custom web-based repository administration interface.
438 # The 'default' value consists of a list of triplets in the form
439 # (label, link, position) where position is the label after which
440 # to insert the link and link is a format string where %n expands
441 # to the project name, %f to the project path within the filesystem,
442 # %h to the current hash (h gitweb parameter) and %b to the current
443 # hash base (hb gitweb parameter); %% expands to %.
445 # To enable system wide have in $GITWEB_CONFIG e.g.
446 # $feature{'actions'}{'default'} = [('graphiclog',
447 # '/git-browser/by-commit.html?r=%n', 'summary')];
448 # Project specific override is not supported.
453 # Allow gitweb scan project content tags of project repository,
454 # and display the popular Web 2.0-ish "tag cloud" near the projects
455 # list. Note that this is something COMPLETELY different from the
458 # gitweb by itself can show existing tags, but it does not handle
459 # tagging itself; you need to do it externally, outside gitweb.
460 # The format is described in git_get_project_ctags() subroutine.
461 # You may want to install the HTML::TagCloud Perl module to get
462 # a pretty tag cloud instead of just a list of tags.
464 # To enable system wide have in $GITWEB_CONFIG
465 # $feature{'ctags'}{'default'} = [1];
466 # Project specific override is not supported.
468 # In the future whether ctags editing is enabled might depend
469 # on the value, but using 1 should always mean no editing of ctags.
474 # The maximum number of patches in a patchset generated in patch
475 # view. Set this to 0 or undef to disable patch view, or to a
476 # negative number to remove any limit.
478 # To disable system wide have in $GITWEB_CONFIG
479 # $feature{'patches'}{'default'} = [0];
480 # To have project specific config enable override in $GITWEB_CONFIG
481 # $feature{'patches'}{'override'} = 1;
482 # and in project config gitweb.patches = 0|n;
483 # where n is the maximum number of patches allowed in a patchset.
485 'sub' => \
&feature_patches
,
489 # Avatar support. When this feature is enabled, views such as
490 # shortlog or commit will display an avatar associated with
491 # the email of the committer(s) and/or author(s).
493 # Currently available providers are gravatar and picon.
494 # If an unknown provider is specified, the feature is disabled.
496 # Picon currently relies on the indiana.edu database.
498 # To enable system wide have in $GITWEB_CONFIG
499 # $feature{'avatar'}{'default'} = ['<provider>'];
500 # where <provider> is either gravatar or picon.
501 # To have project specific config enable override in $GITWEB_CONFIG
502 # $feature{'avatar'}{'override'} = 1;
503 # and in project config gitweb.avatar = <provider>;
505 'sub' => \
&feature_avatar
,
509 # Enable displaying how much time and how many git commands
510 # it took to generate and display page. Disabled by default.
511 # Project specific override is not supported.
516 # Enable turning some links into links to actions which require
517 # JavaScript to run (like 'blame_incremental'). Not enabled by
518 # default. Project specific override is currently not supported.
519 'javascript-actions' => {
523 # Enable and configure ability to change common timezone for dates
524 # in gitweb output via JavaScript. Enabled by default.
525 # Project specific override is not supported.
526 'javascript-timezone' => {
529 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
530 # or undef to turn off this feature
531 'gitweb_tz', # name of cookie where to store selected timezone
532 'datetime', # CSS class used to mark up dates for manipulation
535 # Syntax highlighting support. This is based on Daniel Svensson's
536 # and Sham Chukoury's work in gitweb-xmms2.git.
537 # It requires the 'highlight' program present in $PATH,
538 # and therefore is disabled by default.
540 # To enable system wide have in $GITWEB_CONFIG
541 # $feature{'highlight'}{'default'} = [1];
544 'sub' => sub { feature_bool
('highlight', @_) },
548 # Enable displaying of remote heads in the heads list
550 # To enable system wide have in $GITWEB_CONFIG
551 # $feature{'remote_heads'}{'default'} = [1];
552 # To have project specific config enable override in $GITWEB_CONFIG
553 # $feature{'remote_heads'}{'override'} = 1;
554 # and in project config gitweb.remoteheads = 0|1;
556 'sub' => sub { feature_bool
('remote_heads', @_) },
560 # Enable showing branches under other refs in addition to heads
562 # To set system wide extra branch refs have in $GITWEB_CONFIG
563 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
564 # To have project specific config enable override in $GITWEB_CONFIG
565 # $feature{'extra-branch-refs'}{'override'} = 1;
566 # and in project config gitweb.extrabranchrefs = dirs of choice
567 # Every directory is separated with whitespace.
569 'extra-branch-refs' => {
570 'sub' => \
&feature_extra_branch_refs
,
575 sub gitweb_get_feature
{
577 return unless exists $feature{$name};
578 my ($sub, $override, @defaults) = (
579 $feature{$name}{'sub'},
580 $feature{$name}{'override'},
581 @{$feature{$name}{'default'}});
582 # project specific override is possible only if we have project
583 our $git_dir; # global variable, declared later
584 if (!$override || !defined $git_dir) {
588 warn "feature $name is not overridable";
591 return $sub->(@defaults);
594 # A wrapper to check if a given feature is enabled.
595 # With this, you can say
597 # my $bool_feat = gitweb_check_feature('bool_feat');
598 # gitweb_check_feature('bool_feat') or somecode;
602 # my ($bool_feat) = gitweb_get_feature('bool_feat');
603 # (gitweb_get_feature('bool_feat'))[0] or somecode;
605 sub gitweb_check_feature
{
606 return (gitweb_get_feature
(@_))[0];
612 my ($val) = git_get_project_config
($key, '--bool');
616 } elsif ($val eq 'true') {
618 } elsif ($val eq 'false') {
623 sub feature_snapshot
{
626 my ($val) = git_get_project_config
('snapshot');
629 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
635 sub feature_patches
{
636 my @val = (git_get_project_config
('patches', '--int'));
646 my @val = (git_get_project_config
('avatar'));
648 return @val ? @val : @_;
651 sub feature_extra_branch_refs
{
652 my (@branch_refs) = @_;
653 my $values = git_get_project_config
('extrabranchrefs');
656 $values = config_to_multi
($values);
658 foreach my $value (@{$values}) {
659 push @branch_refs, split /\s+/, $value;
666 # checking HEAD file with -e is fragile if the repository was
667 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
669 sub check_head_link
{
671 my $headfile = "$dir/HEAD";
672 return ((-e
$headfile) ||
673 (-l
$headfile && readlink($headfile) =~ /^refs\/heads\
//));
676 sub check_export_ok
{
678 return (check_head_link
($dir) &&
679 (!$export_ok || -e
"$dir/$export_ok") &&
680 (!$export_auth_hook || $export_auth_hook->($dir)));
683 # process alternate names for backward compatibility
684 # filter out unsupported (unknown) snapshot formats
685 sub filter_snapshot_fmts
{
689 exists $known_snapshot_format_aliases{$_} ?
690 $known_snapshot_format_aliases{$_} : $_} @fmts;
692 exists $known_snapshot_formats{$_} &&
693 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
696 sub filter_and_validate_refs
{
698 my %unique_refs = ();
700 foreach my $ref (@refs) {
701 die_error
(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format
($ref));
702 # 'heads' are added implicitly in get_branch_refs().
703 $unique_refs{$ref} = 1 if ($ref ne 'heads');
705 return sort keys %unique_refs;
708 # If it is set to code reference, it is code that it is to be run once per
709 # request, allowing updating configurations that change with each request,
710 # while running other code in config file only once.
712 # Otherwise, if it is false then gitweb would process config file only once;
713 # if it is true then gitweb config would be run for each request.
714 our $per_request_config = 1;
716 # read and parse gitweb config file given by its parameter.
717 # returns true on success, false on recoverable error, allowing
718 # to chain this subroutine, using first file that exists.
719 # dies on errors during parsing config file, as it is unrecoverable.
720 sub read_config_file
{
721 my $filename = shift;
722 return unless defined $filename;
723 # die if there are errors parsing config file
732 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
733 sub evaluate_gitweb_config
{
734 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
735 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
736 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
738 # Protect against duplications of file names, to not read config twice.
739 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
740 # there possibility of duplication of filename there doesn't matter.
741 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
742 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
744 # Common system-wide settings for convenience.
745 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
746 read_config_file
($GITWEB_CONFIG_COMMON);
748 # Use first config file that exists. This means use the per-instance
749 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
750 read_config_file
($GITWEB_CONFIG) and return;
751 read_config_file
($GITWEB_CONFIG_SYSTEM);
754 # Get loadavg of system, to compare against $maxload.
755 # Currently it requires '/proc/loadavg' present to get loadavg;
756 # if it is not present it returns 0, which means no load checking.
758 if( -e
'/proc/loadavg' ){
759 open my $fd, '<', '/proc/loadavg'
761 my @load = split(/\s+/, scalar <$fd>);
764 # The first three columns measure CPU and IO utilization of the last one,
765 # five, and 10 minute periods. The fourth column shows the number of
766 # currently running processes and the total number of processes in the m/n
767 # format. The last column displays the last process ID used.
768 return $load[0] || 0;
770 # additional checks for load average should go here for things that don't export
776 # version of the core git binary
778 sub evaluate_git_version
{
779 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
780 $number_of_git_cmds++;
784 if (defined $maxload && get_loadavg
() > $maxload) {
785 die_error
(503, "The load average on the server is too high");
789 # ======================================================================
790 # input validation and dispatch
792 # Various hash size-related values.
794 my $sha256_extra_len = 24;
795 my $sha256_len = $sha1_len + $sha256_extra_len;
797 # A regex matching $len hex characters. $len may be a range (e.g. 7,64).
800 my $hchr = qr/[0-9a-fA-F]/;
801 return qr/(?:(?:$hchr){$len})/;
804 # A regex matching two sets of $nlen hex characters, prefixed by the literal
805 # string $prefix and with the literal string $infix between them.
806 sub oid_nlen_prefix_infix_regex
{
811 my $rx = oid_nlen_regex
($nlen);
813 return qr/^\Q$prefix\E$rx\Q$infix\E$rx$/;
816 # A regex matching a valid object ID.
819 my $x = oid_nlen_regex
($sha1_len);
820 my $y = oid_nlen_regex
($sha256_extra_len);
821 $oid_regex = qr/(?:$x(?:$y)?)/;
824 # input parameters can be collected from a variety of sources (presently, CGI
825 # and PATH_INFO), so we define an %input_params hash that collects them all
826 # together during validation: this allows subsequent uses (e.g. href()) to be
827 # agnostic of the parameter origin
829 our %input_params = ();
831 # input parameters are stored with the long parameter name as key. This will
832 # also be used in the href subroutine to convert parameters to their CGI
833 # equivalent, and since the href() usage is the most frequent one, we store
834 # the name -> CGI key mapping here, instead of the reverse.
836 # XXX: Warning: If you touch this, check the search form for updating,
839 our @cgi_param_mapping = (
847 hash_parent_base
=> "hpb",
852 snapshot_format
=> "sf",
853 extra_options
=> "opt",
854 search_use_regexp
=> "sr",
857 project_filter
=> "pf",
858 # this must be last entry (for manipulation from JavaScript)
861 our %cgi_param_mapping = @cgi_param_mapping;
863 # we will also need to know the possible actions, for validation
865 "blame" => \
&git_blame
,
866 "blame_incremental" => \
&git_blame_incremental
,
867 "blame_data" => \
&git_blame_data
,
868 "blobdiff" => \
&git_blobdiff
,
869 "blobdiff_plain" => \
&git_blobdiff_plain
,
870 "blob" => \
&git_blob
,
871 "blob_plain" => \
&git_blob_plain
,
872 "commitdiff" => \
&git_commitdiff
,
873 "commitdiff_plain" => \
&git_commitdiff_plain
,
874 "commit" => \
&git_commit
,
875 "forks" => \
&git_forks
,
876 "heads" => \
&git_heads
,
877 "history" => \
&git_history
,
879 "patch" => \
&git_patch
,
880 "patches" => \
&git_patches
,
881 "remotes" => \
&git_remotes
,
883 "atom" => \
&git_atom
,
884 "search" => \
&git_search
,
885 "search_help" => \
&git_search_help
,
886 "shortlog" => \
&git_shortlog
,
887 "summary" => \
&git_summary
,
889 "tags" => \
&git_tags
,
890 "tree" => \
&git_tree
,
891 "snapshot" => \
&git_snapshot
,
892 "object" => \
&git_object
,
893 # those below don't need $project
894 "opml" => \
&git_opml
,
895 "project_list" => \
&git_project_list
,
896 "project_index" => \
&git_project_index
,
899 # finally, we have the hash of allowed extra_options for the commands that
901 our %allowed_options = (
902 "--no-merges" => [ qw(rss atom log shortlog history) ],
905 # fill %input_params with the CGI parameters. All values except for 'opt'
906 # should be single values, but opt can be an array. We should probably
907 # build an array of parameters that can be multi-valued, but since for the time
908 # being it's only this one, we just single it out
909 sub evaluate_query_params
{
912 while (my ($name, $symbol) = each %cgi_param_mapping) {
913 if ($symbol eq 'opt') {
914 $input_params{$name} = [ map { decode_utf8
($_) } $cgi->multi_param($symbol) ];
916 $input_params{$name} = decode_utf8
($cgi->param($symbol));
921 # now read PATH_INFO and update the parameter list for missing parameters
922 sub evaluate_path_info
{
923 return if defined $input_params{'project'};
924 return if !$path_info;
925 $path_info =~ s
,^/+,,;
926 return if !$path_info;
928 # find which part of PATH_INFO is project
929 my $project = $path_info;
931 while ($project && !check_head_link
("$projectroot/$project")) {
932 $project =~ s
,/*[^/]*$,,;
934 return unless $project;
935 $input_params{'project'} = $project;
937 # do not change any parameters if an action is given using the query string
938 return if $input_params{'action'};
939 $path_info =~ s
,^\Q
$project\E
/*,,;
941 # next, check if we have an action
942 my $action = $path_info;
944 if (exists $actions{$action}) {
945 $path_info =~ s
,^$action/*,,;
946 $input_params{'action'} = $action;
949 # list of actions that want hash_base instead of hash, but can have no
950 # pathname (f) parameter
956 # we want to catch, among others
957 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
958 my ($parentrefname, $parentpathname, $refname, $pathname) =
959 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
961 # first, analyze the 'current' part
962 if (defined $pathname) {
963 # we got "branch:filename" or "branch:dir/"
964 # we could use git_get_type(branch:pathname), but:
965 # - it needs $git_dir
966 # - it does a git() call
967 # - the convention of terminating directories with a slash
968 # makes it superfluous
969 # - embedding the action in the PATH_INFO would make it even
971 $pathname =~ s
,^/+,,;
972 if (!$pathname || substr($pathname, -1) eq "/") {
973 $input_params{'action'} ||= "tree";
976 # the default action depends on whether we had parent info
978 if ($parentrefname) {
979 $input_params{'action'} ||= "blobdiff_plain";
981 $input_params{'action'} ||= "blob_plain";
984 $input_params{'hash_base'} ||= $refname;
985 $input_params{'file_name'} ||= $pathname;
986 } elsif (defined $refname) {
987 # we got "branch". In this case we have to choose if we have to
988 # set hash or hash_base.
990 # Most of the actions without a pathname only want hash to be
991 # set, except for the ones specified in @wants_base that want
992 # hash_base instead. It should also be noted that hand-crafted
993 # links having 'history' as an action and no pathname or hash
994 # set will fail, but that happens regardless of PATH_INFO.
995 if (defined $parentrefname) {
996 # if there is parent let the default be 'shortlog' action
997 # (for http://git.example.com/repo.git/A..B links); if there
998 # is no parent, dispatch will detect type of object and set
999 # action appropriately if required (if action is not set)
1000 $input_params{'action'} ||= "shortlog";
1002 if ($input_params{'action'} &&
1003 grep { $_ eq $input_params{'action'} } @wants_base) {
1004 $input_params{'hash_base'} ||= $refname;
1006 $input_params{'hash'} ||= $refname;
1010 # next, handle the 'parent' part, if present
1011 if (defined $parentrefname) {
1012 # a missing pathspec defaults to the 'current' filename, allowing e.g.
1013 # someproject/blobdiff/oldrev..newrev:/filename
1014 if ($parentpathname) {
1015 $parentpathname =~ s
,^/+,,;
1016 $parentpathname =~ s
,/$,,;
1017 $input_params{'file_parent'} ||= $parentpathname;
1019 $input_params{'file_parent'} ||= $input_params{'file_name'};
1021 # we assume that hash_parent_base is wanted if a path was specified,
1022 # or if the action wants hash_base instead of hash
1023 if (defined $input_params{'file_parent'} ||
1024 grep { $_ eq $input_params{'action'} } @wants_base) {
1025 $input_params{'hash_parent_base'} ||= $parentrefname;
1027 $input_params{'hash_parent'} ||= $parentrefname;
1031 # for the snapshot action, we allow URLs in the form
1032 # $project/snapshot/$hash.ext
1033 # where .ext determines the snapshot and gets removed from the
1034 # passed $refname to provide the $hash.
1036 # To be able to tell that $refname includes the format extension, we
1037 # require the following two conditions to be satisfied:
1038 # - the hash input parameter MUST have been set from the $refname part
1039 # of the URL (i.e. they must be equal)
1040 # - the snapshot format MUST NOT have been defined already (e.g. from
1042 # It's also useless to try any matching unless $refname has a dot,
1043 # so we check for that too
1044 if (defined $input_params{'action'} &&
1045 $input_params{'action'} eq 'snapshot' &&
1046 defined $refname && index($refname, '.') != -1 &&
1047 $refname eq $input_params{'hash'} &&
1048 !defined $input_params{'snapshot_format'}) {
1049 # We loop over the known snapshot formats, checking for
1050 # extensions. Allowed extensions are both the defined suffix
1051 # (which includes the initial dot already) and the snapshot
1052 # format key itself, with a prepended dot
1053 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1054 my $hash = $refname;
1055 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1059 # a valid suffix was found, so set the snapshot format
1060 # and reset the hash parameter
1061 $input_params{'snapshot_format'} = $fmt;
1062 $input_params{'hash'} = $hash;
1063 # we also set the format suffix to the one requested
1064 # in the URL: this way a request for e.g. .tgz returns
1065 # a .tgz instead of a .tar.gz
1066 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1072 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1073 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1074 $searchtext, $search_regexp, $project_filter);
1075 sub evaluate_and_validate_params
{
1076 our $action = $input_params{'action'};
1077 if (defined $action) {
1078 if (!is_valid_action
($action)) {
1079 die_error
(400, "Invalid action parameter");
1083 # parameters which are pathnames
1084 our $project = $input_params{'project'};
1085 if (defined $project) {
1086 if (!is_valid_project
($project)) {
1088 die_error
(404, "No such project");
1092 our $project_filter = $input_params{'project_filter'};
1093 if (defined $project_filter) {
1094 if (!is_valid_pathname
($project_filter)) {
1095 die_error
(404, "Invalid project_filter parameter");
1099 our $file_name = $input_params{'file_name'};
1100 if (defined $file_name) {
1101 if (!is_valid_pathname
($file_name)) {
1102 die_error
(400, "Invalid file parameter");
1106 our $file_parent = $input_params{'file_parent'};
1107 if (defined $file_parent) {
1108 if (!is_valid_pathname
($file_parent)) {
1109 die_error
(400, "Invalid file parent parameter");
1113 # parameters which are refnames
1114 our $hash = $input_params{'hash'};
1115 if (defined $hash) {
1116 if (!is_valid_refname
($hash)) {
1117 die_error
(400, "Invalid hash parameter");
1121 our $hash_parent = $input_params{'hash_parent'};
1122 if (defined $hash_parent) {
1123 if (!is_valid_refname
($hash_parent)) {
1124 die_error
(400, "Invalid hash parent parameter");
1128 our $hash_base = $input_params{'hash_base'};
1129 if (defined $hash_base) {
1130 if (!is_valid_refname
($hash_base)) {
1131 die_error
(400, "Invalid hash base parameter");
1135 our @extra_options = @{$input_params{'extra_options'}};
1136 # @extra_options is always defined, since it can only be (currently) set from
1137 # CGI, and $cgi->param() returns the empty array in array context if the param
1139 foreach my $opt (@extra_options) {
1140 if (not exists $allowed_options{$opt}) {
1141 die_error
(400, "Invalid option parameter");
1143 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1144 die_error
(400, "Invalid option parameter for this action");
1148 our $hash_parent_base = $input_params{'hash_parent_base'};
1149 if (defined $hash_parent_base) {
1150 if (!is_valid_refname
($hash_parent_base)) {
1151 die_error
(400, "Invalid hash parent base parameter");
1156 our $page = $input_params{'page'};
1157 if (defined $page) {
1158 if ($page =~ m/[^0-9]/) {
1159 die_error
(400, "Invalid page parameter");
1163 our $searchtype = $input_params{'searchtype'};
1164 if (defined $searchtype) {
1165 if ($searchtype =~ m/[^a-z]/) {
1166 die_error
(400, "Invalid searchtype parameter");
1170 our $search_use_regexp = $input_params{'search_use_regexp'};
1172 our $searchtext = $input_params{'searchtext'};
1173 our $search_regexp = undef;
1174 if (defined $searchtext) {
1175 if (length($searchtext) < 2) {
1176 die_error
(403, "At least two characters are required for search parameter");
1178 if ($search_use_regexp) {
1179 $search_regexp = $searchtext;
1180 if (!eval { qr/$search_regexp/; 1; }) {
1181 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1182 die_error
(400, "Invalid search regexp '$search_regexp'",
1186 $search_regexp = quotemeta $searchtext;
1191 # path to the current git repository
1193 sub evaluate_git_dir
{
1194 our $git_dir = "$projectroot/$project" if $project;
1197 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1198 sub configure_gitweb_features
{
1199 # list of supported snapshot formats
1200 our @snapshot_fmts = gitweb_get_feature
('snapshot');
1201 @snapshot_fmts = filter_snapshot_fmts
(@snapshot_fmts);
1203 our ($git_avatar) = gitweb_get_feature
('avatar');
1204 $git_avatar = '' unless $git_avatar =~ /^(?:gravatar|picon)$/s;
1206 our @extra_branch_refs = gitweb_get_feature
('extra-branch-refs');
1207 @extra_branch_refs = filter_and_validate_refs
(@extra_branch_refs);
1210 sub get_branch_refs
{
1211 return ('heads', @extra_branch_refs);
1214 # custom error handler: 'die <message>' is Internal Server Error
1215 sub handle_errors_html
{
1216 my $msg = shift; # it is already HTML escaped
1218 # to avoid infinite loop where error occurs in die_error,
1219 # change handler to default handler, disabling handle_errors_html
1220 set_message
("Error occurred when inside die_error:\n$msg");
1222 # you cannot jump out of die_error when called as error handler;
1223 # the subroutine set via CGI::Carp::set_message is called _after_
1224 # HTTP headers are already written, so it cannot write them itself
1225 die_error
(undef, undef, $msg, -error_handler
=> 1, -no_http_header
=> 1);
1227 set_message
(\
&handle_errors_html
);
1231 if (!defined $action) {
1232 if (defined $hash) {
1233 $action = git_get_type
($hash);
1234 $action or die_error
(404, "Object does not exist");
1235 } elsif (defined $hash_base && defined $file_name) {
1236 $action = git_get_type
("$hash_base:$file_name");
1237 $action or die_error
(404, "File or directory does not exist");
1238 } elsif (defined $project) {
1239 $action = 'summary';
1241 $action = 'project_list';
1244 if (!defined($actions{$action})) {
1245 die_error
(400, "Unknown action");
1247 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1249 die_error
(400, "Project needed");
1251 $actions{$action}->();
1255 our $t0 = [ gettimeofday
() ]
1257 our $number_of_git_cmds = 0;
1260 our $first_request = 1;
1265 if ($first_request) {
1266 evaluate_gitweb_config
();
1267 evaluate_git_version
();
1269 if ($per_request_config) {
1270 if (ref($per_request_config) eq 'CODE') {
1271 $per_request_config->();
1272 } elsif (!$first_request) {
1273 evaluate_gitweb_config
();
1278 # $projectroot and $projects_list might be set in gitweb config file
1279 $projects_list ||= $projectroot;
1281 evaluate_query_params
();
1282 evaluate_path_info
();
1283 evaluate_and_validate_params
();
1286 configure_gitweb_features
();
1291 our $is_last_request = sub { 1 };
1292 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1295 sub configure_as_fcgi
{
1297 our $CGI = 'CGI::Fast';
1299 my $request_number = 0;
1300 # let each child service 100 requests
1301 our $is_last_request = sub { ++$request_number > 100 };
1304 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__
;
1306 if $script_name =~ /\.fcgi$/;
1308 return unless (@ARGV);
1310 require Getopt
::Long
;
1311 Getopt
::Long
::GetOptions
(
1312 'fastcgi|fcgi|f' => \
&configure_as_fcgi
,
1313 'nproc|n=i' => sub {
1314 my ($arg, $val) = @_;
1315 return unless eval { require FCGI
::ProcManager
; 1; };
1316 my $proc_manager = FCGI
::ProcManager-
>new({
1317 n_processes
=> $val,
1319 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1320 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1321 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1330 $pre_listen_hook->()
1331 if $pre_listen_hook;
1334 while ($cgi = $CGI->new()) {
1335 $pre_dispatch_hook->()
1336 if $pre_dispatch_hook;
1340 $post_dispatch_hook->()
1341 if $post_dispatch_hook;
1344 last REQUEST
if ($is_last_request->());
1353 if (defined caller) {
1354 # wrapped in a subroutine processing requests,
1355 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1358 # pure CGI script, serving single request
1362 ## ======================================================================
1365 # possible values of extra options
1366 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1367 # -replay => 1 - start from a current view (replay with modifications)
1368 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1369 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1372 # default is to use -absolute url() i.e. $my_uri
1373 my $href = $params{-full
} ? $my_url : $my_uri;
1375 # implicit -replay, must be first of implicit params
1376 $params{-replay
} = 1 if (keys %params == 1 && $params{-anchor
});
1378 $params{'project'} = $project unless exists $params{'project'};
1380 if ($params{-replay
}) {
1381 while (my ($name, $symbol) = each %cgi_param_mapping) {
1382 if (!exists $params{$name}) {
1383 $params{$name} = $input_params{$name};
1388 my $use_pathinfo = gitweb_check_feature
('pathinfo');
1389 if (defined $params{'project'} &&
1390 (exists $params{-path_info
} ? $params{-path_info
} : $use_pathinfo)) {
1391 # try to put as many parameters as possible in PATH_INFO:
1394 # - hash_parent or hash_parent_base:/file_parent
1395 # - hash or hash_base:/filename
1396 # - the snapshot_format as an appropriate suffix
1398 # When the script is the root DirectoryIndex for the domain,
1399 # $href here would be something like http://gitweb.example.com/
1400 # Thus, we strip any trailing / from $href, to spare us double
1401 # slashes in the final URL
1404 # Then add the project name, if present
1405 $href .= "/".esc_path_info
($params{'project'});
1406 delete $params{'project'};
1408 # since we destructively absorb parameters, we keep this
1409 # boolean that remembers if we're handling a snapshot
1410 my $is_snapshot = $params{'action'} eq 'snapshot';
1412 # Summary just uses the project path URL, any other action is
1414 if (defined $params{'action'}) {
1415 $href .= "/".esc_path_info
($params{'action'})
1416 unless $params{'action'} eq 'summary';
1417 delete $params{'action'};
1420 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1421 # stripping nonexistent or useless pieces
1422 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1423 || $params{'hash_parent'} || $params{'hash'});
1424 if (defined $params{'hash_base'}) {
1425 if (defined $params{'hash_parent_base'}) {
1426 $href .= esc_path_info
($params{'hash_parent_base'});
1427 # skip the file_parent if it's the same as the file_name
1428 if (defined $params{'file_parent'}) {
1429 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1430 delete $params{'file_parent'};
1431 } elsif ($params{'file_parent'} !~ /\.\./) {
1432 $href .= ":/".esc_path_info
($params{'file_parent'});
1433 delete $params{'file_parent'};
1437 delete $params{'hash_parent'};
1438 delete $params{'hash_parent_base'};
1439 } elsif (defined $params{'hash_parent'}) {
1440 $href .= esc_path_info
($params{'hash_parent'}). "..";
1441 delete $params{'hash_parent'};
1444 $href .= esc_path_info
($params{'hash_base'});
1445 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1446 $href .= ":/".esc_path_info
($params{'file_name'});
1447 delete $params{'file_name'};
1449 delete $params{'hash'};
1450 delete $params{'hash_base'};
1451 } elsif (defined $params{'hash'}) {
1452 $href .= esc_path_info
($params{'hash'});
1453 delete $params{'hash'};
1456 # If the action was a snapshot, we can absorb the
1457 # snapshot_format parameter too
1459 my $fmt = $params{'snapshot_format'};
1460 # snapshot_format should always be defined when href()
1461 # is called, but just in case some code forgets, we
1462 # fall back to the default
1463 $fmt ||= $snapshot_fmts[0];
1464 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1465 delete $params{'snapshot_format'};
1469 # now encode the parameters explicitly
1471 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1472 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1473 if (defined $params{$name}) {
1474 if (ref($params{$name}) eq "ARRAY") {
1475 foreach my $par (@{$params{$name}}) {
1476 push @result, $symbol . "=" . esc_param
($par);
1479 push @result, $symbol . "=" . esc_param
($params{$name});
1483 $href .= "?" . join(';', @result) if scalar @result;
1485 # final transformation: trailing spaces must be escaped (URI-encoded)
1486 $href =~ s/(\s+)$/CGI::escape($1)/e;
1488 if ($params{-anchor
}) {
1489 $href .= "#".esc_param
($params{-anchor
});
1496 ## ======================================================================
1497 ## validation, quoting/unquoting and escaping
1499 sub is_valid_action
{
1501 return undef unless exists $actions{$input};
1505 sub is_valid_project
{
1508 return unless defined $input;
1509 if (!is_valid_pathname
($input) ||
1510 !(-d
"$projectroot/$input") ||
1511 !check_export_ok
("$projectroot/$input") ||
1512 ($strict_export && !project_in_list
($input))) {
1519 sub is_valid_pathname
{
1522 return undef unless defined $input;
1523 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1524 # at the beginning, at the end, and between slashes.
1525 # also this catches doubled slashes
1526 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1529 # no null characters
1530 if ($input =~ m!\0!) {
1536 sub is_valid_ref_format
{
1539 return undef unless defined $input;
1540 # restrictions on ref name according to git-check-ref-format
1541 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1547 sub is_valid_refname
{
1550 return undef unless defined $input;
1551 # textual hashes are O.K.
1552 if ($input =~ m/^$oid_regex$/) {
1555 # it must be correct pathname
1556 is_valid_pathname
($input) or return undef;
1557 # check git-check-ref-format restrictions
1558 is_valid_ref_format
($input) or return undef;
1562 # decode sequences of octets in utf8 into Perl's internal form,
1563 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1564 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1567 return undef unless defined $str;
1569 if (utf8
::is_utf8
($str) || utf8
::decode
($str)) {
1572 return decode
($fallback_encoding, $str, Encode
::FB_DEFAULT
);
1576 # quote unsafe chars, but keep the slash, even when it's not
1577 # correct, but quoted slashes look too horrible in bookmarks
1580 return undef unless defined $str;
1581 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI
::escape
($1)/eg
;
1586 # the quoting rules for path_info fragment are slightly different
1589 return undef unless defined $str;
1591 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1592 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI
::escape
($1)/eg
;
1597 # quote unsafe chars in whole URL, so some characters cannot be quoted
1600 return undef unless defined $str;
1601 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI
::escape
($1)/eg
;
1606 # quote unsafe characters in HTML attributes
1609 # for XHTML conformance escaping '"' to '"' is not enough
1610 return esc_html
(@_);
1613 # replace invalid utf8 character with SUBSTITUTION sequence
1618 return undef unless defined $str;
1620 $str = to_utf8
($str);
1621 $str = $cgi->escapeHTML($str);
1622 if ($opts{'-nbsp'}) {
1623 $str =~ s/ / /g;
1625 $str =~ s
|([[:cntrl
:]])|(($1 ne "\t") ? quot_cec
($1) : $1)|eg
;
1629 # quote control characters and escape filename to HTML
1634 return undef unless defined $str;
1636 $str = to_utf8
($str);
1637 $str = $cgi->escapeHTML($str);
1638 if ($opts{'-nbsp'}) {
1639 $str =~ s/ / /g;
1641 $str =~ s
|([[:cntrl
:]])|quot_cec
($1)|eg
;
1645 # Sanitize for use in XHTML + application/xml+xhtml (valid XML 1.0)
1649 return undef unless defined $str;
1651 $str = to_utf8
($str);
1652 $str =~ s
|([[:cntrl
:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec
($1))|eg
;
1656 # Make control characters "printable", using character escape codes (CEC)
1660 my %es = ( # character escape codes, aka escape sequences
1661 "\t" => '\t', # tab (HT)
1662 "\n" => '\n', # line feed (LF)
1663 "\r" => '\r', # carriage return (CR)
1664 "\f" => '\f', # form feed (FF)
1665 "\b" => '\b', # backspace (BS)
1666 "\a" => '\a', # alarm (bell) (BEL)
1667 "\e" => '\e', # escape (ESC)
1668 "\013" => '\v', # vertical tab (VT)
1669 "\000" => '\0', # nul character (NUL)
1671 my $chr = ( (exists $es{$cntrl})
1673 : sprintf('\%2x', ord($cntrl)) );
1674 if ($opts{-nohtml
}) {
1677 return "<span class=\"cntrl\">$chr</span>";
1681 # Alternatively use unicode control pictures codepoints,
1682 # Unicode "printable representation" (PR)
1687 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1688 if ($opts{-nohtml
}) {
1691 return "<span class=\"cntrl\">$chr</span>";
1695 # git may return quoted and escaped filenames
1701 my %es = ( # character escape codes, aka escape sequences
1702 't' => "\t", # tab (HT, TAB)
1703 'n' => "\n", # newline (NL)
1704 'r' => "\r", # return (CR)
1705 'f' => "\f", # form feed (FF)
1706 'b' => "\b", # backspace (BS)
1707 'a' => "\a", # alarm (bell) (BEL)
1708 'e' => "\e", # escape (ESC)
1709 'v' => "\013", # vertical tab (VT)
1712 if ($seq =~ m/^[0-7]{1,3}$/) {
1713 # octal char sequence
1714 return chr(oct($seq));
1715 } elsif (exists $es{$seq}) {
1716 # C escape sequence, aka character escape code
1719 # quoted ordinary character
1723 if ($str =~ m/^"(.*)"$/) {
1726 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1731 # escape tabs (convert tabs to spaces)
1735 while ((my $pos = index($line, "\t")) != -1) {
1736 if (my $count = (8 - ($pos % 8))) {
1737 my $spaces = ' ' x
$count;
1738 $line =~ s/\t/$spaces/;
1745 sub project_in_list
{
1746 my $project = shift;
1747 my @list = git_get_projects_list
();
1748 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1751 ## ----------------------------------------------------------------------
1752 ## HTML aware string manipulation
1754 # Try to chop given string on a word boundary between position
1755 # $len and $len+$add_len. If there is no word boundary there,
1756 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1757 # (marking chopped part) would be longer than given string.
1761 my $add_len = shift || 10;
1762 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1764 # Make sure perl knows it is utf8 encoded so we don't
1765 # cut in the middle of a utf8 multibyte char.
1766 $str = to_utf8
($str);
1768 # allow only $len chars, but don't cut a word if it would fit in $add_len
1769 # if it doesn't fit, cut it if it's still longer than the dots we would add
1770 # remove chopped character entities entirely
1772 # when chopping in the middle, distribute $len into left and right part
1773 # return early if chopping wouldn't make string shorter
1774 if ($where eq 'center') {
1775 return $str if ($len + 5 >= length($str)); # filler is length 5
1778 return $str if ($len + 4 >= length($str)); # filler is length 4
1781 # regexps: ending and beginning with word part up to $add_len
1782 my $endre = qr/.{$len}\w{0,$add_len}/;
1783 my $begre = qr/\w{0,$add_len}.{$len}/;
1785 if ($where eq 'left') {
1786 $str =~ m/^(.*?)($begre)$/;
1787 my ($lead, $body) = ($1, $2);
1788 if (length($lead) > 4) {
1791 return "$lead$body";
1793 } elsif ($where eq 'center') {
1794 $str =~ m/^($endre)(.*)$/;
1795 my ($left, $str) = ($1, $2);
1796 $str =~ m/^(.*?)($begre)$/;
1797 my ($mid, $right) = ($1, $2);
1798 if (length($mid) > 5) {
1801 return "$left$mid$right";
1804 $str =~ m/^($endre)(.*)$/;
1807 if (length($tail) > 4) {
1810 return "$body$tail";
1814 # takes the same arguments as chop_str, but also wraps a <span> around the
1815 # result with a title attribute if it does get chopped. Additionally, the
1816 # string is HTML-escaped.
1817 sub chop_and_escape_str
{
1820 my $chopped = chop_str
(@_);
1821 $str = to_utf8
($str);
1822 if ($chopped eq $str) {
1823 return esc_html
($chopped);
1825 $str =~ s/[[:cntrl:]]/?/g;
1826 return $cgi->span({-title
=>$str}, esc_html
($chopped));
1830 # Highlight selected fragments of string, using given CSS class,
1831 # and escape HTML. It is assumed that fragments do not overlap.
1832 # Regions are passed as list of pairs (array references).
1834 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1835 # '<span class="mark">foo</span>bar'
1836 sub esc_html_hl_regions
{
1837 my ($str, $css_class, @sel) = @_;
1838 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1839 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1840 return esc_html
($str, %opts) unless @sel;
1846 my ($begin, $end) = @$s;
1848 # Don't create empty <span> elements.
1849 next if $end <= $begin;
1851 my $escaped = esc_html
(substr($str, $begin, $end - $begin),
1854 $out .= esc_html
(substr($str, $pos, $begin - $pos), %opts)
1855 if ($begin - $pos > 0);
1856 $out .= $cgi->span({-class => $css_class}, $escaped);
1860 $out .= esc_html
(substr($str, $pos), %opts)
1861 if ($pos < length($str));
1866 # return positions of beginning and end of each match
1868 my ($str, $regexp) = @_;
1869 return unless (defined $str && defined $regexp);
1872 while ($str =~ /$regexp/g) {
1873 push @matches, [$-[0], $+[0]];
1878 # highlight match (if any), and escape HTML
1879 sub esc_html_match_hl
{
1880 my ($str, $regexp) = @_;
1881 return esc_html
($str) unless defined $regexp;
1883 my @matches = matchpos_list
($str, $regexp);
1884 return esc_html
($str) unless @matches;
1886 return esc_html_hl_regions
($str, 'match', @matches);
1890 # highlight match (if any) of shortened string, and escape HTML
1891 sub esc_html_match_hl_chopped
{
1892 my ($str, $chopped, $regexp) = @_;
1893 return esc_html_match_hl
($str, $regexp) unless defined $chopped;
1895 my @matches = matchpos_list
($str, $regexp);
1896 return esc_html
($chopped) unless @matches;
1898 # filter matches so that we mark chopped string
1899 my $tail = "... "; # see chop_str
1900 unless ($chopped =~ s/\Q$tail\E$//) {
1903 my $chop_len = length($chopped);
1904 my $tail_len = length($tail);
1907 for my $m (@matches) {
1908 if ($m->[0] > $chop_len) {
1909 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1911 } elsif ($m->[1] > $chop_len) {
1912 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1918 return esc_html_hl_regions
($chopped . $tail, 'match', @filtered);
1921 ## ----------------------------------------------------------------------
1922 ## functions returning short strings
1924 # CSS class for given age value (in seconds)
1928 if (!defined $age) {
1930 } elsif ($age < 60*60*2) {
1932 } elsif ($age < 60*60*24*2) {
1939 # convert age in seconds to "nn units ago" string
1944 if ($age > 60*60*24*365*2) {
1945 $age_str = (int $age/60/60/24/365);
1946 $age_str .= " years ago";
1947 } elsif ($age > 60*60*24*(365/12)*2) {
1948 $age_str = int $age/60/60/24/(365/12);
1949 $age_str .= " months ago";
1950 } elsif ($age > 60*60*24*7*2) {
1951 $age_str = int $age/60/60/24/7;
1952 $age_str .= " weeks ago";
1953 } elsif ($age > 60*60*24*2) {
1954 $age_str = int $age/60/60/24;
1955 $age_str .= " days ago";
1956 } elsif ($age > 60*60*2) {
1957 $age_str = int $age/60/60;
1958 $age_str .= " hours ago";
1959 } elsif ($age > 60*2) {
1960 $age_str = int $age/60;
1961 $age_str .= " min ago";
1962 } elsif ($age > 2) {
1963 $age_str = int $age;
1964 $age_str .= " sec ago";
1966 $age_str .= " right now";
1972 S_IFINVALID
=> 0030000,
1973 S_IFGITLINK
=> 0160000,
1976 # submodule/subproject, a commit object reference
1980 return (($mode & S_IFMT
) == S_IFGITLINK
)
1983 # convert file mode in octal to symbolic file mode string
1985 my $mode = oct shift;
1987 if (S_ISGITLINK
($mode)) {
1988 return 'm---------';
1989 } elsif (S_ISDIR
($mode & S_IFMT
)) {
1990 return 'drwxr-xr-x';
1991 } elsif (S_ISLNK
($mode)) {
1992 return 'lrwxrwxrwx';
1993 } elsif (S_ISREG
($mode)) {
1994 # git cares only about the executable bit
1995 if ($mode & S_IXUSR
) {
1996 return '-rwxr-xr-x';
1998 return '-rw-r--r--';
2001 return '----------';
2005 # convert file mode in octal to file type string
2009 if ($mode !~ m/^[0-7]+$/) {
2015 if (S_ISGITLINK
($mode)) {
2017 } elsif (S_ISDIR
($mode & S_IFMT
)) {
2019 } elsif (S_ISLNK
($mode)) {
2021 } elsif (S_ISREG
($mode)) {
2028 # convert file mode in octal to file type description string
2029 sub file_type_long
{
2032 if ($mode !~ m/^[0-7]+$/) {
2038 if (S_ISGITLINK
($mode)) {
2040 } elsif (S_ISDIR
($mode & S_IFMT
)) {
2042 } elsif (S_ISLNK
($mode)) {
2044 } elsif (S_ISREG
($mode)) {
2045 if ($mode & S_IXUSR
) {
2046 return "executable";
2056 ## ----------------------------------------------------------------------
2057 ## functions returning short HTML fragments, or transforming HTML fragments
2058 ## which don't belong to other sections
2060 # format line of commit message.
2061 sub format_log_line_html
{
2064 # Potentially abbreviated OID.
2065 my $regex = oid_nlen_regex
("7,64");
2067 $line = esc_html
($line, -nbsp
=>1);
2071 # The output of "git describe", e.g. v2.10.0-297-gf6727b0
2072 # or hadoop-20160921-113441-20-g094fb7d
2073 (?<!-) # see strbuf_check_tag_ref(). Tags can't start with -
2075 (?!\
.) # refs can't end with ".", see check_refname_format()
2078 # Just a normal looking Git SHA1
2083 $cgi->a({-href
=> href
(action
=>"object", hash
=>$1),
2084 -class => "text"}, $1);
2090 # format marker of refs pointing to given object
2092 # the destination action is chosen based on object type and current context:
2093 # - for annotated tags, we choose the tag view unless it's the current view
2094 # already, in which case we go to shortlog view
2095 # - for other refs, we keep the current view if we're in history, shortlog or
2096 # log view, and select shortlog otherwise
2097 sub format_ref_marker
{
2098 my ($refs, $id) = @_;
2101 if (defined $refs->{$id}) {
2102 foreach my $ref (@{$refs->{$id}}) {
2103 # this code exploits the fact that non-lightweight tags are the
2104 # only indirect objects, and that they are the only objects for which
2105 # we want to use tag instead of shortlog as action
2106 my ($type, $name) = qw();
2107 my $indirect = ($ref =~ s/\^\{\}$//);
2108 # e.g. tags/v2.6.11 or heads/next
2109 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2118 $class .= " indirect" if $indirect;
2120 my $dest_action = "shortlog";
2123 $dest_action = "tag" unless $action eq "tag";
2124 } elsif ($action =~ /^(history|(short)?log)$/) {
2125 $dest_action = $action;
2129 $dest .= "refs/" unless $ref =~ m
!^refs
/!;
2132 my $link = $cgi->a({
2134 action
=>$dest_action,
2136 )}, esc_html
($name));
2138 $markers .= " <span class=\"".esc_attr
($class)."\" title=\"".esc_attr
($ref)."\">" .
2144 return ' <span class="refs">'. $markers . '</span>';
2150 # format, perhaps shortened and with markers, title line
2151 sub format_subject_html
{
2152 my ($long, $short, $href, $extra) = @_;
2153 $extra = '' unless defined($extra);
2155 if (length($short) < length($long)) {
2156 $long =~ s/[[:cntrl:]]/?/g;
2157 return $cgi->a({-href
=> $href, -class => "list subject",
2158 -title
=> to_utf8
($long)},
2159 esc_html
($short)) . $extra;
2161 return $cgi->a({-href
=> $href, -class => "list subject"},
2162 esc_html
($long)) . $extra;
2166 # Rather than recomputing the url for an email multiple times, we cache it
2167 # after the first hit. This gives a visible benefit in views where the avatar
2168 # for the same email is used repeatedly (e.g. shortlog).
2169 # The cache is shared by all avatar engines (currently gravatar only), which
2170 # are free to use it as preferred. Since only one avatar engine is used for any
2171 # given page, there's no risk for cache conflicts.
2172 our %avatar_cache = ();
2174 # Compute the picon url for a given email, by using the picon search service over at
2175 # http://www.cs.indiana.edu/picons/search.html
2177 my $email = lc shift;
2178 if (!$avatar_cache{$email}) {
2179 my ($user, $domain) = split('@', $email);
2180 $avatar_cache{$email} =
2181 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2183 "users+domains+unknown/up/single";
2185 return $avatar_cache{$email};
2188 # Compute the gravatar url for a given email, if it's not in the cache already.
2189 # Gravatar stores only the part of the URL before the size, since that's the
2190 # one computationally more expensive. This also allows reuse of the cache for
2191 # different sizes (for this particular engine).
2193 my $email = lc shift;
2195 $avatar_cache{$email} ||=
2196 "//www.gravatar.com/avatar/" .
2197 md5_hex
($email) . "?s=";
2198 return $avatar_cache{$email} . $size;
2201 # Insert an avatar for the given $email at the given $size if the feature
2203 sub git_get_avatar
{
2204 my ($email, %opts) = @_;
2205 my $pre_white = ($opts{-pad_before
} ? " " : "");
2206 my $post_white = ($opts{-pad_after
} ? " " : "");
2207 $opts{-size
} ||= 'default';
2208 my $size = $avatar_size{$opts{-size
}} || $avatar_size{'default'};
2210 if ($git_avatar eq 'gravatar') {
2211 $url = gravatar_url
($email, $size);
2212 } elsif ($git_avatar eq 'picon') {
2213 $url = picon_url
($email);
2215 # Other providers can be added by extending the if chain, defining $url
2216 # as needed. If no variant puts something in $url, we assume avatars
2217 # are completely disabled/unavailable.
2220 "<img width=\"$size\" " .
2221 "class=\"avatar\" " .
2222 "src=\"".esc_url
($url)."\" " .
2230 sub format_search_author
{
2231 my ($author, $searchtype, $displaytext) = @_;
2232 my $have_search = gitweb_check_feature
('search');
2236 if ($searchtype eq 'author') {
2237 $performed = "authored";
2238 } elsif ($searchtype eq 'committer') {
2239 $performed = "committed";
2242 return $cgi->a({-href
=> href
(action
=>"search", hash
=>$hash,
2243 searchtext
=>$author,
2244 searchtype
=>$searchtype), class=>"list",
2245 title
=>"Search for commits $performed by $author"},
2249 return $displaytext;
2253 # format the author name of the given commit with the given tag
2254 # the author name is chopped and escaped according to the other
2255 # optional parameters (see chop_str).
2256 sub format_author_html
{
2259 my $author = chop_and_escape_str
($co->{'author_name'}, @_);
2260 return "<$tag class=\"author\">" .
2261 format_search_author
($co->{'author_name'}, "author",
2262 git_get_avatar
($co->{'author_email'}, -pad_after
=> 1) .
2267 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2268 sub format_git_diff_header_line
{
2270 my $diffinfo = shift;
2271 my ($from, $to) = @_;
2273 if ($diffinfo->{'nparents'}) {
2275 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2276 if ($to->{'href'}) {
2277 $line .= $cgi->a({-href
=> $to->{'href'}, -class => "path"},
2278 esc_path
($to->{'file'}));
2279 } else { # file was deleted (no href)
2280 $line .= esc_path
($to->{'file'});
2284 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2285 if ($from->{'href'}) {
2286 $line .= $cgi->a({-href
=> $from->{'href'}, -class => "path"},
2287 'a/' . esc_path
($from->{'file'}));
2288 } else { # file was added (no href)
2289 $line .= 'a/' . esc_path
($from->{'file'});
2292 if ($to->{'href'}) {
2293 $line .= $cgi->a({-href
=> $to->{'href'}, -class => "path"},
2294 'b/' . esc_path
($to->{'file'}));
2295 } else { # file was deleted
2296 $line .= 'b/' . esc_path
($to->{'file'});
2300 return "<div class=\"diff header\">$line</div>\n";
2303 # format extended diff header line, before patch itself
2304 sub format_extended_diff_header_line
{
2306 my $diffinfo = shift;
2307 my ($from, $to) = @_;
2310 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2311 $line .= $cgi->a({-href
=>$from->{'href'}, -class=>"path"},
2312 esc_path
($from->{'file'}));
2314 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2315 $line .= $cgi->a({-href
=>$to->{'href'}, -class=>"path"},
2316 esc_path
($to->{'file'}));
2318 # match single <mode>
2319 if ($line =~ m/\s(\d{6})$/) {
2320 $line .= '<span class="info"> (' .
2321 file_type_long
($1) .
2325 if ($line =~ oid_nlen_prefix_infix_regex
($sha1_len, "index ", ",") |
2326 $line =~ oid_nlen_prefix_infix_regex
($sha256_len, "index ", ",")) {
2327 # can match only for combined diff
2329 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2330 if ($from->{'href'}[$i]) {
2331 $line .= $cgi->a({-href
=>$from->{'href'}[$i],
2333 substr($diffinfo->{'from_id'}[$i],0,7));
2338 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2341 if ($to->{'href'}) {
2342 $line .= $cgi->a({-href
=>$to->{'href'}, -class=>"hash"},
2343 substr($diffinfo->{'to_id'},0,7));
2348 } elsif ($line =~ oid_nlen_prefix_infix_regex
($sha1_len, "index ", "..") |
2349 $line =~ oid_nlen_prefix_infix_regex
($sha256_len, "index ", "..")) {
2350 # can match only for ordinary diff
2351 my ($from_link, $to_link);
2352 if ($from->{'href'}) {
2353 $from_link = $cgi->a({-href
=>$from->{'href'}, -class=>"hash"},
2354 substr($diffinfo->{'from_id'},0,7));
2356 $from_link = '0' x
7;
2358 if ($to->{'href'}) {
2359 $to_link = $cgi->a({-href
=>$to->{'href'}, -class=>"hash"},
2360 substr($diffinfo->{'to_id'},0,7));
2364 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2365 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2368 return $line . "<br/>\n";
2371 # format from-file/to-file diff header
2372 sub format_diff_from_to_header
{
2373 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2378 #assert($line =~ m/^---/) if DEBUG;
2379 # no extra formatting for "^--- /dev/null"
2380 if (! $diffinfo->{'nparents'}) {
2381 # ordinary (single parent) diff
2382 if ($line =~ m!^--- "?a/!) {
2383 if ($from->{'href'}) {
2385 $cgi->a({-href
=>$from->{'href'}, -class=>"path"},
2386 esc_path
($from->{'file'}));
2389 esc_path
($from->{'file'});
2392 $result .= qq
!<div
class="diff from_file">$line</div
>\n!;
2395 # combined diff (merge commit)
2396 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2397 if ($from->{'href'}[$i]) {
2399 $cgi->a({-href
=>href
(action
=>"blobdiff",
2400 hash_parent
=>$diffinfo->{'from_id'}[$i],
2401 hash_parent_base
=>$parents[$i],
2402 file_parent
=>$from->{'file'}[$i],
2403 hash
=>$diffinfo->{'to_id'},
2405 file_name
=>$to->{'file'}),
2407 -title
=>"diff" . ($i+1)},
2410 $cgi->a({-href
=>$from->{'href'}[$i], -class=>"path"},
2411 esc_path
($from->{'file'}[$i]));
2413 $line = '--- /dev/null';
2415 $result .= qq
!<div
class="diff from_file">$line</div
>\n!;
2420 #assert($line =~ m/^\+\+\+/) if DEBUG;
2421 # no extra formatting for "^+++ /dev/null"
2422 if ($line =~ m!^\+\+\+ "?b/!) {
2423 if ($to->{'href'}) {
2425 $cgi->a({-href
=>$to->{'href'}, -class=>"path"},
2426 esc_path
($to->{'file'}));
2429 esc_path
($to->{'file'});
2432 $result .= qq
!<div
class="diff to_file">$line</div
>\n!;
2437 # create note for patch simplified by combined diff
2438 sub format_diff_cc_simplified
{
2439 my ($diffinfo, @parents) = @_;
2442 $result .= "<div class=\"diff header\">" .
2444 if (!is_deleted
($diffinfo)) {
2445 $result .= $cgi->a({-href
=> href
(action
=>"blob",
2447 hash
=>$diffinfo->{'to_id'},
2448 file_name
=>$diffinfo->{'to_file'}),
2450 esc_path
($diffinfo->{'to_file'}));
2452 $result .= esc_path
($diffinfo->{'to_file'});
2454 $result .= "</div>\n" . # class="diff header"
2455 "<div class=\"diff nodifferences\">" .
2457 "</div>\n"; # class="diff nodifferences"
2462 sub diff_line_class
{
2463 my ($line, $from, $to) = @_;
2468 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2469 $num_sign = scalar @{$from->{'href'}};
2472 my @diff_line_classifier = (
2473 { regexp
=> qr/^\@\@{$num_sign} /, class => "chunk_header"},
2474 { regexp
=> qr/^\\/, class => "incomplete" },
2475 { regexp
=> qr/^ {$num_sign}/, class => "ctx" },
2476 # classifier for context must come before classifier add/rem,
2477 # or we would have to use more complicated regexp, for example
2478 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2479 { regexp
=> qr/^[+ ]{$num_sign}/, class => "add" },
2480 { regexp
=> qr/^[- ]{$num_sign}/, class => "rem" },
2482 for my $clsfy (@diff_line_classifier) {
2483 return $clsfy->{'class'}
2484 if ($line =~ $clsfy->{'regexp'});
2491 # assumes that $from and $to are defined and correctly filled,
2492 # and that $line holds a line of chunk header for unified diff
2493 sub format_unidiff_chunk_header
{
2494 my ($line, $from, $to) = @_;
2496 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2497 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2499 $from_lines = 0 unless defined $from_lines;
2500 $to_lines = 0 unless defined $to_lines;
2502 if ($from->{'href'}) {
2503 $from_text = $cgi->a({-href
=>"$from->{'href'}#l$from_start",
2504 -class=>"list"}, $from_text);
2506 if ($to->{'href'}) {
2507 $to_text = $cgi->a({-href
=>"$to->{'href'}#l$to_start",
2508 -class=>"list"}, $to_text);
2510 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2511 "<span class=\"section\">" . esc_html
($section, -nbsp
=>1) . "</span>";
2515 # assumes that $from and $to are defined and correctly filled,
2516 # and that $line holds a line of chunk header for combined diff
2517 sub format_cc_diff_chunk_header
{
2518 my ($line, $from, $to) = @_;
2520 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2521 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2523 @from_text = split(' ', $ranges);
2524 for (my $i = 0; $i < @from_text; ++$i) {
2525 ($from_start[$i], $from_nlines[$i]) =
2526 (split(',', substr($from_text[$i], 1)), 0);
2529 $to_text = pop @from_text;
2530 $to_start = pop @from_start;
2531 $to_nlines = pop @from_nlines;
2533 $line = "<span class=\"chunk_info\">$prefix ";
2534 for (my $i = 0; $i < @from_text; ++$i) {
2535 if ($from->{'href'}[$i]) {
2536 $line .= $cgi->a({-href
=>"$from->{'href'}[$i]#l$from_start[$i]",
2537 -class=>"list"}, $from_text[$i]);
2539 $line .= $from_text[$i];
2543 if ($to->{'href'}) {
2544 $line .= $cgi->a({-href
=>"$to->{'href'}#l$to_start",
2545 -class=>"list"}, $to_text);
2549 $line .= " $prefix</span>" .
2550 "<span class=\"section\">" . esc_html
($section, -nbsp
=>1) . "</span>";
2554 # process patch (diff) line (not to be used for diff headers),
2555 # returning HTML-formatted (but not wrapped) line.
2556 # If the line is passed as a reference, it is treated as HTML and not
2558 sub format_diff_line
{
2559 my ($line, $diff_class, $from, $to) = @_;
2565 $line = untabify
($line);
2567 if ($from && $to && $line =~ m/^\@{2} /) {
2568 $line = format_unidiff_chunk_header
($line, $from, $to);
2569 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2570 $line = format_cc_diff_chunk_header
($line, $from, $to);
2572 $line = esc_html
($line, -nbsp
=>1);
2576 my $diff_classes = "diff";
2577 $diff_classes .= " $diff_class" if ($diff_class);
2578 $line = "<div class=\"$diff_classes\">$line</div>\n";
2583 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2584 # linked. Pass the hash of the tree/commit to snapshot.
2585 sub format_snapshot_links
{
2587 my $num_fmts = @snapshot_fmts;
2588 if ($num_fmts > 1) {
2589 # A parenthesized list of links bearing format names.
2590 # e.g. "snapshot (_tar.gz_ _zip_)"
2591 return "snapshot (" . join(' ', map
2598 }, $known_snapshot_formats{$_}{'display'})
2599 , @snapshot_fmts) . ")";
2600 } elsif ($num_fmts == 1) {
2601 # A single "snapshot" link whose tooltip bears the format name.
2603 my ($fmt) = @snapshot_fmts;
2609 snapshot_format
=>$fmt
2611 -title
=> "in format: $known_snapshot_formats{$fmt}{'display'}"
2613 } else { # $num_fmts == 0
2618 ## ......................................................................
2619 ## functions returning values to be passed, perhaps after some
2620 ## transformation, to other functions; e.g. returning arguments to href()
2622 # returns hash to be passed to href to generate gitweb URL
2623 # in -title key it returns description of link
2625 my $format = shift || 'Atom';
2626 my %res = (action
=> lc($format));
2627 my $matched_ref = 0;
2629 # feed links are possible only for project views
2630 return unless (defined $project);
2631 # some views should link to OPML, or to generic project feed,
2632 # or don't have specific feed yet (so they should use generic)
2633 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2636 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2637 # (fullname) to differentiate from tag links; this also makes
2638 # possible to detect branch links
2639 for my $ref (get_branch_refs
()) {
2640 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2641 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2643 $matched_ref = $ref;
2647 # find log type for feed description (title)
2649 if (defined $file_name) {
2650 $type = "history of $file_name";
2651 $type .= "/" if ($action eq 'tree');
2652 $type .= " on '$branch'" if (defined $branch);
2654 $type = "log of $branch" if (defined $branch);
2657 $res{-title
} = $type;
2658 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2659 $res{'file_name'} = $file_name;
2664 ## ----------------------------------------------------------------------
2665 ## git utility subroutines, invoking git commands
2667 # returns path to the core git executable and the --git-dir parameter as list
2669 $number_of_git_cmds++;
2670 return $GIT, '--git-dir='.$git_dir;
2673 # quote the given arguments for passing them to the shell
2674 # quote_command("command", "arg 1", "arg with ' and ! characters")
2675 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2676 # Try to avoid using this function wherever possible.
2679 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2682 # get HEAD ref of given project as hash
2683 sub git_get_head_hash
{
2684 return git_get_full_hash
(shift, 'HEAD');
2687 sub git_get_full_hash
{
2688 return git_get_hash
(@_);
2691 sub git_get_short_hash
{
2692 return git_get_hash
(@_, '--short=7');
2696 my ($project, $hash, @options) = @_;
2697 my $o_git_dir = $git_dir;
2699 $git_dir = "$projectroot/$project";
2700 if (open my $fd, '-|', git_cmd
(), 'rev-parse',
2701 '--verify', '-q', @options, $hash) {
2703 chomp $retval if defined $retval;
2706 if (defined $o_git_dir) {
2707 $git_dir = $o_git_dir;
2712 # get type of given object
2716 open my $fd, "-|", git_cmd
(), "cat-file", '-t', $hash or return;
2718 close $fd or return;
2723 # repository configuration
2724 our $config_file = '';
2727 # store multiple values for single key as anonymous array reference
2728 # single values stored directly in the hash, not as [ <value> ]
2729 sub hash_set_multi
{
2730 my ($hash, $key, $value) = @_;
2732 if (!exists $hash->{$key}) {
2733 $hash->{$key} = $value;
2734 } elsif (!ref $hash->{$key}) {
2735 $hash->{$key} = [ $hash->{$key}, $value ];
2737 push @{$hash->{$key}}, $value;
2741 # return hash of git project configuration
2742 # optionally limited to some section, e.g. 'gitweb'
2743 sub git_parse_project_config
{
2744 my $section_regexp = shift;
2749 open my $fh, "-|", git_cmd
(), "config", '-z', '-l',
2752 while (my $keyval = <$fh>) {
2754 my ($key, $value) = split(/\n/, $keyval, 2);
2756 hash_set_multi
(\
%config, $key, $value)
2757 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2764 # convert config value to boolean: 'true' or 'false'
2765 # no value, number > 0, 'true' and 'yes' values are true
2766 # rest of values are treated as false (never as error)
2767 sub config_to_bool
{
2770 return 1 if !defined $val; # section.key
2772 # strip leading and trailing whitespace
2776 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2777 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2780 # convert config value to simple decimal number
2781 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2782 # to be multiplied by 1024, 1048576, or 1073741824
2786 # strip leading and trailing whitespace
2790 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2792 # unknown unit is treated as 1
2793 return $num * ($unit eq 'g' ? 1073741824 :
2794 $unit eq 'm' ? 1048576 :
2795 $unit eq 'k' ? 1024 : 1);
2800 # convert config value to array reference, if needed
2801 sub config_to_multi
{
2804 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2807 sub git_get_project_config
{
2808 my ($key, $type) = @_;
2810 return unless defined $git_dir;
2813 return unless ($key);
2814 # only subsection, if exists, is case sensitive,
2815 # and not lowercased by 'git config -z -l'
2816 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2818 $key = join(".", lc($hi), $mi, lc($lo));
2819 return if ($lo =~ /\W/ || $hi =~ /\W/);
2823 return if ($key =~ /\W/);
2825 $key =~ s/^gitweb\.//;
2828 if (defined $type) {
2831 unless ($type eq 'bool' || $type eq 'int');
2835 if (!defined $config_file ||
2836 $config_file ne "$git_dir/config") {
2837 %config = git_parse_project_config
('gitweb');
2838 $config_file = "$git_dir/config";
2841 # check if config variable (key) exists
2842 return unless exists $config{"gitweb.$key"};
2845 if (!defined $type) {
2846 return $config{"gitweb.$key"};
2847 } elsif ($type eq 'bool') {
2848 # backward compatibility: 'git config --bool' returns true/false
2849 return config_to_bool
($config{"gitweb.$key"}) ? 'true' : 'false';
2850 } elsif ($type eq 'int') {
2851 return config_to_int
($config{"gitweb.$key"});
2853 return $config{"gitweb.$key"};
2856 # get hash of given path at given ref
2857 sub git_get_hash_by_path
{
2859 my $path = shift || return undef;
2864 open my $fd, "-|", git_cmd
(), "ls-tree", $base, "--", $path
2865 or die_error
(500, "Open git-ls-tree failed");
2867 close $fd or return undef;
2869 if (!defined $line) {
2870 # there is no tree or hash given by $path at $base
2874 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2875 $line =~ m/^([0-9]+) (.+) ($oid_regex)\t/;
2876 if (defined $type && $type ne $2) {
2877 # type doesn't match
2883 # get path of entry with given hash at given tree-ish (ref)
2884 # used to get 'from' filename for combined diff (merge commit) for renames
2885 sub git_get_path_by_hash
{
2886 my $base = shift || return;
2887 my $hash = shift || return;
2891 open my $fd, "-|", git_cmd
(), "ls-tree", '-r', '-t', '-z', $base
2893 while (my $line = <$fd>) {
2896 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2897 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2898 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2907 ## ......................................................................
2908 ## git utility functions, directly accessing git repository
2910 # get the value of config variable either from file named as the variable
2911 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2912 # configuration variable in the repository config file.
2913 sub git_get_file_or_project_config
{
2914 my ($path, $name) = @_;
2916 $git_dir = "$projectroot/$path";
2917 open my $fd, '<', "$git_dir/$name"
2918 or return git_get_project_config
($name);
2921 if (defined $conf) {
2927 sub git_get_project_description
{
2929 return git_get_file_or_project_config
($path, 'description');
2932 sub git_get_project_category
{
2934 return git_get_file_or_project_config
($path, 'category');
2938 # supported formats:
2939 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2940 # - if its contents is a number, use it as tag weight,
2941 # - otherwise add a tag with weight 1
2942 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2943 # the same value multiple times increases tag weight
2944 # * `gitweb.ctag' multi-valued repo config variable
2945 sub git_get_project_ctags
{
2946 my $project = shift;
2949 $git_dir = "$projectroot/$project";
2950 if (opendir my $dh, "$git_dir/ctags") {
2951 my @files = grep { -f
$_ } map { "$git_dir/ctags/$_" } readdir($dh);
2952 foreach my $tagfile (@files) {
2953 open my $ct, '<', $tagfile
2959 (my $ctag = $tagfile) =~ s
#.*/##;
2960 if ($val =~ /^\d+$/) {
2961 $ctags->{$ctag} = $val;
2963 $ctags->{$ctag} = 1;
2968 } elsif (open my $fh, '<', "$git_dir/ctags") {
2969 while (my $line = <$fh>) {
2971 $ctags->{$line}++ if $line;
2976 my $taglist = config_to_multi
(git_get_project_config
('ctag'));
2977 foreach my $tag (@$taglist) {
2985 # return hash, where keys are content tags ('ctags'),
2986 # and values are sum of weights of given tag in every project
2987 sub git_gather_all_ctags
{
2988 my $projects = shift;
2991 foreach my $p (@$projects) {
2992 foreach my $ct (keys %{$p->{'ctags'}}) {
2993 $ctags->{$ct} += $p->{'ctags'}->{$ct};
3000 sub git_populate_project_tagcloud
{
3003 # First, merge different-cased tags; tags vote on casing
3005 foreach (keys %$ctags) {
3006 $ctags_lc{lc $_}->{count
} += $ctags->{$_};
3007 if (not $ctags_lc{lc $_}->{topcount
}
3008 or $ctags_lc{lc $_}->{topcount
} < $ctags->{$_}) {
3009 $ctags_lc{lc $_}->{topcount
} = $ctags->{$_};
3010 $ctags_lc{lc $_}->{topname
} = $_;
3015 my $matched = $input_params{'ctag'};
3016 if (eval { require HTML
::TagCloud
; 1; }) {
3017 $cloud = HTML
::TagCloud-
>new;
3018 foreach my $ctag (sort keys %ctags_lc) {
3019 # Pad the title with spaces so that the cloud looks
3021 my $title = esc_html
($ctags_lc{$ctag}->{topname
});
3022 $title =~ s/ / /g;
3023 $title =~ s/^/ /g;
3024 $title =~ s/$/ /g;
3025 if (defined $matched && $matched eq $ctag) {
3026 $title = qq(<span class="match">$title</span>);
3028 $cloud->add($title, href
(project
=>undef, ctag
=>$ctag),
3029 $ctags_lc{$ctag}->{count
});
3033 foreach my $ctag (keys %ctags_lc) {
3034 my $title = esc_html
($ctags_lc{$ctag}->{topname
}, -nbsp
=>1);
3035 if (defined $matched && $matched eq $ctag) {
3036 $title = qq(<span class="match">$title</span>);
3038 $cloud->{$ctag}{count
} = $ctags_lc{$ctag}->{count
};
3039 $cloud->{$ctag}{ctag
} =
3040 $cgi->a({-href
=>href
(project
=>undef, ctag
=>$ctag)}, $title);
3046 sub git_show_project_tagcloud
{
3047 my ($cloud, $count) = @_;
3048 if (ref $cloud eq 'HTML::TagCloud') {
3049 return $cloud->html_and_css($count);
3051 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3053 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3055 $cloud->{$_}->{'ctag'}
3056 } splice(@tags, 0, $count)) .
3061 sub git_get_project_url_list
{
3064 $git_dir = "$projectroot/$path";
3065 open my $fd, '<', "$git_dir/cloneurl"
3066 or return wantarray ?
3067 @{ config_to_multi
(git_get_project_config
('url')) } :
3068 config_to_multi
(git_get_project_config
('url'));
3069 my @git_project_url_list = map { chomp; $_ } <$fd>;
3072 return wantarray ? @git_project_url_list : \
@git_project_url_list;
3075 sub git_get_projects_list
{
3076 my $filter = shift || '';
3077 my $paranoid = shift;
3080 if (-d
$projects_list) {
3081 # search in directory
3082 my $dir = $projects_list;
3083 # remove the trailing "/"
3085 my $pfxlen = length("$dir");
3086 my $pfxdepth = ($dir =~ tr!/!!);
3087 # when filtering, search only given subdirectory
3088 if ($filter && !$paranoid) {
3094 follow_fast
=> 1, # follow symbolic links
3095 follow_skip
=> 2, # ignore duplicates
3096 dangling_symlinks
=> 0, # ignore dangling symlinks, silently
3099 our $project_maxdepth;
3101 # skip project-list toplevel, if we get it.
3102 return if (m!^[/.]$!);
3103 # only directories can be git repositories
3104 return unless (-d
$_);
3105 # need search permission
3106 return unless (-x
$_);
3107 # don't traverse too deep (Find is super slow on os x)
3108 # $project_maxdepth excludes depth of $projectroot
3109 if (($File::Find
::name
=~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3110 $File::Find
::prune
= 1;
3114 my $path = substr($File::Find
::name
, $pfxlen + 1);
3115 # paranoidly only filter here
3116 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3119 # we check related file in $projectroot
3120 if (check_export_ok
("$projectroot/$path")) {
3121 push @list, { path
=> $path };
3122 $File::Find
::prune
= 1;
3127 } elsif (-f
$projects_list) {
3128 # read from file(url-encoded):
3129 # 'git%2Fgit.git Linus+Torvalds'
3130 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3131 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3132 open my $fd, '<', $projects_list or return;
3134 while (my $line = <$fd>) {
3136 my ($path, $owner) = split ' ', $line;
3137 $path = unescape
($path);
3138 $owner = unescape
($owner);
3139 if (!defined $path) {
3142 # if $filter is rpovided, check if $path begins with $filter
3143 if ($filter && $path !~ m!^\Q$filter\E/!) {
3146 if (check_export_ok
("$projectroot/$path")) {
3151 $pr->{'owner'} = to_utf8
($owner);
3161 # written with help of Tree::Trie module (Perl Artistic License, GPL compatible)
3162 # as side effects it sets 'forks' field to list of forks for forked projects
3163 sub filter_forks_from_projects_list
{
3164 my $projects = shift;
3166 my %trie; # prefix tree of directories (path components)
3167 # generate trie out of those directories that might contain forks
3168 foreach my $pr (@$projects) {
3169 my $path = $pr->{'path'};
3170 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3171 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3172 next unless ($path); # skip '.git' repository: tests, git-instaweb
3173 next unless (-d
"$projectroot/$path"); # containing directory exists
3174 $pr->{'forks'} = []; # there can be 0 or more forks of project
3177 my @dirs = split('/', $path);
3178 # walk the trie, until either runs out of components or out of trie
3180 while (scalar @dirs &&
3181 exists($ref->{$dirs[0]})) {
3182 $ref = $ref->{shift @dirs};
3184 # create rest of trie structure from rest of components
3185 foreach my $dir (@dirs) {
3186 $ref = $ref->{$dir} = {};
3188 # create end marker, store $pr as a data
3189 $ref->{''} = $pr if (!exists $ref->{''});
3192 # filter out forks, by finding shortest prefix match for paths
3195 foreach my $pr (@$projects) {
3199 foreach my $dir (split('/', $pr->{'path'})) {
3200 if (exists $ref->{''}) {
3201 # found [shortest] prefix, is a fork - skip it
3202 push @{$ref->{''}{'forks'}}, $pr;
3205 if (!exists $ref->{$dir}) {
3206 # not in trie, cannot have prefix, not a fork
3207 push @filtered, $pr;
3210 # If the dir is there, we just walk one step down the trie.
3211 $ref = $ref->{$dir};
3213 # we ran out of trie
3214 # (shouldn't happen: it's either no match, or end marker)
3215 push @filtered, $pr;
3221 # note: fill_project_list_info must be run first,
3222 # for 'descr_long' and 'ctags' to be filled
3223 sub search_projects_list
{
3224 my ($projlist, %opts) = @_;
3225 my $tagfilter = $opts{'tagfilter'};
3226 my $search_re = $opts{'search_regexp'};
3229 unless ($tagfilter || $search_re);
3231 # searching projects require filling to be run before it;
3232 fill_project_list_info
($projlist,
3233 $tagfilter ? 'ctags' : (),
3234 $search_re ? ('path', 'descr') : ());
3237 foreach my $pr (@$projlist) {
3240 next unless ref($pr->{'ctags'}) eq 'HASH';
3242 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3247 $pr->{'path'} =~ /$search_re/ ||
3248 $pr->{'descr_long'} =~ /$search_re/;
3251 push @projects, $pr;
3257 our $gitweb_project_owner = undef;
3258 sub git_get_project_list_from_file
{
3260 return if (defined $gitweb_project_owner);
3262 $gitweb_project_owner = {};
3263 # read from file (url-encoded):
3264 # 'git%2Fgit.git Linus+Torvalds'
3265 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3266 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3267 if (-f
$projects_list) {
3268 open(my $fd, '<', $projects_list);
3269 while (my $line = <$fd>) {
3271 my ($pr, $ow) = split ' ', $line;
3272 $pr = unescape
($pr);
3273 $ow = unescape
($ow);
3274 $gitweb_project_owner->{$pr} = to_utf8
($ow);
3280 sub git_get_project_owner
{
3281 my $project = shift;
3284 return undef unless $project;
3285 $git_dir = "$projectroot/$project";
3287 if (!defined $gitweb_project_owner) {
3288 git_get_project_list_from_file
();
3291 if (exists $gitweb_project_owner->{$project}) {
3292 $owner = $gitweb_project_owner->{$project};
3294 if (!defined $owner){
3295 $owner = git_get_project_config
('owner');
3297 if (!defined $owner) {
3298 $owner = get_file_owner
("$git_dir");
3304 sub git_get_last_activity
{
3308 $git_dir = "$projectroot/$path";
3309 open($fd, "-|", git_cmd
(), 'for-each-ref',
3310 '--format=%(committer)',
3311 '--sort=-committerdate',
3313 map { "refs/$_" } get_branch_refs
()) or return;
3314 my $most_recent = <$fd>;
3315 close $fd or return;
3316 if (defined $most_recent &&
3317 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3319 my $age = time - $timestamp;
3320 return ($age, age_string
($age));
3322 return (undef, undef);
3325 # Implementation note: when a single remote is wanted, we cannot use 'git
3326 # remote show -n' because that command always work (assuming it's a remote URL
3327 # if it's not defined), and we cannot use 'git remote show' because that would
3328 # try to make a network roundtrip. So the only way to find if that particular
3329 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3330 # and when we find what we want.
3331 sub git_get_remotes_list
{
3335 open my $fd, '-|' , git_cmd
(), 'remote', '-v';
3337 while (my $remote = <$fd>) {
3339 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3340 next if $wanted and not $remote eq $wanted;
3341 my ($url, $key) = ($1, $2);
3343 $remotes{$remote} ||= { 'heads' => () };
3344 $remotes{$remote}{$key} = $url;
3346 close $fd or return;
3347 return wantarray ? %remotes : \
%remotes;
3350 # Takes a hash of remotes as first parameter and fills it by adding the
3351 # available remote heads for each of the indicated remotes.
3352 sub fill_remote_heads
{
3353 my $remotes = shift;
3354 my @heads = map { "remotes/$_" } keys %$remotes;
3355 my @remoteheads = git_get_heads_list
(undef, @heads);
3356 foreach my $remote (keys %$remotes) {
3357 $remotes->{$remote}{'heads'} = [ grep {
3358 $_->{'name'} =~ s!^$remote/!!
3363 sub git_get_references
{
3364 my $type = shift || "";
3366 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3367 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3368 open my $fd, "-|", git_cmd
(), "show-ref", "--dereference",
3369 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3372 while (my $line = <$fd>) {
3374 if ($line =~ m!^($oid_regex)\srefs/($type.*)$!) {
3375 if (defined $refs{$1}) {
3376 push @{$refs{$1}}, $2;
3382 close $fd or return;
3386 sub git_get_rev_name_tags
{
3387 my $hash = shift || return undef;
3389 open my $fd, "-|", git_cmd
(), "name-rev", "--tags", $hash
3391 my $name_rev = <$fd>;
3394 if ($name_rev =~ m
|^$hash tags
/(.*)$|) {
3397 # catches also '$hash undefined' output
3402 ## ----------------------------------------------------------------------
3403 ## parse to hash functions
3407 my $tz = shift || "-0000";
3410 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3411 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3412 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3413 $date{'hour'} = $hour;
3414 $date{'minute'} = $min;
3415 $date{'mday'} = $mday;
3416 $date{'day'} = $days[$wday];
3417 $date{'month'} = $months[$mon];
3418 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3419 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3420 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3421 $mday, $months[$mon], $hour ,$min;
3422 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3423 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3425 my ($tz_sign, $tz_hour, $tz_min) =
3426 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3427 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3428 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3429 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3430 $date{'hour_local'} = $hour;
3431 $date{'minute_local'} = $min;
3432 $date{'tz_local'} = $tz;
3433 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3434 1900+$year, $mon+1, $mday,
3435 $hour, $min, $sec, $tz);
3444 open my $fd, "-|", git_cmd
(), "cat-file", "tag", $tag_id or return;
3445 $tag{'id'} = $tag_id;
3446 while (my $line = <$fd>) {
3448 if ($line =~ m/^object ($oid_regex)$/) {
3449 $tag{'object'} = $1;
3450 } elsif ($line =~ m/^type (.+)$/) {
3452 } elsif ($line =~ m/^tag (.+)$/) {
3454 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3455 $tag{'author'} = $1;
3456 $tag{'author_epoch'} = $2;
3457 $tag{'author_tz'} = $3;
3458 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3459 $tag{'author_name'} = $1;
3460 $tag{'author_email'} = $2;
3462 $tag{'author_name'} = $tag{'author'};
3464 } elsif ($line =~ m/--BEGIN/) {
3465 push @comment, $line;
3467 } elsif ($line eq "") {
3471 push @comment, <$fd>;
3472 $tag{'comment'} = \
@comment;
3473 close $fd or return;
3474 if (!defined $tag{'name'}) {
3480 sub parse_commit_text
{
3481 my ($commit_text, $withparents) = @_;
3482 my @commit_lines = split '\n', $commit_text;
3485 pop @commit_lines; # Remove '\0'
3487 if (! @commit_lines) {
3491 my $header = shift @commit_lines;
3492 if ($header !~ m/^$oid_regex/) {
3495 ($co{'id'}, my @parents) = split ' ', $header;
3496 while (my $line = shift @commit_lines) {
3497 last if $line eq "\n";
3498 if ($line =~ m/^tree ($oid_regex)$/) {
3500 } elsif ((!defined $withparents) && ($line =~ m/^parent ($oid_regex)$/)) {
3502 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3503 $co{'author'} = to_utf8
($1);
3504 $co{'author_epoch'} = $2;
3505 $co{'author_tz'} = $3;
3506 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3507 $co{'author_name'} = $1;
3508 $co{'author_email'} = $2;
3510 $co{'author_name'} = $co{'author'};
3512 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3513 $co{'committer'} = to_utf8
($1);
3514 $co{'committer_epoch'} = $2;
3515 $co{'committer_tz'} = $3;
3516 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3517 $co{'committer_name'} = $1;
3518 $co{'committer_email'} = $2;
3520 $co{'committer_name'} = $co{'committer'};
3524 if (!defined $co{'tree'}) {
3527 $co{'parents'} = \
@parents;
3528 $co{'parent'} = $parents[0];
3530 foreach my $title (@commit_lines) {
3533 $co{'title'} = chop_str
($title, 80, 5);
3534 # remove leading stuff of merges to make the interesting part visible
3535 if (length($title) > 50) {
3536 $title =~ s/^Automatic //;
3537 $title =~ s/^merge (of|with) /Merge ... /i;
3538 if (length($title) > 50) {
3539 $title =~ s/(http|rsync):\/\///;
3541 if (length($title) > 50) {
3542 $title =~ s/(master|www|rsync)\.//;
3544 if (length($title) > 50) {
3545 $title =~ s/kernel.org:?//;
3547 if (length($title) > 50) {
3548 $title =~ s/\/pub\/scm//;
3551 $co{'title_short'} = chop_str
($title, 50, 5);
3555 if (! defined $co{'title'} || $co{'title'} eq "") {
3556 $co{'title'} = $co{'title_short'} = '(no commit message)';
3558 # remove added spaces
3559 foreach my $line (@commit_lines) {
3562 $co{'comment'} = \
@commit_lines;
3564 my $age = time - $co{'committer_epoch'};
3566 $co{'age_string'} = age_string
($age);
3567 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3568 if ($age > 60*60*24*7*2) {
3569 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3570 $co{'age_string_age'} = $co{'age_string'};
3572 $co{'age_string_date'} = $co{'age_string'};
3573 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3579 my ($commit_id) = @_;
3584 open my $fd, "-|", git_cmd
(), "rev-list",
3590 or die_error
(500, "Open git-rev-list failed");
3591 %co = parse_commit_text
(<$fd>, 1);
3598 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3606 open my $fd, "-|", git_cmd
(), "rev-list",
3609 ("--max-count=" . $maxcount),
3610 ("--skip=" . $skip),
3614 ($filename ? ($filename) : ())
3615 or die_error
(500, "Open git-rev-list failed");
3616 while (my $line = <$fd>) {
3617 my %co = parse_commit_text
($line);
3622 return wantarray ? @cos : \
@cos;
3625 # parse line of git-diff-tree "raw" output
3626 sub parse_difftree_raw_line
{
3630 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3631 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3632 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ($oid_regex) ($oid_regex) (.)([0-9]{0,3})\t(.*)$/) {
3633 $res{'from_mode'} = $1;
3634 $res{'to_mode'} = $2;
3635 $res{'from_id'} = $3;
3637 $res{'status'} = $5;
3638 $res{'similarity'} = $6;
3639 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3640 ($res{'from_file'}, $res{'to_file'}) = map { unquote
($_) } split("\t", $7);
3642 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote
($7);
3645 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3646 # combined diff (for merge commit)
3647 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:$oid_regex )+)([a-zA-Z]+)\t(.*)$//) {
3648 $res{'nparents'} = length($1);
3649 $res{'from_mode'} = [ split(' ', $2) ];
3650 $res{'to_mode'} = pop @{$res{'from_mode'}};
3651 $res{'from_id'} = [ split(' ', $3) ];
3652 $res{'to_id'} = pop @{$res{'from_id'}};
3653 $res{'status'} = [ split('', $4) ];
3654 $res{'to_file'} = unquote
($5);
3656 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3657 elsif ($line =~ m/^($oid_regex)$/) {
3658 $res{'commit'} = $1;
3661 return wantarray ? %res : \
%res;
3664 # wrapper: return parsed line of git-diff-tree "raw" output
3665 # (the argument might be raw line, or parsed info)
3666 sub parsed_difftree_line
{
3667 my $line_or_ref = shift;
3669 if (ref($line_or_ref) eq "HASH") {
3670 # pre-parsed (or generated by hand)
3671 return $line_or_ref;
3673 return parse_difftree_raw_line
($line_or_ref);
3677 # parse line of git-ls-tree output
3678 sub parse_ls_tree_line
{
3684 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3685 $line =~ m/^([0-9]+) (.+) ($oid_regex) +(-|[0-9]+)\t(.+)$/s;
3694 $res{'name'} = unquote
($5);
3697 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3698 $line =~ m/^([0-9]+) (.+) ($oid_regex)\t(.+)$/s;
3706 $res{'name'} = unquote
($4);
3710 return wantarray ? %res : \
%res;
3713 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3714 sub parse_from_to_diffinfo
{
3715 my ($diffinfo, $from, $to, @parents) = @_;
3717 if ($diffinfo->{'nparents'}) {
3719 $from->{'file'} = [];
3720 $from->{'href'} = [];
3721 fill_from_file_info
($diffinfo, @parents)
3722 unless exists $diffinfo->{'from_file'};
3723 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3724 $from->{'file'}[$i] =
3725 defined $diffinfo->{'from_file'}[$i] ?
3726 $diffinfo->{'from_file'}[$i] :
3727 $diffinfo->{'to_file'};
3728 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3729 $from->{'href'}[$i] = href
(action
=>"blob",
3730 hash_base
=>$parents[$i],
3731 hash
=>$diffinfo->{'from_id'}[$i],
3732 file_name
=>$from->{'file'}[$i]);
3734 $from->{'href'}[$i] = undef;
3738 # ordinary (not combined) diff
3739 $from->{'file'} = $diffinfo->{'from_file'};
3740 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3741 $from->{'href'} = href
(action
=>"blob", hash_base
=>$hash_parent,
3742 hash
=>$diffinfo->{'from_id'},
3743 file_name
=>$from->{'file'});
3745 delete $from->{'href'};
3749 $to->{'file'} = $diffinfo->{'to_file'};
3750 if (!is_deleted
($diffinfo)) { # file exists in result
3751 $to->{'href'} = href
(action
=>"blob", hash_base
=>$hash,
3752 hash
=>$diffinfo->{'to_id'},
3753 file_name
=>$to->{'file'});
3755 delete $to->{'href'};
3759 ## ......................................................................
3760 ## parse to array of hashes functions
3762 sub git_get_heads_list
{
3763 my ($limit, @classes) = @_;
3764 @classes = get_branch_refs
() unless @classes;
3765 my @patterns = map { "refs/$_" } @classes;
3768 open my $fd, '-|', git_cmd
(), 'for-each-ref',
3769 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3770 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3773 while (my $line = <$fd>) {
3777 my ($refinfo, $committerinfo) = split(/\0/, $line);
3778 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3779 my ($committer, $epoch, $tz) =
3780 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3781 $ref_item{'fullname'} = $name;
3782 my $strip_refs = join '|', map { quotemeta } get_branch_refs
();
3783 $name =~ s!^refs/($strip_refs|remotes)/!!;
3784 $ref_item{'name'} = $name;
3785 # for refs neither in 'heads' nor 'remotes' we want to
3786 # show their ref dir
3787 my $ref_dir = (defined $1) ? $1 : '';
3788 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3789 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3792 $ref_item{'id'} = $hash;
3793 $ref_item{'title'} = $title || '(no commit message)';
3794 $ref_item{'epoch'} = $epoch;
3796 $ref_item{'age'} = age_string
(time - $ref_item{'epoch'});
3798 $ref_item{'age'} = "unknown";
3801 push @headslist, \
%ref_item;
3805 return wantarray ? @headslist : \
@headslist;
3808 sub git_get_tags_list
{
3812 open my $fd, '-|', git_cmd
(), 'for-each-ref',
3813 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3814 '--format=%(objectname) %(objecttype) %(refname) '.
3815 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3818 while (my $line = <$fd>) {
3822 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3823 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3824 my ($creator, $epoch, $tz) =
3825 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3826 $ref_item{'fullname'} = $name;
3827 $name =~ s!^refs/tags/!!;
3829 $ref_item{'type'} = $type;
3830 $ref_item{'id'} = $id;
3831 $ref_item{'name'} = $name;
3832 if ($type eq "tag") {
3833 $ref_item{'subject'} = $title;
3834 $ref_item{'reftype'} = $reftype;
3835 $ref_item{'refid'} = $refid;
3837 $ref_item{'reftype'} = $type;
3838 $ref_item{'refid'} = $id;
3841 if ($type eq "tag" || $type eq "commit") {
3842 $ref_item{'epoch'} = $epoch;
3844 $ref_item{'age'} = age_string
(time - $ref_item{'epoch'});
3846 $ref_item{'age'} = "unknown";
3850 push @tagslist, \
%ref_item;
3854 return wantarray ? @tagslist : \
@tagslist;
3857 ## ----------------------------------------------------------------------
3858 ## filesystem-related functions
3860 sub get_file_owner
{
3863 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3864 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3865 if (!defined $gcos) {
3869 $owner =~ s/[,;].*$//;
3870 return to_utf8
($owner);
3873 # assume that file exists
3875 my $filename = shift;
3877 open my $fd, '<', $filename;
3878 print map { to_utf8
($_) } <$fd>;
3882 ## ......................................................................
3883 ## mimetype related functions
3885 sub mimetype_guess_file
{
3886 my $filename = shift;
3887 my $mimemap = shift;
3888 -r
$mimemap or return undef;
3891 open(my $mh, '<', $mimemap) or return undef;
3893 next if m/^#/; # skip comments
3894 my ($mimetype, @exts) = split(/\s+/);
3895 foreach my $ext (@exts) {
3896 $mimemap{$ext} = $mimetype;
3901 $filename =~ /\.([^.]*)$/;
3902 return $mimemap{$1};
3905 sub mimetype_guess
{
3906 my $filename = shift;
3908 $filename =~ /\./ or return undef;
3910 if ($mimetypes_file) {
3911 my $file = $mimetypes_file;
3912 if ($file !~ m!^/!) { # if it is relative path
3913 # it is relative to project
3914 $file = "$projectroot/$project/$file";
3916 $mime = mimetype_guess_file
($filename, $file);
3918 $mime ||= mimetype_guess_file
($filename, '/etc/mime.types');
3924 my $filename = shift;
3927 my $mime = mimetype_guess
($filename);
3928 $mime and return $mime;
3932 return $default_blob_plain_mimetype unless $fd;
3935 return 'text/plain';
3936 } elsif (! $filename) {
3937 return 'application/octet-stream';
3938 } elsif ($filename =~ m/\.png$/i) {
3940 } elsif ($filename =~ m/\.gif$/i) {
3942 } elsif ($filename =~ m/\.jpe?g$/i) {
3943 return 'image/jpeg';
3945 return 'application/octet-stream';
3949 sub blob_contenttype
{
3950 my ($fd, $file_name, $type) = @_;
3952 $type ||= blob_mimetype
($fd, $file_name);
3953 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3954 $type .= "; charset=$default_text_plain_charset";
3960 # guess file syntax for syntax highlighting; return undef if no highlighting
3961 # the name of syntax can (in the future) depend on syntax highlighter used
3962 sub guess_file_syntax
{
3963 my ($highlight, $file_name) = @_;
3964 return undef unless ($highlight && defined $file_name);
3965 my $basename = basename
($file_name, '.in');
3966 return $highlight_basename{$basename}
3967 if exists $highlight_basename{$basename};
3969 $basename =~ /\.([^.]*)$/;
3970 my $ext = $1 or return undef;
3971 return $highlight_ext{$ext}
3972 if exists $highlight_ext{$ext};
3977 # run highlighter and return FD of its output,
3978 # or return original FD if no highlighting
3979 sub run_highlighter
{
3980 my ($fd, $highlight, $syntax) = @_;
3981 return $fd unless ($highlight);
3984 my $syntax_arg = (defined $syntax) ? "--syntax $syntax" : "--force";
3985 open $fd, quote_command
(git_cmd
(), "cat-file", "blob", $hash)." | ".
3986 quote_command
($^X, '-CO', '-MEncode=decode,FB_DEFAULT', '-pse',
3987 '$_ = decode($fe, $_, FB_DEFAULT) if !utf8::decode($_);',
3988 '--', "-fe=$fallback_encoding")." | ".
3989 quote_command
($highlight_bin).
3990 " --replace-tabs=8 --fragment $syntax_arg |"
3991 or die_error
(500, "Couldn't open file or run syntax highlighter");
3995 ## ======================================================================
3996 ## functions printing HTML: header, footer, error page
3998 sub get_page_title
{
3999 my $title = to_utf8
($site_name);
4001 unless (defined $project) {
4002 if (defined $project_filter) {
4003 $title .= " - projects in '" . esc_path
($project_filter) . "'";
4007 $title .= " - " . to_utf8
($project);
4009 return $title unless (defined $action);
4010 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
4012 return $title unless (defined $file_name);
4013 $title .= " - " . esc_path
($file_name);
4014 if ($action eq "tree" && $file_name !~ m
|/$|) {
4021 sub get_content_type_html
{
4022 # require explicit support from the UA if we are to send the page as
4023 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4024 # we have to do this because MSIE sometimes globs '*/*', pretending to
4025 # support xhtml+xml but choking when it gets what it asked for.
4026 if (defined $cgi->http('HTTP_ACCEPT') &&
4027 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\
+xml
(,|;|\s
|$)/ &&
4028 $cgi->Accept('application/xhtml+xml') != 0) {
4029 return 'application/xhtml+xml';
4035 sub print_feed_meta
{
4036 if (defined $project) {
4037 my %href_params = get_feed_info
();
4038 if (!exists $href_params{'-title'}) {
4039 $href_params{'-title'} = 'log';
4042 foreach my $format (qw(RSS Atom)) {
4043 my $type = lc($format);
4045 '-rel' => 'alternate',
4046 '-title' => esc_attr
("$project - $href_params{'-title'} - $format feed"),
4047 '-type' => "application/$type+xml"
4050 $href_params{'extra_options'} = undef;
4051 $href_params{'action'} = $type;
4052 $link_attr{'-href'} = esc_attr
(href
(%href_params));
4054 "rel=\"$link_attr{'-rel'}\" ".
4055 "title=\"$link_attr{'-title'}\" ".
4056 "href=\"$link_attr{'-href'}\" ".
4057 "type=\"$link_attr{'-type'}\" ".
4060 $href_params{'extra_options'} = '--no-merges';
4061 $link_attr{'-href'} = esc_attr
(href
(%href_params));
4062 $link_attr{'-title'} .= ' (no merges)';
4064 "rel=\"$link_attr{'-rel'}\" ".
4065 "title=\"$link_attr{'-title'}\" ".
4066 "href=\"$link_attr{'-href'}\" ".
4067 "type=\"$link_attr{'-type'}\" ".
4072 printf('<link rel="alternate" title="%s projects list" '.
4073 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4074 esc_attr
($site_name),
4075 esc_attr
(href
(project
=>undef, action
=>"project_index")));
4076 printf('<link rel="alternate" title="%s projects feeds" '.
4077 'href="%s" type="text/x-opml" />'."\n",
4078 esc_attr
($site_name),
4079 esc_attr
(href
(project
=>undef, action
=>"opml")));
4083 sub print_header_links
{
4086 # print out each stylesheet that exist, providing backwards capability
4087 # for those people who defined $stylesheet in a config file
4088 if (defined $stylesheet) {
4089 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
4091 foreach my $stylesheet (@stylesheets) {
4092 next unless $stylesheet;
4093 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
4097 if ($status eq '200 OK');
4098 if (defined $favicon) {
4099 print qq(<link rel="shortcut icon" href=").esc_url
($favicon).qq(" type="image/png" />\n);
4103 sub print_nav_breadcrumbs_path
{
4104 my $dirprefix = undef;
4105 while (my $part = shift) {
4106 $dirprefix .= "/" if defined $dirprefix;
4107 $dirprefix .= $part;
4108 print $cgi->a({-href
=> href
(project
=> undef,
4109 project_filter
=> $dirprefix,
4110 action
=> "project_list")},
4111 esc_html
($part)) . " / ";
4115 sub print_nav_breadcrumbs
{
4118 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4119 print $cgi->a({-href
=> esc_url
($crumb->[1])}, $crumb->[0]) . " / ";
4121 if (defined $project) {
4122 my @dirname = split '/', $project;
4123 my $projectbasename = pop @dirname;
4124 print_nav_breadcrumbs_path
(@dirname);
4125 print $cgi->a({-href
=> href
(action
=>"summary")}, esc_html
($projectbasename));
4126 if (defined $action) {
4127 my $action_print = $action ;
4128 if (defined $opts{-action_extra
}) {
4129 $action_print = $cgi->a({-href
=> href
(action
=>$action)},
4132 print " / $action_print";
4134 if (defined $opts{-action_extra
}) {
4135 print " / $opts{-action_extra}";
4138 } elsif (defined $project_filter) {
4139 print_nav_breadcrumbs_path
(split '/', $project_filter);
4143 sub print_search_form
{
4144 if (!defined $searchtext) {
4148 if (defined $hash_base) {
4149 $search_hash = $hash_base;
4150 } elsif (defined $hash) {
4151 $search_hash = $hash;
4153 $search_hash = "HEAD";
4155 my $action = $my_uri;
4156 my $use_pathinfo = gitweb_check_feature
('pathinfo');
4157 if ($use_pathinfo) {
4158 $action .= "/".esc_url
($project);
4160 print $cgi->start_form(-method => "get", -action
=> $action) .
4161 "<div class=\"search\">\n" .
4163 $cgi->input({-name
=>"p", -value
=>$project, -type
=>"hidden"}) . "\n") .
4164 $cgi->input({-name
=>"a", -value
=>"search", -type
=>"hidden"}) . "\n" .
4165 $cgi->input({-name
=>"h", -value
=>$search_hash, -type
=>"hidden"}) . "\n" .
4166 $cgi->popup_menu(-name
=> 'st', -default => 'commit',
4167 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4168 " " . $cgi->a({-href
=> href
(action
=>"search_help"),
4169 -title
=> "search help" }, "?") . " search:\n",
4170 $cgi->textfield(-name
=> "s", -value
=> $searchtext, -override
=> 1) . "\n" .
4171 "<span title=\"Extended regular expression\">" .
4172 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
4173 -checked
=> $search_use_regexp) .
4176 $cgi->end_form() . "\n";
4179 sub git_header_html
{
4180 my $status = shift || "200 OK";
4181 my $expires = shift;
4184 my $title = get_page_title
();
4185 my $content_type = get_content_type_html
();
4186 print $cgi->header(-type
=>$content_type, -charset
=> 'utf-8',
4187 -status
=> $status, -expires
=> $expires)
4188 unless ($opts{'-no_http_header'});
4189 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4191 <?xml version="1.0" encoding="utf-8"?>
4192 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4193 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4194 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4195 <!-- git core binaries version $git_version -->
4197 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4198 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4199 <meta name="robots" content="index, nofollow"/>
4200 <title>$title</title>
4202 # the stylesheet, favicon etc urls won't work correctly with path_info
4203 # unless we set the appropriate base URL
4204 if ($ENV{'PATH_INFO'}) {
4205 print "<base href=\"".esc_url
($base_url)."\" />\n";
4207 print_header_links
($status);
4209 if (defined $site_html_head_string) {
4210 print to_utf8
($site_html_head_string);
4216 if (defined $site_header && -f
$site_header) {
4217 insert_file
($site_header);
4220 print "<div class=\"page_header\">\n";
4221 if (defined $logo) {
4222 print $cgi->a({-href
=> esc_url
($logo_url),
4223 -title
=> $logo_label},
4224 $cgi->img({-src
=> esc_url
($logo),
4225 -width
=> 72, -height
=> 27,
4227 -class => "logo"}));
4229 print_nav_breadcrumbs
(%opts);
4232 my $have_search = gitweb_check_feature
('search');
4233 if (defined $project && $have_search) {
4234 print_search_form
();
4238 sub git_footer_html
{
4239 my $feed_class = 'rss_logo';
4241 print "<div class=\"page_footer\">\n";
4242 if (defined $project) {
4243 my $descr = git_get_project_description
($project);
4244 if (defined $descr) {
4245 print "<div class=\"page_footer_text\">" . esc_html
($descr) . "</div>\n";
4248 my %href_params = get_feed_info
();
4249 if (!%href_params) {
4250 $feed_class .= ' generic';
4252 $href_params{'-title'} ||= 'log';
4254 foreach my $format (qw(RSS Atom)) {
4255 $href_params{'action'} = lc($format);
4256 print $cgi->a({-href
=> href
(%href_params),
4257 -title
=> "$href_params{'-title'} $format feed",
4258 -class => $feed_class}, $format)."\n";
4262 print $cgi->a({-href
=> href
(project
=>undef, action
=>"opml",
4263 project_filter
=> $project_filter),
4264 -class => $feed_class}, "OPML") . " ";
4265 print $cgi->a({-href
=> href
(project
=>undef, action
=>"project_index",
4266 project_filter
=> $project_filter),
4267 -class => $feed_class}, "TXT") . "\n";
4269 print "</div>\n"; # class="page_footer"
4271 if (defined $t0 && gitweb_check_feature
('timed')) {
4272 print "<div id=\"generating_info\">\n";
4273 print 'This page took '.
4274 '<span id="generating_time" class="time_span">'.
4275 tv_interval
($t0, [ gettimeofday
() ]).
4278 '<span id="generating_cmd">'.
4279 $number_of_git_cmds.
4280 '</span> git commands '.
4282 print "</div>\n"; # class="page_footer"
4285 if (defined $site_footer && -f
$site_footer) {
4286 insert_file
($site_footer);
4289 print qq
!<script type
="text/javascript" src
="!.esc_url($javascript).qq!"></script
>\n!;
4290 if (defined $action &&
4291 $action eq 'blame_incremental') {
4292 print qq
!<script type
="text/javascript">\n!.
4293 qq
!startBlame
("!. esc_attr(href(action=>"blame_data
", -replay=>1)) .qq!",\n!.
4294 qq
! "!. esc_attr(href()) .qq!");\n!.
4297 my ($jstimezone, $tz_cookie, $datetime_class) =
4298 gitweb_get_feature
('javascript-timezone');
4300 print qq
!<script type
="text/javascript">\n!.
4301 qq
!window
.onload
= function
() {\n!;
4302 if (gitweb_check_feature
('javascript-actions')) {
4303 print qq
! fixLinks
();\n!;
4305 if ($jstimezone && $tz_cookie && $datetime_class) {
4306 print qq
! var tz_cookie
= { name
: '$tz_cookie', expires
: 14, path
: '/' };\n!. # in days
4307 qq
! onloadTZSetup
('$jstimezone', tz_cookie
, '$datetime_class');\n!;
4317 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4318 # Example: die_error(404, 'Hash not found')
4319 # By convention, use the following status codes (as defined in RFC 2616):
4320 # 400: Invalid or missing CGI parameters, or
4321 # requested object exists but has wrong type.
4322 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4323 # this server or project.
4324 # 404: Requested object/revision/project doesn't exist.
4325 # 500: The server isn't configured properly, or
4326 # an internal error occurred (e.g. failed assertions caused by bugs), or
4327 # an unknown error occurred (e.g. the git binary died unexpectedly).
4328 # 503: The server is currently unavailable (because it is overloaded,
4329 # or down for maintenance). Generally, this is a temporary state.
4331 my $status = shift || 500;
4332 my $error = esc_html
(shift) || "Internal Server Error";
4336 my %http_responses = (
4337 400 => '400 Bad Request',
4338 403 => '403 Forbidden',
4339 404 => '404 Not Found',
4340 500 => '500 Internal Server Error',
4341 503 => '503 Service Unavailable',
4343 git_header_html
($http_responses{$status}, undef, %opts);
4345 <div class="page_body">
4350 if (defined $extra) {
4358 unless ($opts{'-error_handler'});
4361 ## ----------------------------------------------------------------------
4362 ## functions printing or outputting HTML: navigation
4364 sub git_print_page_nav
{
4365 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4366 $extra = '' if !defined $extra; # pager or formats
4368 my @navs = qw(summary shortlog log commit commitdiff tree);
4370 @navs = grep { $_ ne $suppress } @navs;
4373 my %arg = map { $_ => {action
=>$_} } @navs;
4374 if (defined $head) {
4375 for (qw(commit commitdiff)) {
4376 $arg{$_}{'hash'} = $head;
4378 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4379 for (qw(shortlog log)) {
4380 $arg{$_}{'hash'} = $head;
4385 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4386 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4388 my @actions = gitweb_get_feature
('actions');
4391 'n' => $project, # project name
4392 'f' => $git_dir, # project path within filesystem
4393 'h' => $treehead || '', # current hash ('h' parameter)
4394 'b' => $treebase || '', # hash base ('hb' parameter)
4397 my ($label, $link, $pos) = splice(@actions,0,3);
4399 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4401 $link =~ s/%([%nfhb])/$repl{$1}/g;
4402 $arg{$label}{'_href'} = $link;
4405 print "<div class=\"page_nav\">\n" .
4407 map { $_ eq $current ?
4408 $_ : $cgi->a({-href
=> ($arg{$_}{_href
} ? $arg{$_}{_href
} : href
(%{$arg{$_}}))}, "$_")
4410 print "<br/>\n$extra<br/>\n" .
4414 # returns a submenu for the navigation of the refs views (tags, heads,
4415 # remotes) with the current view disabled and the remotes view only
4416 # available if the feature is enabled
4417 sub format_ref_views
{
4419 my @ref_views = qw{tags heads};
4420 push @ref_views, 'remotes' if gitweb_check_feature
('remote_heads');
4421 return join " | ", map {
4422 $_ eq $current ? $_ :
4423 $cgi->a({-href
=> href
(action
=>$_)}, $_)
4427 sub format_paging_nav
{
4428 my ($action, $page, $has_next_link) = @_;
4434 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)}, "first") .
4436 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
4437 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
4439 $paging_nav .= "first ⋅ prev";
4442 if ($has_next_link) {
4443 $paging_nav .= " ⋅ " .
4444 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
4445 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
4447 $paging_nav .= " ⋅ next";
4453 ## ......................................................................
4454 ## functions printing or outputting HTML: div
4456 sub git_print_header_div
{
4457 my ($action, $title, $hash, $hash_base) = @_;
4460 $args{'action'} = $action;
4461 $args{'hash'} = $hash if $hash;
4462 $args{'hash_base'} = $hash_base if $hash_base;
4464 print "<div class=\"header\">\n" .
4465 $cgi->a({-href
=> href
(%args), -class => "title"},
4466 $title ? $title : $action) .
4470 sub format_repo_url
{
4471 my ($name, $url) = @_;
4472 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4475 # Group output by placing it in a DIV element and adding a header.
4476 # Options for start_div() can be provided by passing a hash reference as the
4477 # first parameter to the function.
4478 # Options to git_print_header_div() can be provided by passing an array
4479 # reference. This must follow the options to start_div if they are present.
4480 # The content can be a scalar, which is output as-is, a scalar reference, which
4481 # is output after html escaping, an IO handle passed either as *handle or
4482 # *handle{IO}, or a function reference. In the latter case all following
4483 # parameters will be taken as argument to the content function call.
4484 sub git_print_section
{
4485 my ($div_args, $header_args, $content);
4487 if (ref($arg) eq 'HASH') {
4491 if (ref($arg) eq 'ARRAY') {
4492 $header_args = $arg;
4497 print $cgi->start_div($div_args);
4498 git_print_header_div
(@$header_args);
4500 if (ref($content) eq 'CODE') {
4502 } elsif (ref($content) eq 'SCALAR') {
4503 print esc_html
($$content);
4504 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4506 } elsif (!ref($content) && defined($content)) {
4510 print $cgi->end_div;
4513 sub format_timestamp_html
{
4515 my $strtime = $date->{'rfc2822'};
4517 my (undef, undef, $datetime_class) =
4518 gitweb_get_feature
('javascript-timezone');
4519 if ($datetime_class) {
4520 $strtime = qq
!<span
class="$datetime_class">$strtime</span
>!;
4523 my $localtime_format = '(%02d:%02d %s)';
4524 if ($date->{'hour_local'} < 6) {
4525 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4528 sprintf($localtime_format,
4529 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4534 # Outputs the author name and date in long form
4535 sub git_print_authorship
{
4538 my $tag = $opts{-tag
} || 'div';
4539 my $author = $co->{'author_name'};
4541 my %ad = parse_date
($co->{'author_epoch'}, $co->{'author_tz'});
4542 print "<$tag class=\"author_date\">" .
4543 format_search_author
($author, "author", esc_html
($author)) .
4544 " [".format_timestamp_html
(\
%ad)."]".
4545 git_get_avatar
($co->{'author_email'}, -pad_before
=> 1) .
4549 # Outputs table rows containing the full author or committer information,
4550 # in the format expected for 'commit' view (& similar).
4551 # Parameters are a commit hash reference, followed by the list of people
4552 # to output information for. If the list is empty it defaults to both
4553 # author and committer.
4554 sub git_print_authorship_rows
{
4556 # too bad we can't use @people = @_ || ('author', 'committer')
4558 @people = ('author', 'committer') unless @people;
4559 foreach my $who (@people) {
4560 my %wd = parse_date
($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4561 print "<tr><td>$who</td><td>" .
4562 format_search_author
($co->{"${who}_name"}, $who,
4563 esc_html
($co->{"${who}_name"})) . " " .
4564 format_search_author
($co->{"${who}_email"}, $who,
4565 esc_html
("<" . $co->{"${who}_email"} . ">")) .
4566 "</td><td rowspan=\"2\">" .
4567 git_get_avatar
($co->{"${who}_email"}, -size
=> 'double') .
4571 format_timestamp_html
(\
%wd) .
4577 sub git_print_page_path
{
4583 print "<div class=\"page_path\">";
4584 print $cgi->a({-href
=> href
(action
=>"tree", hash_base
=>$hb),
4585 -title
=> 'tree root'}, to_utf8
("[$project]"));
4587 if (defined $name) {
4588 my @dirname = split '/', $name;
4589 my $basename = pop @dirname;
4592 foreach my $dir (@dirname) {
4593 $fullname .= ($fullname ? '/' : '') . $dir;
4594 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$fullname,
4596 -title
=> $fullname}, esc_path
($dir));
4599 if (defined $type && $type eq 'blob') {
4600 print $cgi->a({-href
=> href
(action
=>"blob_plain", file_name
=>$file_name,
4602 -title
=> $name}, esc_path
($basename));
4603 } elsif (defined $type && $type eq 'tree') {
4604 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$file_name,
4606 -title
=> $name}, esc_path
($basename));
4609 print esc_path
($basename);
4612 print "<br/></div>\n";
4619 if ($opts{'-remove_title'}) {
4620 # remove title, i.e. first line of log
4623 # remove leading empty lines
4624 while (defined $log->[0] && $log->[0] eq "") {
4629 my $skip_blank_line = 0;
4630 foreach my $line (@$log) {
4631 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4632 if (! $opts{'-remove_signoff'}) {
4633 print "<span class=\"signoff\">" . esc_html
($line) . "</span><br/>\n";
4634 $skip_blank_line = 1;
4639 if ($line =~ m
,\s
*([a-z
]*link): (https
?://\S
+),i
) {
4640 if (! $opts{'-remove_signoff'}) {
4641 print "<span class=\"signoff\">" . esc_html
($1) . ": " .
4642 "<a href=\"" . esc_html
($2) . "\">" . esc_html
($2) . "</a>" .
4644 $skip_blank_line = 1;
4649 # print only one empty line
4650 # do not print empty line after signoff
4652 next if ($skip_blank_line);
4653 $skip_blank_line = 1;
4655 $skip_blank_line = 0;
4658 print format_log_line_html
($line) . "<br/>\n";
4661 if ($opts{'-final_empty_line'}) {
4662 # end with single empty line
4663 print "<br/>\n" unless $skip_blank_line;
4667 # return link target (what link points to)
4668 sub git_get_link_target
{
4673 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
4677 $link_target = <$fd>;
4682 return $link_target;
4685 # given link target, and the directory (basedir) the link is in,
4686 # return target of link relative to top directory (top tree);
4687 # return undef if it is not possible (including absolute links).
4688 sub normalize_link_target
{
4689 my ($link_target, $basedir) = @_;
4691 # absolute symlinks (beginning with '/') cannot be normalized
4692 return if (substr($link_target, 0, 1) eq '/');
4694 # normalize link target to path from top (root) tree (dir)
4697 $path = $basedir . '/' . $link_target;
4699 # we are in top (root) tree (dir)
4700 $path = $link_target;
4703 # remove //, /./, and /../
4705 foreach my $part (split('/', $path)) {
4706 # discard '.' and ''
4707 next if (!$part || $part eq '.');
4709 if ($part eq '..') {
4713 # link leads outside repository (outside top dir)
4717 push @path_parts, $part;
4720 $path = join('/', @path_parts);
4725 # print tree entry (row of git_tree), but without encompassing <tr> element
4726 sub git_print_tree_entry
{
4727 my ($t, $basedir, $hash_base, $have_blame) = @_;
4730 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4732 # The format of a table row is: mode list link. Where mode is
4733 # the mode of the entry, list is the name of the entry, an href,
4734 # and link is the action links of the entry.
4736 print "<td class=\"mode\">" . mode_str
($t->{'mode'}) . "</td>\n";
4737 if (exists $t->{'size'}) {
4738 print "<td class=\"size\">$t->{'size'}</td>\n";
4740 if ($t->{'type'} eq "blob") {
4741 print "<td class=\"list\">" .
4742 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4743 file_name
=>"$basedir$t->{'name'}", %base_key),
4744 -class => "list"}, esc_path
($t->{'name'}));
4745 if (S_ISLNK
(oct $t->{'mode'})) {
4746 my $link_target = git_get_link_target
($t->{'hash'});
4748 my $norm_target = normalize_link_target
($link_target, $basedir);
4749 if (defined $norm_target) {
4751 $cgi->a({-href
=> href
(action
=>"object", hash_base
=>$hash_base,
4752 file_name
=>$norm_target),
4753 -title
=> $norm_target}, esc_path
($link_target));
4755 print " -> " . esc_path
($link_target);
4760 print "<td class=\"link\">";
4761 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4762 file_name
=>"$basedir$t->{'name'}", %base_key)},
4766 $cgi->a({-href
=> href
(action
=>"blame", hash
=>$t->{'hash'},
4767 file_name
=>"$basedir$t->{'name'}", %base_key)},
4770 if (defined $hash_base) {
4772 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4773 hash
=>$t->{'hash'}, file_name
=>"$basedir$t->{'name'}")},
4777 $cgi->a({-href
=> href
(action
=>"blob_plain", hash_base
=>$hash_base,
4778 file_name
=>"$basedir$t->{'name'}")},
4782 } elsif ($t->{'type'} eq "tree") {
4783 print "<td class=\"list\">";
4784 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4785 file_name
=>"$basedir$t->{'name'}",
4787 esc_path
($t->{'name'}));
4789 print "<td class=\"link\">";
4790 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4791 file_name
=>"$basedir$t->{'name'}",
4794 if (defined $hash_base) {
4796 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4797 file_name
=>"$basedir$t->{'name'}")},
4802 # unknown object: we can only present history for it
4803 # (this includes 'commit' object, i.e. submodule support)
4804 print "<td class=\"list\">" .
4805 esc_path
($t->{'name'}) .
4807 print "<td class=\"link\">";
4808 if (defined $hash_base) {
4809 print $cgi->a({-href
=> href
(action
=>"history",
4810 hash_base
=>$hash_base,
4811 file_name
=>"$basedir$t->{'name'}")},
4818 ## ......................................................................
4819 ## functions printing large fragments of HTML
4821 # get pre-image filenames for merge (combined) diff
4822 sub fill_from_file_info
{
4823 my ($diff, @parents) = @_;
4825 $diff->{'from_file'} = [ ];
4826 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4827 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4828 if ($diff->{'status'}[$i] eq 'R' ||
4829 $diff->{'status'}[$i] eq 'C') {
4830 $diff->{'from_file'}[$i] =
4831 git_get_path_by_hash
($parents[$i], $diff->{'from_id'}[$i]);
4838 # is current raw difftree line of file deletion
4840 my $diffinfo = shift;
4842 return $diffinfo->{'to_id'} eq ('0' x
40) || $diffinfo->{'to_id'} eq ('0' x
64);
4845 # does patch correspond to [previous] difftree raw line
4846 # $diffinfo - hashref of parsed raw diff format
4847 # $patchinfo - hashref of parsed patch diff format
4848 # (the same keys as in $diffinfo)
4849 sub is_patch_split
{
4850 my ($diffinfo, $patchinfo) = @_;
4852 return defined $diffinfo && defined $patchinfo
4853 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4857 sub git_difftree_body
{
4858 my ($difftree, $hash, @parents) = @_;
4859 my ($parent) = $parents[0];
4860 my $have_blame = gitweb_check_feature
('blame');
4861 print "<div class=\"list_head\">\n";
4862 if ($#{$difftree} > 10) {
4863 print(($#{$difftree} + 1) . " files changed:\n");
4867 print "<table class=\"" .
4868 (@parents > 1 ? "combined " : "") .
4871 # header only for combined diff in 'commitdiff' view
4872 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4875 print "<thead><tr>\n" .
4876 "<th></th><th></th>\n"; # filename, patchN link
4877 for (my $i = 0; $i < @parents; $i++) {
4878 my $par = $parents[$i];
4880 $cgi->a({-href
=> href
(action
=>"commitdiff",
4881 hash
=>$hash, hash_parent
=>$par),
4882 -title
=> 'commitdiff to parent number ' .
4883 ($i+1) . ': ' . substr($par,0,7)},
4887 print "</tr></thead>\n<tbody>\n";
4892 foreach my $line (@{$difftree}) {
4893 my $diff = parsed_difftree_line
($line);
4896 print "<tr class=\"dark\">\n";
4898 print "<tr class=\"light\">\n";
4902 if (exists $diff->{'nparents'}) { # combined diff
4904 fill_from_file_info
($diff, @parents)
4905 unless exists $diff->{'from_file'};
4907 if (!is_deleted
($diff)) {
4908 # file exists in the result (child) commit
4910 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4911 file_name
=>$diff->{'to_file'},
4913 -class => "list"}, esc_path
($diff->{'to_file'})) .
4917 esc_path
($diff->{'to_file'}) .
4921 if ($action eq 'commitdiff') {
4924 print "<td class=\"link\">" .
4925 $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4931 my $has_history = 0;
4932 my $not_deleted = 0;
4933 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4934 my $hash_parent = $parents[$i];
4935 my $from_hash = $diff->{'from_id'}[$i];
4936 my $from_path = $diff->{'from_file'}[$i];
4937 my $status = $diff->{'status'}[$i];
4939 $has_history ||= ($status ne 'A');
4940 $not_deleted ||= ($status ne 'D');
4942 if ($status eq 'A') {
4943 print "<td class=\"link\" align=\"right\"> | </td>\n";
4944 } elsif ($status eq 'D') {
4945 print "<td class=\"link\">" .
4946 $cgi->a({-href
=> href
(action
=>"blob",
4949 file_name
=>$from_path)},
4953 if ($diff->{'to_id'} eq $from_hash) {
4954 print "<td class=\"link nochange\">";
4956 print "<td class=\"link\">";
4958 print $cgi->a({-href
=> href
(action
=>"blobdiff",
4959 hash
=>$diff->{'to_id'},
4960 hash_parent
=>$from_hash,
4962 hash_parent_base
=>$hash_parent,
4963 file_name
=>$diff->{'to_file'},
4964 file_parent
=>$from_path)},
4970 print "<td class=\"link\">";
4972 print $cgi->a({-href
=> href
(action
=>"blob",
4973 hash
=>$diff->{'to_id'},
4974 file_name
=>$diff->{'to_file'},
4977 print " | " if ($has_history);
4980 print $cgi->a({-href
=> href
(action
=>"history",
4981 file_name
=>$diff->{'to_file'},
4988 next; # instead of 'else' clause, to avoid extra indent
4990 # else ordinary diff
4992 my ($to_mode_oct, $to_mode_str, $to_file_type);
4993 my ($from_mode_oct, $from_mode_str, $from_file_type);
4994 if ($diff->{'to_mode'} ne ('0' x
6)) {
4995 $to_mode_oct = oct $diff->{'to_mode'};
4996 if (S_ISREG
($to_mode_oct)) { # only for regular file
4997 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4999 $to_file_type = file_type
($diff->{'to_mode'});
5001 if ($diff->{'from_mode'} ne ('0' x
6)) {
5002 $from_mode_oct = oct $diff->{'from_mode'};
5003 if (S_ISREG
($from_mode_oct)) { # only for regular file
5004 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
5006 $from_file_type = file_type
($diff->{'from_mode'});
5009 if ($diff->{'status'} eq "A") { # created
5010 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5011 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
5012 $mode_chng .= "]</span>";
5014 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5015 hash_base
=>$hash, file_name
=>$diff->{'file'}),
5016 -class => "list"}, esc_path
($diff->{'file'}));
5018 print "<td>$mode_chng</td>\n";
5019 print "<td class=\"link\">";
5020 if ($action eq 'commitdiff') {
5023 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5027 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5028 hash_base
=>$hash, file_name
=>$diff->{'file'})},
5032 } elsif ($diff->{'status'} eq "D") { # deleted
5033 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5035 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
5036 hash_base
=>$parent, file_name
=>$diff->{'file'}),
5037 -class => "list"}, esc_path
($diff->{'file'}));
5039 print "<td>$mode_chng</td>\n";
5040 print "<td class=\"link\">";
5041 if ($action eq 'commitdiff') {
5044 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5048 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
5049 hash_base
=>$parent, file_name
=>$diff->{'file'})},
5052 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$parent,
5053 file_name
=>$diff->{'file'})},
5056 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$parent,
5057 file_name
=>$diff->{'file'})},
5061 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5062 my $mode_chnge = "";
5063 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5064 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5065 if ($from_file_type ne $to_file_type) {
5066 $mode_chnge .= " from $from_file_type to $to_file_type";
5068 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5069 if ($from_mode_str && $to_mode_str) {
5070 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5071 } elsif ($to_mode_str) {
5072 $mode_chnge .= " mode: $to_mode_str";
5075 $mode_chnge .= "]</span>\n";
5078 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5079 hash_base
=>$hash, file_name
=>$diff->{'file'}),
5080 -class => "list"}, esc_path
($diff->{'file'}));
5082 print "<td>$mode_chnge</td>\n";
5083 print "<td class=\"link\">";
5084 if ($action eq 'commitdiff') {
5087 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5090 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5091 # "commit" view and modified file (not onlu mode changed)
5092 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5093 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5094 hash_base
=>$hash, hash_parent_base
=>$parent,
5095 file_name
=>$diff->{'file'})},
5099 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5100 hash_base
=>$hash, file_name
=>$diff->{'file'})},
5103 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5104 file_name
=>$diff->{'file'})},
5107 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5108 file_name
=>$diff->{'file'})},
5112 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5113 my %status_name = ('R' => 'moved', 'C' => 'copied');
5114 my $nstatus = $status_name{$diff->{'status'}};
5116 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5117 # mode also for directories, so we cannot use $to_mode_str
5118 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5121 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$hash,
5122 hash
=>$diff->{'to_id'}, file_name
=>$diff->{'to_file'}),
5123 -class => "list"}, esc_path
($diff->{'to_file'})) . "</td>\n" .
5124 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5125 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$parent,
5126 hash
=>$diff->{'from_id'}, file_name
=>$diff->{'from_file'}),
5127 -class => "list"}, esc_path
($diff->{'from_file'})) .
5128 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5129 "<td class=\"link\">";
5130 if ($action eq 'commitdiff') {
5133 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5136 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5137 # "commit" view and modified file (not only pure rename or copy)
5138 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5139 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5140 hash_base
=>$hash, hash_parent_base
=>$parent,
5141 file_name
=>$diff->{'to_file'}, file_parent
=>$diff->{'from_file'})},
5145 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5146 hash_base
=>$parent, file_name
=>$diff->{'to_file'})},
5149 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5150 file_name
=>$diff->{'to_file'})},
5153 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5154 file_name
=>$diff->{'to_file'})},
5158 } # we should not encounter Unmerged (U) or Unknown (X) status
5161 print "</tbody>" if $has_header;
5165 # Print context lines and then rem/add lines in a side-by-side manner.
5166 sub print_sidebyside_diff_lines
{
5167 my ($ctx, $rem, $add) = @_;
5169 # print context block before add/rem block
5172 '<div class="chunk_block ctx">',
5173 '<div class="old">',
5176 '<div class="new">',
5185 '<div class="chunk_block rem">',
5186 '<div class="old">',
5193 '<div class="chunk_block add">',
5194 '<div class="new">',
5200 '<div class="chunk_block chg">',
5201 '<div class="old">',
5204 '<div class="new">',
5211 # Print context lines and then rem/add lines in inline manner.
5212 sub print_inline_diff_lines
{
5213 my ($ctx, $rem, $add) = @_;
5215 print @$ctx, @$rem, @$add;
5218 # Format removed and added line, mark changed part and HTML-format them.
5219 # Implementation is based on contrib/diff-highlight
5220 sub format_rem_add_lines_pair
{
5221 my ($rem, $add, $num_parents) = @_;
5223 # We need to untabify lines before split()'ing them;
5224 # otherwise offsets would be invalid.
5227 $rem = untabify
($rem);
5228 $add = untabify
($add);
5230 my @rem = split(//, $rem);
5231 my @add = split(//, $add);
5232 my ($esc_rem, $esc_add);
5233 # Ignore leading +/- characters for each parent.
5234 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5235 my ($prefix_has_nonspace, $suffix_has_nonspace);
5237 my $shorter = (@rem < @add) ? @rem : @add;
5238 while ($prefix_len < $shorter) {
5239 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5241 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5245 while ($prefix_len + $suffix_len < $shorter) {
5246 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5248 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5252 # Mark lines that are different from each other, but have some common
5253 # part that isn't whitespace. If lines are completely different, don't
5254 # mark them because that would make output unreadable, especially if
5255 # diff consists of multiple lines.
5256 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5257 $esc_rem = esc_html_hl_regions
($rem, 'marked',
5258 [$prefix_len, @rem - $suffix_len], -nbsp
=>1);
5259 $esc_add = esc_html_hl_regions
($add, 'marked',
5260 [$prefix_len, @add - $suffix_len], -nbsp
=>1);
5262 $esc_rem = esc_html
($rem, -nbsp
=>1);
5263 $esc_add = esc_html
($add, -nbsp
=>1);
5266 return format_diff_line
(\
$esc_rem, 'rem'),
5267 format_diff_line
(\
$esc_add, 'add');
5270 # HTML-format diff context, removed and added lines.
5271 sub format_ctx_rem_add_lines
{
5272 my ($ctx, $rem, $add, $num_parents) = @_;
5273 my (@new_ctx, @new_rem, @new_add);
5274 my $can_highlight = 0;
5275 my $is_combined = ($num_parents > 1);
5277 # Highlight if every removed line has a corresponding added line.
5278 if (@$add > 0 && @$add == @$rem) {
5281 # Highlight lines in combined diff only if the chunk contains
5282 # diff between the same version, e.g.
5289 # Otherwise the highlightling would be confusing.
5291 for (my $i = 0; $i < @$add; $i++) {
5292 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5293 my $prefix_add = substr($add->[$i], 0, $num_parents);
5295 $prefix_rem =~ s/-/+/g;
5297 if ($prefix_rem ne $prefix_add) {
5305 if ($can_highlight) {
5306 for (my $i = 0; $i < @$add; $i++) {
5307 my ($line_rem, $line_add) = format_rem_add_lines_pair
(
5308 $rem->[$i], $add->[$i], $num_parents);
5309 push @new_rem, $line_rem;
5310 push @new_add, $line_add;
5313 @new_rem = map { format_diff_line
($_, 'rem') } @$rem;
5314 @new_add = map { format_diff_line
($_, 'add') } @$add;
5317 @new_ctx = map { format_diff_line
($_, 'ctx') } @$ctx;
5319 return (\
@new_ctx, \
@new_rem, \
@new_add);
5322 # Print context lines and then rem/add lines.
5323 sub print_diff_lines
{
5324 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5325 my $is_combined = $num_parents > 1;
5327 ($ctx, $rem, $add) = format_ctx_rem_add_lines
($ctx, $rem, $add,
5330 if ($diff_style eq 'sidebyside' && !$is_combined) {
5331 print_sidebyside_diff_lines
($ctx, $rem, $add);
5333 # default 'inline' style and unknown styles
5334 print_inline_diff_lines
($ctx, $rem, $add);
5338 sub print_diff_chunk
{
5339 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5340 my (@ctx, @rem, @add);
5342 # The class of the previous line.
5343 my $prev_class = '';
5345 return unless @chunk;
5347 # incomplete last line might be among removed or added lines,
5348 # or both, or among context lines: find which
5349 for (my $i = 1; $i < @chunk; $i++) {
5350 if ($chunk[$i][0] eq 'incomplete') {
5351 $chunk[$i][0] = $chunk[$i-1][0];
5356 push @chunk, ["", ""];
5358 foreach my $line_info (@chunk) {
5359 my ($class, $line) = @$line_info;
5361 # print chunk headers
5362 if ($class && $class eq 'chunk_header') {
5363 print format_diff_line
($line, $class, $from, $to);
5367 ## print from accumulator when have some add/rem lines or end
5368 # of chunk (flush context lines), or when have add and rem
5369 # lines and new block is reached (otherwise add/rem lines could
5371 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5372 (@rem && @add && $class ne $prev_class)) {
5373 print_diff_lines
(\
@ctx, \
@rem, \
@add,
5374 $diff_style, $num_parents);
5375 @ctx = @rem = @add = ();
5378 ## adding lines to accumulator
5381 # rem, add or change
5382 if ($class eq 'rem') {
5384 } elsif ($class eq 'add') {
5388 if ($class eq 'ctx') {
5392 $prev_class = $class;
5396 sub git_patchset_body
{
5397 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5398 my ($hash_parent) = $hash_parents[0];
5400 my $is_combined = (@hash_parents > 1);
5402 my $patch_number = 0;
5407 my @chunk; # for side-by-side diff
5409 print "<div class=\"patchset\">\n";
5411 # skip to first patch
5412 while ($patch_line = <$fd>) {
5415 last if ($patch_line =~ m/^diff /);
5419 while ($patch_line) {
5421 # parse "git diff" header line
5422 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5423 # $1 is from_name, which we do not use
5424 $to_name = unquote
($2);
5425 $to_name =~ s!^b/!!;
5426 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5427 # $1 is 'cc' or 'combined', which we do not use
5428 $to_name = unquote
($2);
5433 # check if current patch belong to current raw line
5434 # and parse raw git-diff line if needed
5435 if (is_patch_split
($diffinfo, { 'to_file' => $to_name })) {
5436 # this is continuation of a split patch
5437 print "<div class=\"patch cont\">\n";
5439 # advance raw git-diff output if needed
5440 $patch_idx++ if defined $diffinfo;
5442 # read and prepare patch information
5443 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5445 # compact combined diff output can have some patches skipped
5446 # find which patch (using pathname of result) we are at now;
5448 while ($to_name ne $diffinfo->{'to_file'}) {
5449 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5450 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5451 "</div>\n"; # class="patch"
5456 last if $patch_idx > $#$difftree;
5457 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5461 # modifies %from, %to hashes
5462 parse_from_to_diffinfo
($diffinfo, \
%from, \
%to, @hash_parents);
5464 # this is first patch for raw difftree line with $patch_idx index
5465 # we index @$difftree array from 0, but number patches from 1
5466 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5470 #assert($patch_line =~ m/^diff /) if DEBUG;
5471 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5473 # print "git diff" header
5474 print format_git_diff_header_line
($patch_line, $diffinfo,
5477 # print extended diff header
5478 print "<div class=\"diff extended_header\">\n";
5480 while ($patch_line = <$fd>) {
5483 last EXTENDED_HEADER
if ($patch_line =~ m/^--- |^diff /);
5485 print format_extended_diff_header_line
($patch_line, $diffinfo,
5488 print "</div>\n"; # class="diff extended_header"
5490 # from-file/to-file diff header
5491 if (! $patch_line) {
5492 print "</div>\n"; # class="patch"
5495 next PATCH
if ($patch_line =~ m/^diff /);
5496 #assert($patch_line =~ m/^---/) if DEBUG;
5498 my $last_patch_line = $patch_line;
5499 $patch_line = <$fd>;
5501 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5503 print format_diff_from_to_header
($last_patch_line, $patch_line,
5504 $diffinfo, \
%from, \
%to,
5509 while ($patch_line = <$fd>) {
5512 next PATCH
if ($patch_line =~ m/^diff /);
5514 my $class = diff_line_class
($patch_line, \
%from, \
%to);
5516 if ($class eq 'chunk_header') {
5517 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5521 push @chunk, [ $class, $patch_line ];
5526 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5529 print "</div>\n"; # class="patch"
5532 # for compact combined (--cc) format, with chunk and patch simplification
5533 # the patchset might be empty, but there might be unprocessed raw lines
5534 for (++$patch_idx if $patch_number > 0;
5535 $patch_idx < @$difftree;
5537 # read and prepare patch information
5538 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5540 # generate anchor for "patch" links in difftree / whatchanged part
5541 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5542 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5543 "</div>\n"; # class="patch"
5548 if ($patch_number == 0) {
5549 if (@hash_parents > 1) {
5550 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5552 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5556 print "</div>\n"; # class="patchset"
5559 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5561 sub git_project_search_form
{
5562 my ($searchtext, $search_use_regexp) = @_;
5565 if ($project_filter) {
5566 $limit = " in '$project_filter/'";
5569 print "<div class=\"projsearch\">\n";
5570 print $cgi->start_form(-method => 'get', -action
=> $my_uri) .
5571 $cgi->hidden(-name
=> 'a', -value
=> 'project_list') . "\n";
5572 print $cgi->hidden(-name
=> 'pf', -value
=> $project_filter). "\n"
5573 if (defined $project_filter);
5574 print $cgi->textfield(-name
=> 's', -value
=> $searchtext,
5575 -title
=> "Search project by name and description$limit",
5576 -size
=> 60) . "\n" .
5577 "<span title=\"Extended regular expression\">" .
5578 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
5579 -checked
=> $search_use_regexp) .
5581 $cgi->submit(-name
=> 'btnS', -value
=> 'Search') .
5582 $cgi->end_form() . "\n" .
5583 $cgi->a({-href
=> href
(project
=> undef, searchtext
=> undef,
5584 project_filter
=> $project_filter)},
5585 esc_html
("List all projects$limit")) . "<br />\n";
5589 # entry for given @keys needs filling if at least one of keys in list
5590 # is not present in %$project_info
5591 sub project_info_needs_filling
{
5592 my ($project_info, @keys) = @_;
5594 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5595 foreach my $key (@keys) {
5596 if (!exists $project_info->{$key}) {
5603 # fills project list info (age, description, owner, category, forks, etc.)
5604 # for each project in the list, removing invalid projects from
5605 # returned list, or fill only specified info.
5607 # Invalid projects are removed from the returned list if and only if you
5608 # ask 'age' or 'age_string' to be filled, because they are the only fields
5609 # that run unconditionally git command that requires repository, and
5610 # therefore do always check if project repository is invalid.
5613 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5614 # ensures that 'descr_long' and 'ctags' fields are filled
5615 # * @project_list = fill_project_list_info(\@project_list)
5616 # ensures that all fields are filled (and invalid projects removed)
5618 # NOTE: modifies $projlist, but does not remove entries from it
5619 sub fill_project_list_info
{
5620 my ($projlist, @wanted_keys) = @_;
5622 my $filter_set = sub { return @_; };
5624 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5625 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5628 my $show_ctags = gitweb_check_feature
('ctags');
5630 foreach my $pr (@$projlist) {
5631 if (project_info_needs_filling
($pr, $filter_set->('age', 'age_string'))) {
5632 my (@activity) = git_get_last_activity
($pr->{'path'});
5633 unless (@activity) {
5636 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5638 if (project_info_needs_filling
($pr, $filter_set->('descr', 'descr_long'))) {
5639 my $descr = git_get_project_description
($pr->{'path'}) || "";
5640 $descr = to_utf8
($descr);
5641 $pr->{'descr_long'} = $descr;
5642 $pr->{'descr'} = chop_str
($descr, $projects_list_description_width, 5);
5644 if (project_info_needs_filling
($pr, $filter_set->('owner'))) {
5645 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}") || "";
5648 project_info_needs_filling
($pr, $filter_set->('ctags'))) {
5649 $pr->{'ctags'} = git_get_project_ctags
($pr->{'path'});
5651 if ($projects_list_group_categories &&
5652 project_info_needs_filling
($pr, $filter_set->('category'))) {
5653 my $cat = git_get_project_category
($pr->{'path'}) ||
5654 $project_list_default_category;
5655 $pr->{'category'} = to_utf8
($cat);
5658 push @projects, $pr;
5664 sub sort_projects_list
{
5665 my ($projlist, $order) = @_;
5669 return sub { $a->{$key} cmp $b->{$key} };
5672 sub order_num_then_undef
{
5675 defined $a->{$key} ?
5676 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5677 (defined $b->{$key} ? 1 : 0)
5682 project
=> order_str
('path'),
5683 descr
=> order_str
('descr_long'),
5684 owner
=> order_str
('owner'),
5685 age
=> order_num_then_undef
('age'),
5688 my $ordering = $orderings{$order};
5689 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5692 # returns a hash of categories, containing the list of project
5693 # belonging to each category
5694 sub build_projlist_by_category
{
5695 my ($projlist, $from, $to) = @_;
5698 $from = 0 unless defined $from;
5699 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5701 for (my $i = $from; $i <= $to; $i++) {
5702 my $pr = $projlist->[$i];
5703 push @{$categories{ $pr->{'category'} }}, $pr;
5706 return wantarray ? %categories : \
%categories;
5709 # print 'sort by' <th> element, generating 'sort by $name' replay link
5710 # if that order is not selected
5712 print format_sort_th
(@_);
5715 sub format_sort_th
{
5716 my ($name, $order, $header) = @_;
5718 $header ||= ucfirst($name);
5720 if ($order eq $name) {
5721 $sort_th .= "<th>$header</th>\n";
5723 $sort_th .= "<th>" .
5724 $cgi->a({-href
=> href
(-replay
=>1, order
=>$name),
5725 -class => "header"}, $header) .
5732 sub git_project_list_rows
{
5733 my ($projlist, $from, $to, $check_forks) = @_;
5735 $from = 0 unless defined $from;
5736 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5739 for (my $i = $from; $i <= $to; $i++) {
5740 my $pr = $projlist->[$i];
5743 print "<tr class=\"dark\">\n";
5745 print "<tr class=\"light\">\n";
5751 if ($pr->{'forks'}) {
5752 my $nforks = scalar @{$pr->{'forks'}};
5754 print $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks"),
5755 -title
=> "$nforks forks"}, "+");
5757 print $cgi->span({-title
=> "$nforks forks"}, "+");
5762 print "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5764 esc_html_match_hl
($pr->{'path'}, $search_regexp)) .
5766 "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5768 -title
=> $pr->{'descr_long'}},
5770 ? esc_html_match_hl_chopped
($pr->{'descr_long'},
5771 $pr->{'descr'}, $search_regexp)
5772 : esc_html
($pr->{'descr'})) .
5774 unless ($omit_owner) {
5775 print "<td><i>" . chop_and_escape_str
($pr->{'owner'}, 15) . "</i></td>\n";
5777 unless ($omit_age_column) {
5778 print "<td class=\"". age_class
($pr->{'age'}) . "\">" .
5779 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5781 print"<td class=\"link\">" .
5782 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary")}, "summary") . " | " .
5783 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"shortlog")}, "shortlog") . " | " .
5784 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"log")}, "log") . " | " .
5785 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"tree")}, "tree") .
5786 ($pr->{'forks'} ? " | " . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks")}, "forks") : '') .
5792 sub git_project_list_body
{
5793 # actually uses global variable $project
5794 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5795 my @projects = @$projlist;
5797 my $check_forks = gitweb_check_feature
('forks');
5798 my $show_ctags = gitweb_check_feature
('ctags');
5799 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5800 $check_forks = undef
5801 if ($tagfilter || $search_regexp);
5803 # filtering out forks before filling info allows to do less work
5804 @projects = filter_forks_from_projects_list
(\
@projects)
5806 # search_projects_list pre-fills required info
5807 @projects = search_projects_list
(\
@projects,
5808 'search_regexp' => $search_regexp,
5809 'tagfilter' => $tagfilter)
5810 if ($tagfilter || $search_regexp);
5812 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5813 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5814 push @all_fields, 'owner' unless($omit_owner);
5815 @projects = fill_project_list_info
(\
@projects, @all_fields);
5817 $order ||= $default_projects_order;
5818 $from = 0 unless defined $from;
5819 $to = $#projects if (!defined $to || $#projects < $to);
5824 "<b>No such projects found</b><br />\n".
5825 "Click ".$cgi->a({-href
=>href
(project
=>undef)},"here")." to view all projects<br />\n".
5826 "</center>\n<br />\n";
5830 @projects = sort_projects_list
(\
@projects, $order);
5833 my $ctags = git_gather_all_ctags
(\
@projects);
5834 my $cloud = git_populate_project_tagcloud
($ctags);
5835 print git_show_project_tagcloud
($cloud, 64);
5838 print "<table class=\"project_list\">\n";
5839 unless ($no_header) {
5842 print "<th></th>\n";
5844 print_sort_th
('project', $order, 'Project');
5845 print_sort_th
('descr', $order, 'Description');
5846 print_sort_th
('owner', $order, 'Owner') unless $omit_owner;
5847 print_sort_th
('age', $order, 'Last Change') unless $omit_age_column;
5848 print "<th></th>\n" . # for links
5852 if ($projects_list_group_categories) {
5853 # only display categories with projects in the $from-$to window
5854 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5855 my %categories = build_projlist_by_category
(\
@projects, $from, $to);
5856 foreach my $cat (sort keys %categories) {
5857 unless ($cat eq "") {
5860 print "<td></td>\n";
5862 print "<td class=\"category\" colspan=\"5\">".esc_html
($cat)."</td>\n";
5866 git_project_list_rows
($categories{$cat}, undef, undef, $check_forks);
5869 git_project_list_rows
(\
@projects, $from, $to, $check_forks);
5872 if (defined $extra) {
5875 print "<td></td>\n";
5877 print "<td colspan=\"5\">$extra</td>\n" .
5884 # uses global variable $project
5885 my ($commitlist, $from, $to, $refs, $extra) = @_;
5887 $from = 0 unless defined $from;
5888 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5890 for (my $i = 0; $i <= $to; $i++) {
5891 my %co = %{$commitlist->[$i]};
5893 my $commit = $co{'id'};
5894 my $ref = format_ref_marker
($refs, $commit);
5895 git_print_header_div
('commit',
5896 "<span class=\"age\">$co{'age_string'}</span>" .
5897 esc_html
($co{'title'}) . $ref,
5899 print "<div class=\"title_text\">\n" .
5900 "<div class=\"log_link\">\n" .
5901 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") .
5903 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") .
5905 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree") .
5908 git_print_authorship
(\
%co, -tag
=> 'span');
5909 print "<br/>\n</div>\n";
5911 print "<div class=\"log_body\">\n";
5912 git_print_log
($co{'comment'}, -final_empty_line
=> 1);
5916 print "<div class=\"page_nav\">\n";
5922 sub git_shortlog_body
{
5923 # uses global variable $project
5924 my ($commitlist, $from, $to, $refs, $extra) = @_;
5926 $from = 0 unless defined $from;
5927 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5929 print "<table class=\"shortlog\">\n";
5931 for (my $i = $from; $i <= $to; $i++) {
5932 my %co = %{$commitlist->[$i]};
5933 my $commit = $co{'id'};
5934 my $ref = format_ref_marker
($refs, $commit);
5936 print "<tr class=\"dark\">\n";
5938 print "<tr class=\"light\">\n";
5941 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5942 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5943 format_author_html
('td', \
%co, 10) . "<td>";
5944 print format_subject_html
($co{'title'}, $co{'title_short'},
5945 href
(action
=>"commit", hash
=>$commit), $ref);
5947 "<td class=\"link\">" .
5948 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") . " | " .
5949 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") . " | " .
5950 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree");
5951 my $snapshot_links = format_snapshot_links
($commit);
5952 if (defined $snapshot_links) {
5953 print " | " . $snapshot_links;
5958 if (defined $extra) {
5960 "<td colspan=\"4\">$extra</td>\n" .
5966 sub git_history_body
{
5967 # Warning: assumes constant type (blob or tree) during history
5968 my ($commitlist, $from, $to, $refs, $extra,
5969 $file_name, $file_hash, $ftype) = @_;
5971 $from = 0 unless defined $from;
5972 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5974 print "<table class=\"history\">\n";
5976 for (my $i = $from; $i <= $to; $i++) {
5977 my %co = %{$commitlist->[$i]};
5981 my $commit = $co{'id'};
5983 my $ref = format_ref_marker
($refs, $commit);
5986 print "<tr class=\"dark\">\n";
5988 print "<tr class=\"light\">\n";
5991 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5992 # shortlog: format_author_html('td', \%co, 10)
5993 format_author_html
('td', \
%co, 15, 3) . "<td>";
5994 # originally git_history used chop_str($co{'title'}, 50)
5995 print format_subject_html
($co{'title'}, $co{'title_short'},
5996 href
(action
=>"commit", hash
=>$commit), $ref);
5998 "<td class=\"link\">" .
5999 $cgi->a({-href
=> href
(action
=>$ftype, hash_base
=>$commit, file_name
=>$file_name)}, $ftype) . " | " .
6000 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff");
6002 if ($ftype eq 'blob') {
6004 $cgi->a({-href
=> href
(action
=>"blob_plain", hash_base
=>$commit, file_name
=>$file_name)}, "raw");
6006 my $blob_current = $file_hash;
6007 my $blob_parent = git_get_hash_by_path
($commit, $file_name);
6008 if (defined $blob_current && defined $blob_parent &&
6009 $blob_current ne $blob_parent) {
6011 $cgi->a({-href
=> href
(action
=>"blobdiff",
6012 hash
=>$blob_current, hash_parent
=>$blob_parent,
6013 hash_base
=>$hash_base, hash_parent_base
=>$commit,
6014 file_name
=>$file_name)},
6021 if (defined $extra) {
6023 "<td colspan=\"4\">$extra</td>\n" .
6030 # uses global variable $project
6031 my ($taglist, $from, $to, $extra) = @_;
6032 $from = 0 unless defined $from;
6033 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6035 print "<table class=\"tags\">\n";
6037 for (my $i = $from; $i <= $to; $i++) {
6038 my $entry = $taglist->[$i];
6040 my $comment = $tag{'subject'};
6042 if (defined $comment) {
6043 $comment_short = chop_str
($comment, 30, 5);
6046 print "<tr class=\"dark\">\n";
6048 print "<tr class=\"light\">\n";
6051 if (defined $tag{'age'}) {
6052 print "<td><i>$tag{'age'}</i></td>\n";
6054 print "<td></td>\n";
6057 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'}),
6058 -class => "list name"}, esc_html
($tag{'name'})) .
6061 if (defined $comment) {
6062 print format_subject_html
($comment, $comment_short,
6063 href
(action
=>"tag", hash
=>$tag{'id'}));
6066 "<td class=\"selflink\">";
6067 if ($tag{'type'} eq "tag") {
6068 print $cgi->a({-href
=> href
(action
=>"tag", hash
=>$tag{'id'})}, "tag");
6073 "<td class=\"link\">" . " | " .
6074 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'})}, $tag{'reftype'});
6075 if ($tag{'reftype'} eq "commit") {
6076 print " | " . $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$tag{'fullname'})}, "shortlog") .
6077 " | " . $cgi->a({-href
=> href
(action
=>"log", hash
=>$tag{'fullname'})}, "log");
6078 } elsif ($tag{'reftype'} eq "blob") {
6079 print " | " . $cgi->a({-href
=> href
(action
=>"blob_plain", hash
=>$tag{'refid'})}, "raw");
6084 if (defined $extra) {
6086 "<td colspan=\"5\">$extra</td>\n" .
6092 sub git_heads_body
{
6093 # uses global variable $project
6094 my ($headlist, $head_at, $from, $to, $extra) = @_;
6095 $from = 0 unless defined $from;
6096 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6098 print "<table class=\"heads\">\n";
6100 for (my $i = $from; $i <= $to; $i++) {
6101 my $entry = $headlist->[$i];
6103 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6105 print "<tr class=\"dark\">\n";
6107 print "<tr class=\"light\">\n";
6110 print "<td><i>$ref{'age'}</i></td>\n" .
6111 ($curr ? "<td class=\"current_head\">" : "<td>") .
6112 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'}),
6113 -class => "list name"},esc_html
($ref{'name'})) .
6115 "<td class=\"link\">" .
6116 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'})}, "shortlog") . " | " .
6117 $cgi->a({-href
=> href
(action
=>"log", hash
=>$ref{'fullname'})}, "log") . " | " .
6118 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$ref{'fullname'}, hash_base
=>$ref{'fullname'})}, "tree") .
6122 if (defined $extra) {
6124 "<td colspan=\"3\">$extra</td>\n" .
6130 # Display a single remote block
6131 sub git_remote_block
{
6132 my ($remote, $rdata, $limit, $head) = @_;
6134 my $heads = $rdata->{'heads'};
6135 my $fetch = $rdata->{'fetch'};
6136 my $push = $rdata->{'push'};
6138 my $urls_table = "<table class=\"projects_list\">\n" ;
6140 if (defined $fetch) {
6141 if ($fetch eq $push) {
6142 $urls_table .= format_repo_url
("URL", $fetch);
6144 $urls_table .= format_repo_url
("Fetch URL", $fetch);
6145 $urls_table .= format_repo_url
("Push URL", $push) if defined $push;
6147 } elsif (defined $push) {
6148 $urls_table .= format_repo_url
("Push URL", $push);
6150 $urls_table .= format_repo_url
("", "No remote URL");
6153 $urls_table .= "</table>\n";
6156 if (defined $limit && $limit < @$heads) {
6157 $dots = $cgi->a({-href
=> href
(action
=>"remotes", hash
=>$remote)}, "...");
6161 git_heads_body
($heads, $head, 0, $limit, $dots);
6164 # Display a list of remote names with the respective fetch and push URLs
6165 sub git_remotes_list
{
6166 my ($remotedata, $limit) = @_;
6167 print "<table class=\"heads\">\n";
6169 my @remotes = sort keys %$remotedata;
6171 my $limited = $limit && $limit < @remotes;
6173 $#remotes = $limit - 1 if $limited;
6175 while (my $remote = shift @remotes) {
6176 my $rdata = $remotedata->{$remote};
6177 my $fetch = $rdata->{'fetch'};
6178 my $push = $rdata->{'push'};
6180 print "<tr class=\"dark\">\n";
6182 print "<tr class=\"light\">\n";
6186 $cgi->a({-href
=> href
(action
=>'remotes', hash
=>$remote),
6187 -class=> "list name"},esc_html
($remote)) .
6189 print "<td class=\"link\">" .
6190 (defined $fetch ? $cgi->a({-href
=> $fetch}, "fetch") : "fetch") .
6192 (defined $push ? $cgi->a({-href
=> $push}, "push") : "push") .
6200 "<td colspan=\"3\">" .
6201 $cgi->a({-href
=> href
(action
=>"remotes")}, "...") .
6202 "</td>\n" . "</tr>\n";
6208 # Display remote heads grouped by remote, unless there are too many
6209 # remotes, in which case we only display the remote names
6210 sub git_remotes_body
{
6211 my ($remotedata, $limit, $head) = @_;
6212 if ($limit and $limit < keys %$remotedata) {
6213 git_remotes_list
($remotedata, $limit);
6215 fill_remote_heads
($remotedata);
6216 while (my ($remote, $rdata) = each %$remotedata) {
6217 git_print_section
({-class=>"remote", -id
=>$remote},
6218 ["remotes", $remote, $remote], sub {
6219 git_remote_block
($remote, $rdata, $limit, $head);
6225 sub git_search_message
{
6229 if ($searchtype eq 'commit') {
6230 $greptype = "--grep=";
6231 } elsif ($searchtype eq 'author') {
6232 $greptype = "--author=";
6233 } elsif ($searchtype eq 'committer') {
6234 $greptype = "--committer=";
6236 $greptype .= $searchtext;
6237 my @commitlist = parse_commits
($hash, 101, (100 * $page), undef,
6238 $greptype, '--regexp-ignore-case',
6239 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6241 my $paging_nav = '';
6244 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)},
6247 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
6248 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
6250 $paging_nav .= "first ⋅ prev";
6253 if ($#commitlist >= 100) {
6255 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
6256 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
6257 $paging_nav .= " ⋅ $next_link";
6259 $paging_nav .= " ⋅ next";
6264 git_print_page_nav
('','', $hash,$co{'tree'},$hash, $paging_nav);
6265 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6266 if ($page == 0 && !@commitlist) {
6267 print "<p>No match.</p>\n";
6269 git_search_grep_body
(\
@commitlist, 0, 99, $next_link);
6275 sub git_search_changes
{
6279 open my $fd, '-|', git_cmd
(), '--no-pager', 'log', @diff_opts,
6280 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6281 ($search_use_regexp ? '--pickaxe-regex' : ())
6282 or die_error
(500, "Open git-log failed");
6286 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6287 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6289 print "<table class=\"pickaxe search\">\n";
6293 while (my $line = <$fd>) {
6297 my %set = parse_difftree_raw_line
($line);
6298 if (defined $set{'commit'}) {
6299 # finish previous commit
6302 "<td class=\"link\">" .
6303 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6306 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6307 hash_base
=>$co{'id'})},
6314 print "<tr class=\"dark\">\n";
6316 print "<tr class=\"light\">\n";
6319 %co = parse_commit
($set{'commit'});
6320 my $author = chop_and_escape_str
($co{'author_name'}, 15, 5);
6321 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6322 "<td><i>$author</i></td>\n" .
6324 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6325 -class => "list subject"},
6326 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6327 } elsif (defined $set{'to_id'}) {
6328 next if is_deleted
(\
%set);
6330 print $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$co{'id'},
6331 hash
=>$set{'to_id'}, file_name
=>$set{'to_file'}),
6333 "<span class=\"match\">" . esc_path
($set{'file'}) . "</span>") .
6339 # finish last commit (warning: repetition!)
6342 "<td class=\"link\">" .
6343 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6346 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6347 hash_base
=>$co{'id'})},
6358 sub git_search_files
{
6362 open my $fd, "-|", git_cmd
(), 'grep', '-n', '-z',
6363 $search_use_regexp ? ('-E', '-i') : '-F',
6364 $searchtext, $co{'tree'}
6365 or die_error
(500, "Open git-grep failed");
6369 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6370 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6372 print "<table class=\"grep_search\">\n";
6377 while (my $line = <$fd>) {
6379 my ($file, $lno, $ltext, $binary);
6380 last if ($matches++ > 1000);
6381 if ($line =~ /^Binary file (.+) matches$/) {
6385 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6386 $file =~ s/^$co{'tree'}://;
6388 if ($file ne $lastfile) {
6389 $lastfile and print "</td></tr>\n";
6391 print "<tr class=\"dark\">\n";
6393 print "<tr class=\"light\">\n";
6395 $file_href = href
(action
=>"blob", hash_base
=>$co{'id'},
6397 print "<td class=\"list\">".
6398 $cgi->a({-href
=> $file_href, -class => "list"}, esc_path
($file));
6399 print "</td><td>\n";
6403 print "<div class=\"binary\">Binary file</div>\n";
6405 $ltext = untabify
($ltext);
6406 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6407 $ltext = esc_html
($1, -nbsp
=>1);
6408 $ltext .= '<span class="match">';
6409 $ltext .= esc_html
($2, -nbsp
=>1);
6410 $ltext .= '</span>';
6411 $ltext .= esc_html
($3, -nbsp
=>1);
6413 $ltext = esc_html
($ltext, -nbsp
=>1);
6415 print "<div class=\"pre\">" .
6416 $cgi->a({-href
=> $file_href.'#l'.$lno,
6417 -class => "linenr"}, sprintf('%4i', $lno)) .
6418 ' ' . $ltext . "</div>\n";
6422 print "</td></tr>\n";
6423 if ($matches > 1000) {
6424 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6427 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6436 sub git_search_grep_body
{
6437 my ($commitlist, $from, $to, $extra) = @_;
6438 $from = 0 unless defined $from;
6439 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6441 print "<table class=\"commit_search\">\n";
6443 for (my $i = $from; $i <= $to; $i++) {
6444 my %co = %{$commitlist->[$i]};
6448 my $commit = $co{'id'};
6450 print "<tr class=\"dark\">\n";
6452 print "<tr class=\"light\">\n";
6455 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6456 format_author_html
('td', \
%co, 15, 5) .
6458 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6459 -class => "list subject"},
6460 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6461 my $comment = $co{'comment'};
6462 foreach my $line (@$comment) {
6463 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6464 my ($lead, $match, $trail) = ($1, $2, $3);
6465 $match = chop_str
($match, 70, 5, 'center');
6466 my $contextlen = int((80 - length($match))/2);
6467 $contextlen = 30 if ($contextlen > 30);
6468 $lead = chop_str
($lead, $contextlen, 10, 'left');
6469 $trail = chop_str
($trail, $contextlen, 10, 'right');
6471 $lead = esc_html
($lead);
6472 $match = esc_html
($match);
6473 $trail = esc_html
($trail);
6475 print "$lead<span class=\"match\">$match</span>$trail<br />";
6479 "<td class=\"link\">" .
6480 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})}, "commit") .
6482 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$co{'id'})}, "commitdiff") .
6484 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$co{'id'})}, "tree");
6488 if (defined $extra) {
6490 "<td colspan=\"3\">$extra</td>\n" .
6496 ## ======================================================================
6497 ## ======================================================================
6500 sub git_project_list
{
6501 my $order = $input_params{'order'};
6502 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6503 die_error
(400, "Unknown order parameter");
6506 my @list = git_get_projects_list
($project_filter, $strict_export);
6508 die_error
(404, "No projects found");
6512 if (defined $home_text && -f
$home_text) {
6513 print "<div class=\"index_include\">\n";
6514 insert_file
($home_text);
6518 git_project_search_form
($searchtext, $search_use_regexp);
6519 git_project_list_body
(\
@list, $order);
6524 my $order = $input_params{'order'};
6525 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6526 die_error
(400, "Unknown order parameter");
6529 my $filter = $project;
6530 $filter =~ s/\.git$//;
6531 my @list = git_get_projects_list
($filter);
6533 die_error
(404, "No forks found");
6537 git_print_page_nav
('','');
6538 git_print_header_div
('summary', "$project forks");
6539 git_project_list_body
(\
@list, $order);
6543 sub git_project_index
{
6544 my @projects = git_get_projects_list
($project_filter, $strict_export);
6546 die_error
(404, "No projects found");
6550 -type
=> 'text/plain',
6551 -charset
=> 'utf-8',
6552 -content_disposition
=> 'inline; filename="index.aux"');
6554 foreach my $pr (@projects) {
6555 if (!exists $pr->{'owner'}) {
6556 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}");
6559 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6560 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6561 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6562 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6566 print "$path $owner\n";
6571 my $descr = git_get_project_description
($project) || "none";
6572 my %co = parse_commit
("HEAD");
6573 my %cd = %co ? parse_date
($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6574 my $head = $co{'id'};
6575 my $remote_heads = gitweb_check_feature
('remote_heads');
6577 my $owner = git_get_project_owner
($project);
6579 my $refs = git_get_references
();
6580 # These get_*_list functions return one more to allow us to see if
6581 # there are more ...
6582 my @taglist = git_get_tags_list
(16);
6583 my @headlist = git_get_heads_list
(16);
6584 my %remotedata = $remote_heads ? git_get_remotes_list
() : ();
6586 my $check_forks = gitweb_check_feature
('forks');
6589 # find forks of a project
6590 my $filter = $project;
6591 $filter =~ s/\.git$//;
6592 @forklist = git_get_projects_list
($filter);
6593 # filter out forks of forks
6594 @forklist = filter_forks_from_projects_list
(\
@forklist)
6599 git_print_page_nav
('summary','', $head);
6601 print "<div class=\"title\"> </div>\n";
6602 print "<table class=\"projects_list\">\n" .
6603 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html
($descr) . "</td></tr>\n";
6604 if ($owner and not $omit_owner) {
6605 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html
($owner) . "</td></tr>\n";
6607 if (defined $cd{'rfc2822'}) {
6608 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6609 "<td>".format_timestamp_html
(\
%cd)."</td></tr>\n";
6612 # use per project git URL list in $projectroot/$project/cloneurl
6613 # or make project git URL from git base URL and project name
6614 my $url_tag = "URL";
6615 my @url_list = git_get_project_url_list
($project);
6616 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6617 foreach my $git_url (@url_list) {
6618 next unless $git_url;
6619 print format_repo_url
($url_tag, $git_url);
6624 my $show_ctags = gitweb_check_feature
('ctags');
6626 my $ctags = git_get_project_ctags
($project);
6628 # without ability to add tags, don't show if there are none
6629 my $cloud = git_populate_project_tagcloud
($ctags);
6630 print "<tr id=\"metadata_ctags\">" .
6631 "<td>content tags</td>" .
6632 "<td>".git_show_project_tagcloud
($cloud, 48)."</td>" .
6639 # If XSS prevention is on, we don't include README.html.
6640 # TODO: Allow a readme in some safe format.
6641 if (!$prevent_xss && -s
"$projectroot/$project/README.html") {
6642 print "<div class=\"title\">readme</div>\n" .
6643 "<div class=\"readme\">\n";
6644 insert_file
("$projectroot/$project/README.html");
6645 print "\n</div>\n"; # class="readme"
6648 # we need to request one more than 16 (0..15) to check if
6650 my @commitlist = $head ? parse_commits
($head, 17) : ();
6652 git_print_header_div
('shortlog');
6653 git_shortlog_body
(\
@commitlist, 0, 15, $refs,
6654 $#commitlist <= 15 ? undef :
6655 $cgi->a({-href
=> href
(action
=>"shortlog")}, "..."));
6659 git_print_header_div
('tags');
6660 git_tags_body
(\
@taglist, 0, 15,
6661 $#taglist <= 15 ? undef :
6662 $cgi->a({-href
=> href
(action
=>"tags")}, "..."));
6666 git_print_header_div
('heads');
6667 git_heads_body
(\
@headlist, $head, 0, 15,
6668 $#headlist <= 15 ? undef :
6669 $cgi->a({-href
=> href
(action
=>"heads")}, "..."));
6673 git_print_header_div
('remotes');
6674 git_remotes_body
(\
%remotedata, 15, $head);
6678 git_print_header_div
('forks');
6679 git_project_list_body
(\
@forklist, 'age', 0, 15,
6680 $#forklist <= 15 ? undef :
6681 $cgi->a({-href
=> href
(action
=>"forks")}, "..."),
6689 my %tag = parse_tag
($hash);
6692 die_error
(404, "Unknown tag object");
6695 my $head = git_get_head_hash
($project);
6697 git_print_page_nav
('','', $head,undef,$head);
6698 git_print_header_div
('commit', esc_html
($tag{'name'}), $hash);
6699 print "<div class=\"title_text\">\n" .
6700 "<table class=\"object_header\">\n" .
6702 "<td>object</td>\n" .
6703 "<td>" . $cgi->a({-class => "list", -href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6704 $tag{'object'}) . "</td>\n" .
6705 "<td class=\"link\">" . $cgi->a({-href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6706 $tag{'type'}) . "</td>\n" .
6708 if (defined($tag{'author'})) {
6709 git_print_authorship_rows
(\
%tag, 'author');
6711 print "</table>\n\n" .
6713 print "<div class=\"page_body\">";
6714 my $comment = $tag{'comment'};
6715 foreach my $line (@$comment) {
6717 print esc_html
($line, -nbsp
=>1) . "<br/>\n";
6723 sub git_blame_common
{
6724 my $format = shift || 'porcelain';
6725 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6726 $format = 'incremental';
6727 $action = 'blame_incremental'; # for page title etc
6731 gitweb_check_feature
('blame')
6732 or die_error
(403, "Blame view not allowed");
6735 die_error
(400, "No file name given") unless $file_name;
6736 $hash_base ||= git_get_head_hash
($project);
6737 die_error
(404, "Couldn't find base commit") unless $hash_base;
6738 my %co = parse_commit
($hash_base)
6739 or die_error
(404, "Commit not found");
6741 if (!defined $hash) {
6742 $hash = git_get_hash_by_path
($hash_base, $file_name, "blob")
6743 or die_error
(404, "Error looking up file");
6745 $ftype = git_get_type
($hash);
6746 if ($ftype !~ "blob") {
6747 die_error
(400, "Object is not a blob");
6752 if ($format eq 'incremental') {
6753 # get file contents (as base)
6754 open $fd, "-|", git_cmd
(), 'cat-file', 'blob', $hash
6755 or die_error
(500, "Open git-cat-file failed");
6756 } elsif ($format eq 'data') {
6757 # run git-blame --incremental
6758 open $fd, "-|", git_cmd
(), "blame", "--incremental",
6759 $hash_base, "--", $file_name
6760 or die_error
(500, "Open git-blame --incremental failed");
6762 # run git-blame --porcelain
6763 open $fd, "-|", git_cmd
(), "blame", '-p',
6764 $hash_base, '--', $file_name
6765 or die_error
(500, "Open git-blame --porcelain failed");
6767 binmode $fd, ':utf8';
6769 # incremental blame data returns early
6770 if ($format eq 'data') {
6772 -type
=>"text/plain", -charset
=> "utf-8",
6773 -status
=> "200 OK");
6774 local $| = 1; # output autoflush
6775 while (my $line = <$fd>) {
6776 print to_utf8
($line);
6779 or print "ERROR $!\n";
6782 if (defined $t0 && gitweb_check_feature
('timed')) {
6784 tv_interval
($t0, [ gettimeofday
() ]).
6785 ' '.$number_of_git_cmds;
6795 $cgi->a({-href
=> href
(action
=>"blob", -replay
=>1)},
6798 if ($format eq 'incremental') {
6800 $cgi->a({-href
=> href
(action
=>"blame", javascript
=>0, -replay
=>1)},
6801 "blame") . " (non-incremental)";
6804 $cgi->a({-href
=> href
(action
=>"blame_incremental", -replay
=>1)},
6805 "blame") . " (incremental)";
6809 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
6812 $cgi->a({-href
=> href
(action
=>$action, file_name
=>$file_name)},
6814 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6815 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
6816 git_print_page_path
($file_name, $ftype, $hash_base);
6819 if ($format eq 'incremental') {
6820 print "<noscript>\n<div class=\"error\"><center><b>\n".
6821 "This page requires JavaScript to run.\n Use ".
6822 $cgi->a({-href
=> href
(action
=>'blame',javascript
=>0,-replay
=>1)},
6825 "</b></center></div>\n</noscript>\n";
6827 print qq
!<div id
="progress_bar" style
="width: 100%; background-color: yellow"></div
>\n!;
6830 print qq
!<div
class="page_body">\n!;
6831 print qq
!<div id
="progress_info">... / ...</div
>\n!
6832 if ($format eq 'incremental');
6833 print qq
!<table id
="blame_table" class="blame" width
="100%">\n!.
6834 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6836 qq
!<tr
><th
>Commit
</th><th>Line</th
><th
>Data
</th></tr
>\n!.
6840 my @rev_color = qw(light dark);
6841 my $num_colors = scalar(@rev_color);
6842 my $current_color = 0;
6844 if ($format eq 'incremental') {
6845 my $color_class = $rev_color[$current_color];
6850 while (my $line = <$fd>) {
6854 print qq
!<tr id
="l$linenr" class="$color_class">!.
6855 qq
!<td
class="sha1"><a href
=""> </a></td
>!.
6856 qq
!<td
class="linenr">!.
6857 qq
!<a
class="linenr" href
="">$linenr</a></td
>!;
6858 print qq
!<td
class="pre">! . esc_html
($line) . "</td>\n";
6862 } else { # porcelain, i.e. ordinary blame
6863 my %metainfo = (); # saves information about commits
6867 while (my $line = <$fd>) {
6869 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6870 # no <lines in group> for subsequent lines in group of lines
6871 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6872 ($line =~ /^($oid_regex) (\d+) (\d+)(?: (\d+))?$/);
6873 if (!exists $metainfo{$full_rev}) {
6874 $metainfo{$full_rev} = { 'nprevious' => 0 };
6876 my $meta = $metainfo{$full_rev};
6878 while ($data = <$fd>) {
6880 last if ($data =~ s/^\t//); # contents of line
6881 if ($data =~ /^(\S+)(?: (.*))?$/) {
6882 $meta->{$1} = $2 unless exists $meta->{$1};
6884 if ($data =~ /^previous /) {
6885 $meta->{'nprevious'}++;
6888 my $short_rev = substr($full_rev, 0, 8);
6889 my $author = $meta->{'author'};
6891 parse_date
($meta->{'author-time'}, $meta->{'author-tz'});
6892 my $date = $date{'iso-tz'};
6894 $current_color = ($current_color + 1) % $num_colors;
6896 my $tr_class = $rev_color[$current_color];
6897 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6898 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6899 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6900 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6902 print "<td class=\"sha1\"";
6903 print " title=\"". esc_html
($author) . ", $date\"";
6904 print " rowspan=\"$group_size\"" if ($group_size > 1);
6906 print $cgi->a({-href
=> href
(action
=>"commit",
6908 file_name
=>$file_name)},
6909 esc_html
($short_rev));
6910 if ($group_size >= 2) {
6911 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6912 if (@author_initials) {
6914 esc_html
(join('', @author_initials));
6920 # 'previous' <sha1 of parent commit> <filename at commit>
6921 if (exists $meta->{'previous'} &&
6922 $meta->{'previous'} =~ /^($oid_regex) (.*)$/) {
6923 $meta->{'parent'} = $1;
6924 $meta->{'file_parent'} = unquote
($2);
6927 exists($meta->{'parent'}) ?
6928 $meta->{'parent'} : $full_rev;
6929 my $linenr_filename =
6930 exists($meta->{'file_parent'}) ?
6931 $meta->{'file_parent'} : unquote
($meta->{'filename'});
6932 my $blamed = href
(action
=> 'blame',
6933 file_name
=> $linenr_filename,
6934 hash_base
=> $linenr_commit);
6935 print "<td class=\"linenr\">";
6936 print $cgi->a({ -href
=> "$blamed#l$orig_lineno",
6937 -class => "linenr" },
6940 print "<td class=\"pre\">" . esc_html
($data) . "</td>\n";
6948 "</table>\n"; # class="blame"
6949 print "</div>\n"; # class="blame_body"
6951 or print "Reading blob failed\n";
6960 sub git_blame_incremental
{
6961 git_blame_common
('incremental');
6964 sub git_blame_data
{
6965 git_blame_common
('data');
6969 my $head = git_get_head_hash
($project);
6971 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('tags'));
6972 git_print_header_div
('summary', $project);
6974 my @tagslist = git_get_tags_list
();
6976 git_tags_body
(\
@tagslist);
6982 my $head = git_get_head_hash
($project);
6984 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('heads'));
6985 git_print_header_div
('summary', $project);
6987 my @headslist = git_get_heads_list
();
6989 git_heads_body
(\
@headslist, $head);
6994 # used both for single remote view and for list of all the remotes
6996 gitweb_check_feature
('remote_heads')
6997 or die_error
(403, "Remote heads view is disabled");
6999 my $head = git_get_head_hash
($project);
7000 my $remote = $input_params{'hash'};
7002 my $remotedata = git_get_remotes_list
($remote);
7003 die_error
(500, "Unable to get remote information") unless defined $remotedata;
7005 unless (%$remotedata) {
7006 die_error
(404, defined $remote ?
7007 "Remote $remote not found" :
7008 "No remotes found");
7011 git_header_html
(undef, undef, -action_extra
=> $remote);
7012 git_print_page_nav
('', '', $head, undef, $head,
7013 format_ref_views
($remote ? '' : 'remotes'));
7015 fill_remote_heads
($remotedata);
7016 if (defined $remote) {
7017 git_print_header_div
('remotes', "$remote remote for $project");
7018 git_remote_block
($remote, $remotedata->{$remote}, undef, $head);
7020 git_print_header_div
('summary', "$project remotes");
7021 git_remotes_body
($remotedata, undef, $head);
7027 sub git_blob_plain
{
7031 if (!defined $hash) {
7032 if (defined $file_name) {
7033 my $base = $hash_base || git_get_head_hash
($project);
7034 $hash = git_get_hash_by_path
($base, $file_name, "blob")
7035 or die_error
(404, "Cannot find file");
7037 die_error
(400, "No file name defined");
7039 } elsif ($hash =~ m/^$oid_regex$/) {
7040 # blobs defined by non-textual hash id's can be cached
7044 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
7045 or die_error
(500, "Open git-cat-file blob '$hash' failed");
7047 # content-type (can include charset)
7048 $type = blob_contenttype
($fd, $file_name, $type);
7050 # "save as" filename, even when no $file_name is given
7051 my $save_as = "$hash";
7052 if (defined $file_name) {
7053 $save_as = $file_name;
7054 } elsif ($type =~ m/^text\//) {
7058 # With XSS prevention on, blobs of all types except a few known safe
7059 # ones are served with "Content-Disposition: attachment" to make sure
7060 # they don't run in our security domain. For certain image types,
7061 # blob view writes an <img> tag referring to blob_plain view, and we
7062 # want to be sure not to break that by serving the image as an
7063 # attachment (though Firefox 3 doesn't seem to care).
7064 my $sandbox = $prevent_xss &&
7065 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7067 # serve text/* as text/plain
7069 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7070 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T
$fd))) {
7072 $rest = defined $rest ? $rest : '';
7073 $type = "text/plain$rest";
7078 -expires
=> $expires,
7079 -content_disposition
=>
7080 ($sandbox ? 'attachment' : 'inline')
7081 . '; filename="' . $save_as . '"');
7083 binmode STDOUT
, ':raw';
7085 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7092 if (!defined $hash) {
7093 if (defined $file_name) {
7094 my $base = $hash_base || git_get_head_hash
($project);
7095 $hash = git_get_hash_by_path
($base, $file_name, "blob")
7096 or die_error
(404, "Cannot find file");
7098 die_error
(400, "No file name defined");
7100 } elsif ($hash =~ m/^$oid_regex$/) {
7101 # blobs defined by non-textual hash id's can be cached
7105 my $have_blame = gitweb_check_feature
('blame');
7106 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
7107 or die_error
(500, "Couldn't cat $file_name, $hash");
7108 my $mimetype = blob_mimetype
($fd, $file_name);
7109 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7110 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B
$fd) {
7112 return git_blob_plain
($mimetype);
7114 # we can have blame only for text/* mimetype
7115 $have_blame &&= ($mimetype =~ m!^text/!);
7117 my $highlight = gitweb_check_feature
('highlight');
7118 my $syntax = guess_file_syntax
($highlight, $file_name);
7119 $fd = run_highlighter
($fd, $highlight, $syntax);
7121 git_header_html
(undef, $expires);
7122 my $formats_nav = '';
7123 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7124 if (defined $file_name) {
7127 $cgi->a({-href
=> href
(action
=>"blame", -replay
=>1)},
7132 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7135 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7138 $cgi->a({-href
=> href
(action
=>"blob",
7139 hash_base
=>"HEAD", file_name
=>$file_name)},
7143 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7146 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7147 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7149 print "<div class=\"page_nav\">\n" .
7150 "<br/><br/></div>\n" .
7151 "<div class=\"title\">".esc_html
($hash)."</div>\n";
7153 git_print_page_path
($file_name, "blob", $hash_base);
7154 print "<div class=\"page_body\">\n";
7155 if ($mimetype =~ m!^image/!) {
7156 print qq
!<img
class="blob" type
="!.esc_attr($mimetype).qq!"!;
7158 print qq
! alt
="!.esc_attr($file_name).qq!" title
="!.esc_attr($file_name).qq!"!;
7161 esc_attr(href(action=>"blob_plain
", hash=>$hash,
7162 hash_base=>$hash_base, file_name=>$file_name)) .
7166 while (my $line = <$fd>) {
7169 $line = untabify
($line);
7170 printf qq
!<div
class="pre"><a id
="l%i" href
="%s#l%i" class="linenr">%4i</a> %s</div
>\n!,
7171 $nr, esc_attr
(href
(-replay
=> 1)), $nr, $nr,
7172 $highlight ? sanitize
($line) : esc_html
($line, -nbsp
=>1);
7176 or print "Reading blob failed.\n";
7182 if (!defined $hash_base) {
7183 $hash_base = "HEAD";
7185 if (!defined $hash) {
7186 if (defined $file_name) {
7187 $hash = git_get_hash_by_path
($hash_base, $file_name, "tree");
7192 die_error
(404, "No such tree") unless defined($hash);
7194 my $show_sizes = gitweb_check_feature
('show-sizes');
7195 my $have_blame = gitweb_check_feature
('blame');
7200 open my $fd, "-|", git_cmd
(), "ls-tree", '-z',
7201 ($show_sizes ? '-l' : ()), @extra_options, $hash
7202 or die_error
(500, "Open git-ls-tree failed");
7203 @entries = map { chomp; $_ } <$fd>;
7205 or die_error
(404, "Reading tree failed");
7208 my $refs = git_get_references
();
7209 my $ref = format_ref_marker
($refs, $hash_base);
7212 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7214 if (defined $file_name) {
7216 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7218 $cgi->a({-href
=> href
(action
=>"tree",
7219 hash_base
=>"HEAD", file_name
=>$file_name)},
7222 my $snapshot_links = format_snapshot_links
($hash);
7223 if (defined $snapshot_links) {
7224 # FIXME: Should be available when we have no hash base as well.
7225 push @views_nav, $snapshot_links;
7227 git_print_page_nav
('tree','', $hash_base, undef, undef,
7228 join(' | ', @views_nav));
7229 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash_base);
7232 print "<div class=\"page_nav\">\n";
7233 print "<br/><br/></div>\n";
7234 print "<div class=\"title\">".esc_html
($hash)."</div>\n";
7236 if (defined $file_name) {
7237 $basedir = $file_name;
7238 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7241 git_print_page_path
($file_name, 'tree', $hash_base);
7243 print "<div class=\"page_body\">\n";
7244 print "<table class=\"tree\">\n";
7246 # '..' (top directory) link if possible
7247 if (defined $hash_base &&
7248 defined $file_name && $file_name =~ m![^/]+$!) {
7250 print "<tr class=\"dark\">\n";
7252 print "<tr class=\"light\">\n";
7256 my $up = $file_name;
7257 $up =~ s!/?[^/]+$!!;
7258 undef $up unless $up;
7259 # based on git_print_tree_entry
7260 print '<td class="mode">' . mode_str
('040000') . "</td>\n";
7261 print '<td class="size"> </td>'."\n" if $show_sizes;
7262 print '<td class="list">';
7263 print $cgi->a({-href
=> href
(action
=>"tree",
7264 hash_base
=>$hash_base,
7268 print "<td class=\"link\"></td>\n";
7272 foreach my $line (@entries) {
7273 my %t = parse_ls_tree_line
($line, -z
=> 1, -l
=> $show_sizes);
7276 print "<tr class=\"dark\">\n";
7278 print "<tr class=\"light\">\n";
7282 git_print_tree_entry
(\
%t, $basedir, $hash_base, $have_blame);
7286 print "</table>\n" .
7291 sub sanitize_for_filename
{
7295 $name =~ s/[^[:alnum:]_.-]//g;
7301 my ($project, $hash) = @_;
7303 # path/to/project.git -> project
7304 # path/to/project/.git -> project
7305 my $name = to_utf8
($project);
7306 $name =~ s
,([^/])/*\
.git
$,$1,;
7307 $name = sanitize_for_filename
(basename
($name));
7310 if ($hash =~ /^[0-9a-fA-F]+$/) {
7311 # shorten SHA-1 hash
7312 my $full_hash = git_get_full_hash
($project, $hash);
7313 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7314 $ver = git_get_short_hash
($project, $hash);
7316 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7317 # tags don't need shortened SHA-1 hash
7320 # branches and other need shortened SHA-1 hash
7321 my $strip_refs = join '|', map { quotemeta } get_branch_refs
();
7322 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7323 my $ref_dir = (defined $1) ? $1 : '';
7326 $ref_dir = sanitize_for_filename
($ref_dir);
7327 # for refs neither in heads nor remotes we want to
7328 # add a ref dir to archive name
7329 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7330 $ver = $ref_dir . '-' . $ver;
7333 $ver .= '-' . git_get_short_hash
($project, $hash);
7335 # special case of sanitization for filename - we change
7336 # slashes to dots instead of dashes
7337 # in case of hierarchical branch names
7339 $ver =~ s/[^[:alnum:]_.-]//g;
7341 # name = project-version_string
7342 $name = "$name-$ver";
7344 return wantarray ? ($name, $name) : $name;
7347 sub exit_if_unmodified_since
{
7348 my ($latest_epoch) = @_;
7351 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7352 if (defined $if_modified) {
7354 if (eval { require HTTP
::Date
; 1; }) {
7355 $since = HTTP
::Date
::str2time
($if_modified);
7356 } elsif (eval { require Time
::ParseDate
; 1; }) {
7357 $since = Time
::ParseDate
::parsedate
($if_modified, GMT
=> 1);
7359 if (defined $since && $latest_epoch <= $since) {
7360 my %latest_date = parse_date
($latest_epoch);
7362 -last_modified
=> $latest_date{'rfc2822'},
7363 -status
=> '304 Not Modified');
7370 my $format = $input_params{'snapshot_format'};
7371 if (!@snapshot_fmts) {
7372 die_error
(403, "Snapshots not allowed");
7374 # default to first supported snapshot format
7375 $format ||= $snapshot_fmts[0];
7376 if ($format !~ m/^[a-z0-9]+$/) {
7377 die_error
(400, "Invalid snapshot format parameter");
7378 } elsif (!exists($known_snapshot_formats{$format})) {
7379 die_error
(400, "Unknown snapshot format");
7380 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7381 die_error
(403, "Snapshot format not allowed");
7382 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7383 die_error
(403, "Unsupported snapshot format");
7386 my $type = git_get_type
("$hash^{}");
7388 die_error
(404, 'Object does not exist');
7389 } elsif ($type eq 'blob') {
7390 die_error
(400, 'Object is not a tree-ish');
7393 my ($name, $prefix) = snapshot_name
($project, $hash);
7394 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7396 my %co = parse_commit
($hash);
7397 exit_if_unmodified_since
($co{'committer_epoch'}) if %co;
7399 my $cmd = quote_command
(
7400 git_cmd
(), 'archive',
7401 "--format=$known_snapshot_formats{$format}{'format'}",
7402 "--prefix=$prefix/", $hash);
7403 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7404 $cmd .= ' | ' . quote_command
(@{$known_snapshot_formats{$format}{'compressor'}});
7407 $filename =~ s/(["\\])/\\$1/g;
7410 %latest_date = parse_date
($co{'committer_epoch'}, $co{'committer_tz'});
7414 -type
=> $known_snapshot_formats{$format}{'type'},
7415 -content_disposition
=> 'inline; filename="' . $filename . '"',
7416 %co ? (-last_modified
=> $latest_date{'rfc2822'}) : (),
7417 -status
=> '200 OK');
7419 open my $fd, "-|", $cmd
7420 or die_error
(500, "Execute git-archive failed");
7421 binmode STDOUT
, ':raw';
7423 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7427 sub git_log_generic
{
7428 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7430 my $head = git_get_head_hash
($project);
7431 if (!defined $base) {
7434 if (!defined $page) {
7437 my $refs = git_get_references
();
7439 my $commit_hash = $base;
7440 if (defined $parent) {
7441 $commit_hash = "$parent..$base";
7444 parse_commits
($commit_hash, 101, (100 * $page),
7445 defined $file_name ? ($file_name, "--full-history") : ());
7448 if (!defined $file_hash && defined $file_name) {
7449 # some commits could have deleted file in question,
7450 # and not have it in tree, but one of them has to have it
7451 for (my $i = 0; $i < @commitlist; $i++) {
7452 $file_hash = git_get_hash_by_path
($commitlist[$i]{'id'}, $file_name);
7453 last if defined $file_hash;
7456 if (defined $file_hash) {
7457 $ftype = git_get_type
($file_hash);
7459 if (defined $file_name && !defined $ftype) {
7460 die_error
(500, "Unknown type of object");
7463 if (defined $file_name) {
7464 %co = parse_commit
($base)
7465 or die_error
(404, "Unknown commit object");
7469 my $paging_nav = format_paging_nav
($fmt_name, $page, $#commitlist >= 100);
7471 if ($#commitlist >= 100) {
7473 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
7474 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
7476 my $patch_max = gitweb_get_feature
('patches');
7477 if ($patch_max && !defined $file_name) {
7478 if ($patch_max < 0 || @commitlist <= $patch_max) {
7479 $paging_nav .= " ⋅ " .
7480 $cgi->a({-href
=> href
(action
=>"patches", -replay
=>1)},
7486 git_print_page_nav
($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7487 if (defined $file_name) {
7488 git_print_header_div
('commit', esc_html
($co{'title'}), $base);
7490 git_print_header_div
('summary', $project)
7492 git_print_page_path
($file_name, $ftype, $hash_base)
7493 if (defined $file_name);
7495 $body_subr->(\
@commitlist, 0, 99, $refs, $next_link,
7496 $file_name, $file_hash, $ftype);
7502 git_log_generic
('log', \
&git_log_body
,
7503 $hash, $hash_parent);
7507 $hash ||= $hash_base || "HEAD";
7508 my %co = parse_commit
($hash)
7509 or die_error
(404, "Unknown commit object");
7511 my $parent = $co{'parent'};
7512 my $parents = $co{'parents'}; # listref
7514 # we need to prepare $formats_nav before any parameter munging
7516 if (!defined $parent) {
7518 $formats_nav .= '(initial)';
7519 } elsif (@$parents == 1) {
7520 # single parent commit
7523 $cgi->a({-href
=> href
(action
=>"commit",
7525 esc_html
(substr($parent, 0, 7))) .
7532 $cgi->a({-href
=> href
(action
=>"commit",
7534 esc_html
(substr($_, 0, 7)));
7538 if (gitweb_check_feature
('patches') && @$parents <= 1) {
7539 $formats_nav .= " | " .
7540 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7544 if (!defined $parent) {
7548 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', "--no-commit-id",
7550 (@$parents <= 1 ? $parent : '-c'),
7552 or die_error
(500, "Open git-diff-tree failed");
7553 @difftree = map { chomp; $_ } <$fd>;
7554 close $fd or die_error
(404, "Reading git-diff-tree failed");
7556 # non-textual hash id's can be cached
7558 if ($hash =~ m/^$oid_regex$/) {
7561 my $refs = git_get_references
();
7562 my $ref = format_ref_marker
($refs, $co{'id'});
7564 git_header_html
(undef, $expires);
7565 git_print_page_nav
('commit', '',
7566 $hash, $co{'tree'}, $hash,
7569 if (defined $co{'parent'}) {
7570 git_print_header_div
('commitdiff', esc_html
($co{'title'}) . $ref, $hash);
7572 git_print_header_div
('tree', esc_html
($co{'title'}) . $ref, $co{'tree'}, $hash);
7574 print "<div class=\"title_text\">\n" .
7575 "<table class=\"object_header\">\n";
7576 git_print_authorship_rows
(\
%co);
7577 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7580 "<td class=\"sha1\">" .
7581 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash),
7582 class => "list"}, $co{'tree'}) .
7584 "<td class=\"link\">" .
7585 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash)},
7587 my $snapshot_links = format_snapshot_links
($hash);
7588 if (defined $snapshot_links) {
7589 print " | " . $snapshot_links;
7594 foreach my $par (@$parents) {
7597 "<td class=\"sha1\">" .
7598 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par),
7599 class => "list"}, $par) .
7601 "<td class=\"link\">" .
7602 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par)}, "commit") .
7604 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$hash, hash_parent
=>$par)}, "diff") .
7611 print "<div class=\"page_body\">\n";
7612 git_print_log
($co{'comment'});
7615 git_difftree_body
(\
@difftree, $hash, @$parents);
7621 # object is defined by:
7622 # - hash or hash_base alone
7623 # - hash_base and file_name
7626 # - hash or hash_base alone
7627 if ($hash || ($hash_base && !defined $file_name)) {
7628 my $object_id = $hash || $hash_base;
7630 open my $fd, "-|", quote_command
(
7631 git_cmd
(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7632 or die_error
(404, "Object does not exist");
7634 defined $type && chomp $type;
7636 or die_error
(404, "Object does not exist");
7638 # - hash_base and file_name
7639 } elsif ($hash_base && defined $file_name) {
7640 $file_name =~ s
,/+$,,;
7642 system(git_cmd
(), "cat-file", '-e', $hash_base) == 0
7643 or die_error
(404, "Base object does not exist");
7645 # here errors should not happen
7646 open my $fd, "-|", git_cmd
(), "ls-tree", $hash_base, "--", $file_name
7647 or die_error
(500, "Open git-ls-tree failed");
7651 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7652 unless ($line && $line =~ m/^([0-9]+) (.+) ($oid_regex)\t/) {
7653 die_error
(404, "File or directory for given base does not exist");
7658 die_error
(400, "Not enough information to find object");
7661 print $cgi->redirect(-uri
=> href
(action
=>$type, -full
=>1,
7662 hash
=>$hash, hash_base
=>$hash_base,
7663 file_name
=>$file_name),
7664 -status
=> '302 Found');
7668 my $format = shift || 'html';
7669 my $diff_style = $input_params{'diff_style'} || 'inline';
7676 # preparing $fd and %diffinfo for git_patchset_body
7678 if (defined $hash_base && defined $hash_parent_base) {
7679 if (defined $file_name) {
7681 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7682 $hash_parent_base, $hash_base,
7683 "--", (defined $file_parent ? $file_parent : ()), $file_name
7684 or die_error
(500, "Open git-diff-tree failed");
7685 @difftree = map { chomp; $_ } <$fd>;
7687 or die_error
(404, "Reading git-diff-tree failed");
7689 or die_error
(404, "Blob diff not found");
7691 } elsif (defined $hash &&
7692 $hash =~ $oid_regex) {
7693 # try to find filename from $hash
7695 # read filtered raw output
7696 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7697 $hash_parent_base, $hash_base, "--"
7698 or die_error
(500, "Open git-diff-tree failed");
7700 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7702 grep { /^:[0-7]{6} [0-7]{6} $oid_regex $hash/ }
7703 map { chomp; $_ } <$fd>;
7705 or die_error
(404, "Reading git-diff-tree failed");
7707 or die_error
(404, "Blob diff not found");
7710 die_error
(400, "Missing one of the blob diff parameters");
7713 if (@difftree > 1) {
7714 die_error
(400, "Ambiguous blob diff specification");
7717 %diffinfo = parse_difftree_raw_line
($difftree[0]);
7718 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7719 $file_name ||= $diffinfo{'to_file'};
7721 $hash_parent ||= $diffinfo{'from_id'};
7722 $hash ||= $diffinfo{'to_id'};
7724 # non-textual hash id's can be cached
7725 if ($hash_base =~ m/^$oid_regex$/ &&
7726 $hash_parent_base =~ m/^$oid_regex$/) {
7731 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7732 '-p', ($format eq 'html' ? "--full-index" : ()),
7733 $hash_parent_base, $hash_base,
7734 "--", (defined $file_parent ? $file_parent : ()), $file_name
7735 or die_error
(500, "Open git-diff-tree failed");
7738 # old/legacy style URI -- not generated anymore since 1.4.3.
7740 die_error
('404 Not Found', "Missing one of the blob diff parameters")
7744 if ($format eq 'html') {
7746 $cgi->a({-href
=> href
(action
=>"blobdiff_plain", -replay
=>1)},
7748 $formats_nav .= diff_style_nav
($diff_style);
7749 git_header_html
(undef, $expires);
7750 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7751 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7752 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7754 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7755 print "<div class=\"title\">".esc_html
("$hash vs $hash_parent")."</div>\n";
7757 if (defined $file_name) {
7758 git_print_page_path
($file_name, "blob", $hash_base);
7760 print "<div class=\"page_path\"></div>\n";
7763 } elsif ($format eq 'plain') {
7765 -type
=> 'text/plain',
7766 -charset
=> 'utf-8',
7767 -expires
=> $expires,
7768 -content_disposition
=> 'inline; filename="' . "$file_name" . '.patch"');
7770 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7773 die_error
(400, "Unknown blobdiff format");
7777 if ($format eq 'html') {
7778 print "<div class=\"page_body\">\n";
7780 git_patchset_body
($fd, $diff_style,
7781 [ \
%diffinfo ], $hash_base, $hash_parent_base);
7784 print "</div>\n"; # class="page_body"
7788 while (my $line = <$fd>) {
7789 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7790 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7794 last if $line =~ m!^\+\+\+!;
7802 sub git_blobdiff_plain
{
7803 git_blobdiff
('plain');
7806 # assumes that it is added as later part of already existing navigation,
7807 # so it returns "| foo | bar" rather than just "foo | bar"
7808 sub diff_style_nav
{
7809 my ($diff_style, $is_combined) = @_;
7810 $diff_style ||= 'inline';
7812 return "" if ($is_combined);
7814 my @styles = (inline
=> 'inline', 'sidebyside' => 'side by side');
7815 my %styles = @styles;
7817 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7822 $_ eq $diff_style ? $styles{$_} :
7823 $cgi->a({-href
=> href
(-replay
=>1, diff_style
=> $_)}, $styles{$_})
7827 sub git_commitdiff
{
7829 my $format = $params{-format
} || 'html';
7830 my $diff_style = $input_params{'diff_style'} || 'inline';
7832 my ($patch_max) = gitweb_get_feature
('patches');
7833 if ($format eq 'patch') {
7834 die_error
(403, "Patch view not allowed") unless $patch_max;
7837 $hash ||= $hash_base || "HEAD";
7838 my %co = parse_commit
($hash)
7839 or die_error
(404, "Unknown commit object");
7841 # choose format for commitdiff for merge
7842 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7843 $hash_parent = '--cc';
7845 # we need to prepare $formats_nav before almost any parameter munging
7847 if ($format eq 'html') {
7849 $cgi->a({-href
=> href
(action
=>"commitdiff_plain", -replay
=>1)},
7851 if ($patch_max && @{$co{'parents'}} <= 1) {
7852 $formats_nav .= " | " .
7853 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7856 $formats_nav .= diff_style_nav
($diff_style, @{$co{'parents'}} > 1);
7858 if (defined $hash_parent &&
7859 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7860 # commitdiff with two commits given
7861 my $hash_parent_short = $hash_parent;
7862 if ($hash_parent =~ m/^$oid_regex$/) {
7863 $hash_parent_short = substr($hash_parent, 0, 7);
7867 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7868 if ($co{'parents'}[$i] eq $hash_parent) {
7869 $formats_nav .= ' parent ' . ($i+1);
7873 $formats_nav .= ': ' .
7874 $cgi->a({-href
=> href
(-replay
=>1,
7875 hash
=>$hash_parent, hash_base
=>undef)},
7876 esc_html
($hash_parent_short)) .
7878 } elsif (!$co{'parent'}) {
7880 $formats_nav .= ' (initial)';
7881 } elsif (scalar @{$co{'parents'}} == 1) {
7882 # single parent commit
7885 $cgi->a({-href
=> href
(-replay
=>1,
7886 hash
=>$co{'parent'}, hash_base
=>undef)},
7887 esc_html
(substr($co{'parent'}, 0, 7))) .
7891 if ($hash_parent eq '--cc') {
7892 $formats_nav .= ' | ' .
7893 $cgi->a({-href
=> href
(-replay
=>1,
7894 hash
=>$hash, hash_parent
=>'-c')},
7896 } else { # $hash_parent eq '-c'
7897 $formats_nav .= ' | ' .
7898 $cgi->a({-href
=> href
(-replay
=>1,
7899 hash
=>$hash, hash_parent
=>'--cc')},
7905 $cgi->a({-href
=> href
(-replay
=>1,
7906 hash
=>$_, hash_base
=>undef)},
7907 esc_html
(substr($_, 0, 7)));
7908 } @{$co{'parents'}} ) .
7913 my $hash_parent_param = $hash_parent;
7914 if (!defined $hash_parent_param) {
7915 # --cc for multiple parents, --root for parentless
7916 $hash_parent_param =
7917 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7923 if ($format eq 'html') {
7924 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7925 "--no-commit-id", "--patch-with-raw", "--full-index",
7926 $hash_parent_param, $hash, "--"
7927 or die_error
(500, "Open git-diff-tree failed");
7929 while (my $line = <$fd>) {
7931 # empty line ends raw part of diff-tree output
7933 push @difftree, scalar parse_difftree_raw_line
($line);
7936 } elsif ($format eq 'plain') {
7937 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7938 '-p', $hash_parent_param, $hash, "--"
7939 or die_error
(500, "Open git-diff-tree failed");
7940 } elsif ($format eq 'patch') {
7941 # For commit ranges, we limit the output to the number of
7942 # patches specified in the 'patches' feature.
7943 # For single commits, we limit the output to a single patch,
7944 # diverging from the git-format-patch default.
7945 my @commit_spec = ();
7947 if ($patch_max > 0) {
7948 push @commit_spec, "-$patch_max";
7950 push @commit_spec, '-n', "$hash_parent..$hash";
7952 if ($params{-single
}) {
7953 push @commit_spec, '-1';
7955 if ($patch_max > 0) {
7956 push @commit_spec, "-$patch_max";
7958 push @commit_spec, "-n";
7960 push @commit_spec, '--root', $hash;
7962 open $fd, "-|", git_cmd
(), "format-patch", @diff_opts,
7963 '--encoding=utf8', '--stdout', @commit_spec
7964 or die_error
(500, "Open git-format-patch failed");
7966 die_error
(400, "Unknown commitdiff format");
7969 # non-textual hash id's can be cached
7971 if ($hash =~ m/^$oid_regex$/) {
7975 # write commit message
7976 if ($format eq 'html') {
7977 my $refs = git_get_references
();
7978 my $ref = format_ref_marker
($refs, $co{'id'});
7980 git_header_html
(undef, $expires);
7981 git_print_page_nav
('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7982 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash);
7983 print "<div class=\"title_text\">\n" .
7984 "<table class=\"object_header\">\n";
7985 git_print_authorship_rows
(\
%co);
7988 print "<div class=\"page_body\">\n";
7989 if (@{$co{'comment'}} > 1) {
7990 print "<div class=\"log\">\n";
7991 git_print_log
($co{'comment'}, -final_empty_line
=> 1, -remove_title
=> 1);
7992 print "</div>\n"; # class="log"
7995 } elsif ($format eq 'plain') {
7996 my $refs = git_get_references
("tags");
7997 my $tagname = git_get_rev_name_tags
($hash);
7998 my $filename = basename
($project) . "-$hash.patch";
8001 -type
=> 'text/plain',
8002 -charset
=> 'utf-8',
8003 -expires
=> $expires,
8004 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
8005 my %ad = parse_date
($co{'author_epoch'}, $co{'author_tz'});
8006 print "From: " . to_utf8
($co{'author'}) . "\n";
8007 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8008 print "Subject: " . to_utf8
($co{'title'}) . "\n";
8010 print "X-Git-Tag: $tagname\n" if $tagname;
8011 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8013 foreach my $line (@{$co{'comment'}}) {
8014 print to_utf8
($line) . "\n";
8017 } elsif ($format eq 'patch') {
8018 my $filename = basename
($project) . "-$hash.patch";
8021 -type
=> 'text/plain',
8022 -charset
=> 'utf-8',
8023 -expires
=> $expires,
8024 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
8028 if ($format eq 'html') {
8029 my $use_parents = !defined $hash_parent ||
8030 $hash_parent eq '-c' || $hash_parent eq '--cc';
8031 git_difftree_body
(\
@difftree, $hash,
8032 $use_parents ? @{$co{'parents'}} : $hash_parent);
8035 git_patchset_body
($fd, $diff_style,
8037 $use_parents ? @{$co{'parents'}} : $hash_parent);
8039 print "</div>\n"; # class="page_body"
8042 } elsif ($format eq 'plain') {
8046 or print "Reading git-diff-tree failed\n";
8047 } elsif ($format eq 'patch') {
8051 or print "Reading git-format-patch failed\n";
8055 sub git_commitdiff_plain
{
8056 git_commitdiff
(-format
=> 'plain');
8059 # format-patch-style patches
8061 git_commitdiff
(-format
=> 'patch', -single
=> 1);
8065 git_commitdiff
(-format
=> 'patch');
8069 git_log_generic
('history', \
&git_history_body
,
8070 $hash_base, $hash_parent_base,
8075 $searchtype ||= 'commit';
8077 # check if appropriate features are enabled
8078 gitweb_check_feature
('search')
8079 or die_error
(403, "Search is disabled");
8080 if ($searchtype eq 'pickaxe') {
8081 # pickaxe may take all resources of your box and run for several minutes
8082 # with every query - so decide by yourself how public you make this feature
8083 gitweb_check_feature
('pickaxe')
8084 or die_error
(403, "Pickaxe search is disabled");
8086 if ($searchtype eq 'grep') {
8087 # grep search might be potentially CPU-intensive, too
8088 gitweb_check_feature
('grep')
8089 or die_error
(403, "Grep search is disabled");
8092 if (!defined $searchtext) {
8093 die_error
(400, "Text field is empty");
8095 if (!defined $hash) {
8096 $hash = git_get_head_hash
($project);
8098 my %co = parse_commit
($hash);
8100 die_error
(404, "Unknown commit object");
8102 if (!defined $page) {
8106 if ($searchtype eq 'commit' ||
8107 $searchtype eq 'author' ||
8108 $searchtype eq 'committer') {
8109 git_search_message
(%co);
8110 } elsif ($searchtype eq 'pickaxe') {
8111 git_search_changes
(%co);
8112 } elsif ($searchtype eq 'grep') {
8113 git_search_files
(%co);
8115 die_error
(400, "Unknown search type");
8119 sub git_search_help
{
8121 git_print_page_nav
('','', $hash,$hash,$hash);
8123 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8124 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8125 the pattern entered is recognized as the POSIX extended
8126 <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8129 <dt><b>commit</b></dt>
8130 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8132 my $have_grep = gitweb_check_feature
('grep');
8135 <dt><b>grep</b></dt>
8136 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8137 a different one) are searched for the given pattern. On large trees, this search can take
8138 a while and put some strain on the server, so please use it with some consideration. Note that
8139 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8140 case-sensitive.</dd>
8144 <dt><b>author</b></dt>
8145 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8146 <dt><b>committer</b></dt>
8147 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8149 my $have_pickaxe = gitweb_check_feature
('pickaxe');
8150 if ($have_pickaxe) {
8152 <dt><b>pickaxe</b></dt>
8153 <dd>All commits that caused the string to appear or disappear from any file (changes that
8154 added, removed or "modified" the string) will be listed. This search can take a while and
8155 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8156 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8164 git_log_generic
('shortlog', \
&git_shortlog_body
,
8165 $hash, $hash_parent);
8168 ## ......................................................................
8169 ## feeds (RSS, Atom; OPML)
8172 my $format = shift || 'atom';
8173 my $have_blame = gitweb_check_feature
('blame');
8175 # Atom: http://www.atomenabled.org/developers/syndication/
8176 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8177 if ($format ne 'rss' && $format ne 'atom') {
8178 die_error
(400, "Unknown web feed format");
8181 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8182 my $head = $hash || 'HEAD';
8183 my @commitlist = parse_commits
($head, 150, 0, $file_name);
8187 my $content_type = "application/$format+xml";
8188 if (defined $cgi->http('HTTP_ACCEPT') &&
8189 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8190 # browser (feed reader) prefers text/xml
8191 $content_type = 'text/xml';
8193 if (defined($commitlist[0])) {
8194 %latest_commit = %{$commitlist[0]};
8195 my $latest_epoch = $latest_commit{'committer_epoch'};
8196 exit_if_unmodified_since
($latest_epoch);
8197 %latest_date = parse_date
($latest_epoch, $latest_commit{'committer_tz'});
8200 -type
=> $content_type,
8201 -charset
=> 'utf-8',
8202 %latest_date ? (-last_modified
=> $latest_date{'rfc2822'}) : (),
8203 -status
=> '200 OK');
8205 # Optimization: skip generating the body if client asks only
8206 # for Last-Modified date.
8207 return if ($cgi->request_method() eq 'HEAD');
8210 my $title = "$site_name - $project/$action";
8211 my $feed_type = 'log';
8212 if (defined $hash) {
8213 $title .= " - '$hash'";
8214 $feed_type = 'branch log';
8215 if (defined $file_name) {
8216 $title .= " :: $file_name";
8217 $feed_type = 'history';
8219 } elsif (defined $file_name) {
8220 $title .= " - $file_name";
8221 $feed_type = 'history';
8223 $title .= " $feed_type";
8224 $title = esc_html
($title);
8225 my $descr = git_get_project_description
($project);
8226 if (defined $descr) {
8227 $descr = esc_html
($descr);
8229 $descr = "$project " .
8230 ($format eq 'rss' ? 'RSS' : 'Atom') .
8233 my $owner = git_get_project_owner
($project);
8234 $owner = esc_html
($owner);
8238 if (defined $file_name) {
8239 $alt_url = href
(-full
=>1, action
=>"history", hash
=>$hash, file_name
=>$file_name);
8240 } elsif (defined $hash) {
8241 $alt_url = href
(-full
=>1, action
=>"log", hash
=>$hash);
8243 $alt_url = href
(-full
=>1, action
=>"summary");
8245 $alt_url = esc_attr
($alt_url);
8246 print qq
!<?xml version
="1.0" encoding
="utf-8"?>\n!;
8247 if ($format eq 'rss') {
8249 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8252 print "<title>$title</title>\n" .
8253 "<link>$alt_url</link>\n" .
8254 "<description>$descr</description>\n" .
8255 "<language>en</language>\n" .
8256 # project owner is responsible for 'editorial' content
8257 "<managingEditor>$owner</managingEditor>\n";
8258 if (defined $logo || defined $favicon) {
8259 # prefer the logo to the favicon, since RSS
8260 # doesn't allow both
8261 my $img = esc_url
($logo || $favicon);
8263 "<url>$img</url>\n" .
8264 "<title>$title</title>\n" .
8265 "<link>$alt_url</link>\n" .
8269 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8270 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8272 print "<generator>gitweb v.$version/$git_version</generator>\n";
8273 } elsif ($format eq 'atom') {
8275 <feed xmlns="http://www.w3.org/2005/Atom">
8277 print "<title>$title</title>\n" .
8278 "<subtitle>$descr</subtitle>\n" .
8279 '<link rel="alternate" type="text/html" href="' .
8280 $alt_url . '" />' . "\n" .
8281 '<link rel="self" type="' . $content_type . '" href="' .
8282 $cgi->self_url() . '" />' . "\n" .
8283 "<id>" . esc_url
(href
(-full
=>1)) . "</id>\n" .
8284 # use project owner for feed author
8285 "<author><name>$owner</name></author>\n";
8286 if (defined $favicon) {
8287 print "<icon>" . esc_url
($favicon) . "</icon>\n";
8289 if (defined $logo) {
8290 # not twice as wide as tall: 72 x 27 pixels
8291 print "<logo>" . esc_url
($logo) . "</logo>\n";
8293 if (! %latest_date) {
8294 # dummy date to keep the feed valid until commits trickle in:
8295 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8297 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8299 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8303 for (my $i = 0; $i <= $#commitlist; $i++) {
8304 my %co = %{$commitlist[$i]};
8305 my $commit = $co{'id'};
8306 # we read 150, we always show 30 and the ones more recent than 48 hours
8307 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8310 my %cd = parse_date
($co{'author_epoch'}, $co{'author_tz'});
8312 # get list of changed files
8313 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
8314 $co{'parent'} || "--root",
8315 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8317 my @difftree = map { chomp; $_ } <$fd>;
8321 # print element (entry, item)
8322 my $co_url = href
(-full
=>1, action
=>"commitdiff", hash
=>$commit);
8323 if ($format eq 'rss') {
8325 "<title>" . esc_html
($co{'title'}) . "</title>\n" .
8326 "<author>" . esc_html
($co{'author'}) . "</author>\n" .
8327 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8328 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8329 "<link>" . esc_html
($co_url) . "</link>\n" .
8330 "<description>" . esc_html
($co{'title'}) . "</description>\n" .
8331 "<content:encoded>" .
8333 } elsif ($format eq 'atom') {
8335 "<title type=\"html\">" . esc_html
($co{'title'}) . "</title>\n" .
8336 "<updated>$cd{'iso-8601'}</updated>\n" .
8338 " <name>" . esc_html
($co{'author_name'}) . "</name>\n";
8339 if ($co{'author_email'}) {
8340 print " <email>" . esc_html
($co{'author_email'}) . "</email>\n";
8342 print "</author>\n" .
8343 # use committer for contributor
8345 " <name>" . esc_html
($co{'committer_name'}) . "</name>\n";
8346 if ($co{'committer_email'}) {
8347 print " <email>" . esc_html
($co{'committer_email'}) . "</email>\n";
8349 print "</contributor>\n" .
8350 "<published>$cd{'iso-8601'}</published>\n" .
8351 "<link rel=\"alternate\" type=\"text/html\" href=\"" . esc_attr
($co_url) . "\" />\n" .
8352 "<id>" . esc_html
($co_url) . "</id>\n" .
8353 "<content type=\"xhtml\" xml:base=\"" . esc_url
($my_url) . "\">\n" .
8354 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8356 my $comment = $co{'comment'};
8358 foreach my $line (@$comment) {
8359 $line = esc_html
($line);
8362 print "</pre><ul>\n";
8363 foreach my $difftree_line (@difftree) {
8364 my %difftree = parse_difftree_raw_line
($difftree_line);
8365 next if !$difftree{'from_id'};
8367 my $file = $difftree{'file'} || $difftree{'to_file'};
8371 $cgi->a({-href
=> href
(-full
=>1, action
=>"blobdiff",
8372 hash
=>$difftree{'to_id'}, hash_parent
=>$difftree{'from_id'},
8373 hash_base
=>$co{'id'}, hash_parent_base
=>$co{'parent'},
8374 file_name
=>$file, file_parent
=>$difftree{'from_file'}),
8375 -title
=> "diff"}, 'D');
8377 print $cgi->a({-href
=> href
(-full
=>1, action
=>"blame",
8378 file_name
=>$file, hash_base
=>$commit),
8379 -title
=> "blame"}, 'B');
8381 # if this is not a feed of a file history
8382 if (!defined $file_name || $file_name ne $file) {
8383 print $cgi->a({-href
=> href
(-full
=>1, action
=>"history",
8384 file_name
=>$file, hash
=>$commit),
8385 -title
=> "history"}, 'H');
8387 $file = esc_path
($file);
8391 if ($format eq 'rss') {
8392 print "</ul>]]>\n" .
8393 "</content:encoded>\n" .
8395 } elsif ($format eq 'atom') {
8396 print "</ul>\n</div>\n" .
8403 if ($format eq 'rss') {
8404 print "</channel>\n</rss>\n";
8405 } elsif ($format eq 'atom') {
8419 my @list = git_get_projects_list
($project_filter, $strict_export);
8421 die_error
(404, "No projects found");
8425 -type
=> 'text/xml',
8426 -charset
=> 'utf-8',
8427 -content_disposition
=> 'inline; filename="opml.xml"');
8429 my $title = esc_html
($site_name);
8430 my $filter = " within subdirectory ";
8431 if (defined $project_filter) {
8432 $filter .= esc_html
($project_filter);
8437 <?xml version="1.0" encoding="utf-8"?>
8438 <opml version="1.0">
8440 <title>$title OPML Export$filter</title>
8443 <outline text="git RSS feeds">
8446 foreach my $pr (@list) {
8448 my $head = git_get_head_hash
($proj{'path'});
8449 if (!defined $head) {
8452 $git_dir = "$projectroot/$proj{'path'}";
8453 my %co = parse_commit
($head);
8458 my $path = esc_html
(chop_str
($proj{'path'}, 25, 5));
8459 my $rss = esc_attr
(href
('project' => $proj{'path'}, 'action' => 'rss', -full
=> 1));
8460 my $html = esc_attr
(href
('project' => $proj{'path'}, 'action' => 'summary', -full
=> 1));
8461 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";