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', # carrige 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'} = 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'} = 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), href
(project
=>undef, action
=>"project_index"));
4075 printf('<link rel="alternate" title="%s projects feeds" '.
4076 'href="%s" type="text/x-opml" />'."\n",
4077 esc_attr
($site_name), href
(project
=>undef, action
=>"opml"));
4081 sub print_header_links
{
4084 # print out each stylesheet that exist, providing backwards capability
4085 # for those people who defined $stylesheet in a config file
4086 if (defined $stylesheet) {
4087 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
4089 foreach my $stylesheet (@stylesheets) {
4090 next unless $stylesheet;
4091 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
4095 if ($status eq '200 OK');
4096 if (defined $favicon) {
4097 print qq(<link rel="shortcut icon" href=").esc_url
($favicon).qq(" type="image/png" />\n);
4101 sub print_nav_breadcrumbs_path
{
4102 my $dirprefix = undef;
4103 while (my $part = shift) {
4104 $dirprefix .= "/" if defined $dirprefix;
4105 $dirprefix .= $part;
4106 print $cgi->a({-href
=> href
(project
=> undef,
4107 project_filter
=> $dirprefix,
4108 action
=> "project_list")},
4109 esc_html
($part)) . " / ";
4113 sub print_nav_breadcrumbs
{
4116 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4117 print $cgi->a({-href
=> esc_url
($crumb->[1])}, $crumb->[0]) . " / ";
4119 if (defined $project) {
4120 my @dirname = split '/', $project;
4121 my $projectbasename = pop @dirname;
4122 print_nav_breadcrumbs_path
(@dirname);
4123 print $cgi->a({-href
=> href
(action
=>"summary")}, esc_html
($projectbasename));
4124 if (defined $action) {
4125 my $action_print = $action ;
4126 if (defined $opts{-action_extra
}) {
4127 $action_print = $cgi->a({-href
=> href
(action
=>$action)},
4130 print " / $action_print";
4132 if (defined $opts{-action_extra
}) {
4133 print " / $opts{-action_extra}";
4136 } elsif (defined $project_filter) {
4137 print_nav_breadcrumbs_path
(split '/', $project_filter);
4141 sub print_search_form
{
4142 if (!defined $searchtext) {
4146 if (defined $hash_base) {
4147 $search_hash = $hash_base;
4148 } elsif (defined $hash) {
4149 $search_hash = $hash;
4151 $search_hash = "HEAD";
4153 my $action = $my_uri;
4154 my $use_pathinfo = gitweb_check_feature
('pathinfo');
4155 if ($use_pathinfo) {
4156 $action .= "/".esc_url
($project);
4158 print $cgi->start_form(-method => "get", -action
=> $action) .
4159 "<div class=\"search\">\n" .
4161 $cgi->input({-name
=>"p", -value
=>$project, -type
=>"hidden"}) . "\n") .
4162 $cgi->input({-name
=>"a", -value
=>"search", -type
=>"hidden"}) . "\n" .
4163 $cgi->input({-name
=>"h", -value
=>$search_hash, -type
=>"hidden"}) . "\n" .
4164 $cgi->popup_menu(-name
=> 'st', -default => 'commit',
4165 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4166 " " . $cgi->a({-href
=> href
(action
=>"search_help"),
4167 -title
=> "search help" }, "?") . " search:\n",
4168 $cgi->textfield(-name
=> "s", -value
=> $searchtext, -override
=> 1) . "\n" .
4169 "<span title=\"Extended regular expression\">" .
4170 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
4171 -checked
=> $search_use_regexp) .
4174 $cgi->end_form() . "\n";
4177 sub git_header_html
{
4178 my $status = shift || "200 OK";
4179 my $expires = shift;
4182 my $title = get_page_title
();
4183 my $content_type = get_content_type_html
();
4184 print $cgi->header(-type
=>$content_type, -charset
=> 'utf-8',
4185 -status
=> $status, -expires
=> $expires)
4186 unless ($opts{'-no_http_header'});
4187 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4189 <?xml version="1.0" encoding="utf-8"?>
4190 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4191 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4192 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4193 <!-- git core binaries version $git_version -->
4195 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4196 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4197 <meta name="robots" content="index, nofollow"/>
4198 <title>$title</title>
4200 # the stylesheet, favicon etc urls won't work correctly with path_info
4201 # unless we set the appropriate base URL
4202 if ($ENV{'PATH_INFO'}) {
4203 print "<base href=\"".esc_url
($base_url)."\" />\n";
4205 print_header_links
($status);
4207 if (defined $site_html_head_string) {
4208 print to_utf8
($site_html_head_string);
4214 if (defined $site_header && -f
$site_header) {
4215 insert_file
($site_header);
4218 print "<div class=\"page_header\">\n";
4219 if (defined $logo) {
4220 print $cgi->a({-href
=> esc_url
($logo_url),
4221 -title
=> $logo_label},
4222 $cgi->img({-src
=> esc_url
($logo),
4223 -width
=> 72, -height
=> 27,
4225 -class => "logo"}));
4227 print_nav_breadcrumbs
(%opts);
4230 my $have_search = gitweb_check_feature
('search');
4231 if (defined $project && $have_search) {
4232 print_search_form
();
4236 sub git_footer_html
{
4237 my $feed_class = 'rss_logo';
4239 print "<div class=\"page_footer\">\n";
4240 if (defined $project) {
4241 my $descr = git_get_project_description
($project);
4242 if (defined $descr) {
4243 print "<div class=\"page_footer_text\">" . esc_html
($descr) . "</div>\n";
4246 my %href_params = get_feed_info
();
4247 if (!%href_params) {
4248 $feed_class .= ' generic';
4250 $href_params{'-title'} ||= 'log';
4252 foreach my $format (qw(RSS Atom)) {
4253 $href_params{'action'} = lc($format);
4254 print $cgi->a({-href
=> href
(%href_params),
4255 -title
=> "$href_params{'-title'} $format feed",
4256 -class => $feed_class}, $format)."\n";
4260 print $cgi->a({-href
=> href
(project
=>undef, action
=>"opml",
4261 project_filter
=> $project_filter),
4262 -class => $feed_class}, "OPML") . " ";
4263 print $cgi->a({-href
=> href
(project
=>undef, action
=>"project_index",
4264 project_filter
=> $project_filter),
4265 -class => $feed_class}, "TXT") . "\n";
4267 print "</div>\n"; # class="page_footer"
4269 if (defined $t0 && gitweb_check_feature
('timed')) {
4270 print "<div id=\"generating_info\">\n";
4271 print 'This page took '.
4272 '<span id="generating_time" class="time_span">'.
4273 tv_interval
($t0, [ gettimeofday
() ]).
4276 '<span id="generating_cmd">'.
4277 $number_of_git_cmds.
4278 '</span> git commands '.
4280 print "</div>\n"; # class="page_footer"
4283 if (defined $site_footer && -f
$site_footer) {
4284 insert_file
($site_footer);
4287 print qq
!<script type
="text/javascript" src
="!.esc_url($javascript).qq!"></script
>\n!;
4288 if (defined $action &&
4289 $action eq 'blame_incremental') {
4290 print qq
!<script type
="text/javascript">\n!.
4291 qq
!startBlame
("!. href(action=>"blame_data
", -replay=>1) .qq!",\n!.
4292 qq
! "!. href() .qq!");\n!.
4295 my ($jstimezone, $tz_cookie, $datetime_class) =
4296 gitweb_get_feature
('javascript-timezone');
4298 print qq
!<script type
="text/javascript">\n!.
4299 qq
!window
.onload
= function
() {\n!;
4300 if (gitweb_check_feature
('javascript-actions')) {
4301 print qq
! fixLinks
();\n!;
4303 if ($jstimezone && $tz_cookie && $datetime_class) {
4304 print qq
! var tz_cookie
= { name
: '$tz_cookie', expires
: 14, path
: '/' };\n!. # in days
4305 qq
! onloadTZSetup
('$jstimezone', tz_cookie
, '$datetime_class');\n!;
4315 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4316 # Example: die_error(404, 'Hash not found')
4317 # By convention, use the following status codes (as defined in RFC 2616):
4318 # 400: Invalid or missing CGI parameters, or
4319 # requested object exists but has wrong type.
4320 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4321 # this server or project.
4322 # 404: Requested object/revision/project doesn't exist.
4323 # 500: The server isn't configured properly, or
4324 # an internal error occurred (e.g. failed assertions caused by bugs), or
4325 # an unknown error occurred (e.g. the git binary died unexpectedly).
4326 # 503: The server is currently unavailable (because it is overloaded,
4327 # or down for maintenance). Generally, this is a temporary state.
4329 my $status = shift || 500;
4330 my $error = esc_html
(shift) || "Internal Server Error";
4334 my %http_responses = (
4335 400 => '400 Bad Request',
4336 403 => '403 Forbidden',
4337 404 => '404 Not Found',
4338 500 => '500 Internal Server Error',
4339 503 => '503 Service Unavailable',
4341 git_header_html
($http_responses{$status}, undef, %opts);
4343 <div class="page_body">
4348 if (defined $extra) {
4356 unless ($opts{'-error_handler'});
4359 ## ----------------------------------------------------------------------
4360 ## functions printing or outputting HTML: navigation
4362 sub git_print_page_nav
{
4363 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4364 $extra = '' if !defined $extra; # pager or formats
4366 my @navs = qw(summary shortlog log commit commitdiff tree);
4368 @navs = grep { $_ ne $suppress } @navs;
4371 my %arg = map { $_ => {action
=>$_} } @navs;
4372 if (defined $head) {
4373 for (qw(commit commitdiff)) {
4374 $arg{$_}{'hash'} = $head;
4376 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4377 for (qw(shortlog log)) {
4378 $arg{$_}{'hash'} = $head;
4383 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4384 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4386 my @actions = gitweb_get_feature
('actions');
4389 'n' => $project, # project name
4390 'f' => $git_dir, # project path within filesystem
4391 'h' => $treehead || '', # current hash ('h' parameter)
4392 'b' => $treebase || '', # hash base ('hb' parameter)
4395 my ($label, $link, $pos) = splice(@actions,0,3);
4397 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4399 $link =~ s/%([%nfhb])/$repl{$1}/g;
4400 $arg{$label}{'_href'} = $link;
4403 print "<div class=\"page_nav\">\n" .
4405 map { $_ eq $current ?
4406 $_ : $cgi->a({-href
=> ($arg{$_}{_href
} ? $arg{$_}{_href
} : href
(%{$arg{$_}}))}, "$_")
4408 print "<br/>\n$extra<br/>\n" .
4412 # returns a submenu for the navigation of the refs views (tags, heads,
4413 # remotes) with the current view disabled and the remotes view only
4414 # available if the feature is enabled
4415 sub format_ref_views
{
4417 my @ref_views = qw{tags heads};
4418 push @ref_views, 'remotes' if gitweb_check_feature
('remote_heads');
4419 return join " | ", map {
4420 $_ eq $current ? $_ :
4421 $cgi->a({-href
=> href
(action
=>$_)}, $_)
4425 sub format_paging_nav
{
4426 my ($action, $page, $has_next_link) = @_;
4432 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)}, "first") .
4434 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
4435 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
4437 $paging_nav .= "first ⋅ prev";
4440 if ($has_next_link) {
4441 $paging_nav .= " ⋅ " .
4442 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
4443 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
4445 $paging_nav .= " ⋅ next";
4451 ## ......................................................................
4452 ## functions printing or outputting HTML: div
4454 sub git_print_header_div
{
4455 my ($action, $title, $hash, $hash_base) = @_;
4458 $args{'action'} = $action;
4459 $args{'hash'} = $hash if $hash;
4460 $args{'hash_base'} = $hash_base if $hash_base;
4462 print "<div class=\"header\">\n" .
4463 $cgi->a({-href
=> href
(%args), -class => "title"},
4464 $title ? $title : $action) .
4468 sub format_repo_url
{
4469 my ($name, $url) = @_;
4470 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4473 # Group output by placing it in a DIV element and adding a header.
4474 # Options for start_div() can be provided by passing a hash reference as the
4475 # first parameter to the function.
4476 # Options to git_print_header_div() can be provided by passing an array
4477 # reference. This must follow the options to start_div if they are present.
4478 # The content can be a scalar, which is output as-is, a scalar reference, which
4479 # is output after html escaping, an IO handle passed either as *handle or
4480 # *handle{IO}, or a function reference. In the latter case all following
4481 # parameters will be taken as argument to the content function call.
4482 sub git_print_section
{
4483 my ($div_args, $header_args, $content);
4485 if (ref($arg) eq 'HASH') {
4489 if (ref($arg) eq 'ARRAY') {
4490 $header_args = $arg;
4495 print $cgi->start_div($div_args);
4496 git_print_header_div
(@$header_args);
4498 if (ref($content) eq 'CODE') {
4500 } elsif (ref($content) eq 'SCALAR') {
4501 print esc_html
($$content);
4502 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4504 } elsif (!ref($content) && defined($content)) {
4508 print $cgi->end_div;
4511 sub format_timestamp_html
{
4513 my $strtime = $date->{'rfc2822'};
4515 my (undef, undef, $datetime_class) =
4516 gitweb_get_feature
('javascript-timezone');
4517 if ($datetime_class) {
4518 $strtime = qq
!<span
class="$datetime_class">$strtime</span
>!;
4521 my $localtime_format = '(%02d:%02d %s)';
4522 if ($date->{'hour_local'} < 6) {
4523 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4526 sprintf($localtime_format,
4527 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4532 # Outputs the author name and date in long form
4533 sub git_print_authorship
{
4536 my $tag = $opts{-tag
} || 'div';
4537 my $author = $co->{'author_name'};
4539 my %ad = parse_date
($co->{'author_epoch'}, $co->{'author_tz'});
4540 print "<$tag class=\"author_date\">" .
4541 format_search_author
($author, "author", esc_html
($author)) .
4542 " [".format_timestamp_html
(\
%ad)."]".
4543 git_get_avatar
($co->{'author_email'}, -pad_before
=> 1) .
4547 # Outputs table rows containing the full author or committer information,
4548 # in the format expected for 'commit' view (& similar).
4549 # Parameters are a commit hash reference, followed by the list of people
4550 # to output information for. If the list is empty it defaults to both
4551 # author and committer.
4552 sub git_print_authorship_rows
{
4554 # too bad we can't use @people = @_ || ('author', 'committer')
4556 @people = ('author', 'committer') unless @people;
4557 foreach my $who (@people) {
4558 my %wd = parse_date
($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4559 print "<tr><td>$who</td><td>" .
4560 format_search_author
($co->{"${who}_name"}, $who,
4561 esc_html
($co->{"${who}_name"})) . " " .
4562 format_search_author
($co->{"${who}_email"}, $who,
4563 esc_html
("<" . $co->{"${who}_email"} . ">")) .
4564 "</td><td rowspan=\"2\">" .
4565 git_get_avatar
($co->{"${who}_email"}, -size
=> 'double') .
4569 format_timestamp_html
(\
%wd) .
4575 sub git_print_page_path
{
4581 print "<div class=\"page_path\">";
4582 print $cgi->a({-href
=> href
(action
=>"tree", hash_base
=>$hb),
4583 -title
=> 'tree root'}, to_utf8
("[$project]"));
4585 if (defined $name) {
4586 my @dirname = split '/', $name;
4587 my $basename = pop @dirname;
4590 foreach my $dir (@dirname) {
4591 $fullname .= ($fullname ? '/' : '') . $dir;
4592 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$fullname,
4594 -title
=> $fullname}, esc_path
($dir));
4597 if (defined $type && $type eq 'blob') {
4598 print $cgi->a({-href
=> href
(action
=>"blob_plain", file_name
=>$file_name,
4600 -title
=> $name}, esc_path
($basename));
4601 } elsif (defined $type && $type eq 'tree') {
4602 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$file_name,
4604 -title
=> $name}, esc_path
($basename));
4607 print esc_path
($basename);
4610 print "<br/></div>\n";
4617 if ($opts{'-remove_title'}) {
4618 # remove title, i.e. first line of log
4621 # remove leading empty lines
4622 while (defined $log->[0] && $log->[0] eq "") {
4627 my $skip_blank_line = 0;
4628 foreach my $line (@$log) {
4629 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4630 if (! $opts{'-remove_signoff'}) {
4631 print "<span class=\"signoff\">" . esc_html
($line) . "</span><br/>\n";
4632 $skip_blank_line = 1;
4637 if ($line =~ m
,\s
*([a-z
]*link): (https
?://\S
+),i
) {
4638 if (! $opts{'-remove_signoff'}) {
4639 print "<span class=\"signoff\">" . esc_html
($1) . ": " .
4640 "<a href=\"" . esc_html
($2) . "\">" . esc_html
($2) . "</a>" .
4642 $skip_blank_line = 1;
4647 # print only one empty line
4648 # do not print empty line after signoff
4650 next if ($skip_blank_line);
4651 $skip_blank_line = 1;
4653 $skip_blank_line = 0;
4656 print format_log_line_html
($line) . "<br/>\n";
4659 if ($opts{'-final_empty_line'}) {
4660 # end with single empty line
4661 print "<br/>\n" unless $skip_blank_line;
4665 # return link target (what link points to)
4666 sub git_get_link_target
{
4671 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
4675 $link_target = <$fd>;
4680 return $link_target;
4683 # given link target, and the directory (basedir) the link is in,
4684 # return target of link relative to top directory (top tree);
4685 # return undef if it is not possible (including absolute links).
4686 sub normalize_link_target
{
4687 my ($link_target, $basedir) = @_;
4689 # absolute symlinks (beginning with '/') cannot be normalized
4690 return if (substr($link_target, 0, 1) eq '/');
4692 # normalize link target to path from top (root) tree (dir)
4695 $path = $basedir . '/' . $link_target;
4697 # we are in top (root) tree (dir)
4698 $path = $link_target;
4701 # remove //, /./, and /../
4703 foreach my $part (split('/', $path)) {
4704 # discard '.' and ''
4705 next if (!$part || $part eq '.');
4707 if ($part eq '..') {
4711 # link leads outside repository (outside top dir)
4715 push @path_parts, $part;
4718 $path = join('/', @path_parts);
4723 # print tree entry (row of git_tree), but without encompassing <tr> element
4724 sub git_print_tree_entry
{
4725 my ($t, $basedir, $hash_base, $have_blame) = @_;
4728 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4730 # The format of a table row is: mode list link. Where mode is
4731 # the mode of the entry, list is the name of the entry, an href,
4732 # and link is the action links of the entry.
4734 print "<td class=\"mode\">" . mode_str
($t->{'mode'}) . "</td>\n";
4735 if (exists $t->{'size'}) {
4736 print "<td class=\"size\">$t->{'size'}</td>\n";
4738 if ($t->{'type'} eq "blob") {
4739 print "<td class=\"list\">" .
4740 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4741 file_name
=>"$basedir$t->{'name'}", %base_key),
4742 -class => "list"}, esc_path
($t->{'name'}));
4743 if (S_ISLNK
(oct $t->{'mode'})) {
4744 my $link_target = git_get_link_target
($t->{'hash'});
4746 my $norm_target = normalize_link_target
($link_target, $basedir);
4747 if (defined $norm_target) {
4749 $cgi->a({-href
=> href
(action
=>"object", hash_base
=>$hash_base,
4750 file_name
=>$norm_target),
4751 -title
=> $norm_target}, esc_path
($link_target));
4753 print " -> " . esc_path
($link_target);
4758 print "<td class=\"link\">";
4759 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4760 file_name
=>"$basedir$t->{'name'}", %base_key)},
4764 $cgi->a({-href
=> href
(action
=>"blame", hash
=>$t->{'hash'},
4765 file_name
=>"$basedir$t->{'name'}", %base_key)},
4768 if (defined $hash_base) {
4770 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4771 hash
=>$t->{'hash'}, file_name
=>"$basedir$t->{'name'}")},
4775 $cgi->a({-href
=> href
(action
=>"blob_plain", hash_base
=>$hash_base,
4776 file_name
=>"$basedir$t->{'name'}")},
4780 } elsif ($t->{'type'} eq "tree") {
4781 print "<td class=\"list\">";
4782 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4783 file_name
=>"$basedir$t->{'name'}",
4785 esc_path
($t->{'name'}));
4787 print "<td class=\"link\">";
4788 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4789 file_name
=>"$basedir$t->{'name'}",
4792 if (defined $hash_base) {
4794 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4795 file_name
=>"$basedir$t->{'name'}")},
4800 # unknown object: we can only present history for it
4801 # (this includes 'commit' object, i.e. submodule support)
4802 print "<td class=\"list\">" .
4803 esc_path
($t->{'name'}) .
4805 print "<td class=\"link\">";
4806 if (defined $hash_base) {
4807 print $cgi->a({-href
=> href
(action
=>"history",
4808 hash_base
=>$hash_base,
4809 file_name
=>"$basedir$t->{'name'}")},
4816 ## ......................................................................
4817 ## functions printing large fragments of HTML
4819 # get pre-image filenames for merge (combined) diff
4820 sub fill_from_file_info
{
4821 my ($diff, @parents) = @_;
4823 $diff->{'from_file'} = [ ];
4824 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4825 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4826 if ($diff->{'status'}[$i] eq 'R' ||
4827 $diff->{'status'}[$i] eq 'C') {
4828 $diff->{'from_file'}[$i] =
4829 git_get_path_by_hash
($parents[$i], $diff->{'from_id'}[$i]);
4836 # is current raw difftree line of file deletion
4838 my $diffinfo = shift;
4840 return $diffinfo->{'to_id'} eq ('0' x
40) || $diffinfo->{'to_id'} eq ('0' x
64);
4843 # does patch correspond to [previous] difftree raw line
4844 # $diffinfo - hashref of parsed raw diff format
4845 # $patchinfo - hashref of parsed patch diff format
4846 # (the same keys as in $diffinfo)
4847 sub is_patch_split
{
4848 my ($diffinfo, $patchinfo) = @_;
4850 return defined $diffinfo && defined $patchinfo
4851 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4855 sub git_difftree_body
{
4856 my ($difftree, $hash, @parents) = @_;
4857 my ($parent) = $parents[0];
4858 my $have_blame = gitweb_check_feature
('blame');
4859 print "<div class=\"list_head\">\n";
4860 if ($#{$difftree} > 10) {
4861 print(($#{$difftree} + 1) . " files changed:\n");
4865 print "<table class=\"" .
4866 (@parents > 1 ? "combined " : "") .
4869 # header only for combined diff in 'commitdiff' view
4870 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4873 print "<thead><tr>\n" .
4874 "<th></th><th></th>\n"; # filename, patchN link
4875 for (my $i = 0; $i < @parents; $i++) {
4876 my $par = $parents[$i];
4878 $cgi->a({-href
=> href
(action
=>"commitdiff",
4879 hash
=>$hash, hash_parent
=>$par),
4880 -title
=> 'commitdiff to parent number ' .
4881 ($i+1) . ': ' . substr($par,0,7)},
4885 print "</tr></thead>\n<tbody>\n";
4890 foreach my $line (@{$difftree}) {
4891 my $diff = parsed_difftree_line
($line);
4894 print "<tr class=\"dark\">\n";
4896 print "<tr class=\"light\">\n";
4900 if (exists $diff->{'nparents'}) { # combined diff
4902 fill_from_file_info
($diff, @parents)
4903 unless exists $diff->{'from_file'};
4905 if (!is_deleted
($diff)) {
4906 # file exists in the result (child) commit
4908 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4909 file_name
=>$diff->{'to_file'},
4911 -class => "list"}, esc_path
($diff->{'to_file'})) .
4915 esc_path
($diff->{'to_file'}) .
4919 if ($action eq 'commitdiff') {
4922 print "<td class=\"link\">" .
4923 $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4929 my $has_history = 0;
4930 my $not_deleted = 0;
4931 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4932 my $hash_parent = $parents[$i];
4933 my $from_hash = $diff->{'from_id'}[$i];
4934 my $from_path = $diff->{'from_file'}[$i];
4935 my $status = $diff->{'status'}[$i];
4937 $has_history ||= ($status ne 'A');
4938 $not_deleted ||= ($status ne 'D');
4940 if ($status eq 'A') {
4941 print "<td class=\"link\" align=\"right\"> | </td>\n";
4942 } elsif ($status eq 'D') {
4943 print "<td class=\"link\">" .
4944 $cgi->a({-href
=> href
(action
=>"blob",
4947 file_name
=>$from_path)},
4951 if ($diff->{'to_id'} eq $from_hash) {
4952 print "<td class=\"link nochange\">";
4954 print "<td class=\"link\">";
4956 print $cgi->a({-href
=> href
(action
=>"blobdiff",
4957 hash
=>$diff->{'to_id'},
4958 hash_parent
=>$from_hash,
4960 hash_parent_base
=>$hash_parent,
4961 file_name
=>$diff->{'to_file'},
4962 file_parent
=>$from_path)},
4968 print "<td class=\"link\">";
4970 print $cgi->a({-href
=> href
(action
=>"blob",
4971 hash
=>$diff->{'to_id'},
4972 file_name
=>$diff->{'to_file'},
4975 print " | " if ($has_history);
4978 print $cgi->a({-href
=> href
(action
=>"history",
4979 file_name
=>$diff->{'to_file'},
4986 next; # instead of 'else' clause, to avoid extra indent
4988 # else ordinary diff
4990 my ($to_mode_oct, $to_mode_str, $to_file_type);
4991 my ($from_mode_oct, $from_mode_str, $from_file_type);
4992 if ($diff->{'to_mode'} ne ('0' x
6)) {
4993 $to_mode_oct = oct $diff->{'to_mode'};
4994 if (S_ISREG
($to_mode_oct)) { # only for regular file
4995 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4997 $to_file_type = file_type
($diff->{'to_mode'});
4999 if ($diff->{'from_mode'} ne ('0' x
6)) {
5000 $from_mode_oct = oct $diff->{'from_mode'};
5001 if (S_ISREG
($from_mode_oct)) { # only for regular file
5002 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
5004 $from_file_type = file_type
($diff->{'from_mode'});
5007 if ($diff->{'status'} eq "A") { # created
5008 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5009 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
5010 $mode_chng .= "]</span>";
5012 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5013 hash_base
=>$hash, file_name
=>$diff->{'file'}),
5014 -class => "list"}, esc_path
($diff->{'file'}));
5016 print "<td>$mode_chng</td>\n";
5017 print "<td class=\"link\">";
5018 if ($action eq 'commitdiff') {
5021 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5025 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5026 hash_base
=>$hash, file_name
=>$diff->{'file'})},
5030 } elsif ($diff->{'status'} eq "D") { # deleted
5031 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5033 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
5034 hash_base
=>$parent, file_name
=>$diff->{'file'}),
5035 -class => "list"}, esc_path
($diff->{'file'}));
5037 print "<td>$mode_chng</td>\n";
5038 print "<td class=\"link\">";
5039 if ($action eq 'commitdiff') {
5042 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5046 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
5047 hash_base
=>$parent, file_name
=>$diff->{'file'})},
5050 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$parent,
5051 file_name
=>$diff->{'file'})},
5054 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$parent,
5055 file_name
=>$diff->{'file'})},
5059 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5060 my $mode_chnge = "";
5061 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5062 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5063 if ($from_file_type ne $to_file_type) {
5064 $mode_chnge .= " from $from_file_type to $to_file_type";
5066 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5067 if ($from_mode_str && $to_mode_str) {
5068 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5069 } elsif ($to_mode_str) {
5070 $mode_chnge .= " mode: $to_mode_str";
5073 $mode_chnge .= "]</span>\n";
5076 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5077 hash_base
=>$hash, file_name
=>$diff->{'file'}),
5078 -class => "list"}, esc_path
($diff->{'file'}));
5080 print "<td>$mode_chnge</td>\n";
5081 print "<td class=\"link\">";
5082 if ($action eq 'commitdiff') {
5085 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5088 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5089 # "commit" view and modified file (not onlu mode changed)
5090 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5091 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5092 hash_base
=>$hash, hash_parent_base
=>$parent,
5093 file_name
=>$diff->{'file'})},
5097 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5098 hash_base
=>$hash, file_name
=>$diff->{'file'})},
5101 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5102 file_name
=>$diff->{'file'})},
5105 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5106 file_name
=>$diff->{'file'})},
5110 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5111 my %status_name = ('R' => 'moved', 'C' => 'copied');
5112 my $nstatus = $status_name{$diff->{'status'}};
5114 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5115 # mode also for directories, so we cannot use $to_mode_str
5116 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5119 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$hash,
5120 hash
=>$diff->{'to_id'}, file_name
=>$diff->{'to_file'}),
5121 -class => "list"}, esc_path
($diff->{'to_file'})) . "</td>\n" .
5122 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5123 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$parent,
5124 hash
=>$diff->{'from_id'}, file_name
=>$diff->{'from_file'}),
5125 -class => "list"}, esc_path
($diff->{'from_file'})) .
5126 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5127 "<td class=\"link\">";
5128 if ($action eq 'commitdiff') {
5131 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5134 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5135 # "commit" view and modified file (not only pure rename or copy)
5136 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5137 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5138 hash_base
=>$hash, hash_parent_base
=>$parent,
5139 file_name
=>$diff->{'to_file'}, file_parent
=>$diff->{'from_file'})},
5143 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5144 hash_base
=>$parent, file_name
=>$diff->{'to_file'})},
5147 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5148 file_name
=>$diff->{'to_file'})},
5151 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5152 file_name
=>$diff->{'to_file'})},
5156 } # we should not encounter Unmerged (U) or Unknown (X) status
5159 print "</tbody>" if $has_header;
5163 # Print context lines and then rem/add lines in a side-by-side manner.
5164 sub print_sidebyside_diff_lines
{
5165 my ($ctx, $rem, $add) = @_;
5167 # print context block before add/rem block
5170 '<div class="chunk_block ctx">',
5171 '<div class="old">',
5174 '<div class="new">',
5183 '<div class="chunk_block rem">',
5184 '<div class="old">',
5191 '<div class="chunk_block add">',
5192 '<div class="new">',
5198 '<div class="chunk_block chg">',
5199 '<div class="old">',
5202 '<div class="new">',
5209 # Print context lines and then rem/add lines in inline manner.
5210 sub print_inline_diff_lines
{
5211 my ($ctx, $rem, $add) = @_;
5213 print @$ctx, @$rem, @$add;
5216 # Format removed and added line, mark changed part and HTML-format them.
5217 # Implementation is based on contrib/diff-highlight
5218 sub format_rem_add_lines_pair
{
5219 my ($rem, $add, $num_parents) = @_;
5221 # We need to untabify lines before split()'ing them;
5222 # otherwise offsets would be invalid.
5225 $rem = untabify
($rem);
5226 $add = untabify
($add);
5228 my @rem = split(//, $rem);
5229 my @add = split(//, $add);
5230 my ($esc_rem, $esc_add);
5231 # Ignore leading +/- characters for each parent.
5232 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5233 my ($prefix_has_nonspace, $suffix_has_nonspace);
5235 my $shorter = (@rem < @add) ? @rem : @add;
5236 while ($prefix_len < $shorter) {
5237 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5239 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5243 while ($prefix_len + $suffix_len < $shorter) {
5244 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5246 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5250 # Mark lines that are different from each other, but have some common
5251 # part that isn't whitespace. If lines are completely different, don't
5252 # mark them because that would make output unreadable, especially if
5253 # diff consists of multiple lines.
5254 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5255 $esc_rem = esc_html_hl_regions
($rem, 'marked',
5256 [$prefix_len, @rem - $suffix_len], -nbsp
=>1);
5257 $esc_add = esc_html_hl_regions
($add, 'marked',
5258 [$prefix_len, @add - $suffix_len], -nbsp
=>1);
5260 $esc_rem = esc_html
($rem, -nbsp
=>1);
5261 $esc_add = esc_html
($add, -nbsp
=>1);
5264 return format_diff_line
(\
$esc_rem, 'rem'),
5265 format_diff_line
(\
$esc_add, 'add');
5268 # HTML-format diff context, removed and added lines.
5269 sub format_ctx_rem_add_lines
{
5270 my ($ctx, $rem, $add, $num_parents) = @_;
5271 my (@new_ctx, @new_rem, @new_add);
5272 my $can_highlight = 0;
5273 my $is_combined = ($num_parents > 1);
5275 # Highlight if every removed line has a corresponding added line.
5276 if (@$add > 0 && @$add == @$rem) {
5279 # Highlight lines in combined diff only if the chunk contains
5280 # diff between the same version, e.g.
5287 # Otherwise the highlightling would be confusing.
5289 for (my $i = 0; $i < @$add; $i++) {
5290 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5291 my $prefix_add = substr($add->[$i], 0, $num_parents);
5293 $prefix_rem =~ s/-/+/g;
5295 if ($prefix_rem ne $prefix_add) {
5303 if ($can_highlight) {
5304 for (my $i = 0; $i < @$add; $i++) {
5305 my ($line_rem, $line_add) = format_rem_add_lines_pair
(
5306 $rem->[$i], $add->[$i], $num_parents);
5307 push @new_rem, $line_rem;
5308 push @new_add, $line_add;
5311 @new_rem = map { format_diff_line
($_, 'rem') } @$rem;
5312 @new_add = map { format_diff_line
($_, 'add') } @$add;
5315 @new_ctx = map { format_diff_line
($_, 'ctx') } @$ctx;
5317 return (\
@new_ctx, \
@new_rem, \
@new_add);
5320 # Print context lines and then rem/add lines.
5321 sub print_diff_lines
{
5322 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5323 my $is_combined = $num_parents > 1;
5325 ($ctx, $rem, $add) = format_ctx_rem_add_lines
($ctx, $rem, $add,
5328 if ($diff_style eq 'sidebyside' && !$is_combined) {
5329 print_sidebyside_diff_lines
($ctx, $rem, $add);
5331 # default 'inline' style and unknown styles
5332 print_inline_diff_lines
($ctx, $rem, $add);
5336 sub print_diff_chunk
{
5337 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5338 my (@ctx, @rem, @add);
5340 # The class of the previous line.
5341 my $prev_class = '';
5343 return unless @chunk;
5345 # incomplete last line might be among removed or added lines,
5346 # or both, or among context lines: find which
5347 for (my $i = 1; $i < @chunk; $i++) {
5348 if ($chunk[$i][0] eq 'incomplete') {
5349 $chunk[$i][0] = $chunk[$i-1][0];
5354 push @chunk, ["", ""];
5356 foreach my $line_info (@chunk) {
5357 my ($class, $line) = @$line_info;
5359 # print chunk headers
5360 if ($class && $class eq 'chunk_header') {
5361 print format_diff_line
($line, $class, $from, $to);
5365 ## print from accumulator when have some add/rem lines or end
5366 # of chunk (flush context lines), or when have add and rem
5367 # lines and new block is reached (otherwise add/rem lines could
5369 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5370 (@rem && @add && $class ne $prev_class)) {
5371 print_diff_lines
(\
@ctx, \
@rem, \
@add,
5372 $diff_style, $num_parents);
5373 @ctx = @rem = @add = ();
5376 ## adding lines to accumulator
5379 # rem, add or change
5380 if ($class eq 'rem') {
5382 } elsif ($class eq 'add') {
5386 if ($class eq 'ctx') {
5390 $prev_class = $class;
5394 sub git_patchset_body
{
5395 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5396 my ($hash_parent) = $hash_parents[0];
5398 my $is_combined = (@hash_parents > 1);
5400 my $patch_number = 0;
5405 my @chunk; # for side-by-side diff
5407 print "<div class=\"patchset\">\n";
5409 # skip to first patch
5410 while ($patch_line = <$fd>) {
5413 last if ($patch_line =~ m/^diff /);
5417 while ($patch_line) {
5419 # parse "git diff" header line
5420 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5421 # $1 is from_name, which we do not use
5422 $to_name = unquote
($2);
5423 $to_name =~ s!^b/!!;
5424 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5425 # $1 is 'cc' or 'combined', which we do not use
5426 $to_name = unquote
($2);
5431 # check if current patch belong to current raw line
5432 # and parse raw git-diff line if needed
5433 if (is_patch_split
($diffinfo, { 'to_file' => $to_name })) {
5434 # this is continuation of a split patch
5435 print "<div class=\"patch cont\">\n";
5437 # advance raw git-diff output if needed
5438 $patch_idx++ if defined $diffinfo;
5440 # read and prepare patch information
5441 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5443 # compact combined diff output can have some patches skipped
5444 # find which patch (using pathname of result) we are at now;
5446 while ($to_name ne $diffinfo->{'to_file'}) {
5447 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5448 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5449 "</div>\n"; # class="patch"
5454 last if $patch_idx > $#$difftree;
5455 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5459 # modifies %from, %to hashes
5460 parse_from_to_diffinfo
($diffinfo, \
%from, \
%to, @hash_parents);
5462 # this is first patch for raw difftree line with $patch_idx index
5463 # we index @$difftree array from 0, but number patches from 1
5464 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5468 #assert($patch_line =~ m/^diff /) if DEBUG;
5469 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5471 # print "git diff" header
5472 print format_git_diff_header_line
($patch_line, $diffinfo,
5475 # print extended diff header
5476 print "<div class=\"diff extended_header\">\n";
5478 while ($patch_line = <$fd>) {
5481 last EXTENDED_HEADER
if ($patch_line =~ m/^--- |^diff /);
5483 print format_extended_diff_header_line
($patch_line, $diffinfo,
5486 print "</div>\n"; # class="diff extended_header"
5488 # from-file/to-file diff header
5489 if (! $patch_line) {
5490 print "</div>\n"; # class="patch"
5493 next PATCH
if ($patch_line =~ m/^diff /);
5494 #assert($patch_line =~ m/^---/) if DEBUG;
5496 my $last_patch_line = $patch_line;
5497 $patch_line = <$fd>;
5499 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5501 print format_diff_from_to_header
($last_patch_line, $patch_line,
5502 $diffinfo, \
%from, \
%to,
5507 while ($patch_line = <$fd>) {
5510 next PATCH
if ($patch_line =~ m/^diff /);
5512 my $class = diff_line_class
($patch_line, \
%from, \
%to);
5514 if ($class eq 'chunk_header') {
5515 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5519 push @chunk, [ $class, $patch_line ];
5524 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5527 print "</div>\n"; # class="patch"
5530 # for compact combined (--cc) format, with chunk and patch simplification
5531 # the patchset might be empty, but there might be unprocessed raw lines
5532 for (++$patch_idx if $patch_number > 0;
5533 $patch_idx < @$difftree;
5535 # read and prepare patch information
5536 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5538 # generate anchor for "patch" links in difftree / whatchanged part
5539 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5540 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5541 "</div>\n"; # class="patch"
5546 if ($patch_number == 0) {
5547 if (@hash_parents > 1) {
5548 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5550 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5554 print "</div>\n"; # class="patchset"
5557 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5559 sub git_project_search_form
{
5560 my ($searchtext, $search_use_regexp) = @_;
5563 if ($project_filter) {
5564 $limit = " in '$project_filter/'";
5567 print "<div class=\"projsearch\">\n";
5568 print $cgi->start_form(-method => 'get', -action
=> $my_uri) .
5569 $cgi->hidden(-name
=> 'a', -value
=> 'project_list') . "\n";
5570 print $cgi->hidden(-name
=> 'pf', -value
=> $project_filter). "\n"
5571 if (defined $project_filter);
5572 print $cgi->textfield(-name
=> 's', -value
=> $searchtext,
5573 -title
=> "Search project by name and description$limit",
5574 -size
=> 60) . "\n" .
5575 "<span title=\"Extended regular expression\">" .
5576 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
5577 -checked
=> $search_use_regexp) .
5579 $cgi->submit(-name
=> 'btnS', -value
=> 'Search') .
5580 $cgi->end_form() . "\n" .
5581 $cgi->a({-href
=> href
(project
=> undef, searchtext
=> undef,
5582 project_filter
=> $project_filter)},
5583 esc_html
("List all projects$limit")) . "<br />\n";
5587 # entry for given @keys needs filling if at least one of keys in list
5588 # is not present in %$project_info
5589 sub project_info_needs_filling
{
5590 my ($project_info, @keys) = @_;
5592 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5593 foreach my $key (@keys) {
5594 if (!exists $project_info->{$key}) {
5601 # fills project list info (age, description, owner, category, forks, etc.)
5602 # for each project in the list, removing invalid projects from
5603 # returned list, or fill only specified info.
5605 # Invalid projects are removed from the returned list if and only if you
5606 # ask 'age' or 'age_string' to be filled, because they are the only fields
5607 # that run unconditionally git command that requires repository, and
5608 # therefore do always check if project repository is invalid.
5611 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5612 # ensures that 'descr_long' and 'ctags' fields are filled
5613 # * @project_list = fill_project_list_info(\@project_list)
5614 # ensures that all fields are filled (and invalid projects removed)
5616 # NOTE: modifies $projlist, but does not remove entries from it
5617 sub fill_project_list_info
{
5618 my ($projlist, @wanted_keys) = @_;
5620 my $filter_set = sub { return @_; };
5622 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5623 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5626 my $show_ctags = gitweb_check_feature
('ctags');
5628 foreach my $pr (@$projlist) {
5629 if (project_info_needs_filling
($pr, $filter_set->('age', 'age_string'))) {
5630 my (@activity) = git_get_last_activity
($pr->{'path'});
5631 unless (@activity) {
5634 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5636 if (project_info_needs_filling
($pr, $filter_set->('descr', 'descr_long'))) {
5637 my $descr = git_get_project_description
($pr->{'path'}) || "";
5638 $descr = to_utf8
($descr);
5639 $pr->{'descr_long'} = $descr;
5640 $pr->{'descr'} = chop_str
($descr, $projects_list_description_width, 5);
5642 if (project_info_needs_filling
($pr, $filter_set->('owner'))) {
5643 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}") || "";
5646 project_info_needs_filling
($pr, $filter_set->('ctags'))) {
5647 $pr->{'ctags'} = git_get_project_ctags
($pr->{'path'});
5649 if ($projects_list_group_categories &&
5650 project_info_needs_filling
($pr, $filter_set->('category'))) {
5651 my $cat = git_get_project_category
($pr->{'path'}) ||
5652 $project_list_default_category;
5653 $pr->{'category'} = to_utf8
($cat);
5656 push @projects, $pr;
5662 sub sort_projects_list
{
5663 my ($projlist, $order) = @_;
5667 return sub { $a->{$key} cmp $b->{$key} };
5670 sub order_num_then_undef
{
5673 defined $a->{$key} ?
5674 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5675 (defined $b->{$key} ? 1 : 0)
5680 project
=> order_str
('path'),
5681 descr
=> order_str
('descr_long'),
5682 owner
=> order_str
('owner'),
5683 age
=> order_num_then_undef
('age'),
5686 my $ordering = $orderings{$order};
5687 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5690 # returns a hash of categories, containing the list of project
5691 # belonging to each category
5692 sub build_projlist_by_category
{
5693 my ($projlist, $from, $to) = @_;
5696 $from = 0 unless defined $from;
5697 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5699 for (my $i = $from; $i <= $to; $i++) {
5700 my $pr = $projlist->[$i];
5701 push @{$categories{ $pr->{'category'} }}, $pr;
5704 return wantarray ? %categories : \
%categories;
5707 # print 'sort by' <th> element, generating 'sort by $name' replay link
5708 # if that order is not selected
5710 print format_sort_th
(@_);
5713 sub format_sort_th
{
5714 my ($name, $order, $header) = @_;
5716 $header ||= ucfirst($name);
5718 if ($order eq $name) {
5719 $sort_th .= "<th>$header</th>\n";
5721 $sort_th .= "<th>" .
5722 $cgi->a({-href
=> href
(-replay
=>1, order
=>$name),
5723 -class => "header"}, $header) .
5730 sub git_project_list_rows
{
5731 my ($projlist, $from, $to, $check_forks) = @_;
5733 $from = 0 unless defined $from;
5734 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5737 for (my $i = $from; $i <= $to; $i++) {
5738 my $pr = $projlist->[$i];
5741 print "<tr class=\"dark\">\n";
5743 print "<tr class=\"light\">\n";
5749 if ($pr->{'forks'}) {
5750 my $nforks = scalar @{$pr->{'forks'}};
5752 print $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks"),
5753 -title
=> "$nforks forks"}, "+");
5755 print $cgi->span({-title
=> "$nforks forks"}, "+");
5760 print "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5762 esc_html_match_hl
($pr->{'path'}, $search_regexp)) .
5764 "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5766 -title
=> $pr->{'descr_long'}},
5768 ? esc_html_match_hl_chopped
($pr->{'descr_long'},
5769 $pr->{'descr'}, $search_regexp)
5770 : esc_html
($pr->{'descr'})) .
5772 unless ($omit_owner) {
5773 print "<td><i>" . chop_and_escape_str
($pr->{'owner'}, 15) . "</i></td>\n";
5775 unless ($omit_age_column) {
5776 print "<td class=\"". age_class
($pr->{'age'}) . "\">" .
5777 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5779 print"<td class=\"link\">" .
5780 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary")}, "summary") . " | " .
5781 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"shortlog")}, "shortlog") . " | " .
5782 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"log")}, "log") . " | " .
5783 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"tree")}, "tree") .
5784 ($pr->{'forks'} ? " | " . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks")}, "forks") : '') .
5790 sub git_project_list_body
{
5791 # actually uses global variable $project
5792 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5793 my @projects = @$projlist;
5795 my $check_forks = gitweb_check_feature
('forks');
5796 my $show_ctags = gitweb_check_feature
('ctags');
5797 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5798 $check_forks = undef
5799 if ($tagfilter || $search_regexp);
5801 # filtering out forks before filling info allows to do less work
5802 @projects = filter_forks_from_projects_list
(\
@projects)
5804 # search_projects_list pre-fills required info
5805 @projects = search_projects_list
(\
@projects,
5806 'search_regexp' => $search_regexp,
5807 'tagfilter' => $tagfilter)
5808 if ($tagfilter || $search_regexp);
5810 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5811 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5812 push @all_fields, 'owner' unless($omit_owner);
5813 @projects = fill_project_list_info
(\
@projects, @all_fields);
5815 $order ||= $default_projects_order;
5816 $from = 0 unless defined $from;
5817 $to = $#projects if (!defined $to || $#projects < $to);
5822 "<b>No such projects found</b><br />\n".
5823 "Click ".$cgi->a({-href
=>href
(project
=>undef)},"here")." to view all projects<br />\n".
5824 "</center>\n<br />\n";
5828 @projects = sort_projects_list
(\
@projects, $order);
5831 my $ctags = git_gather_all_ctags
(\
@projects);
5832 my $cloud = git_populate_project_tagcloud
($ctags);
5833 print git_show_project_tagcloud
($cloud, 64);
5836 print "<table class=\"project_list\">\n";
5837 unless ($no_header) {
5840 print "<th></th>\n";
5842 print_sort_th
('project', $order, 'Project');
5843 print_sort_th
('descr', $order, 'Description');
5844 print_sort_th
('owner', $order, 'Owner') unless $omit_owner;
5845 print_sort_th
('age', $order, 'Last Change') unless $omit_age_column;
5846 print "<th></th>\n" . # for links
5850 if ($projects_list_group_categories) {
5851 # only display categories with projects in the $from-$to window
5852 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5853 my %categories = build_projlist_by_category
(\
@projects, $from, $to);
5854 foreach my $cat (sort keys %categories) {
5855 unless ($cat eq "") {
5858 print "<td></td>\n";
5860 print "<td class=\"category\" colspan=\"5\">".esc_html
($cat)."</td>\n";
5864 git_project_list_rows
($categories{$cat}, undef, undef, $check_forks);
5867 git_project_list_rows
(\
@projects, $from, $to, $check_forks);
5870 if (defined $extra) {
5873 print "<td></td>\n";
5875 print "<td colspan=\"5\">$extra</td>\n" .
5882 # uses global variable $project
5883 my ($commitlist, $from, $to, $refs, $extra) = @_;
5885 $from = 0 unless defined $from;
5886 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5888 for (my $i = 0; $i <= $to; $i++) {
5889 my %co = %{$commitlist->[$i]};
5891 my $commit = $co{'id'};
5892 my $ref = format_ref_marker
($refs, $commit);
5893 git_print_header_div
('commit',
5894 "<span class=\"age\">$co{'age_string'}</span>" .
5895 esc_html
($co{'title'}) . $ref,
5897 print "<div class=\"title_text\">\n" .
5898 "<div class=\"log_link\">\n" .
5899 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") .
5901 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") .
5903 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree") .
5906 git_print_authorship
(\
%co, -tag
=> 'span');
5907 print "<br/>\n</div>\n";
5909 print "<div class=\"log_body\">\n";
5910 git_print_log
($co{'comment'}, -final_empty_line
=> 1);
5914 print "<div class=\"page_nav\">\n";
5920 sub git_shortlog_body
{
5921 # uses global variable $project
5922 my ($commitlist, $from, $to, $refs, $extra) = @_;
5924 $from = 0 unless defined $from;
5925 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5927 print "<table class=\"shortlog\">\n";
5929 for (my $i = $from; $i <= $to; $i++) {
5930 my %co = %{$commitlist->[$i]};
5931 my $commit = $co{'id'};
5932 my $ref = format_ref_marker
($refs, $commit);
5934 print "<tr class=\"dark\">\n";
5936 print "<tr class=\"light\">\n";
5939 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5940 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5941 format_author_html
('td', \
%co, 10) . "<td>";
5942 print format_subject_html
($co{'title'}, $co{'title_short'},
5943 href
(action
=>"commit", hash
=>$commit), $ref);
5945 "<td class=\"link\">" .
5946 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") . " | " .
5947 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") . " | " .
5948 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree");
5949 my $snapshot_links = format_snapshot_links
($commit);
5950 if (defined $snapshot_links) {
5951 print " | " . $snapshot_links;
5956 if (defined $extra) {
5958 "<td colspan=\"4\">$extra</td>\n" .
5964 sub git_history_body
{
5965 # Warning: assumes constant type (blob or tree) during history
5966 my ($commitlist, $from, $to, $refs, $extra,
5967 $file_name, $file_hash, $ftype) = @_;
5969 $from = 0 unless defined $from;
5970 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5972 print "<table class=\"history\">\n";
5974 for (my $i = $from; $i <= $to; $i++) {
5975 my %co = %{$commitlist->[$i]};
5979 my $commit = $co{'id'};
5981 my $ref = format_ref_marker
($refs, $commit);
5984 print "<tr class=\"dark\">\n";
5986 print "<tr class=\"light\">\n";
5989 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5990 # shortlog: format_author_html('td', \%co, 10)
5991 format_author_html
('td', \
%co, 15, 3) . "<td>";
5992 # originally git_history used chop_str($co{'title'}, 50)
5993 print format_subject_html
($co{'title'}, $co{'title_short'},
5994 href
(action
=>"commit", hash
=>$commit), $ref);
5996 "<td class=\"link\">" .
5997 $cgi->a({-href
=> href
(action
=>$ftype, hash_base
=>$commit, file_name
=>$file_name)}, $ftype) . " | " .
5998 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff");
6000 if ($ftype eq 'blob') {
6002 $cgi->a({-href
=> href
(action
=>"blob_plain", hash_base
=>$commit, file_name
=>$file_name)}, "raw");
6004 my $blob_current = $file_hash;
6005 my $blob_parent = git_get_hash_by_path
($commit, $file_name);
6006 if (defined $blob_current && defined $blob_parent &&
6007 $blob_current ne $blob_parent) {
6009 $cgi->a({-href
=> href
(action
=>"blobdiff",
6010 hash
=>$blob_current, hash_parent
=>$blob_parent,
6011 hash_base
=>$hash_base, hash_parent_base
=>$commit,
6012 file_name
=>$file_name)},
6019 if (defined $extra) {
6021 "<td colspan=\"4\">$extra</td>\n" .
6028 # uses global variable $project
6029 my ($taglist, $from, $to, $extra) = @_;
6030 $from = 0 unless defined $from;
6031 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6033 print "<table class=\"tags\">\n";
6035 for (my $i = $from; $i <= $to; $i++) {
6036 my $entry = $taglist->[$i];
6038 my $comment = $tag{'subject'};
6040 if (defined $comment) {
6041 $comment_short = chop_str
($comment, 30, 5);
6044 print "<tr class=\"dark\">\n";
6046 print "<tr class=\"light\">\n";
6049 if (defined $tag{'age'}) {
6050 print "<td><i>$tag{'age'}</i></td>\n";
6052 print "<td></td>\n";
6055 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'}),
6056 -class => "list name"}, esc_html
($tag{'name'})) .
6059 if (defined $comment) {
6060 print format_subject_html
($comment, $comment_short,
6061 href
(action
=>"tag", hash
=>$tag{'id'}));
6064 "<td class=\"selflink\">";
6065 if ($tag{'type'} eq "tag") {
6066 print $cgi->a({-href
=> href
(action
=>"tag", hash
=>$tag{'id'})}, "tag");
6071 "<td class=\"link\">" . " | " .
6072 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'})}, $tag{'reftype'});
6073 if ($tag{'reftype'} eq "commit") {
6074 print " | " . $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$tag{'fullname'})}, "shortlog") .
6075 " | " . $cgi->a({-href
=> href
(action
=>"log", hash
=>$tag{'fullname'})}, "log");
6076 } elsif ($tag{'reftype'} eq "blob") {
6077 print " | " . $cgi->a({-href
=> href
(action
=>"blob_plain", hash
=>$tag{'refid'})}, "raw");
6082 if (defined $extra) {
6084 "<td colspan=\"5\">$extra</td>\n" .
6090 sub git_heads_body
{
6091 # uses global variable $project
6092 my ($headlist, $head_at, $from, $to, $extra) = @_;
6093 $from = 0 unless defined $from;
6094 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6096 print "<table class=\"heads\">\n";
6098 for (my $i = $from; $i <= $to; $i++) {
6099 my $entry = $headlist->[$i];
6101 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6103 print "<tr class=\"dark\">\n";
6105 print "<tr class=\"light\">\n";
6108 print "<td><i>$ref{'age'}</i></td>\n" .
6109 ($curr ? "<td class=\"current_head\">" : "<td>") .
6110 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'}),
6111 -class => "list name"},esc_html
($ref{'name'})) .
6113 "<td class=\"link\">" .
6114 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'})}, "shortlog") . " | " .
6115 $cgi->a({-href
=> href
(action
=>"log", hash
=>$ref{'fullname'})}, "log") . " | " .
6116 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$ref{'fullname'}, hash_base
=>$ref{'fullname'})}, "tree") .
6120 if (defined $extra) {
6122 "<td colspan=\"3\">$extra</td>\n" .
6128 # Display a single remote block
6129 sub git_remote_block
{
6130 my ($remote, $rdata, $limit, $head) = @_;
6132 my $heads = $rdata->{'heads'};
6133 my $fetch = $rdata->{'fetch'};
6134 my $push = $rdata->{'push'};
6136 my $urls_table = "<table class=\"projects_list\">\n" ;
6138 if (defined $fetch) {
6139 if ($fetch eq $push) {
6140 $urls_table .= format_repo_url
("URL", $fetch);
6142 $urls_table .= format_repo_url
("Fetch URL", $fetch);
6143 $urls_table .= format_repo_url
("Push URL", $push) if defined $push;
6145 } elsif (defined $push) {
6146 $urls_table .= format_repo_url
("Push URL", $push);
6148 $urls_table .= format_repo_url
("", "No remote URL");
6151 $urls_table .= "</table>\n";
6154 if (defined $limit && $limit < @$heads) {
6155 $dots = $cgi->a({-href
=> href
(action
=>"remotes", hash
=>$remote)}, "...");
6159 git_heads_body
($heads, $head, 0, $limit, $dots);
6162 # Display a list of remote names with the respective fetch and push URLs
6163 sub git_remotes_list
{
6164 my ($remotedata, $limit) = @_;
6165 print "<table class=\"heads\">\n";
6167 my @remotes = sort keys %$remotedata;
6169 my $limited = $limit && $limit < @remotes;
6171 $#remotes = $limit - 1 if $limited;
6173 while (my $remote = shift @remotes) {
6174 my $rdata = $remotedata->{$remote};
6175 my $fetch = $rdata->{'fetch'};
6176 my $push = $rdata->{'push'};
6178 print "<tr class=\"dark\">\n";
6180 print "<tr class=\"light\">\n";
6184 $cgi->a({-href
=> href
(action
=>'remotes', hash
=>$remote),
6185 -class=> "list name"},esc_html
($remote)) .
6187 print "<td class=\"link\">" .
6188 (defined $fetch ? $cgi->a({-href
=> $fetch}, "fetch") : "fetch") .
6190 (defined $push ? $cgi->a({-href
=> $push}, "push") : "push") .
6198 "<td colspan=\"3\">" .
6199 $cgi->a({-href
=> href
(action
=>"remotes")}, "...") .
6200 "</td>\n" . "</tr>\n";
6206 # Display remote heads grouped by remote, unless there are too many
6207 # remotes, in which case we only display the remote names
6208 sub git_remotes_body
{
6209 my ($remotedata, $limit, $head) = @_;
6210 if ($limit and $limit < keys %$remotedata) {
6211 git_remotes_list
($remotedata, $limit);
6213 fill_remote_heads
($remotedata);
6214 while (my ($remote, $rdata) = each %$remotedata) {
6215 git_print_section
({-class=>"remote", -id
=>$remote},
6216 ["remotes", $remote, $remote], sub {
6217 git_remote_block
($remote, $rdata, $limit, $head);
6223 sub git_search_message
{
6227 if ($searchtype eq 'commit') {
6228 $greptype = "--grep=";
6229 } elsif ($searchtype eq 'author') {
6230 $greptype = "--author=";
6231 } elsif ($searchtype eq 'committer') {
6232 $greptype = "--committer=";
6234 $greptype .= $searchtext;
6235 my @commitlist = parse_commits
($hash, 101, (100 * $page), undef,
6236 $greptype, '--regexp-ignore-case',
6237 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6239 my $paging_nav = '';
6242 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)},
6245 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
6246 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
6248 $paging_nav .= "first ⋅ prev";
6251 if ($#commitlist >= 100) {
6253 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
6254 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
6255 $paging_nav .= " ⋅ $next_link";
6257 $paging_nav .= " ⋅ next";
6262 git_print_page_nav
('','', $hash,$co{'tree'},$hash, $paging_nav);
6263 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6264 if ($page == 0 && !@commitlist) {
6265 print "<p>No match.</p>\n";
6267 git_search_grep_body
(\
@commitlist, 0, 99, $next_link);
6273 sub git_search_changes
{
6277 open my $fd, '-|', git_cmd
(), '--no-pager', 'log', @diff_opts,
6278 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6279 ($search_use_regexp ? '--pickaxe-regex' : ())
6280 or die_error
(500, "Open git-log failed");
6284 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6285 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6287 print "<table class=\"pickaxe search\">\n";
6291 while (my $line = <$fd>) {
6295 my %set = parse_difftree_raw_line
($line);
6296 if (defined $set{'commit'}) {
6297 # finish previous commit
6300 "<td class=\"link\">" .
6301 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6304 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6305 hash_base
=>$co{'id'})},
6312 print "<tr class=\"dark\">\n";
6314 print "<tr class=\"light\">\n";
6317 %co = parse_commit
($set{'commit'});
6318 my $author = chop_and_escape_str
($co{'author_name'}, 15, 5);
6319 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6320 "<td><i>$author</i></td>\n" .
6322 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6323 -class => "list subject"},
6324 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6325 } elsif (defined $set{'to_id'}) {
6326 next if is_deleted
(\
%set);
6328 print $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$co{'id'},
6329 hash
=>$set{'to_id'}, file_name
=>$set{'to_file'}),
6331 "<span class=\"match\">" . esc_path
($set{'file'}) . "</span>") .
6337 # finish last commit (warning: repetition!)
6340 "<td class=\"link\">" .
6341 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6344 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6345 hash_base
=>$co{'id'})},
6356 sub git_search_files
{
6360 open my $fd, "-|", git_cmd
(), 'grep', '-n', '-z',
6361 $search_use_regexp ? ('-E', '-i') : '-F',
6362 $searchtext, $co{'tree'}
6363 or die_error
(500, "Open git-grep failed");
6367 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6368 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6370 print "<table class=\"grep_search\">\n";
6375 while (my $line = <$fd>) {
6377 my ($file, $lno, $ltext, $binary);
6378 last if ($matches++ > 1000);
6379 if ($line =~ /^Binary file (.+) matches$/) {
6383 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6384 $file =~ s/^$co{'tree'}://;
6386 if ($file ne $lastfile) {
6387 $lastfile and print "</td></tr>\n";
6389 print "<tr class=\"dark\">\n";
6391 print "<tr class=\"light\">\n";
6393 $file_href = href
(action
=>"blob", hash_base
=>$co{'id'},
6395 print "<td class=\"list\">".
6396 $cgi->a({-href
=> $file_href, -class => "list"}, esc_path
($file));
6397 print "</td><td>\n";
6401 print "<div class=\"binary\">Binary file</div>\n";
6403 $ltext = untabify
($ltext);
6404 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6405 $ltext = esc_html
($1, -nbsp
=>1);
6406 $ltext .= '<span class="match">';
6407 $ltext .= esc_html
($2, -nbsp
=>1);
6408 $ltext .= '</span>';
6409 $ltext .= esc_html
($3, -nbsp
=>1);
6411 $ltext = esc_html
($ltext, -nbsp
=>1);
6413 print "<div class=\"pre\">" .
6414 $cgi->a({-href
=> $file_href.'#l'.$lno,
6415 -class => "linenr"}, sprintf('%4i', $lno)) .
6416 ' ' . $ltext . "</div>\n";
6420 print "</td></tr>\n";
6421 if ($matches > 1000) {
6422 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6425 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6434 sub git_search_grep_body
{
6435 my ($commitlist, $from, $to, $extra) = @_;
6436 $from = 0 unless defined $from;
6437 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6439 print "<table class=\"commit_search\">\n";
6441 for (my $i = $from; $i <= $to; $i++) {
6442 my %co = %{$commitlist->[$i]};
6446 my $commit = $co{'id'};
6448 print "<tr class=\"dark\">\n";
6450 print "<tr class=\"light\">\n";
6453 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6454 format_author_html
('td', \
%co, 15, 5) .
6456 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6457 -class => "list subject"},
6458 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6459 my $comment = $co{'comment'};
6460 foreach my $line (@$comment) {
6461 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6462 my ($lead, $match, $trail) = ($1, $2, $3);
6463 $match = chop_str
($match, 70, 5, 'center');
6464 my $contextlen = int((80 - length($match))/2);
6465 $contextlen = 30 if ($contextlen > 30);
6466 $lead = chop_str
($lead, $contextlen, 10, 'left');
6467 $trail = chop_str
($trail, $contextlen, 10, 'right');
6469 $lead = esc_html
($lead);
6470 $match = esc_html
($match);
6471 $trail = esc_html
($trail);
6473 print "$lead<span class=\"match\">$match</span>$trail<br />";
6477 "<td class=\"link\">" .
6478 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})}, "commit") .
6480 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$co{'id'})}, "commitdiff") .
6482 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$co{'id'})}, "tree");
6486 if (defined $extra) {
6488 "<td colspan=\"3\">$extra</td>\n" .
6494 ## ======================================================================
6495 ## ======================================================================
6498 sub git_project_list
{
6499 my $order = $input_params{'order'};
6500 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6501 die_error
(400, "Unknown order parameter");
6504 my @list = git_get_projects_list
($project_filter, $strict_export);
6506 die_error
(404, "No projects found");
6510 if (defined $home_text && -f
$home_text) {
6511 print "<div class=\"index_include\">\n";
6512 insert_file
($home_text);
6516 git_project_search_form
($searchtext, $search_use_regexp);
6517 git_project_list_body
(\
@list, $order);
6522 my $order = $input_params{'order'};
6523 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6524 die_error
(400, "Unknown order parameter");
6527 my $filter = $project;
6528 $filter =~ s/\.git$//;
6529 my @list = git_get_projects_list
($filter);
6531 die_error
(404, "No forks found");
6535 git_print_page_nav
('','');
6536 git_print_header_div
('summary', "$project forks");
6537 git_project_list_body
(\
@list, $order);
6541 sub git_project_index
{
6542 my @projects = git_get_projects_list
($project_filter, $strict_export);
6544 die_error
(404, "No projects found");
6548 -type
=> 'text/plain',
6549 -charset
=> 'utf-8',
6550 -content_disposition
=> 'inline; filename="index.aux"');
6552 foreach my $pr (@projects) {
6553 if (!exists $pr->{'owner'}) {
6554 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}");
6557 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6558 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6559 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6560 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6564 print "$path $owner\n";
6569 my $descr = git_get_project_description
($project) || "none";
6570 my %co = parse_commit
("HEAD");
6571 my %cd = %co ? parse_date
($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6572 my $head = $co{'id'};
6573 my $remote_heads = gitweb_check_feature
('remote_heads');
6575 my $owner = git_get_project_owner
($project);
6577 my $refs = git_get_references
();
6578 # These get_*_list functions return one more to allow us to see if
6579 # there are more ...
6580 my @taglist = git_get_tags_list
(16);
6581 my @headlist = git_get_heads_list
(16);
6582 my %remotedata = $remote_heads ? git_get_remotes_list
() : ();
6584 my $check_forks = gitweb_check_feature
('forks');
6587 # find forks of a project
6588 my $filter = $project;
6589 $filter =~ s/\.git$//;
6590 @forklist = git_get_projects_list
($filter);
6591 # filter out forks of forks
6592 @forklist = filter_forks_from_projects_list
(\
@forklist)
6597 git_print_page_nav
('summary','', $head);
6599 print "<div class=\"title\"> </div>\n";
6600 print "<table class=\"projects_list\">\n" .
6601 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html
($descr) . "</td></tr>\n";
6602 if ($owner and not $omit_owner) {
6603 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html
($owner) . "</td></tr>\n";
6605 if (defined $cd{'rfc2822'}) {
6606 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6607 "<td>".format_timestamp_html
(\
%cd)."</td></tr>\n";
6610 # use per project git URL list in $projectroot/$project/cloneurl
6611 # or make project git URL from git base URL and project name
6612 my $url_tag = "URL";
6613 my @url_list = git_get_project_url_list
($project);
6614 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6615 foreach my $git_url (@url_list) {
6616 next unless $git_url;
6617 print format_repo_url
($url_tag, $git_url);
6622 my $show_ctags = gitweb_check_feature
('ctags');
6624 my $ctags = git_get_project_ctags
($project);
6626 # without ability to add tags, don't show if there are none
6627 my $cloud = git_populate_project_tagcloud
($ctags);
6628 print "<tr id=\"metadata_ctags\">" .
6629 "<td>content tags</td>" .
6630 "<td>".git_show_project_tagcloud
($cloud, 48)."</td>" .
6637 # If XSS prevention is on, we don't include README.html.
6638 # TODO: Allow a readme in some safe format.
6639 if (!$prevent_xss && -s
"$projectroot/$project/README.html") {
6640 print "<div class=\"title\">readme</div>\n" .
6641 "<div class=\"readme\">\n";
6642 insert_file
("$projectroot/$project/README.html");
6643 print "\n</div>\n"; # class="readme"
6646 # we need to request one more than 16 (0..15) to check if
6648 my @commitlist = $head ? parse_commits
($head, 17) : ();
6650 git_print_header_div
('shortlog');
6651 git_shortlog_body
(\
@commitlist, 0, 15, $refs,
6652 $#commitlist <= 15 ? undef :
6653 $cgi->a({-href
=> href
(action
=>"shortlog")}, "..."));
6657 git_print_header_div
('tags');
6658 git_tags_body
(\
@taglist, 0, 15,
6659 $#taglist <= 15 ? undef :
6660 $cgi->a({-href
=> href
(action
=>"tags")}, "..."));
6664 git_print_header_div
('heads');
6665 git_heads_body
(\
@headlist, $head, 0, 15,
6666 $#headlist <= 15 ? undef :
6667 $cgi->a({-href
=> href
(action
=>"heads")}, "..."));
6671 git_print_header_div
('remotes');
6672 git_remotes_body
(\
%remotedata, 15, $head);
6676 git_print_header_div
('forks');
6677 git_project_list_body
(\
@forklist, 'age', 0, 15,
6678 $#forklist <= 15 ? undef :
6679 $cgi->a({-href
=> href
(action
=>"forks")}, "..."),
6687 my %tag = parse_tag
($hash);
6690 die_error
(404, "Unknown tag object");
6693 my $head = git_get_head_hash
($project);
6695 git_print_page_nav
('','', $head,undef,$head);
6696 git_print_header_div
('commit', esc_html
($tag{'name'}), $hash);
6697 print "<div class=\"title_text\">\n" .
6698 "<table class=\"object_header\">\n" .
6700 "<td>object</td>\n" .
6701 "<td>" . $cgi->a({-class => "list", -href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6702 $tag{'object'}) . "</td>\n" .
6703 "<td class=\"link\">" . $cgi->a({-href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6704 $tag{'type'}) . "</td>\n" .
6706 if (defined($tag{'author'})) {
6707 git_print_authorship_rows
(\
%tag, 'author');
6709 print "</table>\n\n" .
6711 print "<div class=\"page_body\">";
6712 my $comment = $tag{'comment'};
6713 foreach my $line (@$comment) {
6715 print esc_html
($line, -nbsp
=>1) . "<br/>\n";
6721 sub git_blame_common
{
6722 my $format = shift || 'porcelain';
6723 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6724 $format = 'incremental';
6725 $action = 'blame_incremental'; # for page title etc
6729 gitweb_check_feature
('blame')
6730 or die_error
(403, "Blame view not allowed");
6733 die_error
(400, "No file name given") unless $file_name;
6734 $hash_base ||= git_get_head_hash
($project);
6735 die_error
(404, "Couldn't find base commit") unless $hash_base;
6736 my %co = parse_commit
($hash_base)
6737 or die_error
(404, "Commit not found");
6739 if (!defined $hash) {
6740 $hash = git_get_hash_by_path
($hash_base, $file_name, "blob")
6741 or die_error
(404, "Error looking up file");
6743 $ftype = git_get_type
($hash);
6744 if ($ftype !~ "blob") {
6745 die_error
(400, "Object is not a blob");
6750 if ($format eq 'incremental') {
6751 # get file contents (as base)
6752 open $fd, "-|", git_cmd
(), 'cat-file', 'blob', $hash
6753 or die_error
(500, "Open git-cat-file failed");
6754 } elsif ($format eq 'data') {
6755 # run git-blame --incremental
6756 open $fd, "-|", git_cmd
(), "blame", "--incremental",
6757 $hash_base, "--", $file_name
6758 or die_error
(500, "Open git-blame --incremental failed");
6760 # run git-blame --porcelain
6761 open $fd, "-|", git_cmd
(), "blame", '-p',
6762 $hash_base, '--', $file_name
6763 or die_error
(500, "Open git-blame --porcelain failed");
6765 binmode $fd, ':utf8';
6767 # incremental blame data returns early
6768 if ($format eq 'data') {
6770 -type
=>"text/plain", -charset
=> "utf-8",
6771 -status
=> "200 OK");
6772 local $| = 1; # output autoflush
6773 while (my $line = <$fd>) {
6774 print to_utf8
($line);
6777 or print "ERROR $!\n";
6780 if (defined $t0 && gitweb_check_feature
('timed')) {
6782 tv_interval
($t0, [ gettimeofday
() ]).
6783 ' '.$number_of_git_cmds;
6793 $cgi->a({-href
=> href
(action
=>"blob", -replay
=>1)},
6796 if ($format eq 'incremental') {
6798 $cgi->a({-href
=> href
(action
=>"blame", javascript
=>0, -replay
=>1)},
6799 "blame") . " (non-incremental)";
6802 $cgi->a({-href
=> href
(action
=>"blame_incremental", -replay
=>1)},
6803 "blame") . " (incremental)";
6807 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
6810 $cgi->a({-href
=> href
(action
=>$action, file_name
=>$file_name)},
6812 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6813 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
6814 git_print_page_path
($file_name, $ftype, $hash_base);
6817 if ($format eq 'incremental') {
6818 print "<noscript>\n<div class=\"error\"><center><b>\n".
6819 "This page requires JavaScript to run.\n Use ".
6820 $cgi->a({-href
=> href
(action
=>'blame',javascript
=>0,-replay
=>1)},
6823 "</b></center></div>\n</noscript>\n";
6825 print qq
!<div id
="progress_bar" style
="width: 100%; background-color: yellow"></div
>\n!;
6828 print qq
!<div
class="page_body">\n!;
6829 print qq
!<div id
="progress_info">... / ...</div
>\n!
6830 if ($format eq 'incremental');
6831 print qq
!<table id
="blame_table" class="blame" width
="100%">\n!.
6832 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6834 qq
!<tr
><th
>Commit
</th><th>Line</th
><th
>Data
</th></tr
>\n!.
6838 my @rev_color = qw(light dark);
6839 my $num_colors = scalar(@rev_color);
6840 my $current_color = 0;
6842 if ($format eq 'incremental') {
6843 my $color_class = $rev_color[$current_color];
6848 while (my $line = <$fd>) {
6852 print qq
!<tr id
="l$linenr" class="$color_class">!.
6853 qq
!<td
class="sha1"><a href
=""> </a></td
>!.
6854 qq
!<td
class="linenr">!.
6855 qq
!<a
class="linenr" href
="">$linenr</a></td
>!;
6856 print qq
!<td
class="pre">! . esc_html
($line) . "</td>\n";
6860 } else { # porcelain, i.e. ordinary blame
6861 my %metainfo = (); # saves information about commits
6865 while (my $line = <$fd>) {
6867 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6868 # no <lines in group> for subsequent lines in group of lines
6869 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6870 ($line =~ /^($oid_regex) (\d+) (\d+)(?: (\d+))?$/);
6871 if (!exists $metainfo{$full_rev}) {
6872 $metainfo{$full_rev} = { 'nprevious' => 0 };
6874 my $meta = $metainfo{$full_rev};
6876 while ($data = <$fd>) {
6878 last if ($data =~ s/^\t//); # contents of line
6879 if ($data =~ /^(\S+)(?: (.*))?$/) {
6880 $meta->{$1} = $2 unless exists $meta->{$1};
6882 if ($data =~ /^previous /) {
6883 $meta->{'nprevious'}++;
6886 my $short_rev = substr($full_rev, 0, 8);
6887 my $author = $meta->{'author'};
6889 parse_date
($meta->{'author-time'}, $meta->{'author-tz'});
6890 my $date = $date{'iso-tz'};
6892 $current_color = ($current_color + 1) % $num_colors;
6894 my $tr_class = $rev_color[$current_color];
6895 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6896 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6897 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6898 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6900 print "<td class=\"sha1\"";
6901 print " title=\"". esc_html
($author) . ", $date\"";
6902 print " rowspan=\"$group_size\"" if ($group_size > 1);
6904 print $cgi->a({-href
=> href
(action
=>"commit",
6906 file_name
=>$file_name)},
6907 esc_html
($short_rev));
6908 if ($group_size >= 2) {
6909 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6910 if (@author_initials) {
6912 esc_html
(join('', @author_initials));
6918 # 'previous' <sha1 of parent commit> <filename at commit>
6919 if (exists $meta->{'previous'} &&
6920 $meta->{'previous'} =~ /^($oid_regex) (.*)$/) {
6921 $meta->{'parent'} = $1;
6922 $meta->{'file_parent'} = unquote
($2);
6925 exists($meta->{'parent'}) ?
6926 $meta->{'parent'} : $full_rev;
6927 my $linenr_filename =
6928 exists($meta->{'file_parent'}) ?
6929 $meta->{'file_parent'} : unquote
($meta->{'filename'});
6930 my $blamed = href
(action
=> 'blame',
6931 file_name
=> $linenr_filename,
6932 hash_base
=> $linenr_commit);
6933 print "<td class=\"linenr\">";
6934 print $cgi->a({ -href
=> "$blamed#l$orig_lineno",
6935 -class => "linenr" },
6938 print "<td class=\"pre\">" . esc_html
($data) . "</td>\n";
6946 "</table>\n"; # class="blame"
6947 print "</div>\n"; # class="blame_body"
6949 or print "Reading blob failed\n";
6958 sub git_blame_incremental
{
6959 git_blame_common
('incremental');
6962 sub git_blame_data
{
6963 git_blame_common
('data');
6967 my $head = git_get_head_hash
($project);
6969 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('tags'));
6970 git_print_header_div
('summary', $project);
6972 my @tagslist = git_get_tags_list
();
6974 git_tags_body
(\
@tagslist);
6980 my $head = git_get_head_hash
($project);
6982 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('heads'));
6983 git_print_header_div
('summary', $project);
6985 my @headslist = git_get_heads_list
();
6987 git_heads_body
(\
@headslist, $head);
6992 # used both for single remote view and for list of all the remotes
6994 gitweb_check_feature
('remote_heads')
6995 or die_error
(403, "Remote heads view is disabled");
6997 my $head = git_get_head_hash
($project);
6998 my $remote = $input_params{'hash'};
7000 my $remotedata = git_get_remotes_list
($remote);
7001 die_error
(500, "Unable to get remote information") unless defined $remotedata;
7003 unless (%$remotedata) {
7004 die_error
(404, defined $remote ?
7005 "Remote $remote not found" :
7006 "No remotes found");
7009 git_header_html
(undef, undef, -action_extra
=> $remote);
7010 git_print_page_nav
('', '', $head, undef, $head,
7011 format_ref_views
($remote ? '' : 'remotes'));
7013 fill_remote_heads
($remotedata);
7014 if (defined $remote) {
7015 git_print_header_div
('remotes', "$remote remote for $project");
7016 git_remote_block
($remote, $remotedata->{$remote}, undef, $head);
7018 git_print_header_div
('summary', "$project remotes");
7019 git_remotes_body
($remotedata, undef, $head);
7025 sub git_blob_plain
{
7029 if (!defined $hash) {
7030 if (defined $file_name) {
7031 my $base = $hash_base || git_get_head_hash
($project);
7032 $hash = git_get_hash_by_path
($base, $file_name, "blob")
7033 or die_error
(404, "Cannot find file");
7035 die_error
(400, "No file name defined");
7037 } elsif ($hash =~ m/^$oid_regex$/) {
7038 # blobs defined by non-textual hash id's can be cached
7042 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
7043 or die_error
(500, "Open git-cat-file blob '$hash' failed");
7045 # content-type (can include charset)
7046 $type = blob_contenttype
($fd, $file_name, $type);
7048 # "save as" filename, even when no $file_name is given
7049 my $save_as = "$hash";
7050 if (defined $file_name) {
7051 $save_as = $file_name;
7052 } elsif ($type =~ m/^text\//) {
7056 # With XSS prevention on, blobs of all types except a few known safe
7057 # ones are served with "Content-Disposition: attachment" to make sure
7058 # they don't run in our security domain. For certain image types,
7059 # blob view writes an <img> tag referring to blob_plain view, and we
7060 # want to be sure not to break that by serving the image as an
7061 # attachment (though Firefox 3 doesn't seem to care).
7062 my $sandbox = $prevent_xss &&
7063 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7065 # serve text/* as text/plain
7067 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7068 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T
$fd))) {
7070 $rest = defined $rest ? $rest : '';
7071 $type = "text/plain$rest";
7076 -expires
=> $expires,
7077 -content_disposition
=>
7078 ($sandbox ? 'attachment' : 'inline')
7079 . '; filename="' . $save_as . '"');
7081 binmode STDOUT
, ':raw';
7083 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7090 if (!defined $hash) {
7091 if (defined $file_name) {
7092 my $base = $hash_base || git_get_head_hash
($project);
7093 $hash = git_get_hash_by_path
($base, $file_name, "blob")
7094 or die_error
(404, "Cannot find file");
7096 die_error
(400, "No file name defined");
7098 } elsif ($hash =~ m/^$oid_regex$/) {
7099 # blobs defined by non-textual hash id's can be cached
7103 my $have_blame = gitweb_check_feature
('blame');
7104 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
7105 or die_error
(500, "Couldn't cat $file_name, $hash");
7106 my $mimetype = blob_mimetype
($fd, $file_name);
7107 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7108 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B
$fd) {
7110 return git_blob_plain
($mimetype);
7112 # we can have blame only for text/* mimetype
7113 $have_blame &&= ($mimetype =~ m!^text/!);
7115 my $highlight = gitweb_check_feature
('highlight');
7116 my $syntax = guess_file_syntax
($highlight, $file_name);
7117 $fd = run_highlighter
($fd, $highlight, $syntax);
7119 git_header_html
(undef, $expires);
7120 my $formats_nav = '';
7121 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7122 if (defined $file_name) {
7125 $cgi->a({-href
=> href
(action
=>"blame", -replay
=>1)},
7130 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7133 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7136 $cgi->a({-href
=> href
(action
=>"blob",
7137 hash_base
=>"HEAD", file_name
=>$file_name)},
7141 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7144 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7145 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7147 print "<div class=\"page_nav\">\n" .
7148 "<br/><br/></div>\n" .
7149 "<div class=\"title\">".esc_html
($hash)."</div>\n";
7151 git_print_page_path
($file_name, "blob", $hash_base);
7152 print "<div class=\"page_body\">\n";
7153 if ($mimetype =~ m!^image/!) {
7154 print qq
!<img
class="blob" type
="!.esc_attr($mimetype).qq!"!;
7156 print qq
! alt
="!.esc_attr($file_name).qq!" title
="!.esc_attr($file_name).qq!"!;
7159 href(action=>"blob_plain
", hash=>$hash,
7160 hash_base=>$hash_base, file_name=>$file_name) .
7164 while (my $line = <$fd>) {
7167 $line = untabify
($line);
7168 printf qq
!<div
class="pre"><a id
="l%i" href
="%s#l%i" class="linenr">%4i</a> %s</div
>\n!,
7169 $nr, esc_attr
(href
(-replay
=> 1)), $nr, $nr,
7170 $highlight ? sanitize
($line) : esc_html
($line, -nbsp
=>1);
7174 or print "Reading blob failed.\n";
7180 if (!defined $hash_base) {
7181 $hash_base = "HEAD";
7183 if (!defined $hash) {
7184 if (defined $file_name) {
7185 $hash = git_get_hash_by_path
($hash_base, $file_name, "tree");
7190 die_error
(404, "No such tree") unless defined($hash);
7192 my $show_sizes = gitweb_check_feature
('show-sizes');
7193 my $have_blame = gitweb_check_feature
('blame');
7198 open my $fd, "-|", git_cmd
(), "ls-tree", '-z',
7199 ($show_sizes ? '-l' : ()), @extra_options, $hash
7200 or die_error
(500, "Open git-ls-tree failed");
7201 @entries = map { chomp; $_ } <$fd>;
7203 or die_error
(404, "Reading tree failed");
7206 my $refs = git_get_references
();
7207 my $ref = format_ref_marker
($refs, $hash_base);
7210 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7212 if (defined $file_name) {
7214 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7216 $cgi->a({-href
=> href
(action
=>"tree",
7217 hash_base
=>"HEAD", file_name
=>$file_name)},
7220 my $snapshot_links = format_snapshot_links
($hash);
7221 if (defined $snapshot_links) {
7222 # FIXME: Should be available when we have no hash base as well.
7223 push @views_nav, $snapshot_links;
7225 git_print_page_nav
('tree','', $hash_base, undef, undef,
7226 join(' | ', @views_nav));
7227 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash_base);
7230 print "<div class=\"page_nav\">\n";
7231 print "<br/><br/></div>\n";
7232 print "<div class=\"title\">".esc_html
($hash)."</div>\n";
7234 if (defined $file_name) {
7235 $basedir = $file_name;
7236 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7239 git_print_page_path
($file_name, 'tree', $hash_base);
7241 print "<div class=\"page_body\">\n";
7242 print "<table class=\"tree\">\n";
7244 # '..' (top directory) link if possible
7245 if (defined $hash_base &&
7246 defined $file_name && $file_name =~ m![^/]+$!) {
7248 print "<tr class=\"dark\">\n";
7250 print "<tr class=\"light\">\n";
7254 my $up = $file_name;
7255 $up =~ s!/?[^/]+$!!;
7256 undef $up unless $up;
7257 # based on git_print_tree_entry
7258 print '<td class="mode">' . mode_str
('040000') . "</td>\n";
7259 print '<td class="size"> </td>'."\n" if $show_sizes;
7260 print '<td class="list">';
7261 print $cgi->a({-href
=> href
(action
=>"tree",
7262 hash_base
=>$hash_base,
7266 print "<td class=\"link\"></td>\n";
7270 foreach my $line (@entries) {
7271 my %t = parse_ls_tree_line
($line, -z
=> 1, -l
=> $show_sizes);
7274 print "<tr class=\"dark\">\n";
7276 print "<tr class=\"light\">\n";
7280 git_print_tree_entry
(\
%t, $basedir, $hash_base, $have_blame);
7284 print "</table>\n" .
7289 sub sanitize_for_filename
{
7293 $name =~ s/[^[:alnum:]_.-]//g;
7299 my ($project, $hash) = @_;
7301 # path/to/project.git -> project
7302 # path/to/project/.git -> project
7303 my $name = to_utf8
($project);
7304 $name =~ s
,([^/])/*\
.git
$,$1,;
7305 $name = sanitize_for_filename
(basename
($name));
7308 if ($hash =~ /^[0-9a-fA-F]+$/) {
7309 # shorten SHA-1 hash
7310 my $full_hash = git_get_full_hash
($project, $hash);
7311 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7312 $ver = git_get_short_hash
($project, $hash);
7314 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7315 # tags don't need shortened SHA-1 hash
7318 # branches and other need shortened SHA-1 hash
7319 my $strip_refs = join '|', map { quotemeta } get_branch_refs
();
7320 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7321 my $ref_dir = (defined $1) ? $1 : '';
7324 $ref_dir = sanitize_for_filename
($ref_dir);
7325 # for refs neither in heads nor remotes we want to
7326 # add a ref dir to archive name
7327 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7328 $ver = $ref_dir . '-' . $ver;
7331 $ver .= '-' . git_get_short_hash
($project, $hash);
7333 # special case of sanitization for filename - we change
7334 # slashes to dots instead of dashes
7335 # in case of hierarchical branch names
7337 $ver =~ s/[^[:alnum:]_.-]//g;
7339 # name = project-version_string
7340 $name = "$name-$ver";
7342 return wantarray ? ($name, $name) : $name;
7345 sub exit_if_unmodified_since
{
7346 my ($latest_epoch) = @_;
7349 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7350 if (defined $if_modified) {
7352 if (eval { require HTTP
::Date
; 1; }) {
7353 $since = HTTP
::Date
::str2time
($if_modified);
7354 } elsif (eval { require Time
::ParseDate
; 1; }) {
7355 $since = Time
::ParseDate
::parsedate
($if_modified, GMT
=> 1);
7357 if (defined $since && $latest_epoch <= $since) {
7358 my %latest_date = parse_date
($latest_epoch);
7360 -last_modified
=> $latest_date{'rfc2822'},
7361 -status
=> '304 Not Modified');
7368 my $format = $input_params{'snapshot_format'};
7369 if (!@snapshot_fmts) {
7370 die_error
(403, "Snapshots not allowed");
7372 # default to first supported snapshot format
7373 $format ||= $snapshot_fmts[0];
7374 if ($format !~ m/^[a-z0-9]+$/) {
7375 die_error
(400, "Invalid snapshot format parameter");
7376 } elsif (!exists($known_snapshot_formats{$format})) {
7377 die_error
(400, "Unknown snapshot format");
7378 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7379 die_error
(403, "Snapshot format not allowed");
7380 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7381 die_error
(403, "Unsupported snapshot format");
7384 my $type = git_get_type
("$hash^{}");
7386 die_error
(404, 'Object does not exist');
7387 } elsif ($type eq 'blob') {
7388 die_error
(400, 'Object is not a tree-ish');
7391 my ($name, $prefix) = snapshot_name
($project, $hash);
7392 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7394 my %co = parse_commit
($hash);
7395 exit_if_unmodified_since
($co{'committer_epoch'}) if %co;
7397 my $cmd = quote_command
(
7398 git_cmd
(), 'archive',
7399 "--format=$known_snapshot_formats{$format}{'format'}",
7400 "--prefix=$prefix/", $hash);
7401 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7402 $cmd .= ' | ' . quote_command
(@{$known_snapshot_formats{$format}{'compressor'}});
7405 $filename =~ s/(["\\])/\\$1/g;
7408 %latest_date = parse_date
($co{'committer_epoch'}, $co{'committer_tz'});
7412 -type
=> $known_snapshot_formats{$format}{'type'},
7413 -content_disposition
=> 'inline; filename="' . $filename . '"',
7414 %co ? (-last_modified
=> $latest_date{'rfc2822'}) : (),
7415 -status
=> '200 OK');
7417 open my $fd, "-|", $cmd
7418 or die_error
(500, "Execute git-archive failed");
7419 binmode STDOUT
, ':raw';
7421 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7425 sub git_log_generic
{
7426 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7428 my $head = git_get_head_hash
($project);
7429 if (!defined $base) {
7432 if (!defined $page) {
7435 my $refs = git_get_references
();
7437 my $commit_hash = $base;
7438 if (defined $parent) {
7439 $commit_hash = "$parent..$base";
7442 parse_commits
($commit_hash, 101, (100 * $page),
7443 defined $file_name ? ($file_name, "--full-history") : ());
7446 if (!defined $file_hash && defined $file_name) {
7447 # some commits could have deleted file in question,
7448 # and not have it in tree, but one of them has to have it
7449 for (my $i = 0; $i < @commitlist; $i++) {
7450 $file_hash = git_get_hash_by_path
($commitlist[$i]{'id'}, $file_name);
7451 last if defined $file_hash;
7454 if (defined $file_hash) {
7455 $ftype = git_get_type
($file_hash);
7457 if (defined $file_name && !defined $ftype) {
7458 die_error
(500, "Unknown type of object");
7461 if (defined $file_name) {
7462 %co = parse_commit
($base)
7463 or die_error
(404, "Unknown commit object");
7467 my $paging_nav = format_paging_nav
($fmt_name, $page, $#commitlist >= 100);
7469 if ($#commitlist >= 100) {
7471 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
7472 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
7474 my $patch_max = gitweb_get_feature
('patches');
7475 if ($patch_max && !defined $file_name) {
7476 if ($patch_max < 0 || @commitlist <= $patch_max) {
7477 $paging_nav .= " ⋅ " .
7478 $cgi->a({-href
=> href
(action
=>"patches", -replay
=>1)},
7484 git_print_page_nav
($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7485 if (defined $file_name) {
7486 git_print_header_div
('commit', esc_html
($co{'title'}), $base);
7488 git_print_header_div
('summary', $project)
7490 git_print_page_path
($file_name, $ftype, $hash_base)
7491 if (defined $file_name);
7493 $body_subr->(\
@commitlist, 0, 99, $refs, $next_link,
7494 $file_name, $file_hash, $ftype);
7500 git_log_generic
('log', \
&git_log_body
,
7501 $hash, $hash_parent);
7505 $hash ||= $hash_base || "HEAD";
7506 my %co = parse_commit
($hash)
7507 or die_error
(404, "Unknown commit object");
7509 my $parent = $co{'parent'};
7510 my $parents = $co{'parents'}; # listref
7512 # we need to prepare $formats_nav before any parameter munging
7514 if (!defined $parent) {
7516 $formats_nav .= '(initial)';
7517 } elsif (@$parents == 1) {
7518 # single parent commit
7521 $cgi->a({-href
=> href
(action
=>"commit",
7523 esc_html
(substr($parent, 0, 7))) .
7530 $cgi->a({-href
=> href
(action
=>"commit",
7532 esc_html
(substr($_, 0, 7)));
7536 if (gitweb_check_feature
('patches') && @$parents <= 1) {
7537 $formats_nav .= " | " .
7538 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7542 if (!defined $parent) {
7546 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', "--no-commit-id",
7548 (@$parents <= 1 ? $parent : '-c'),
7550 or die_error
(500, "Open git-diff-tree failed");
7551 @difftree = map { chomp; $_ } <$fd>;
7552 close $fd or die_error
(404, "Reading git-diff-tree failed");
7554 # non-textual hash id's can be cached
7556 if ($hash =~ m/^$oid_regex$/) {
7559 my $refs = git_get_references
();
7560 my $ref = format_ref_marker
($refs, $co{'id'});
7562 git_header_html
(undef, $expires);
7563 git_print_page_nav
('commit', '',
7564 $hash, $co{'tree'}, $hash,
7567 if (defined $co{'parent'}) {
7568 git_print_header_div
('commitdiff', esc_html
($co{'title'}) . $ref, $hash);
7570 git_print_header_div
('tree', esc_html
($co{'title'}) . $ref, $co{'tree'}, $hash);
7572 print "<div class=\"title_text\">\n" .
7573 "<table class=\"object_header\">\n";
7574 git_print_authorship_rows
(\
%co);
7575 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7578 "<td class=\"sha1\">" .
7579 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash),
7580 class => "list"}, $co{'tree'}) .
7582 "<td class=\"link\">" .
7583 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash)},
7585 my $snapshot_links = format_snapshot_links
($hash);
7586 if (defined $snapshot_links) {
7587 print " | " . $snapshot_links;
7592 foreach my $par (@$parents) {
7595 "<td class=\"sha1\">" .
7596 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par),
7597 class => "list"}, $par) .
7599 "<td class=\"link\">" .
7600 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par)}, "commit") .
7602 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$hash, hash_parent
=>$par)}, "diff") .
7609 print "<div class=\"page_body\">\n";
7610 git_print_log
($co{'comment'});
7613 git_difftree_body
(\
@difftree, $hash, @$parents);
7619 # object is defined by:
7620 # - hash or hash_base alone
7621 # - hash_base and file_name
7624 # - hash or hash_base alone
7625 if ($hash || ($hash_base && !defined $file_name)) {
7626 my $object_id = $hash || $hash_base;
7628 open my $fd, "-|", quote_command
(
7629 git_cmd
(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7630 or die_error
(404, "Object does not exist");
7632 defined $type && chomp $type;
7634 or die_error
(404, "Object does not exist");
7636 # - hash_base and file_name
7637 } elsif ($hash_base && defined $file_name) {
7638 $file_name =~ s
,/+$,,;
7640 system(git_cmd
(), "cat-file", '-e', $hash_base) == 0
7641 or die_error
(404, "Base object does not exist");
7643 # here errors should not happen
7644 open my $fd, "-|", git_cmd
(), "ls-tree", $hash_base, "--", $file_name
7645 or die_error
(500, "Open git-ls-tree failed");
7649 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7650 unless ($line && $line =~ m/^([0-9]+) (.+) ($oid_regex)\t/) {
7651 die_error
(404, "File or directory for given base does not exist");
7656 die_error
(400, "Not enough information to find object");
7659 print $cgi->redirect(-uri
=> href
(action
=>$type, -full
=>1,
7660 hash
=>$hash, hash_base
=>$hash_base,
7661 file_name
=>$file_name),
7662 -status
=> '302 Found');
7666 my $format = shift || 'html';
7667 my $diff_style = $input_params{'diff_style'} || 'inline';
7674 # preparing $fd and %diffinfo for git_patchset_body
7676 if (defined $hash_base && defined $hash_parent_base) {
7677 if (defined $file_name) {
7679 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7680 $hash_parent_base, $hash_base,
7681 "--", (defined $file_parent ? $file_parent : ()), $file_name
7682 or die_error
(500, "Open git-diff-tree failed");
7683 @difftree = map { chomp; $_ } <$fd>;
7685 or die_error
(404, "Reading git-diff-tree failed");
7687 or die_error
(404, "Blob diff not found");
7689 } elsif (defined $hash &&
7690 $hash =~ $oid_regex) {
7691 # try to find filename from $hash
7693 # read filtered raw output
7694 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7695 $hash_parent_base, $hash_base, "--"
7696 or die_error
(500, "Open git-diff-tree failed");
7698 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7700 grep { /^:[0-7]{6} [0-7]{6} $oid_regex $hash/ }
7701 map { chomp; $_ } <$fd>;
7703 or die_error
(404, "Reading git-diff-tree failed");
7705 or die_error
(404, "Blob diff not found");
7708 die_error
(400, "Missing one of the blob diff parameters");
7711 if (@difftree > 1) {
7712 die_error
(400, "Ambiguous blob diff specification");
7715 %diffinfo = parse_difftree_raw_line
($difftree[0]);
7716 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7717 $file_name ||= $diffinfo{'to_file'};
7719 $hash_parent ||= $diffinfo{'from_id'};
7720 $hash ||= $diffinfo{'to_id'};
7722 # non-textual hash id's can be cached
7723 if ($hash_base =~ m/^$oid_regex$/ &&
7724 $hash_parent_base =~ m/^$oid_regex$/) {
7729 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7730 '-p', ($format eq 'html' ? "--full-index" : ()),
7731 $hash_parent_base, $hash_base,
7732 "--", (defined $file_parent ? $file_parent : ()), $file_name
7733 or die_error
(500, "Open git-diff-tree failed");
7736 # old/legacy style URI -- not generated anymore since 1.4.3.
7738 die_error
('404 Not Found', "Missing one of the blob diff parameters")
7742 if ($format eq 'html') {
7744 $cgi->a({-href
=> href
(action
=>"blobdiff_plain", -replay
=>1)},
7746 $formats_nav .= diff_style_nav
($diff_style);
7747 git_header_html
(undef, $expires);
7748 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7749 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7750 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7752 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7753 print "<div class=\"title\">".esc_html
("$hash vs $hash_parent")."</div>\n";
7755 if (defined $file_name) {
7756 git_print_page_path
($file_name, "blob", $hash_base);
7758 print "<div class=\"page_path\"></div>\n";
7761 } elsif ($format eq 'plain') {
7763 -type
=> 'text/plain',
7764 -charset
=> 'utf-8',
7765 -expires
=> $expires,
7766 -content_disposition
=> 'inline; filename="' . "$file_name" . '.patch"');
7768 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7771 die_error
(400, "Unknown blobdiff format");
7775 if ($format eq 'html') {
7776 print "<div class=\"page_body\">\n";
7778 git_patchset_body
($fd, $diff_style,
7779 [ \
%diffinfo ], $hash_base, $hash_parent_base);
7782 print "</div>\n"; # class="page_body"
7786 while (my $line = <$fd>) {
7787 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7788 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7792 last if $line =~ m!^\+\+\+!;
7800 sub git_blobdiff_plain
{
7801 git_blobdiff
('plain');
7804 # assumes that it is added as later part of already existing navigation,
7805 # so it returns "| foo | bar" rather than just "foo | bar"
7806 sub diff_style_nav
{
7807 my ($diff_style, $is_combined) = @_;
7808 $diff_style ||= 'inline';
7810 return "" if ($is_combined);
7812 my @styles = (inline
=> 'inline', 'sidebyside' => 'side by side');
7813 my %styles = @styles;
7815 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7820 $_ eq $diff_style ? $styles{$_} :
7821 $cgi->a({-href
=> href
(-replay
=>1, diff_style
=> $_)}, $styles{$_})
7825 sub git_commitdiff
{
7827 my $format = $params{-format
} || 'html';
7828 my $diff_style = $input_params{'diff_style'} || 'inline';
7830 my ($patch_max) = gitweb_get_feature
('patches');
7831 if ($format eq 'patch') {
7832 die_error
(403, "Patch view not allowed") unless $patch_max;
7835 $hash ||= $hash_base || "HEAD";
7836 my %co = parse_commit
($hash)
7837 or die_error
(404, "Unknown commit object");
7839 # choose format for commitdiff for merge
7840 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7841 $hash_parent = '--cc';
7843 # we need to prepare $formats_nav before almost any parameter munging
7845 if ($format eq 'html') {
7847 $cgi->a({-href
=> href
(action
=>"commitdiff_plain", -replay
=>1)},
7849 if ($patch_max && @{$co{'parents'}} <= 1) {
7850 $formats_nav .= " | " .
7851 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7854 $formats_nav .= diff_style_nav
($diff_style, @{$co{'parents'}} > 1);
7856 if (defined $hash_parent &&
7857 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7858 # commitdiff with two commits given
7859 my $hash_parent_short = $hash_parent;
7860 if ($hash_parent =~ m/^$oid_regex$/) {
7861 $hash_parent_short = substr($hash_parent, 0, 7);
7865 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7866 if ($co{'parents'}[$i] eq $hash_parent) {
7867 $formats_nav .= ' parent ' . ($i+1);
7871 $formats_nav .= ': ' .
7872 $cgi->a({-href
=> href
(-replay
=>1,
7873 hash
=>$hash_parent, hash_base
=>undef)},
7874 esc_html
($hash_parent_short)) .
7876 } elsif (!$co{'parent'}) {
7878 $formats_nav .= ' (initial)';
7879 } elsif (scalar @{$co{'parents'}} == 1) {
7880 # single parent commit
7883 $cgi->a({-href
=> href
(-replay
=>1,
7884 hash
=>$co{'parent'}, hash_base
=>undef)},
7885 esc_html
(substr($co{'parent'}, 0, 7))) .
7889 if ($hash_parent eq '--cc') {
7890 $formats_nav .= ' | ' .
7891 $cgi->a({-href
=> href
(-replay
=>1,
7892 hash
=>$hash, hash_parent
=>'-c')},
7894 } else { # $hash_parent eq '-c'
7895 $formats_nav .= ' | ' .
7896 $cgi->a({-href
=> href
(-replay
=>1,
7897 hash
=>$hash, hash_parent
=>'--cc')},
7903 $cgi->a({-href
=> href
(-replay
=>1,
7904 hash
=>$_, hash_base
=>undef)},
7905 esc_html
(substr($_, 0, 7)));
7906 } @{$co{'parents'}} ) .
7911 my $hash_parent_param = $hash_parent;
7912 if (!defined $hash_parent_param) {
7913 # --cc for multiple parents, --root for parentless
7914 $hash_parent_param =
7915 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7921 if ($format eq 'html') {
7922 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7923 "--no-commit-id", "--patch-with-raw", "--full-index",
7924 $hash_parent_param, $hash, "--"
7925 or die_error
(500, "Open git-diff-tree failed");
7927 while (my $line = <$fd>) {
7929 # empty line ends raw part of diff-tree output
7931 push @difftree, scalar parse_difftree_raw_line
($line);
7934 } elsif ($format eq 'plain') {
7935 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7936 '-p', $hash_parent_param, $hash, "--"
7937 or die_error
(500, "Open git-diff-tree failed");
7938 } elsif ($format eq 'patch') {
7939 # For commit ranges, we limit the output to the number of
7940 # patches specified in the 'patches' feature.
7941 # For single commits, we limit the output to a single patch,
7942 # diverging from the git-format-patch default.
7943 my @commit_spec = ();
7945 if ($patch_max > 0) {
7946 push @commit_spec, "-$patch_max";
7948 push @commit_spec, '-n', "$hash_parent..$hash";
7950 if ($params{-single
}) {
7951 push @commit_spec, '-1';
7953 if ($patch_max > 0) {
7954 push @commit_spec, "-$patch_max";
7956 push @commit_spec, "-n";
7958 push @commit_spec, '--root', $hash;
7960 open $fd, "-|", git_cmd
(), "format-patch", @diff_opts,
7961 '--encoding=utf8', '--stdout', @commit_spec
7962 or die_error
(500, "Open git-format-patch failed");
7964 die_error
(400, "Unknown commitdiff format");
7967 # non-textual hash id's can be cached
7969 if ($hash =~ m/^$oid_regex$/) {
7973 # write commit message
7974 if ($format eq 'html') {
7975 my $refs = git_get_references
();
7976 my $ref = format_ref_marker
($refs, $co{'id'});
7978 git_header_html
(undef, $expires);
7979 git_print_page_nav
('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7980 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash);
7981 print "<div class=\"title_text\">\n" .
7982 "<table class=\"object_header\">\n";
7983 git_print_authorship_rows
(\
%co);
7986 print "<div class=\"page_body\">\n";
7987 if (@{$co{'comment'}} > 1) {
7988 print "<div class=\"log\">\n";
7989 git_print_log
($co{'comment'}, -final_empty_line
=> 1, -remove_title
=> 1);
7990 print "</div>\n"; # class="log"
7993 } elsif ($format eq 'plain') {
7994 my $refs = git_get_references
("tags");
7995 my $tagname = git_get_rev_name_tags
($hash);
7996 my $filename = basename
($project) . "-$hash.patch";
7999 -type
=> 'text/plain',
8000 -charset
=> 'utf-8',
8001 -expires
=> $expires,
8002 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
8003 my %ad = parse_date
($co{'author_epoch'}, $co{'author_tz'});
8004 print "From: " . to_utf8
($co{'author'}) . "\n";
8005 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8006 print "Subject: " . to_utf8
($co{'title'}) . "\n";
8008 print "X-Git-Tag: $tagname\n" if $tagname;
8009 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8011 foreach my $line (@{$co{'comment'}}) {
8012 print to_utf8
($line) . "\n";
8015 } elsif ($format eq 'patch') {
8016 my $filename = basename
($project) . "-$hash.patch";
8019 -type
=> 'text/plain',
8020 -charset
=> 'utf-8',
8021 -expires
=> $expires,
8022 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
8026 if ($format eq 'html') {
8027 my $use_parents = !defined $hash_parent ||
8028 $hash_parent eq '-c' || $hash_parent eq '--cc';
8029 git_difftree_body
(\
@difftree, $hash,
8030 $use_parents ? @{$co{'parents'}} : $hash_parent);
8033 git_patchset_body
($fd, $diff_style,
8035 $use_parents ? @{$co{'parents'}} : $hash_parent);
8037 print "</div>\n"; # class="page_body"
8040 } elsif ($format eq 'plain') {
8044 or print "Reading git-diff-tree failed\n";
8045 } elsif ($format eq 'patch') {
8049 or print "Reading git-format-patch failed\n";
8053 sub git_commitdiff_plain
{
8054 git_commitdiff
(-format
=> 'plain');
8057 # format-patch-style patches
8059 git_commitdiff
(-format
=> 'patch', -single
=> 1);
8063 git_commitdiff
(-format
=> 'patch');
8067 git_log_generic
('history', \
&git_history_body
,
8068 $hash_base, $hash_parent_base,
8073 $searchtype ||= 'commit';
8075 # check if appropriate features are enabled
8076 gitweb_check_feature
('search')
8077 or die_error
(403, "Search is disabled");
8078 if ($searchtype eq 'pickaxe') {
8079 # pickaxe may take all resources of your box and run for several minutes
8080 # with every query - so decide by yourself how public you make this feature
8081 gitweb_check_feature
('pickaxe')
8082 or die_error
(403, "Pickaxe search is disabled");
8084 if ($searchtype eq 'grep') {
8085 # grep search might be potentially CPU-intensive, too
8086 gitweb_check_feature
('grep')
8087 or die_error
(403, "Grep search is disabled");
8090 if (!defined $searchtext) {
8091 die_error
(400, "Text field is empty");
8093 if (!defined $hash) {
8094 $hash = git_get_head_hash
($project);
8096 my %co = parse_commit
($hash);
8098 die_error
(404, "Unknown commit object");
8100 if (!defined $page) {
8104 if ($searchtype eq 'commit' ||
8105 $searchtype eq 'author' ||
8106 $searchtype eq 'committer') {
8107 git_search_message
(%co);
8108 } elsif ($searchtype eq 'pickaxe') {
8109 git_search_changes
(%co);
8110 } elsif ($searchtype eq 'grep') {
8111 git_search_files
(%co);
8113 die_error
(400, "Unknown search type");
8117 sub git_search_help
{
8119 git_print_page_nav
('','', $hash,$hash,$hash);
8121 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8122 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8123 the pattern entered is recognized as the POSIX extended
8124 <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8127 <dt><b>commit</b></dt>
8128 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8130 my $have_grep = gitweb_check_feature
('grep');
8133 <dt><b>grep</b></dt>
8134 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8135 a different one) are searched for the given pattern. On large trees, this search can take
8136 a while and put some strain on the server, so please use it with some consideration. Note that
8137 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8138 case-sensitive.</dd>
8142 <dt><b>author</b></dt>
8143 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8144 <dt><b>committer</b></dt>
8145 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8147 my $have_pickaxe = gitweb_check_feature
('pickaxe');
8148 if ($have_pickaxe) {
8150 <dt><b>pickaxe</b></dt>
8151 <dd>All commits that caused the string to appear or disappear from any file (changes that
8152 added, removed or "modified" the string) will be listed. This search can take a while and
8153 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8154 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8162 git_log_generic
('shortlog', \
&git_shortlog_body
,
8163 $hash, $hash_parent);
8166 ## ......................................................................
8167 ## feeds (RSS, Atom; OPML)
8170 my $format = shift || 'atom';
8171 my $have_blame = gitweb_check_feature
('blame');
8173 # Atom: http://www.atomenabled.org/developers/syndication/
8174 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8175 if ($format ne 'rss' && $format ne 'atom') {
8176 die_error
(400, "Unknown web feed format");
8179 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8180 my $head = $hash || 'HEAD';
8181 my @commitlist = parse_commits
($head, 150, 0, $file_name);
8185 my $content_type = "application/$format+xml";
8186 if (defined $cgi->http('HTTP_ACCEPT') &&
8187 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8188 # browser (feed reader) prefers text/xml
8189 $content_type = 'text/xml';
8191 if (defined($commitlist[0])) {
8192 %latest_commit = %{$commitlist[0]};
8193 my $latest_epoch = $latest_commit{'committer_epoch'};
8194 exit_if_unmodified_since
($latest_epoch);
8195 %latest_date = parse_date
($latest_epoch, $latest_commit{'committer_tz'});
8198 -type
=> $content_type,
8199 -charset
=> 'utf-8',
8200 %latest_date ? (-last_modified
=> $latest_date{'rfc2822'}) : (),
8201 -status
=> '200 OK');
8203 # Optimization: skip generating the body if client asks only
8204 # for Last-Modified date.
8205 return if ($cgi->request_method() eq 'HEAD');
8208 my $title = "$site_name - $project/$action";
8209 my $feed_type = 'log';
8210 if (defined $hash) {
8211 $title .= " - '$hash'";
8212 $feed_type = 'branch log';
8213 if (defined $file_name) {
8214 $title .= " :: $file_name";
8215 $feed_type = 'history';
8217 } elsif (defined $file_name) {
8218 $title .= " - $file_name";
8219 $feed_type = 'history';
8221 $title .= " $feed_type";
8222 $title = esc_html
($title);
8223 my $descr = git_get_project_description
($project);
8224 if (defined $descr) {
8225 $descr = esc_html
($descr);
8227 $descr = "$project " .
8228 ($format eq 'rss' ? 'RSS' : 'Atom') .
8231 my $owner = git_get_project_owner
($project);
8232 $owner = esc_html
($owner);
8236 if (defined $file_name) {
8237 $alt_url = href
(-full
=>1, action
=>"history", hash
=>$hash, file_name
=>$file_name);
8238 } elsif (defined $hash) {
8239 $alt_url = href
(-full
=>1, action
=>"log", hash
=>$hash);
8241 $alt_url = href
(-full
=>1, action
=>"summary");
8243 print qq
!<?xml version
="1.0" encoding
="utf-8"?>\n!;
8244 if ($format eq 'rss') {
8246 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8249 print "<title>$title</title>\n" .
8250 "<link>$alt_url</link>\n" .
8251 "<description>$descr</description>\n" .
8252 "<language>en</language>\n" .
8253 # project owner is responsible for 'editorial' content
8254 "<managingEditor>$owner</managingEditor>\n";
8255 if (defined $logo || defined $favicon) {
8256 # prefer the logo to the favicon, since RSS
8257 # doesn't allow both
8258 my $img = esc_url
($logo || $favicon);
8260 "<url>$img</url>\n" .
8261 "<title>$title</title>\n" .
8262 "<link>$alt_url</link>\n" .
8266 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8267 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8269 print "<generator>gitweb v.$version/$git_version</generator>\n";
8270 } elsif ($format eq 'atom') {
8272 <feed xmlns="http://www.w3.org/2005/Atom">
8274 print "<title>$title</title>\n" .
8275 "<subtitle>$descr</subtitle>\n" .
8276 '<link rel="alternate" type="text/html" href="' .
8277 $alt_url . '" />' . "\n" .
8278 '<link rel="self" type="' . $content_type . '" href="' .
8279 $cgi->self_url() . '" />' . "\n" .
8280 "<id>" . href
(-full
=>1) . "</id>\n" .
8281 # use project owner for feed author
8282 "<author><name>$owner</name></author>\n";
8283 if (defined $favicon) {
8284 print "<icon>" . esc_url
($favicon) . "</icon>\n";
8286 if (defined $logo) {
8287 # not twice as wide as tall: 72 x 27 pixels
8288 print "<logo>" . esc_url
($logo) . "</logo>\n";
8290 if (! %latest_date) {
8291 # dummy date to keep the feed valid until commits trickle in:
8292 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8294 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8296 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8300 for (my $i = 0; $i <= $#commitlist; $i++) {
8301 my %co = %{$commitlist[$i]};
8302 my $commit = $co{'id'};
8303 # we read 150, we always show 30 and the ones more recent than 48 hours
8304 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8307 my %cd = parse_date
($co{'author_epoch'}, $co{'author_tz'});
8309 # get list of changed files
8310 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
8311 $co{'parent'} || "--root",
8312 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8314 my @difftree = map { chomp; $_ } <$fd>;
8318 # print element (entry, item)
8319 my $co_url = href
(-full
=>1, action
=>"commitdiff", hash
=>$commit);
8320 if ($format eq 'rss') {
8322 "<title>" . esc_html
($co{'title'}) . "</title>\n" .
8323 "<author>" . esc_html
($co{'author'}) . "</author>\n" .
8324 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8325 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8326 "<link>$co_url</link>\n" .
8327 "<description>" . esc_html
($co{'title'}) . "</description>\n" .
8328 "<content:encoded>" .
8330 } elsif ($format eq 'atom') {
8332 "<title type=\"html\">" . esc_html
($co{'title'}) . "</title>\n" .
8333 "<updated>$cd{'iso-8601'}</updated>\n" .
8335 " <name>" . esc_html
($co{'author_name'}) . "</name>\n";
8336 if ($co{'author_email'}) {
8337 print " <email>" . esc_html
($co{'author_email'}) . "</email>\n";
8339 print "</author>\n" .
8340 # use committer for contributor
8342 " <name>" . esc_html
($co{'committer_name'}) . "</name>\n";
8343 if ($co{'committer_email'}) {
8344 print " <email>" . esc_html
($co{'committer_email'}) . "</email>\n";
8346 print "</contributor>\n" .
8347 "<published>$cd{'iso-8601'}</published>\n" .
8348 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8349 "<id>$co_url</id>\n" .
8350 "<content type=\"xhtml\" xml:base=\"" . esc_url
($my_url) . "\">\n" .
8351 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8353 my $comment = $co{'comment'};
8355 foreach my $line (@$comment) {
8356 $line = esc_html
($line);
8359 print "</pre><ul>\n";
8360 foreach my $difftree_line (@difftree) {
8361 my %difftree = parse_difftree_raw_line
($difftree_line);
8362 next if !$difftree{'from_id'};
8364 my $file = $difftree{'file'} || $difftree{'to_file'};
8368 $cgi->a({-href
=> href
(-full
=>1, action
=>"blobdiff",
8369 hash
=>$difftree{'to_id'}, hash_parent
=>$difftree{'from_id'},
8370 hash_base
=>$co{'id'}, hash_parent_base
=>$co{'parent'},
8371 file_name
=>$file, file_parent
=>$difftree{'from_file'}),
8372 -title
=> "diff"}, 'D');
8374 print $cgi->a({-href
=> href
(-full
=>1, action
=>"blame",
8375 file_name
=>$file, hash_base
=>$commit),
8376 -title
=> "blame"}, 'B');
8378 # if this is not a feed of a file history
8379 if (!defined $file_name || $file_name ne $file) {
8380 print $cgi->a({-href
=> href
(-full
=>1, action
=>"history",
8381 file_name
=>$file, hash
=>$commit),
8382 -title
=> "history"}, 'H');
8384 $file = esc_path
($file);
8388 if ($format eq 'rss') {
8389 print "</ul>]]>\n" .
8390 "</content:encoded>\n" .
8392 } elsif ($format eq 'atom') {
8393 print "</ul>\n</div>\n" .
8400 if ($format eq 'rss') {
8401 print "</channel>\n</rss>\n";
8402 } elsif ($format eq 'atom') {
8416 my @list = git_get_projects_list
($project_filter, $strict_export);
8418 die_error
(404, "No projects found");
8422 -type
=> 'text/xml',
8423 -charset
=> 'utf-8',
8424 -content_disposition
=> 'inline; filename="opml.xml"');
8426 my $title = esc_html
($site_name);
8427 my $filter = " within subdirectory ";
8428 if (defined $project_filter) {
8429 $filter .= esc_html
($project_filter);
8434 <?xml version="1.0" encoding="utf-8"?>
8435 <opml version="1.0">
8437 <title>$title OPML Export$filter</title>
8440 <outline text="git RSS feeds">
8443 foreach my $pr (@list) {
8445 my $head = git_get_head_hash
($proj{'path'});
8446 if (!defined $head) {
8449 $git_dir = "$projectroot/$proj{'path'}";
8450 my %co = parse_commit
($head);
8455 my $path = esc_html
(chop_str
($proj{'path'}, 25, 5));
8456 my $rss = href
('project' => $proj{'path'}, 'action' => 'rss', -full
=> 1);
8457 my $html = href
('project' => $proj{'path'}, 'action' => 'summary', -full
=> 1);
8458 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";