3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
13 use CGI
qw(:standard :escapeHTML -nosticky);
14 use CGI
::Util
qw(unescape);
15 use CGI
::Carp
qw(fatalsToBrowser set_message);
19 use File
::Basename
qw(basename);
20 use Time
::HiRes
qw(gettimeofday tv_interval);
21 binmode STDOUT
, ':utf8';
23 if (!defined($CGI::VERSION
) || $CGI::VERSION
< 4.08) {
24 eval 'sub CGI::multi_param { CGI::param(@_) }'
27 our $t0 = [ gettimeofday
() ];
28 our $number_of_git_cmds = 0;
31 CGI
->compile() if $ENV{'MOD_PERL'};
34 our $version = "++GIT_VERSION++";
36 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
40 our $my_url = $cgi->url();
41 our $my_uri = $cgi->url(-absolute
=> 1);
43 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
44 # needed and used only for URLs with nonempty PATH_INFO
45 our $base_url = $my_url;
47 # When the script is used as DirectoryIndex, the URL does not contain the name
48 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
49 # have to do it ourselves. We make $path_info global because it's also used
52 # Another issue with the script being the DirectoryIndex is that the resulting
53 # $my_url data is not the full script URL: this is good, because we want
54 # generated links to keep implying the script name if it wasn't explicitly
55 # indicated in the URL we're handling, but it means that $my_url cannot be used
57 # Therefore, if we needed to strip PATH_INFO, then we know that we have
58 # to build the base URL ourselves:
59 our $path_info = decode_utf8
($ENV{"PATH_INFO"});
61 # $path_info has already been URL-decoded by the web server, but
62 # $my_url and $my_uri have not. URL-decode them so we can properly
64 $my_url = unescape
($my_url);
65 $my_uri = unescape
($my_uri);
66 if ($my_url =~ s
,\Q
$path_info\E
$,, &&
67 $my_uri =~ s
,\Q
$path_info\E
$,, &&
68 defined $ENV{'SCRIPT_NAME'}) {
69 $base_url = $cgi->url(-base
=> 1) . $ENV{'SCRIPT_NAME'};
73 # target of the home link on top of all pages
74 our $home_link = $my_uri || "/";
77 # core git executable to use
78 # this can just be "git" if your webserver has a sensible PATH
79 our $GIT = "++GIT_BINDIR++/git";
81 # absolute fs-path which will be prepended to the project path
82 #our $projectroot = "/pub/scm";
83 our $projectroot = "++GITWEB_PROJECTROOT++";
85 # fs traversing limit for getting project list
86 # the number is relative to the projectroot
87 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
89 # string of the home link on top of all pages
90 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
92 # extra breadcrumbs preceding the home link
93 our @extra_breadcrumbs = ();
95 # name of your site or organization to appear in page titles
96 # replace this with something more descriptive for clearer bookmarks
97 our $site_name = "++GITWEB_SITENAME++"
98 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
100 # html snippet to include in the <head> section of each page
101 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
102 # filename of html text to include at top of each page
103 our $site_header = "++GITWEB_SITE_HEADER++";
104 # html text to include at home page
105 our $home_text = "++GITWEB_HOMETEXT++";
106 # filename of html text to include at bottom of each page
107 our $site_footer = "++GITWEB_SITE_FOOTER++";
110 our @stylesheets = ("++GITWEB_CSS++");
111 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
112 our $stylesheet = undef;
113 # URI of GIT logo (72x27 size)
114 our $logo = "++GITWEB_LOGO++";
115 # URI of GIT favicon, assumed to be image/png type
116 our $favicon = "++GITWEB_FAVICON++";
117 # URI of gitweb.js (JavaScript code for gitweb)
118 our $javascript = "++GITWEB_JS++";
120 # URI and label (title) of GIT logo link
121 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
122 #our $logo_label = "git documentation";
123 our $logo_url = "http://git-scm.com/";
124 our $logo_label = "git homepage";
126 # source of projects list
127 our $projects_list = "++GITWEB_LIST++";
129 # the width (in characters) of the projects list "Description" column
130 our $projects_list_description_width = 25;
132 # group projects by category on the projects list
133 # (enabled if this variable evaluates to true)
134 our $projects_list_group_categories = 0;
136 # default category if none specified
137 # (leave the empty string for no category)
138 our $project_list_default_category = "";
140 # default order of projects list
141 # valid values are none, project, descr, owner, and age
142 our $default_projects_order = "project";
144 # show repository only if this file exists
145 # (only effective if this variable evaluates to true)
146 our $export_ok = "++GITWEB_EXPORT_OK++";
148 # don't generate age column on the projects list page
149 our $omit_age_column = 0;
151 # don't generate information about owners of repositories
154 # show repository only if this subroutine returns true
155 # when given the path to the project, for example:
156 # sub { return -e "$_[0]/git-daemon-export-ok"; }
157 our $export_auth_hook = undef;
159 # only allow viewing of repositories also shown on the overview page
160 our $strict_export = "++GITWEB_STRICT_EXPORT++";
162 # list of git base URLs used for URL to where fetch project from,
163 # i.e. full URL is "$git_base_url/$project"
164 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
166 # default blob_plain mimetype and default charset for text/plain blob
167 our $default_blob_plain_mimetype = 'text/plain';
168 our $default_text_plain_charset = undef;
170 # file to use for guessing MIME types before trying /etc/mime.types
171 # (relative to the current git repository)
172 our $mimetypes_file = undef;
174 # assume this charset if line contains non-UTF-8 characters;
175 # it should be valid encoding (see Encoding::Supported(3pm) for list),
176 # for which encoding all byte sequences are valid, for example
177 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
178 # could be even 'utf-8' for the old behavior)
179 our $fallback_encoding = 'latin1';
181 # rename detection options for git-diff and git-diff-tree
182 # - default is '-M', with the cost proportional to
183 # (number of removed files) * (number of new files).
184 # - more costly is '-C' (which implies '-M'), with the cost proportional to
185 # (number of changed files + number of removed files) * (number of new files)
186 # - even more costly is '-C', '--find-copies-harder' with cost
187 # (number of files in the original tree) * (number of new files)
188 # - one might want to include '-B' option, e.g. '-B', '-M'
189 our @diff_opts = ('-M'); # taken from git_commit
191 # Disables features that would allow repository owners to inject script into
193 our $prevent_xss = 0;
195 # Path to the highlight executable to use (must be the one from
196 # http://www.andre-simon.de due to assumptions about parameters and output).
197 # Useful if highlight is not installed on your webserver's PATH.
198 # [Default: highlight]
199 our $highlight_bin = "++HIGHLIGHT_BIN++";
201 # information about snapshot formats that gitweb is capable of serving
202 our %known_snapshot_formats = (
204 # 'display' => display name,
205 # 'type' => mime type,
206 # 'suffix' => filename suffix,
207 # 'format' => --format for git-archive,
208 # 'compressor' => [compressor command and arguments]
209 # (array reference, optional)
210 # 'disabled' => boolean (optional)}
213 'display' => 'tar.gz',
214 'type' => 'application/x-gzip',
215 'suffix' => '.tar.gz',
217 'compressor' => ['gzip', '-n']},
220 'display' => 'tar.bz2',
221 'type' => 'application/x-bzip2',
222 'suffix' => '.tar.bz2',
224 'compressor' => ['bzip2']},
227 'display' => 'tar.xz',
228 'type' => 'application/x-xz',
229 'suffix' => '.tar.xz',
231 'compressor' => ['xz'],
236 'type' => 'application/x-zip',
241 # Aliases so we understand old gitweb.snapshot values in repository
243 our %known_snapshot_format_aliases = (
248 # backward compatibility: legacy gitweb config support
249 'x-gzip' => undef, 'gz' => undef,
250 'x-bzip2' => undef, 'bz2' => undef,
251 'x-zip' => undef, '' => undef,
254 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
255 # are changed, it may be appropriate to change these values too via
262 # Used to set the maximum load that we will still respond to gitweb queries.
263 # If server load exceed this value then return "503 server busy" error.
264 # If gitweb cannot determined server load, it is taken to be 0.
265 # Leave it undefined (or set to 'undef') to turn off load checking.
268 # configuration for 'highlight' (http://www.andre-simon.de/)
270 our %highlight_basename = (
273 'SConstruct' => 'py', # SCons equivalent of Makefile
274 'Makefile' => 'make',
277 our %highlight_ext = (
278 # main extensions, defining name of syntax;
279 # see files in /usr/share/highlight/langDefs/ directory
280 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
281 # alternate extensions, see /etc/highlight/filetypes.conf
282 (map { $_ => 'c' } qw(c h)),
283 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
284 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
285 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
286 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
287 (map { $_ => 'make'} qw(make mak mk)),
288 (map { $_ => 'xml' } qw(xml xhtml html htm)),
291 # You define site-wide feature defaults here; override them with
292 # $GITWEB_CONFIG as necessary.
295 # 'sub' => feature-sub (subroutine),
296 # 'override' => allow-override (boolean),
297 # 'default' => [ default options...] (array reference)}
299 # if feature is overridable (it means that allow-override has true value),
300 # then feature-sub will be called with default options as parameters;
301 # return value of feature-sub indicates if to enable specified feature
303 # if there is no 'sub' key (no feature-sub), then feature cannot be
306 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
307 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
310 # Enable the 'blame' blob view, showing the last commit that modified
311 # each line in the file. This can be very CPU-intensive.
313 # To enable system wide have in $GITWEB_CONFIG
314 # $feature{'blame'}{'default'} = [1];
315 # To have project specific config enable override in $GITWEB_CONFIG
316 # $feature{'blame'}{'override'} = 1;
317 # and in project config gitweb.blame = 0|1;
319 'sub' => sub { feature_bool
('blame', @_) },
323 # Enable the 'snapshot' link, providing a compressed archive of any
324 # tree. This can potentially generate high traffic if you have large
327 # Value is a list of formats defined in %known_snapshot_formats that
329 # To disable system wide have in $GITWEB_CONFIG
330 # $feature{'snapshot'}{'default'} = [];
331 # To have project specific config enable override in $GITWEB_CONFIG
332 # $feature{'snapshot'}{'override'} = 1;
333 # and in project config, a comma-separated list of formats or "none"
334 # to disable. Example: gitweb.snapshot = tbz2,zip;
336 'sub' => \
&feature_snapshot
,
338 'default' => ['tgz']},
340 # Enable text search, which will list the commits which match author,
341 # committer or commit text to a given string. Enabled by default.
342 # Project specific override is not supported.
344 # Note that this controls all search features, which means that if
345 # it is disabled, then 'grep' and 'pickaxe' search would also be
351 # Enable grep search, which will list the files in currently selected
352 # tree containing the given string. Enabled by default. This can be
353 # potentially CPU-intensive, of course.
354 # Note that you need to have 'search' feature enabled too.
356 # To enable system wide have in $GITWEB_CONFIG
357 # $feature{'grep'}{'default'} = [1];
358 # To have project specific config enable override in $GITWEB_CONFIG
359 # $feature{'grep'}{'override'} = 1;
360 # and in project config gitweb.grep = 0|1;
362 'sub' => sub { feature_bool
('grep', @_) },
366 # Enable the pickaxe search, which will list the commits that modified
367 # a given string in a file. This can be practical and quite faster
368 # alternative to 'blame', but still potentially CPU-intensive.
369 # Note that you need to have 'search' feature enabled too.
371 # To enable system wide have in $GITWEB_CONFIG
372 # $feature{'pickaxe'}{'default'} = [1];
373 # To have project specific config enable override in $GITWEB_CONFIG
374 # $feature{'pickaxe'}{'override'} = 1;
375 # and in project config gitweb.pickaxe = 0|1;
377 'sub' => sub { feature_bool
('pickaxe', @_) },
381 # Enable showing size of blobs in a 'tree' view, in a separate
382 # column, similar to what 'ls -l' does. This cost a bit of IO.
384 # To disable system wide have in $GITWEB_CONFIG
385 # $feature{'show-sizes'}{'default'} = [0];
386 # To have project specific config enable override in $GITWEB_CONFIG
387 # $feature{'show-sizes'}{'override'} = 1;
388 # and in project config gitweb.showsizes = 0|1;
390 'sub' => sub { feature_bool
('showsizes', @_) },
394 # Make gitweb use an alternative format of the URLs which can be
395 # more readable and natural-looking: project name is embedded
396 # directly in the path and the query string contains other
397 # auxiliary information. All gitweb installations recognize
398 # URL in either format; this configures in which formats gitweb
401 # To enable system wide have in $GITWEB_CONFIG
402 # $feature{'pathinfo'}{'default'} = [1];
403 # Project specific override is not supported.
405 # Note that you will need to change the default location of CSS,
406 # favicon, logo and possibly other files to an absolute URL. Also,
407 # if gitweb.cgi serves as your indexfile, you will need to force
408 # $my_uri to contain the script name in your $GITWEB_CONFIG.
410 # For FCGI use, note that $my_uri and $home_link are recomputed at the
411 # beginning of every request. If they need to be forced for pathinfo
412 # mode to work properly (likely) then $per_request_config must not be
413 # false (it defaults to true). To avoid the overhead of running the
414 # config on every FCGI request, set $per_request_config to a CODE ref
415 # that forces the needed values.
420 # Make gitweb consider projects in project root subdirectories
421 # to be forks of existing projects. Given project $projname.git,
422 # projects matching $projname/*.git will not be shown in the main
423 # projects list, instead a '+' mark will be added to $projname
424 # there and a 'forks' view will be enabled for the project, listing
425 # all the forks. If project list is taken from a file, forks have
426 # to be listed after the main project.
428 # To enable system wide have in $GITWEB_CONFIG
429 # $feature{'forks'}{'default'} = [1];
430 # Project specific override is not supported.
435 # Insert custom links to the action bar of all project pages.
436 # This enables you mainly to link to third-party scripts integrating
437 # into gitweb; e.g. git-browser for graphical history representation
438 # or custom web-based repository administration interface.
440 # The 'default' value consists of a list of triplets in the form
441 # (label, link, position) where position is the label after which
442 # to insert the link and link is a format string where %n expands
443 # to the project name, %f to the project path within the filesystem,
444 # %h to the current hash (h gitweb parameter) and %b to the current
445 # hash base (hb gitweb parameter); %% expands to %.
447 # To enable system wide have in $GITWEB_CONFIG e.g.
448 # $feature{'actions'}{'default'} = [('graphiclog',
449 # '/git-browser/by-commit.html?r=%n', 'summary')];
450 # Project specific override is not supported.
455 # Allow gitweb scan project content tags of project repository,
456 # and display the popular Web 2.0-ish "tag cloud" near the projects
457 # list. Note that this is something COMPLETELY different from the
460 # gitweb by itself can show existing tags, but it does not handle
461 # tagging itself; you need to do it externally, outside gitweb.
462 # The format is described in git_get_project_ctags() subroutine.
463 # You may want to install the HTML::TagCloud Perl module to get
464 # a pretty tag cloud instead of just a list of tags.
466 # To enable system wide have in $GITWEB_CONFIG
467 # $feature{'ctags'}{'default'} = [1];
468 # Project specific override is not supported.
470 # In the future whether ctags editing is enabled might depend
471 # on the value, but using 1 should always mean no editing of ctags.
476 # The maximum number of patches in a patchset generated in patch
477 # view. Set this to 0 or undef to disable patch view, or to a
478 # negative number to remove any limit.
480 # To disable system wide have in $GITWEB_CONFIG
481 # $feature{'patches'}{'default'} = [0];
482 # To have project specific config enable override in $GITWEB_CONFIG
483 # $feature{'patches'}{'override'} = 1;
484 # and in project config gitweb.patches = 0|n;
485 # where n is the maximum number of patches allowed in a patchset.
487 'sub' => \
&feature_patches
,
491 # Avatar support. When this feature is enabled, views such as
492 # shortlog or commit will display an avatar associated with
493 # the email of the committer(s) and/or author(s).
495 # Currently available providers are gravatar and picon.
496 # If an unknown provider is specified, the feature is disabled.
498 # Gravatar depends on Digest::MD5.
499 # Picon currently relies on the indiana.edu database.
501 # To enable system wide have in $GITWEB_CONFIG
502 # $feature{'avatar'}{'default'} = ['<provider>'];
503 # where <provider> is either gravatar or picon.
504 # To have project specific config enable override in $GITWEB_CONFIG
505 # $feature{'avatar'}{'override'} = 1;
506 # and in project config gitweb.avatar = <provider>;
508 'sub' => \
&feature_avatar
,
512 # Enable displaying how much time and how many git commands
513 # it took to generate and display page. Disabled by default.
514 # Project specific override is not supported.
519 # Enable turning some links into links to actions which require
520 # JavaScript to run (like 'blame_incremental'). Not enabled by
521 # default. Project specific override is currently not supported.
522 'javascript-actions' => {
526 # Enable and configure ability to change common timezone for dates
527 # in gitweb output via JavaScript. Enabled by default.
528 # Project specific override is not supported.
529 'javascript-timezone' => {
532 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
533 # or undef to turn off this feature
534 'gitweb_tz', # name of cookie where to store selected timezone
535 'datetime', # CSS class used to mark up dates for manipulation
538 # Syntax highlighting support. This is based on Daniel Svensson's
539 # and Sham Chukoury's work in gitweb-xmms2.git.
540 # It requires the 'highlight' program present in $PATH,
541 # and therefore is disabled by default.
543 # To enable system wide have in $GITWEB_CONFIG
544 # $feature{'highlight'}{'default'} = [1];
547 'sub' => sub { feature_bool
('highlight', @_) },
551 # Enable displaying of remote heads in the heads list
553 # To enable system wide have in $GITWEB_CONFIG
554 # $feature{'remote_heads'}{'default'} = [1];
555 # To have project specific config enable override in $GITWEB_CONFIG
556 # $feature{'remote_heads'}{'override'} = 1;
557 # and in project config gitweb.remoteheads = 0|1;
559 'sub' => sub { feature_bool
('remote_heads', @_) },
563 # Enable showing branches under other refs in addition to heads
565 # To set system wide extra branch refs have in $GITWEB_CONFIG
566 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
567 # To have project specific config enable override in $GITWEB_CONFIG
568 # $feature{'extra-branch-refs'}{'override'} = 1;
569 # and in project config gitweb.extrabranchrefs = dirs of choice
570 # Every directory is separated with whitespace.
572 'extra-branch-refs' => {
573 'sub' => \
&feature_extra_branch_refs
,
578 sub gitweb_get_feature
{
580 return unless exists $feature{$name};
581 my ($sub, $override, @defaults) = (
582 $feature{$name}{'sub'},
583 $feature{$name}{'override'},
584 @
{$feature{$name}{'default'}});
585 # project specific override is possible only if we have project
586 our $git_dir; # global variable, declared later
587 if (!$override || !defined $git_dir) {
591 warn "feature $name is not overridable";
594 return $sub->(@defaults);
597 # A wrapper to check if a given feature is enabled.
598 # With this, you can say
600 # my $bool_feat = gitweb_check_feature('bool_feat');
601 # gitweb_check_feature('bool_feat') or somecode;
605 # my ($bool_feat) = gitweb_get_feature('bool_feat');
606 # (gitweb_get_feature('bool_feat'))[0] or somecode;
608 sub gitweb_check_feature
{
609 return (gitweb_get_feature
(@_))[0];
615 my ($val) = git_get_project_config
($key, '--bool');
619 } elsif ($val eq 'true') {
621 } elsif ($val eq 'false') {
626 sub feature_snapshot
{
629 my ($val) = git_get_project_config
('snapshot');
632 @fmts = ($val eq 'none' ?
() : split /\s*[,\s]\s*/, $val);
638 sub feature_patches
{
639 my @val = (git_get_project_config
('patches', '--int'));
649 my @val = (git_get_project_config
('avatar'));
651 return @val ?
@val : @_;
654 sub feature_extra_branch_refs
{
655 my (@branch_refs) = @_;
656 my $values = git_get_project_config
('extrabranchrefs');
659 $values = config_to_multi
($values);
661 foreach my $value (@
{$values}) {
662 push @branch_refs, split /\s+/, $value;
669 # checking HEAD file with -e is fragile if the repository was
670 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
672 sub check_head_link
{
674 my $headfile = "$dir/HEAD";
675 return ((-e
$headfile) ||
676 (-l
$headfile && readlink($headfile) =~ /^refs\/heads\
//));
679 sub check_export_ok
{
681 return (check_head_link
($dir) &&
682 (!$export_ok || -e
"$dir/$export_ok") &&
683 (!$export_auth_hook || $export_auth_hook->($dir)));
686 # process alternate names for backward compatibility
687 # filter out unsupported (unknown) snapshot formats
688 sub filter_snapshot_fmts
{
692 exists $known_snapshot_format_aliases{$_} ?
693 $known_snapshot_format_aliases{$_} : $_} @fmts;
695 exists $known_snapshot_formats{$_} &&
696 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
699 sub filter_and_validate_refs
{
701 my %unique_refs = ();
703 foreach my $ref (@refs) {
704 die_error
(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format
($ref));
705 # 'heads' are added implicitly in get_branch_refs().
706 $unique_refs{$ref} = 1 if ($ref ne 'heads');
708 return sort keys %unique_refs;
711 # If it is set to code reference, it is code that it is to be run once per
712 # request, allowing updating configurations that change with each request,
713 # while running other code in config file only once.
715 # Otherwise, if it is false then gitweb would process config file only once;
716 # if it is true then gitweb config would be run for each request.
717 our $per_request_config = 1;
719 # If true and fileno STDIN is 0 and getsockname succeeds, then FCGI mode will
720 # be activated automatically as though the --fcgi option was given.
723 # read and parse gitweb config file given by its parameter.
724 # returns true on success, false on recoverable error, allowing
725 # to chain this subroutine, using first file that exists.
726 # dies on errors during parsing config file, as it is unrecoverable.
727 sub read_config_file
{
728 my $filename = shift;
729 return unless defined $filename;
730 # die if there are errors parsing config file
739 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
740 sub evaluate_gitweb_config
{
741 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
742 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
743 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
745 # Protect against duplications of file names, to not read config twice.
746 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
747 # there possibility of duplication of filename there doesn't matter.
748 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
749 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
751 # Common system-wide settings for convenience.
752 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
753 read_config_file
($GITWEB_CONFIG_COMMON);
755 # Use first config file that exists. This means use the per-instance
756 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
757 read_config_file
($GITWEB_CONFIG) and return;
758 read_config_file
($GITWEB_CONFIG_SYSTEM);
761 # Get loadavg of system, to compare against $maxload.
762 # Currently it requires '/proc/loadavg' present to get loadavg;
763 # if it is not present it returns 0, which means no load checking.
765 if( -e
'/proc/loadavg' ){
766 open my $fd, '<', '/proc/loadavg'
768 my @load = split(/\s+/, scalar <$fd>);
771 # The first three columns measure CPU and IO utilization of the last one,
772 # five, and 10 minute periods. The fourth column shows the number of
773 # currently running processes and the total number of processes in the m/n
774 # format. The last column displays the last process ID used.
775 return $load[0] || 0;
777 # additional checks for load average should go here for things that don't export
783 # version of the core git binary
785 sub evaluate_git_version
{
786 our $git_version = qx("$GIT" --version
) =~ m/git version (.*)$/ ?
$1 : "unknown";
787 $number_of_git_cmds++;
791 if (defined $maxload && get_loadavg
() > $maxload) {
792 die_error
(503, "The load average on the server is too high");
796 # ======================================================================
797 # input validation and dispatch
799 # input parameters can be collected from a variety of sources (presently, CGI
800 # and PATH_INFO), so we define an %input_params hash that collects them all
801 # together during validation: this allows subsequent uses (e.g. href()) to be
802 # agnostic of the parameter origin
804 our %input_params = ();
806 # input parameters are stored with the long parameter name as key. This will
807 # also be used in the href subroutine to convert parameters to their CGI
808 # equivalent, and since the href() usage is the most frequent one, we store
809 # the name -> CGI key mapping here, instead of the reverse.
811 # XXX: Warning: If you touch this, check the search form for updating,
814 our @cgi_param_mapping = (
822 hash_parent_base
=> "hpb",
827 snapshot_format
=> "sf",
828 extra_options
=> "opt",
829 search_use_regexp
=> "sr",
832 project_filter
=> "pf",
833 # this must be last entry (for manipulation from JavaScript)
836 our %cgi_param_mapping = @cgi_param_mapping;
838 # we will also need to know the possible actions, for validation
840 "blame" => \
&git_blame
,
841 "blame_incremental" => \
&git_blame_incremental
,
842 "blame_data" => \
&git_blame_data
,
843 "blobdiff" => \
&git_blobdiff
,
844 "blobdiff_plain" => \
&git_blobdiff_plain
,
845 "blob" => \
&git_blob
,
846 "blob_plain" => \
&git_blob_plain
,
847 "commitdiff" => \
&git_commitdiff
,
848 "commitdiff_plain" => \
&git_commitdiff_plain
,
849 "commit" => \
&git_commit
,
850 "forks" => \
&git_forks
,
851 "heads" => \
&git_heads
,
852 "history" => \
&git_history
,
854 "patch" => \
&git_patch
,
855 "patches" => \
&git_patches
,
856 "remotes" => \
&git_remotes
,
858 "atom" => \
&git_atom
,
859 "search" => \
&git_search
,
860 "search_help" => \
&git_search_help
,
861 "shortlog" => \
&git_shortlog
,
862 "summary" => \
&git_summary
,
864 "tags" => \
&git_tags
,
865 "tree" => \
&git_tree
,
866 "snapshot" => \
&git_snapshot
,
867 "object" => \
&git_object
,
868 # those below don't need $project
869 "opml" => \
&git_opml
,
870 "project_list" => \
&git_project_list
,
871 "project_index" => \
&git_project_index
,
874 # finally, we have the hash of allowed extra_options for the commands that
876 our %allowed_options = (
877 "--no-merges" => [ qw(rss atom log shortlog history) ],
880 # fill %input_params with the CGI parameters. All values except for 'opt'
881 # should be single values, but opt can be an array. We should probably
882 # build an array of parameters that can be multi-valued, but since for the time
883 # being it's only this one, we just single it out
884 sub evaluate_query_params
{
887 while (my ($name, $symbol) = each %cgi_param_mapping) {
888 if ($symbol eq 'opt') {
889 $input_params{$name} = [ map { decode_utf8
($_) } $cgi->multi_param($symbol) ];
891 $input_params{$name} = decode_utf8
($cgi->param($symbol));
896 # now read PATH_INFO and update the parameter list for missing parameters
897 sub evaluate_path_info
{
898 return if defined $input_params{'project'};
899 return if !$path_info;
900 $path_info =~ s
,^/+,,;
901 return if !$path_info;
903 # find which part of PATH_INFO is project
904 my $project = $path_info;
906 while ($project && !check_head_link
("$projectroot/$project")) {
907 $project =~ s
,/*[^/]*$,,;
909 return unless $project;
910 $input_params{'project'} = $project;
912 # do not change any parameters if an action is given using the query string
913 return if $input_params{'action'};
914 $path_info =~ s
,^\Q
$project\E
/*,,;
916 # next, check if we have an action
917 my $action = $path_info;
919 if (exists $actions{$action}) {
920 $path_info =~ s
,^$action/*,,;
921 $input_params{'action'} = $action;
924 # list of actions that want hash_base instead of hash, but can have no
925 # pathname (f) parameter
931 # we want to catch, among others
932 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
933 my ($parentrefname, $parentpathname, $refname, $pathname) =
934 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
936 # first, analyze the 'current' part
937 if (defined $pathname) {
938 # we got "branch:filename" or "branch:dir/"
939 # we could use git_get_type(branch:pathname), but:
940 # - it needs $git_dir
941 # - it does a git() call
942 # - the convention of terminating directories with a slash
943 # makes it superfluous
944 # - embedding the action in the PATH_INFO would make it even
946 $pathname =~ s
,^/+,,;
947 if (!$pathname || substr($pathname, -1) eq "/") {
948 $input_params{'action'} ||= "tree";
951 # the default action depends on whether we had parent info
953 if ($parentrefname) {
954 $input_params{'action'} ||= "blobdiff_plain";
956 $input_params{'action'} ||= "blob_plain";
959 $input_params{'hash_base'} ||= $refname;
960 $input_params{'file_name'} ||= $pathname;
961 } elsif (defined $refname) {
962 # we got "branch". In this case we have to choose if we have to
963 # set hash or hash_base.
965 # Most of the actions without a pathname only want hash to be
966 # set, except for the ones specified in @wants_base that want
967 # hash_base instead. It should also be noted that hand-crafted
968 # links having 'history' as an action and no pathname or hash
969 # set will fail, but that happens regardless of PATH_INFO.
970 if (defined $parentrefname) {
971 # if there is parent let the default be 'shortlog' action
972 # (for http://git.example.com/repo.git/A..B links); if there
973 # is no parent, dispatch will detect type of object and set
974 # action appropriately if required (if action is not set)
975 $input_params{'action'} ||= "shortlog";
977 if ($input_params{'action'} &&
978 grep { $_ eq $input_params{'action'} } @wants_base) {
979 $input_params{'hash_base'} ||= $refname;
981 $input_params{'hash'} ||= $refname;
985 # next, handle the 'parent' part, if present
986 if (defined $parentrefname) {
987 # a missing pathspec defaults to the 'current' filename, allowing e.g.
988 # someproject/blobdiff/oldrev..newrev:/filename
989 if ($parentpathname) {
990 $parentpathname =~ s
,^/+,,;
991 $parentpathname =~ s
,/$,,;
992 $input_params{'file_parent'} ||= $parentpathname;
994 $input_params{'file_parent'} ||= $input_params{'file_name'};
996 # we assume that hash_parent_base is wanted if a path was specified,
997 # or if the action wants hash_base instead of hash
998 if (defined $input_params{'file_parent'} ||
999 grep { $_ eq $input_params{'action'} } @wants_base) {
1000 $input_params{'hash_parent_base'} ||= $parentrefname;
1002 $input_params{'hash_parent'} ||= $parentrefname;
1006 # for the snapshot action, we allow URLs in the form
1007 # $project/snapshot/$hash.ext
1008 # where .ext determines the snapshot and gets removed from the
1009 # passed $refname to provide the $hash.
1011 # To be able to tell that $refname includes the format extension, we
1012 # require the following two conditions to be satisfied:
1013 # - the hash input parameter MUST have been set from the $refname part
1014 # of the URL (i.e. they must be equal)
1015 # - the snapshot format MUST NOT have been defined already (e.g. from
1017 # It's also useless to try any matching unless $refname has a dot,
1018 # so we check for that too
1019 if (defined $input_params{'action'} &&
1020 $input_params{'action'} eq 'snapshot' &&
1021 defined $refname && index($refname, '.') != -1 &&
1022 $refname eq $input_params{'hash'} &&
1023 !defined $input_params{'snapshot_format'}) {
1024 # We loop over the known snapshot formats, checking for
1025 # extensions. Allowed extensions are both the defined suffix
1026 # (which includes the initial dot already) and the snapshot
1027 # format key itself, with a prepended dot
1028 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1029 my $hash = $refname;
1030 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1034 # a valid suffix was found, so set the snapshot format
1035 # and reset the hash parameter
1036 $input_params{'snapshot_format'} = $fmt;
1037 $input_params{'hash'} = $hash;
1038 # we also set the format suffix to the one requested
1039 # in the URL: this way a request for e.g. .tgz returns
1040 # a .tgz instead of a .tar.gz
1041 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1047 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1048 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1049 $searchtext, $search_regexp, $project_filter);
1050 sub evaluate_and_validate_params
{
1051 our $action = $input_params{'action'};
1052 if (defined $action) {
1053 if (!is_valid_action
($action)) {
1054 die_error
(400, "Invalid action parameter");
1058 # parameters which are pathnames
1059 our $project = $input_params{'project'};
1060 if (defined $project) {
1061 if (!is_valid_project
($project)) {
1063 die_error
(404, "No such project");
1067 our $project_filter = $input_params{'project_filter'};
1068 if (defined $project_filter) {
1069 if (!is_valid_pathname
($project_filter)) {
1070 die_error
(404, "Invalid project_filter parameter");
1074 our $file_name = $input_params{'file_name'};
1075 if (defined $file_name) {
1076 if (!is_valid_pathname
($file_name)) {
1077 die_error
(400, "Invalid file parameter");
1081 our $file_parent = $input_params{'file_parent'};
1082 if (defined $file_parent) {
1083 if (!is_valid_pathname
($file_parent)) {
1084 die_error
(400, "Invalid file parent parameter");
1088 # parameters which are refnames
1089 our $hash = $input_params{'hash'};
1090 if (defined $hash) {
1091 if (!is_valid_refname
($hash)) {
1092 die_error
(400, "Invalid hash parameter");
1096 our $hash_parent = $input_params{'hash_parent'};
1097 if (defined $hash_parent) {
1098 if (!is_valid_refname
($hash_parent)) {
1099 die_error
(400, "Invalid hash parent parameter");
1103 our $hash_base = $input_params{'hash_base'};
1104 if (defined $hash_base) {
1105 if (!is_valid_refname
($hash_base)) {
1106 die_error
(400, "Invalid hash base parameter");
1110 our @extra_options = @
{$input_params{'extra_options'}};
1111 # @extra_options is always defined, since it can only be (currently) set from
1112 # CGI, and $cgi->param() returns the empty array in array context if the param
1114 foreach my $opt (@extra_options) {
1115 if (not exists $allowed_options{$opt}) {
1116 die_error
(400, "Invalid option parameter");
1118 if (not grep(/^$action$/, @
{$allowed_options{$opt}})) {
1119 die_error
(400, "Invalid option parameter for this action");
1123 our $hash_parent_base = $input_params{'hash_parent_base'};
1124 if (defined $hash_parent_base) {
1125 if (!is_valid_refname
($hash_parent_base)) {
1126 die_error
(400, "Invalid hash parent base parameter");
1131 our $page = $input_params{'page'};
1132 if (defined $page) {
1133 if ($page =~ m/[^0-9]/) {
1134 die_error
(400, "Invalid page parameter");
1138 our $searchtype = $input_params{'searchtype'};
1139 if (defined $searchtype) {
1140 if ($searchtype =~ m/[^a-z]/) {
1141 die_error
(400, "Invalid searchtype parameter");
1145 our $search_use_regexp = $input_params{'search_use_regexp'};
1147 our $searchtext = $input_params{'searchtext'};
1148 our $search_regexp = undef;
1149 if (defined $searchtext) {
1150 if (length($searchtext) < 2) {
1151 die_error
(403, "At least two characters are required for search parameter");
1153 if ($search_use_regexp) {
1154 $search_regexp = $searchtext;
1155 if (!eval { qr/$search_regexp/; 1; }) {
1156 (my $error = $@
) =~ s/ at \S+ line \d+.*\n?//;
1157 die_error
(400, "Invalid search regexp '$search_regexp'",
1161 $search_regexp = quotemeta $searchtext;
1166 # path to the current git repository
1168 sub evaluate_git_dir
{
1169 our $git_dir = "$projectroot/$project" if $project;
1172 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1173 sub configure_gitweb_features
{
1174 # list of supported snapshot formats
1175 our @snapshot_fmts = gitweb_get_feature
('snapshot');
1176 @snapshot_fmts = filter_snapshot_fmts
(@snapshot_fmts);
1178 # check that the avatar feature is set to a known provider name,
1179 # and for each provider check if the dependencies are satisfied.
1180 # if the provider name is invalid or the dependencies are not met,
1181 # reset $git_avatar to the empty string.
1182 our ($git_avatar) = gitweb_get_feature
('avatar');
1183 if ($git_avatar eq 'gravatar') {
1184 $git_avatar = '' unless (eval { require Digest
::MD5
; 1; });
1185 } elsif ($git_avatar eq 'picon') {
1191 our @extra_branch_refs = gitweb_get_feature
('extra-branch-refs');
1192 @extra_branch_refs = filter_and_validate_refs
(@extra_branch_refs);
1195 sub get_branch_refs
{
1196 return ('heads', @extra_branch_refs);
1199 # custom error handler: 'die <message>' is Internal Server Error
1200 sub handle_errors_html
{
1201 my $msg = shift; # it is already HTML escaped
1203 # to avoid infinite loop where error occurs in die_error,
1204 # change handler to default handler, disabling handle_errors_html
1205 set_message
("Error occurred when inside die_error:\n$msg");
1207 # you cannot jump out of die_error when called as error handler;
1208 # the subroutine set via CGI::Carp::set_message is called _after_
1209 # HTTP headers are already written, so it cannot write them itself
1210 die_error
(undef, undef, $msg, -error_handler
=> 1, -no_http_header
=> 1);
1212 set_message
(\
&handle_errors_html
);
1216 if (!defined $action) {
1217 if (defined $hash) {
1218 $action = git_get_type
($hash);
1219 $action or die_error
(404, "Object does not exist");
1220 } elsif (defined $hash_base && defined $file_name) {
1221 $action = git_get_type
("$hash_base:$file_name");
1222 $action or die_error
(404, "File or directory does not exist");
1223 } elsif (defined $project) {
1224 $action = 'summary';
1226 $action = 'project_list';
1229 if (!defined($actions{$action})) {
1230 die_error
(400, "Unknown action");
1232 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1234 die_error
(400, "Project needed");
1236 $actions{$action}->();
1240 our $t0 = [ gettimeofday
() ]
1242 our $number_of_git_cmds = 0;
1245 our $first_request = 1;
1247 my ($old_uri, $old_hl);
1250 # Only allow GET and HEAD methods
1251 if (!$ENV{'REQUEST_METHOD'} || ($ENV{'REQUEST_METHOD'} ne 'GET' && $ENV{'REQUEST_METHOD'} ne 'HEAD')) {
1253 Status: 405 Method Not Allowed
1254 Content-Type: text/plain
1257 405 Method Not Allowed
1262 ($old_uri, $old_hl) = ($my_uri, $home_link) if $first_request;
1264 if ($first_request) {
1265 $my_uri = $old_uri if defined $old_uri && $old_uri ne '';
1266 $home_link = $old_hl if defined $old_hl && $old_hl ne '';
1268 if ($per_request_config) {
1269 if (ref($per_request_config) eq 'CODE') {
1270 $per_request_config->();
1271 } elsif (!$first_request) {
1272 evaluate_gitweb_config
();
1277 # $projectroot and $projects_list might be set in gitweb config file
1278 $projects_list ||= $projectroot;
1280 evaluate_query_params
();
1281 evaluate_path_info
();
1282 evaluate_and_validate_params
();
1285 configure_gitweb_features
();
1290 our $is_last_request = sub { 1 };
1291 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1295 sub configure_as_fcgi
{
1296 return if $fcgi_mode;
1299 our $CGI = 'CGI::Fast';
1303 my $request_number = 0;
1304 # let each child service 100 requests
1305 our $is_last_request = sub { ++$request_number > 100 };
1308 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__
;
1310 if $script_name =~ /\.fcgi$/
1311 or $auto_fcgi && defined fileno STDIN
&& fileno STDIN
== 0 && getsockname(STDIN
);
1313 return unless (@ARGV);
1315 require Getopt
::Long
;
1316 Getopt
::Long
::GetOptions
(
1317 'fastcgi|fcgi|f' => \
&configure_as_fcgi
,
1318 'nproc|n=i' => sub {
1319 my ($arg, $val) = @_;
1320 return unless eval { require FCGI
::ProcManager
; 1; };
1321 my $proc_manager = FCGI
::ProcManager
->new({
1322 n_processes
=> $val,
1324 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1325 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1326 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1332 evaluate_gitweb_config
();
1333 evaluate_git_version
();
1338 $pre_listen_hook->()
1339 if $pre_listen_hook;
1342 while ($cgi = $CGI->new()) {
1343 $pre_dispatch_hook->()
1344 if $pre_dispatch_hook;
1348 $post_dispatch_hook->()
1349 if $post_dispatch_hook;
1352 last REQUEST
if ($is_last_request->());
1361 if (defined caller) {
1362 # wrapped in a subroutine processing requests,
1363 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1366 # pure CGI script, serving single request
1370 ## ======================================================================
1373 # possible values of extra options
1374 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1375 # -replay => 1 - start from a current view (replay with modifications)
1376 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1377 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1380 # default is to use -absolute url() i.e. $my_uri
1381 my $href = $params{-full
} ?
$my_url : $my_uri;
1383 # implicit -replay, must be first of implicit params
1384 $params{-replay
} = 1 if (keys %params == 1 && $params{-anchor
});
1386 $params{'project'} = $project unless exists $params{'project'};
1388 if ($params{-replay
}) {
1389 while (my ($name, $symbol) = each %cgi_param_mapping) {
1390 if (!exists $params{$name}) {
1391 $params{$name} = $input_params{$name};
1396 my $use_pathinfo = gitweb_check_feature
('pathinfo');
1397 if (defined $params{'project'} &&
1398 (exists $params{-path_info
} ?
$params{-path_info
} : $use_pathinfo)) {
1399 # try to put as many parameters as possible in PATH_INFO:
1402 # - hash_parent or hash_parent_base:/file_parent
1403 # - hash or hash_base:/filename
1404 # - the snapshot_format as an appropriate suffix
1406 # When the script is the root DirectoryIndex for the domain,
1407 # $href here would be something like http://gitweb.example.com/
1408 # Thus, we strip any trailing / from $href, to spare us double
1409 # slashes in the final URL
1412 # Then add the project name, if present
1413 $href .= "/".esc_path_info
($params{'project'});
1414 delete $params{'project'};
1416 # since we destructively absorb parameters, we keep this
1417 # boolean that remembers if we're handling a snapshot
1418 my $is_snapshot = $params{'action'} eq 'snapshot';
1420 # Summary just uses the project path URL, any other action is
1422 if (defined $params{'action'}) {
1423 $href .= "/".esc_path_info
($params{'action'})
1424 unless $params{'action'} eq 'summary';
1425 delete $params{'action'};
1428 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1429 # stripping nonexistent or useless pieces
1430 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1431 || $params{'hash_parent'} || $params{'hash'});
1432 if (defined $params{'hash_base'}) {
1433 if (defined $params{'hash_parent_base'}) {
1434 $href .= esc_path_info
($params{'hash_parent_base'});
1435 # skip the file_parent if it's the same as the file_name
1436 if (defined $params{'file_parent'}) {
1437 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1438 delete $params{'file_parent'};
1439 } elsif ($params{'file_parent'} !~ /\.\./) {
1440 $href .= ":/".esc_path_info
($params{'file_parent'});
1441 delete $params{'file_parent'};
1445 delete $params{'hash_parent'};
1446 delete $params{'hash_parent_base'};
1447 } elsif (defined $params{'hash_parent'}) {
1448 $href .= esc_path_info
($params{'hash_parent'}). "..";
1449 delete $params{'hash_parent'};
1452 $href .= esc_path_info
($params{'hash_base'});
1453 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1454 $href .= ":/".esc_path_info
($params{'file_name'});
1455 delete $params{'file_name'};
1457 delete $params{'hash'};
1458 delete $params{'hash_base'};
1459 } elsif (defined $params{'hash'}) {
1460 $href .= esc_path_info
($params{'hash'});
1461 delete $params{'hash'};
1464 # If the action was a snapshot, we can absorb the
1465 # snapshot_format parameter too
1467 my $fmt = $params{'snapshot_format'};
1468 # snapshot_format should always be defined when href()
1469 # is called, but just in case some code forgets, we
1470 # fall back to the default
1471 $fmt ||= $snapshot_fmts[0];
1472 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1473 delete $params{'snapshot_format'};
1477 # now encode the parameters explicitly
1479 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1480 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1481 if (defined $params{$name}) {
1482 if (ref($params{$name}) eq "ARRAY") {
1483 foreach my $par (@
{$params{$name}}) {
1484 push @result, $symbol . "=" . esc_param
($par);
1487 push @result, $symbol . "=" . esc_param
($params{$name});
1491 $href .= "?" . join(';', @result) if scalar @result;
1493 # final transformation: trailing spaces must be escaped (URI-encoded)
1494 $href =~ s/(\s+)$/CGI::escape($1)/e;
1496 if ($params{-anchor
}) {
1497 $href .= "#".esc_param
($params{-anchor
});
1504 ## ======================================================================
1505 ## validation, quoting/unquoting and escaping
1507 sub is_valid_action
{
1509 return undef unless exists $actions{$input};
1513 sub is_valid_project
{
1516 return unless defined $input;
1517 if (!is_valid_pathname
($input) ||
1518 !(-d
"$projectroot/$input") ||
1519 !check_export_ok
("$projectroot/$input") ||
1520 ($strict_export && !project_in_list
($input))) {
1527 sub is_valid_pathname
{
1530 return undef unless defined $input;
1531 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1532 # at the beginning, at the end, and between slashes.
1533 # also this catches doubled slashes
1534 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1537 # no null characters
1538 if ($input =~ m!\0!) {
1544 sub is_valid_ref_format
{
1547 return undef unless defined $input;
1548 # restrictions on ref name according to git-check-ref-format
1549 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1555 sub is_valid_refname
{
1558 return undef unless defined $input;
1559 # textual hashes are O.K.
1560 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1563 # it must be correct pathname
1564 is_valid_pathname
($input) or return undef;
1565 # check git-check-ref-format restrictions
1566 is_valid_ref_format
($input) or return undef;
1570 # decode sequences of octets in utf8 into Perl's internal form,
1571 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1572 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1575 return undef unless defined $str;
1577 if (utf8
::is_utf8
($str) || utf8
::decode
($str)) {
1580 return decode
($fallback_encoding, $str, Encode
::FB_DEFAULT
);
1584 # quote unsafe chars, but keep the slash, even when it's not
1585 # correct, but quoted slashes look too horrible in bookmarks
1588 return undef unless defined $str;
1589 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI
::escape
($1)/eg
;
1594 # the quoting rules for path_info fragment are slightly different
1597 return undef unless defined $str;
1599 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1600 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI
::escape
($1)/eg
;
1605 # quote unsafe chars in whole URL, so some characters cannot be quoted
1608 return undef unless defined $str;
1609 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI
::escape
($1)/eg
;
1614 # quote unsafe characters in HTML attributes
1617 # for XHTML conformance escaping '"' to '"' is not enough
1618 return esc_html
(@_);
1621 # replace invalid utf8 character with SUBSTITUTION sequence
1626 return undef unless defined $str;
1628 $str = to_utf8
($str);
1629 $str = $cgi->escapeHTML($str);
1630 if ($opts{'-nbsp'}) {
1631 $str =~ s/ / /g;
1633 $str =~ s
|([[:cntrl
:]])|(($1 ne "\t") ? quot_cec
($1) : $1)|eg
;
1637 # quote control characters and escape filename to HTML
1642 return undef unless defined $str;
1644 $str = to_utf8
($str);
1645 $str = $cgi->escapeHTML($str);
1646 if ($opts{'-nbsp'}) {
1647 $str =~ s/ / /g;
1649 $str =~ s
|([[:cntrl
:]])|quot_cec
($1)|eg
;
1653 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1657 return undef unless defined $str;
1659 $str = to_utf8
($str);
1660 $str =~ s
|([[:cntrl
:]])|(index("\t\n\r", $1) != -1 ?
$1 : quot_cec
($1))|eg
;
1664 # Make control characters "printable", using character escape codes (CEC)
1668 my %es = ( # character escape codes, aka escape sequences
1669 "\t" => '\t', # tab (HT)
1670 "\n" => '\n', # line feed (LF)
1671 "\r" => '\r', # carrige return (CR)
1672 "\f" => '\f', # form feed (FF)
1673 "\b" => '\b', # backspace (BS)
1674 "\a" => '\a', # alarm (bell) (BEL)
1675 "\e" => '\e', # escape (ESC)
1676 "\013" => '\v', # vertical tab (VT)
1677 "\000" => '\0', # nul character (NUL)
1679 my $chr = ( (exists $es{$cntrl})
1681 : sprintf('\%2x', ord($cntrl)) );
1682 if ($opts{-nohtml
}) {
1685 return "<span class=\"cntrl\">$chr</span>";
1689 # Alternatively use unicode control pictures codepoints,
1690 # Unicode "printable representation" (PR)
1695 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1696 if ($opts{-nohtml
}) {
1699 return "<span class=\"cntrl\">$chr</span>";
1703 # git may return quoted and escaped filenames
1709 my %es = ( # character escape codes, aka escape sequences
1710 't' => "\t", # tab (HT, TAB)
1711 'n' => "\n", # newline (NL)
1712 'r' => "\r", # return (CR)
1713 'f' => "\f", # form feed (FF)
1714 'b' => "\b", # backspace (BS)
1715 'a' => "\a", # alarm (bell) (BEL)
1716 'e' => "\e", # escape (ESC)
1717 'v' => "\013", # vertical tab (VT)
1720 if ($seq =~ m/^[0-7]{1,3}$/) {
1721 # octal char sequence
1722 return chr(oct($seq));
1723 } elsif (exists $es{$seq}) {
1724 # C escape sequence, aka character escape code
1727 # quoted ordinary character
1731 if ($str =~ m/^"(.*)"$/) {
1734 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1739 # escape tabs (convert tabs to spaces)
1743 while ((my $pos = index($line, "\t")) != -1) {
1744 if (my $count = (8 - ($pos % 8))) {
1745 my $spaces = ' ' x
$count;
1746 $line =~ s/\t/$spaces/;
1753 sub project_in_list
{
1754 my $project = shift;
1755 my @list = git_get_projects_list
();
1756 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1759 ## ----------------------------------------------------------------------
1760 ## HTML aware string manipulation
1762 # Try to chop given string on a word boundary between position
1763 # $len and $len+$add_len. If there is no word boundary there,
1764 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1765 # (marking chopped part) would be longer than given string.
1769 my $add_len = shift || 10;
1770 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1772 # Make sure perl knows it is utf8 encoded so we don't
1773 # cut in the middle of a utf8 multibyte char.
1774 $str = to_utf8
($str);
1776 # allow only $len chars, but don't cut a word if it would fit in $add_len
1777 # if it doesn't fit, cut it if it's still longer than the dots we would add
1778 # remove chopped character entities entirely
1780 # when chopping in the middle, distribute $len into left and right part
1781 # return early if chopping wouldn't make string shorter
1782 if ($where eq 'center') {
1783 return $str if ($len + 5 >= length($str)); # filler is length 5
1786 return $str if ($len + 4 >= length($str)); # filler is length 4
1789 # regexps: ending and beginning with word part up to $add_len
1790 my $endre = qr/.{$len}\w{0,$add_len}/;
1791 my $begre = qr/\w{0,$add_len}.{$len}/;
1793 if ($where eq 'left') {
1794 $str =~ m/^(.*?)($begre)$/;
1795 my ($lead, $body) = ($1, $2);
1796 if (length($lead) > 4) {
1799 return "$lead$body";
1801 } elsif ($where eq 'center') {
1802 $str =~ m/^($endre)(.*)$/;
1803 my ($left, $str) = ($1, $2);
1804 $str =~ m/^(.*?)($begre)$/;
1805 my ($mid, $right) = ($1, $2);
1806 if (length($mid) > 5) {
1809 return "$left$mid$right";
1812 $str =~ m/^($endre)(.*)$/;
1815 if (length($tail) > 4) {
1818 return "$body$tail";
1822 # takes the same arguments as chop_str, but also wraps a <span> around the
1823 # result with a title attribute if it does get chopped. Additionally, the
1824 # string is HTML-escaped.
1825 sub chop_and_escape_str
{
1828 my $chopped = chop_str
(@_);
1829 $str = to_utf8
($str);
1830 if ($chopped eq $str) {
1831 return esc_html
($chopped);
1833 $str =~ s/[[:cntrl:]]/?/g;
1834 return $cgi->span({-title
=>$str}, esc_html
($chopped));
1838 # Highlight selected fragments of string, using given CSS class,
1839 # and escape HTML. It is assumed that fragments do not overlap.
1840 # Regions are passed as list of pairs (array references).
1842 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1843 # '<span class="mark">foo</span>bar'
1844 sub esc_html_hl_regions
{
1845 my ($str, $css_class, @sel) = @_;
1846 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1847 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1848 return esc_html
($str, %opts) unless @sel;
1854 my ($begin, $end) = @
$s;
1856 # Don't create empty <span> elements.
1857 next if $end <= $begin;
1859 my $escaped = esc_html
(substr($str, $begin, $end - $begin),
1862 $out .= esc_html
(substr($str, $pos, $begin - $pos), %opts)
1863 if ($begin - $pos > 0);
1864 $out .= $cgi->span({-class => $css_class}, $escaped);
1868 $out .= esc_html
(substr($str, $pos), %opts)
1869 if ($pos < length($str));
1874 # return positions of beginning and end of each match
1876 my ($str, $regexp) = @_;
1877 return unless (defined $str && defined $regexp);
1880 while ($str =~ /$regexp/g) {
1881 push @matches, [$-[0], $+[0]];
1886 # highlight match (if any), and escape HTML
1887 sub esc_html_match_hl
{
1888 my ($str, $regexp) = @_;
1889 return esc_html
($str) unless defined $regexp;
1891 my @matches = matchpos_list
($str, $regexp);
1892 return esc_html
($str) unless @matches;
1894 return esc_html_hl_regions
($str, 'match', @matches);
1898 # highlight match (if any) of shortened string, and escape HTML
1899 sub esc_html_match_hl_chopped
{
1900 my ($str, $chopped, $regexp) = @_;
1901 return esc_html_match_hl
($str, $regexp) unless defined $chopped;
1903 my @matches = matchpos_list
($str, $regexp);
1904 return esc_html
($chopped) unless @matches;
1906 # filter matches so that we mark chopped string
1907 my $tail = "... "; # see chop_str
1908 unless ($chopped =~ s/\Q$tail\E$//) {
1911 my $chop_len = length($chopped);
1912 my $tail_len = length($tail);
1915 for my $m (@matches) {
1916 if ($m->[0] > $chop_len) {
1917 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1919 } elsif ($m->[1] > $chop_len) {
1920 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1926 return esc_html_hl_regions
($chopped . $tail, 'match', @filtered);
1929 ## ----------------------------------------------------------------------
1930 ## functions returning short strings
1932 # CSS class for given age value (in seconds)
1936 if (!defined $age) {
1938 } elsif ($age < 60*60*2) {
1940 } elsif ($age < 60*60*24*2) {
1947 # convert age in seconds to "nn units ago" string
1952 if ($age > 60*60*24*365*2) {
1953 $age_str = (int $age/60/60/24/365);
1954 $age_str .= " years ago";
1955 } elsif ($age > 60*60*24*(365/12)*2) {
1956 $age_str = int $age/60/60/24/(365/12);
1957 $age_str .= " months ago";
1958 } elsif ($age > 60*60*24*7*2) {
1959 $age_str = int $age/60/60/24/7;
1960 $age_str .= " weeks ago";
1961 } elsif ($age > 60*60*24*2) {
1962 $age_str = int $age/60/60/24;
1963 $age_str .= " days ago";
1964 } elsif ($age > 60*60*2) {
1965 $age_str = int $age/60/60;
1966 $age_str .= " hours ago";
1967 } elsif ($age > 60*2) {
1968 $age_str = int $age/60;
1969 $age_str .= " min ago";
1970 } elsif ($age > 2) {
1971 $age_str = int $age;
1972 $age_str .= " sec ago";
1974 $age_str .= " right now";
1980 S_IFINVALID
=> 0030000,
1981 S_IFGITLINK
=> 0160000,
1984 # submodule/subproject, a commit object reference
1988 return (($mode & S_IFMT
) == S_IFGITLINK
)
1991 # convert file mode in octal to symbolic file mode string
1993 my $mode = oct shift;
1995 if (S_ISGITLINK
($mode)) {
1996 return 'm---------';
1997 } elsif (S_ISDIR
($mode & S_IFMT
)) {
1998 return 'drwxr-xr-x';
1999 } elsif (S_ISLNK
($mode)) {
2000 return 'lrwxrwxrwx';
2001 } elsif (S_ISREG
($mode)) {
2002 # git cares only about the executable bit
2003 if ($mode & S_IXUSR
) {
2004 return '-rwxr-xr-x';
2006 return '-rw-r--r--';
2009 return '----------';
2013 # convert file mode in octal to file type string
2017 if ($mode !~ m/^[0-7]+$/) {
2023 if (S_ISGITLINK
($mode)) {
2025 } elsif (S_ISDIR
($mode & S_IFMT
)) {
2027 } elsif (S_ISLNK
($mode)) {
2029 } elsif (S_ISREG
($mode)) {
2036 # convert file mode in octal to file type description string
2037 sub file_type_long
{
2040 if ($mode !~ m/^[0-7]+$/) {
2046 if (S_ISGITLINK
($mode)) {
2048 } elsif (S_ISDIR
($mode & S_IFMT
)) {
2050 } elsif (S_ISLNK
($mode)) {
2052 } elsif (S_ISREG
($mode)) {
2053 if ($mode & S_IXUSR
) {
2054 return "executable";
2064 ## ----------------------------------------------------------------------
2065 ## functions returning short HTML fragments, or transforming HTML fragments
2066 ## which don't belong to other sections
2068 # format line of commit message.
2069 sub format_log_line_html
{
2072 $line = esc_html
($line, -nbsp
=>1);
2073 $line =~ s
{\b([0-9a
-fA
-F
]{8,40})\b}{
2074 $cgi->a({-href
=> href
(action
=>"object", hash
=>$1),
2075 -class => "text"}, $1);
2081 # format marker of refs pointing to given object
2083 # the destination action is chosen based on object type and current context:
2084 # - for annotated tags, we choose the tag view unless it's the current view
2085 # already, in which case we go to shortlog view
2086 # - for other refs, we keep the current view if we're in history, shortlog or
2087 # log view, and select shortlog otherwise
2088 sub format_ref_marker
{
2089 my ($refs, $id) = @_;
2092 if (defined $refs->{$id}) {
2093 foreach my $ref (@
{$refs->{$id}}) {
2094 # this code exploits the fact that non-lightweight tags are the
2095 # only indirect objects, and that they are the only objects for which
2096 # we want to use tag instead of shortlog as action
2097 my ($type, $name) = qw();
2098 my $indirect = ($ref =~ s/\^\{\}$//);
2099 # e.g. tags/v2.6.11 or heads/next
2100 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2109 $class .= " indirect" if $indirect;
2111 my $dest_action = "shortlog";
2114 $dest_action = "tag" unless $action eq "tag";
2115 } elsif ($action =~ /^(history|(short)?log)$/) {
2116 $dest_action = $action;
2120 $dest .= "refs/" unless $ref =~ m
!^refs
/!;
2123 my $link = $cgi->a({
2125 action
=>$dest_action,
2129 $markers .= " <span class=\"".esc_attr
($class)."\" title=\"".esc_attr
($ref)."\">" .
2135 return ' <span class="refs">'. $markers . '</span>';
2141 # format, perhaps shortened and with markers, title line
2142 sub format_subject_html
{
2143 my ($long, $short, $href, $extra) = @_;
2144 $extra = '' unless defined($extra);
2146 if (length($short) < length($long)) {
2147 $long =~ s/[[:cntrl:]]/?/g;
2148 return $cgi->a({-href
=> $href, -class => "list subject",
2149 -title
=> to_utf8
($long)},
2150 esc_html
($short)) . $extra;
2152 return $cgi->a({-href
=> $href, -class => "list subject"},
2153 esc_html
($long)) . $extra;
2157 # Rather than recomputing the url for an email multiple times, we cache it
2158 # after the first hit. This gives a visible benefit in views where the avatar
2159 # for the same email is used repeatedly (e.g. shortlog).
2160 # The cache is shared by all avatar engines (currently gravatar only), which
2161 # are free to use it as preferred. Since only one avatar engine is used for any
2162 # given page, there's no risk for cache conflicts.
2163 our %avatar_cache = ();
2165 # Compute the picon url for a given email, by using the picon search service over at
2166 # http://www.cs.indiana.edu/picons/search.html
2168 my $email = lc shift;
2169 if (!$avatar_cache{$email}) {
2170 my ($user, $domain) = split('@', $email);
2171 $avatar_cache{$email} =
2172 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2174 "users+domains+unknown/up/single";
2176 return $avatar_cache{$email};
2179 # Compute the gravatar url for a given email, if it's not in the cache already.
2180 # Gravatar stores only the part of the URL before the size, since that's the
2181 # one computationally more expensive. This also allows reuse of the cache for
2182 # different sizes (for this particular engine).
2184 my $email = lc shift;
2186 $avatar_cache{$email} ||=
2187 "//www.gravatar.com/avatar/" .
2188 Digest
::MD5
::md5_hex
($email) . "?s=";
2189 return $avatar_cache{$email} . $size;
2192 # Insert an avatar for the given $email at the given $size if the feature
2194 sub git_get_avatar
{
2195 my ($email, %opts) = @_;
2196 my $pre_white = ($opts{-pad_before
} ?
" " : "");
2197 my $post_white = ($opts{-pad_after
} ?
" " : "");
2198 $opts{-size
} ||= 'default';
2199 my $size = $avatar_size{$opts{-size
}} || $avatar_size{'default'};
2201 if ($git_avatar eq 'gravatar') {
2202 $url = gravatar_url
($email, $size);
2203 } elsif ($git_avatar eq 'picon') {
2204 $url = picon_url
($email);
2206 # Other providers can be added by extending the if chain, defining $url
2207 # as needed. If no variant puts something in $url, we assume avatars
2208 # are completely disabled/unavailable.
2211 "<img width=\"$size\" " .
2212 "class=\"avatar\" " .
2213 "src=\"".esc_url
($url)."\" " .
2221 sub format_search_author
{
2222 my ($author, $searchtype, $displaytext) = @_;
2223 my $have_search = gitweb_check_feature
('search');
2227 if ($searchtype eq 'author') {
2228 $performed = "authored";
2229 } elsif ($searchtype eq 'committer') {
2230 $performed = "committed";
2233 return $cgi->a({-href
=> href
(action
=>"search", hash
=>$hash,
2234 searchtext
=>$author,
2235 searchtype
=>$searchtype), class=>"list",
2236 title
=>"Search for commits $performed by $author"},
2240 return $displaytext;
2244 # format the author name of the given commit with the given tag
2245 # the author name is chopped and escaped according to the other
2246 # optional parameters (see chop_str).
2247 sub format_author_html
{
2250 my $author = chop_and_escape_str
($co->{'author_name'}, @_);
2251 return "<$tag class=\"author\">" .
2252 format_search_author
($co->{'author_name'}, "author",
2253 git_get_avatar
($co->{'author_email'}, -pad_after
=> 1) .
2258 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2259 sub format_git_diff_header_line
{
2261 my $diffinfo = shift;
2262 my ($from, $to) = @_;
2264 if ($diffinfo->{'nparents'}) {
2266 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2267 if ($to->{'href'}) {
2268 $line .= $cgi->a({-href
=> $to->{'href'}, -class => "path"},
2269 esc_path
($to->{'file'}));
2270 } else { # file was deleted (no href)
2271 $line .= esc_path
($to->{'file'});
2275 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2276 if ($from->{'href'}) {
2277 $line .= $cgi->a({-href
=> $from->{'href'}, -class => "path"},
2278 'a/' . esc_path
($from->{'file'}));
2279 } else { # file was added (no href)
2280 $line .= 'a/' . esc_path
($from->{'file'});
2283 if ($to->{'href'}) {
2284 $line .= $cgi->a({-href
=> $to->{'href'}, -class => "path"},
2285 'b/' . esc_path
($to->{'file'}));
2286 } else { # file was deleted
2287 $line .= 'b/' . esc_path
($to->{'file'});
2291 return "<div class=\"diff header\">$line</div>\n";
2294 # format extended diff header line, before patch itself
2295 sub format_extended_diff_header_line
{
2297 my $diffinfo = shift;
2298 my ($from, $to) = @_;
2301 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2302 $line .= $cgi->a({-href
=>$from->{'href'}, -class=>"path"},
2303 esc_path
($from->{'file'}));
2305 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2306 $line .= $cgi->a({-href
=>$to->{'href'}, -class=>"path"},
2307 esc_path
($to->{'file'}));
2309 # match single <mode>
2310 if ($line =~ m/\s(\d{6})$/) {
2311 $line .= '<span class="info"> (' .
2312 file_type_long
($1) .
2316 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2317 # can match only for combined diff
2319 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2320 if ($from->{'href'}[$i]) {
2321 $line .= $cgi->a({-href
=>$from->{'href'}[$i],
2323 substr($diffinfo->{'from_id'}[$i],0,7));
2328 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2331 if ($to->{'href'}) {
2332 $line .= $cgi->a({-href
=>$to->{'href'}, -class=>"hash"},
2333 substr($diffinfo->{'to_id'},0,7));
2338 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2339 # can match only for ordinary diff
2340 my ($from_link, $to_link);
2341 if ($from->{'href'}) {
2342 $from_link = $cgi->a({-href
=>$from->{'href'}, -class=>"hash"},
2343 substr($diffinfo->{'from_id'},0,7));
2345 $from_link = '0' x
7;
2347 if ($to->{'href'}) {
2348 $to_link = $cgi->a({-href
=>$to->{'href'}, -class=>"hash"},
2349 substr($diffinfo->{'to_id'},0,7));
2353 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2354 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2357 return $line . "<br/>\n";
2360 # format from-file/to-file diff header
2361 sub format_diff_from_to_header
{
2362 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2367 #assert($line =~ m/^---/) if DEBUG;
2368 # no extra formatting for "^--- /dev/null"
2369 if (! $diffinfo->{'nparents'}) {
2370 # ordinary (single parent) diff
2371 if ($line =~ m!^--- "?a/!) {
2372 if ($from->{'href'}) {
2374 $cgi->a({-href
=>$from->{'href'}, -class=>"path"},
2375 esc_path
($from->{'file'}));
2378 esc_path
($from->{'file'});
2381 $result .= qq!<div
class="diff from_file">$line</div
>\n!;
2384 # combined diff (merge commit)
2385 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2386 if ($from->{'href'}[$i]) {
2388 $cgi->a({-href
=>href
(action
=>"blobdiff",
2389 hash_parent
=>$diffinfo->{'from_id'}[$i],
2390 hash_parent_base
=>$parents[$i],
2391 file_parent
=>$from->{'file'}[$i],
2392 hash
=>$diffinfo->{'to_id'},
2394 file_name
=>$to->{'file'}),
2396 -title
=>"diff" . ($i+1)},
2399 $cgi->a({-href
=>$from->{'href'}[$i], -class=>"path"},
2400 esc_path
($from->{'file'}[$i]));
2402 $line = '--- /dev/null';
2404 $result .= qq!<div
class="diff from_file">$line</div
>\n!;
2409 #assert($line =~ m/^\+\+\+/) if DEBUG;
2410 # no extra formatting for "^+++ /dev/null"
2411 if ($line =~ m!^\+\+\+ "?b/!) {
2412 if ($to->{'href'}) {
2414 $cgi->a({-href
=>$to->{'href'}, -class=>"path"},
2415 esc_path
($to->{'file'}));
2418 esc_path
($to->{'file'});
2421 $result .= qq!<div
class="diff to_file">$line</div
>\n!;
2426 # create note for patch simplified by combined diff
2427 sub format_diff_cc_simplified
{
2428 my ($diffinfo, @parents) = @_;
2431 $result .= "<div class=\"diff header\">" .
2433 if (!is_deleted
($diffinfo)) {
2434 $result .= $cgi->a({-href
=> href
(action
=>"blob",
2436 hash
=>$diffinfo->{'to_id'},
2437 file_name
=>$diffinfo->{'to_file'}),
2439 esc_path
($diffinfo->{'to_file'}));
2441 $result .= esc_path
($diffinfo->{'to_file'});
2443 $result .= "</div>\n" . # class="diff header"
2444 "<div class=\"diff nodifferences\">" .
2446 "</div>\n"; # class="diff nodifferences"
2451 sub diff_line_class
{
2452 my ($line, $from, $to) = @_;
2457 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2458 $num_sign = scalar @
{$from->{'href'}};
2461 my @diff_line_classifier = (
2462 { regexp
=> qr/^\@\@{$num_sign} /, class => "chunk_header"},
2463 { regexp
=> qr/^\\/, class => "incomplete" },
2464 { regexp
=> qr/^ {$num_sign}/, class => "ctx" },
2465 # classifier for context must come before classifier add/rem,
2466 # or we would have to use more complicated regexp, for example
2467 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2468 { regexp
=> qr/^[+ ]{$num_sign}/, class => "add" },
2469 { regexp
=> qr/^[- ]{$num_sign}/, class => "rem" },
2471 for my $clsfy (@diff_line_classifier) {
2472 return $clsfy->{'class'}
2473 if ($line =~ $clsfy->{'regexp'});
2480 # assumes that $from and $to are defined and correctly filled,
2481 # and that $line holds a line of chunk header for unified diff
2482 sub format_unidiff_chunk_header
{
2483 my ($line, $from, $to) = @_;
2485 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2486 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2488 $from_lines = 0 unless defined $from_lines;
2489 $to_lines = 0 unless defined $to_lines;
2491 if ($from->{'href'}) {
2492 $from_text = $cgi->a({-href
=>"$from->{'href'}#l$from_start",
2493 -class=>"list"}, $from_text);
2495 if ($to->{'href'}) {
2496 $to_text = $cgi->a({-href
=>"$to->{'href'}#l$to_start",
2497 -class=>"list"}, $to_text);
2499 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2500 "<span class=\"section\">" . esc_html
($section, -nbsp
=>1) . "</span>";
2504 # assumes that $from and $to are defined and correctly filled,
2505 # and that $line holds a line of chunk header for combined diff
2506 sub format_cc_diff_chunk_header
{
2507 my ($line, $from, $to) = @_;
2509 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2510 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2512 @from_text = split(' ', $ranges);
2513 for (my $i = 0; $i < @from_text; ++$i) {
2514 ($from_start[$i], $from_nlines[$i]) =
2515 (split(',', substr($from_text[$i], 1)), 0);
2518 $to_text = pop @from_text;
2519 $to_start = pop @from_start;
2520 $to_nlines = pop @from_nlines;
2522 $line = "<span class=\"chunk_info\">$prefix ";
2523 for (my $i = 0; $i < @from_text; ++$i) {
2524 if ($from->{'href'}[$i]) {
2525 $line .= $cgi->a({-href
=>"$from->{'href'}[$i]#l$from_start[$i]",
2526 -class=>"list"}, $from_text[$i]);
2528 $line .= $from_text[$i];
2532 if ($to->{'href'}) {
2533 $line .= $cgi->a({-href
=>"$to->{'href'}#l$to_start",
2534 -class=>"list"}, $to_text);
2538 $line .= " $prefix</span>" .
2539 "<span class=\"section\">" . esc_html
($section, -nbsp
=>1) . "</span>";
2543 # process patch (diff) line (not to be used for diff headers),
2544 # returning HTML-formatted (but not wrapped) line.
2545 # If the line is passed as a reference, it is treated as HTML and not
2547 sub format_diff_line
{
2548 my ($line, $diff_class, $from, $to) = @_;
2554 $line = untabify
($line);
2556 if ($from && $to && $line =~ m/^\@{2} /) {
2557 $line = format_unidiff_chunk_header
($line, $from, $to);
2558 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2559 $line = format_cc_diff_chunk_header
($line, $from, $to);
2561 $line = esc_html
($line, -nbsp
=>1);
2565 my $diff_classes = "diff";
2566 $diff_classes .= " $diff_class" if ($diff_class);
2567 $line = "<div class=\"$diff_classes\">$line</div>\n";
2572 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2573 # linked. Pass the hash of the tree/commit to snapshot.
2574 sub format_snapshot_links
{
2576 my $num_fmts = @snapshot_fmts;
2577 if ($num_fmts > 1) {
2578 # A parenthesized list of links bearing format names.
2579 # e.g. "snapshot (_tar.gz_ _zip_)"
2580 return "snapshot (" . join(' ', map
2587 }, $known_snapshot_formats{$_}{'display'})
2588 , @snapshot_fmts) . ")";
2589 } elsif ($num_fmts == 1) {
2590 # A single "snapshot" link whose tooltip bears the format name.
2592 my ($fmt) = @snapshot_fmts;
2598 snapshot_format
=>$fmt
2600 -title
=> "in format: $known_snapshot_formats{$fmt}{'display'}"
2602 } else { # $num_fmts == 0
2607 ## ......................................................................
2608 ## functions returning values to be passed, perhaps after some
2609 ## transformation, to other functions; e.g. returning arguments to href()
2611 # returns hash to be passed to href to generate gitweb URL
2612 # in -title key it returns description of link
2614 my $format = shift || 'Atom';
2615 my %res = (action
=> lc($format));
2616 my $matched_ref = 0;
2618 # feed links are possible only for project views
2619 return unless (defined $project);
2620 # some views should link to OPML, or to generic project feed,
2621 # or don't have specific feed yet (so they should use generic)
2622 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2625 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2626 # (fullname) to differentiate from tag links; this also makes
2627 # possible to detect branch links
2628 for my $ref (get_branch_refs
()) {
2629 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2630 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2632 $matched_ref = $ref;
2636 # find log type for feed description (title)
2638 if (defined $file_name) {
2639 $type = "history of $file_name";
2640 $type .= "/" if ($action eq 'tree');
2641 $type .= " on '$branch'" if (defined $branch);
2643 $type = "log of $branch" if (defined $branch);
2646 $res{-title
} = $type;
2647 $res{'hash'} = (defined $branch ?
"refs/$matched_ref/$branch" : undef);
2648 $res{'file_name'} = $file_name;
2653 ## ----------------------------------------------------------------------
2654 ## git utility subroutines, invoking git commands
2656 # returns path to the core git executable and the --git-dir parameter as list
2658 $number_of_git_cmds++;
2659 return $GIT, '--git-dir='.$git_dir;
2662 # quote the given arguments for passing them to the shell
2663 # quote_command("command", "arg 1", "arg with ' and ! characters")
2664 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2665 # Try to avoid using this function wherever possible.
2668 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2671 # get HEAD ref of given project as hash
2672 sub git_get_head_hash
{
2673 return git_get_full_hash
(shift, 'HEAD');
2676 sub git_get_full_hash
{
2677 return git_get_hash
(@_);
2680 sub git_get_short_hash
{
2681 return git_get_hash
(@_, '--short=7');
2685 my ($project, $hash, @options) = @_;
2686 my $o_git_dir = $git_dir;
2688 $git_dir = "$projectroot/$project";
2689 if (open my $fd, '-|', git_cmd
(), 'rev-parse',
2690 '--verify', '-q', @options, $hash) {
2692 chomp $retval if defined $retval;
2695 if (defined $o_git_dir) {
2696 $git_dir = $o_git_dir;
2701 # get type of given object
2705 open my $fd, "-|", git_cmd
(), "cat-file", '-t', $hash or return;
2707 close $fd or return;
2712 # repository configuration
2713 our $config_file = '';
2716 # store multiple values for single key as anonymous array reference
2717 # single values stored directly in the hash, not as [ <value> ]
2718 sub hash_set_multi
{
2719 my ($hash, $key, $value) = @_;
2721 if (!exists $hash->{$key}) {
2722 $hash->{$key} = $value;
2723 } elsif (!ref $hash->{$key}) {
2724 $hash->{$key} = [ $hash->{$key}, $value ];
2726 push @
{$hash->{$key}}, $value;
2730 # return hash of git project configuration
2731 # optionally limited to some section, e.g. 'gitweb'
2732 sub git_parse_project_config
{
2733 my $section_regexp = shift;
2738 open my $fh, "-|", git_cmd
(), "config", '-z', '-l',
2741 while (my $keyval = <$fh>) {
2743 my ($key, $value) = split(/\n/, $keyval, 2);
2745 hash_set_multi
(\
%config, $key, $value)
2746 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2753 # convert config value to boolean: 'true' or 'false'
2754 # no value, number > 0, 'true' and 'yes' values are true
2755 # rest of values are treated as false (never as error)
2756 sub config_to_bool
{
2759 return 1 if !defined $val; # section.key
2761 # strip leading and trailing whitespace
2765 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2766 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2769 # convert config value to simple decimal number
2770 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2771 # to be multiplied by 1024, 1048576, or 1073741824
2775 # strip leading and trailing whitespace
2779 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2781 # unknown unit is treated as 1
2782 return $num * ($unit eq 'g' ?
1073741824 :
2783 $unit eq 'm' ?
1048576 :
2784 $unit eq 'k' ?
1024 : 1);
2789 # convert config value to array reference, if needed
2790 sub config_to_multi
{
2793 return ref($val) ?
$val : (defined($val) ?
[ $val ] : []);
2796 sub git_get_project_config
{
2797 my ($key, $type) = @_;
2799 return unless defined $git_dir;
2802 return unless ($key);
2803 # only subsection, if exists, is case sensitive,
2804 # and not lowercased by 'git config -z -l'
2805 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2807 $key = join(".", lc($hi), $mi, lc($lo));
2808 return if ($lo =~ /\W/ || $hi =~ /\W/);
2812 return if ($key =~ /\W/);
2814 $key =~ s/^gitweb\.//;
2817 if (defined $type) {
2820 unless ($type eq 'bool' || $type eq 'int');
2824 if (!defined $config_file ||
2825 $config_file ne "$git_dir/config") {
2826 %config = git_parse_project_config
('gitweb');
2827 $config_file = "$git_dir/config";
2830 # check if config variable (key) exists
2831 return unless exists $config{"gitweb.$key"};
2834 if (!defined $type) {
2835 return $config{"gitweb.$key"};
2836 } elsif ($type eq 'bool') {
2837 # backward compatibility: 'git config --bool' returns true/false
2838 return config_to_bool
($config{"gitweb.$key"}) ?
'true' : 'false';
2839 } elsif ($type eq 'int') {
2840 return config_to_int
($config{"gitweb.$key"});
2842 return $config{"gitweb.$key"};
2845 # get hash of given path at given ref
2846 sub git_get_hash_by_path
{
2848 my $path = shift || return undef;
2853 open my $fd, "-|", git_cmd
(), "ls-tree", $base, "--", $path
2854 or die_error
(500, "Open git-ls-tree failed");
2856 close $fd or return undef;
2858 if (!defined $line) {
2859 # there is no tree or hash given by $path at $base
2863 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2864 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2865 if (defined $type && $type ne $2) {
2866 # type doesn't match
2872 # get path of entry with given hash at given tree-ish (ref)
2873 # used to get 'from' filename for combined diff (merge commit) for renames
2874 sub git_get_path_by_hash
{
2875 my $base = shift || return;
2876 my $hash = shift || return;
2880 open my $fd, "-|", git_cmd
(), "ls-tree", '-r', '-t', '-z', $base
2882 while (my $line = <$fd>) {
2885 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2886 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2887 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2896 ## ......................................................................
2897 ## git utility functions, directly accessing git repository
2899 # get the value of config variable either from file named as the variable
2900 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2901 # configuration variable in the repository config file.
2902 sub git_get_file_or_project_config
{
2903 my ($path, $name) = @_;
2905 $git_dir = "$projectroot/$path";
2906 open my $fd, '<', "$git_dir/$name"
2907 or return git_get_project_config
($name);
2910 if (defined $conf) {
2916 sub git_get_project_description
{
2918 return git_get_file_or_project_config
($path, 'description');
2921 sub git_get_project_category
{
2923 return git_get_file_or_project_config
($path, 'category');
2927 # supported formats:
2928 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2929 # - if its contents is a number, use it as tag weight,
2930 # - otherwise add a tag with weight 1
2931 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2932 # the same value multiple times increases tag weight
2933 # * `gitweb.ctag' multi-valued repo config variable
2934 sub git_get_project_ctags
{
2935 my $project = shift;
2938 $git_dir = "$projectroot/$project";
2939 if (opendir my $dh, "$git_dir/ctags") {
2940 my @files = grep { -f
$_ } map { "$git_dir/ctags/$_" } readdir($dh);
2941 foreach my $tagfile (@files) {
2942 open my $ct, '<', $tagfile
2948 (my $ctag = $tagfile) =~ s
#.*/##;
2949 if ($val =~ /^\d+$/) {
2950 $ctags->{$ctag} = $val;
2952 $ctags->{$ctag} = 1;
2957 } elsif (open my $fh, '<', "$git_dir/ctags") {
2958 while (my $line = <$fh>) {
2960 $ctags->{$line}++ if $line;
2965 my $taglist = config_to_multi
(git_get_project_config
('ctag'));
2966 foreach my $tag (@
$taglist) {
2974 # return hash, where keys are content tags ('ctags'),
2975 # and values are sum of weights of given tag in every project
2976 sub git_gather_all_ctags
{
2977 my $projects = shift;
2980 foreach my $p (@
$projects) {
2981 foreach my $ct (keys %{$p->{'ctags'}}) {
2982 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2989 sub git_populate_project_tagcloud
{
2992 # First, merge different-cased tags; tags vote on casing
2994 foreach (keys %$ctags) {
2995 $ctags_lc{lc $_}->{count
} += $ctags->{$_};
2996 if (not $ctags_lc{lc $_}->{topcount
}
2997 or $ctags_lc{lc $_}->{topcount
} < $ctags->{$_}) {
2998 $ctags_lc{lc $_}->{topcount
} = $ctags->{$_};
2999 $ctags_lc{lc $_}->{topname
} = $_;
3004 my $matched = $input_params{'ctag'};
3005 if (eval { require HTML
::TagCloud
; 1; }) {
3006 $cloud = HTML
::TagCloud
->new;
3007 foreach my $ctag (sort keys %ctags_lc) {
3008 # Pad the title with spaces so that the cloud looks
3010 my $title = esc_html
($ctags_lc{$ctag}->{topname
});
3011 $title =~ s/ / /g;
3012 $title =~ s/^/ /g;
3013 $title =~ s/$/ /g;
3014 if (defined $matched && $matched eq $ctag) {
3015 $title = qq(<span
class="match">$title</span
>);
3017 $cloud->add($title, href
(project
=>undef, ctag
=>$ctag),
3018 $ctags_lc{$ctag}->{count
});
3022 foreach my $ctag (keys %ctags_lc) {
3023 my $title = esc_html
($ctags_lc{$ctag}->{topname
}, -nbsp
=>1);
3024 if (defined $matched && $matched eq $ctag) {
3025 $title = qq(<span
class="match">$title</span
>);
3027 $cloud->{$ctag}{count
} = $ctags_lc{$ctag}->{count
};
3028 $cloud->{$ctag}{ctag
} =
3029 $cgi->a({-href
=>href
(project
=>undef, ctag
=>$ctag)}, $title);
3035 sub git_show_project_tagcloud
{
3036 my ($cloud, $count) = @_;
3037 if (ref $cloud eq 'HTML::TagCloud') {
3038 return $cloud->html_and_css($count);
3040 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3042 '<div id="htmltagcloud"'.($project ?
'' : ' align="center"').'>' .
3044 $cloud->{$_}->{'ctag'}
3045 } splice(@tags, 0, $count)) .
3050 sub git_get_project_url_list
{
3053 $git_dir = "$projectroot/$path";
3054 open my $fd, '<', "$git_dir/cloneurl"
3055 or return wantarray ?
3056 @
{ config_to_multi
(git_get_project_config
('url')) } :
3057 config_to_multi
(git_get_project_config
('url'));
3058 my @git_project_url_list = map { chomp; $_ } <$fd>;
3061 return wantarray ?
@git_project_url_list : \
@git_project_url_list;
3064 sub git_get_projects_list
{
3065 my $filter = shift || '';
3066 my $paranoid = shift;
3069 if (-d
$projects_list) {
3070 # search in directory
3071 my $dir = $projects_list;
3072 # remove the trailing "/"
3074 my $pfxlen = length("$dir");
3075 my $pfxdepth = ($dir =~ tr!/!!);
3076 # when filtering, search only given subdirectory
3077 if ($filter && !$paranoid) {
3083 follow_fast
=> 1, # follow symbolic links
3084 follow_skip
=> 2, # ignore duplicates
3085 dangling_symlinks
=> 0, # ignore dangling symlinks, silently
3088 our $project_maxdepth;
3090 # skip project-list toplevel, if we get it.
3091 return if (m!^[/.]$!);
3092 # only directories can be git repositories
3093 return unless (-d
$_);
3094 # don't traverse too deep (Find is super slow on os x)
3095 # $project_maxdepth excludes depth of $projectroot
3096 if (($File::Find
::name
=~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3097 $File::Find
::prune
= 1;
3101 my $path = substr($File::Find
::name
, $pfxlen + 1);
3102 # paranoidly only filter here
3103 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3106 # we check related file in $projectroot
3107 if (check_export_ok
("$projectroot/$path")) {
3108 push @list, { path
=> $path };
3109 $File::Find
::prune
= 1;
3114 } elsif (-f
$projects_list) {
3115 # read from file(url-encoded):
3116 # 'git%2Fgit.git Linus+Torvalds'
3117 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3118 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3119 open my $fd, '<', $projects_list or return;
3121 while (my $line = <$fd>) {
3123 my ($path, $owner) = split ' ', $line;
3124 $path = unescape
($path);
3125 $owner = unescape
($owner);
3126 if (!defined $path) {
3129 # if $filter is rpovided, check if $path begins with $filter
3130 if ($filter && $path !~ m!^\Q$filter\E/!) {
3133 if (check_export_ok
("$projectroot/$path")) {
3138 $pr->{'owner'} = to_utf8
($owner);
3148 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3149 # as side effects it sets 'forks' field to list of forks for forked projects
3150 sub filter_forks_from_projects_list
{
3151 my $projects = shift;
3153 my %trie; # prefix tree of directories (path components)
3154 # generate trie out of those directories that might contain forks
3155 foreach my $pr (@
$projects) {
3156 my $path = $pr->{'path'};
3157 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3158 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3159 next unless ($path); # skip '.git' repository: tests, git-instaweb
3160 next unless (-d
"$projectroot/$path"); # containing directory exists
3161 $pr->{'forks'} = []; # there can be 0 or more forks of project
3164 my @dirs = split('/', $path);
3165 # walk the trie, until either runs out of components or out of trie
3167 while (scalar @dirs &&
3168 exists($ref->{$dirs[0]})) {
3169 $ref = $ref->{shift @dirs};
3171 # create rest of trie structure from rest of components
3172 foreach my $dir (@dirs) {
3173 $ref = $ref->{$dir} = {};
3175 # create end marker, store $pr as a data
3176 $ref->{''} = $pr if (!exists $ref->{''});
3179 # filter out forks, by finding shortest prefix match for paths
3182 foreach my $pr (@
$projects) {
3186 foreach my $dir (split('/', $pr->{'path'})) {
3187 if (exists $ref->{''}) {
3188 # found [shortest] prefix, is a fork - skip it
3189 push @
{$ref->{''}{'forks'}}, $pr;
3192 if (!exists $ref->{$dir}) {
3193 # not in trie, cannot have prefix, not a fork
3194 push @filtered, $pr;
3197 # If the dir is there, we just walk one step down the trie.
3198 $ref = $ref->{$dir};
3200 # we ran out of trie
3201 # (shouldn't happen: it's either no match, or end marker)
3202 push @filtered, $pr;
3208 # note: fill_project_list_info must be run first,
3209 # for 'descr_long' and 'ctags' to be filled
3210 sub search_projects_list
{
3211 my ($projlist, %opts) = @_;
3212 my $tagfilter = $opts{'tagfilter'};
3213 my $search_re = $opts{'search_regexp'};
3216 unless ($tagfilter || $search_re);
3218 # searching projects require filling to be run before it;
3219 fill_project_list_info
($projlist,
3220 $tagfilter ?
'ctags' : (),
3221 $search_re ?
('path', 'descr') : ());
3224 foreach my $pr (@
$projlist) {
3227 next unless ref($pr->{'ctags'}) eq 'HASH';
3229 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3234 $pr->{'path'} =~ /$search_re/ ||
3235 $pr->{'descr_long'} =~ /$search_re/;
3238 push @projects, $pr;
3244 our $gitweb_project_owner = undef;
3245 sub git_get_project_list_from_file
{
3247 return if (defined $gitweb_project_owner);
3249 $gitweb_project_owner = {};
3250 # read from file (url-encoded):
3251 # 'git%2Fgit.git Linus+Torvalds'
3252 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3253 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3254 if (-f
$projects_list) {
3255 open(my $fd, '<', $projects_list);
3256 while (my $line = <$fd>) {
3258 my ($pr, $ow) = split ' ', $line;
3259 $pr = unescape
($pr);
3260 $ow = unescape
($ow);
3261 $gitweb_project_owner->{$pr} = to_utf8
($ow);
3267 sub git_get_project_owner
{
3268 my $project = shift;
3271 return undef unless $project;
3272 $git_dir = "$projectroot/$project";
3274 if (!defined $gitweb_project_owner) {
3275 git_get_project_list_from_file
();
3278 if (exists $gitweb_project_owner->{$project}) {
3279 $owner = $gitweb_project_owner->{$project};
3281 if (!defined $owner){
3282 $owner = git_get_project_config
('owner');
3284 if (!defined $owner) {
3285 $owner = get_file_owner
("$git_dir");
3291 sub git_get_last_activity
{
3295 $git_dir = "$projectroot/$path";
3296 open($fd, "-|", git_cmd
(), 'for-each-ref',
3297 '--format=%(committer)',
3298 '--sort=-committerdate',
3300 map { "refs/$_" } get_branch_refs
()) or return;
3301 my $most_recent = <$fd>;
3302 close $fd or return;
3303 if (defined $most_recent &&
3304 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3306 my $age = time - $timestamp;
3307 return ($age, age_string
($age));
3309 return (undef, undef);
3312 # Implementation note: when a single remote is wanted, we cannot use 'git
3313 # remote show -n' because that command always work (assuming it's a remote URL
3314 # if it's not defined), and we cannot use 'git remote show' because that would
3315 # try to make a network roundtrip. So the only way to find if that particular
3316 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3317 # and when we find what we want.
3318 sub git_get_remotes_list
{
3322 open my $fd, '-|' , git_cmd
(), 'remote', '-v';
3324 while (my $remote = <$fd>) {
3326 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3327 next if $wanted and not $remote eq $wanted;
3328 my ($url, $key) = ($1, $2);
3330 $remotes{$remote} ||= { 'heads' => () };
3331 $remotes{$remote}{$key} = $url;
3333 close $fd or return;
3334 return wantarray ?
%remotes : \
%remotes;
3337 # Takes a hash of remotes as first parameter and fills it by adding the
3338 # available remote heads for each of the indicated remotes.
3339 sub fill_remote_heads
{
3340 my $remotes = shift;
3341 my @heads = map { "remotes/$_" } keys %$remotes;
3342 my @remoteheads = git_get_heads_list
(undef, @heads);
3343 foreach my $remote (keys %$remotes) {
3344 $remotes->{$remote}{'heads'} = [ grep {
3345 $_->{'name'} =~ s!^$remote/!!
3350 sub git_get_references
{
3351 my $type = shift || "";
3353 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3354 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3355 open my $fd, "-|", git_cmd
(), "show-ref", "--dereference",
3356 ($type ?
("--", "refs/$type") : ()) # use -- <pattern> if $type
3359 while (my $line = <$fd>) {
3361 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3362 if (defined $refs{$1}) {
3363 push @
{$refs{$1}}, $2;
3369 close $fd or return;
3373 sub git_get_rev_name_tags
{
3374 my $hash = shift || return undef;
3376 open my $fd, "-|", git_cmd
(), "name-rev", "--tags", $hash
3378 my $name_rev = <$fd>;
3381 if ($name_rev =~ m
|^$hash tags
/(.*)$|) {
3384 # catches also '$hash undefined' output
3389 ## ----------------------------------------------------------------------
3390 ## parse to hash functions
3394 my $tz = shift || "-0000";
3397 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3398 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3399 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3400 $date{'hour'} = $hour;
3401 $date{'minute'} = $min;
3402 $date{'mday'} = $mday;
3403 $date{'day'} = $days[$wday];
3404 $date{'month'} = $months[$mon];
3405 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3406 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3407 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3408 $mday, $months[$mon], $hour ,$min;
3409 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3410 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3412 my ($tz_sign, $tz_hour, $tz_min) =
3413 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3414 $tz_sign = ($tz_sign eq '-' ?
-1 : +1);
3415 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3416 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3417 $date{'hour_local'} = $hour;
3418 $date{'minute_local'} = $min;
3419 $date{'tz_local'} = $tz;
3420 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3421 1900+$year, $mon+1, $mday,
3422 $hour, $min, $sec, $tz);
3431 open my $fd, "-|", git_cmd
(), "cat-file", "tag", $tag_id or return;
3432 $tag{'id'} = $tag_id;
3433 while (my $line = <$fd>) {
3435 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3436 $tag{'object'} = $1;
3437 } elsif ($line =~ m/^type (.+)$/) {
3439 } elsif ($line =~ m/^tag (.+)$/) {
3441 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3442 $tag{'author'} = $1;
3443 $tag{'author_epoch'} = $2;
3444 $tag{'author_tz'} = $3;
3445 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3446 $tag{'author_name'} = $1;
3447 $tag{'author_email'} = $2;
3449 $tag{'author_name'} = $tag{'author'};
3451 } elsif ($line =~ m/--BEGIN/) {
3452 push @comment, $line;
3454 } elsif ($line eq "") {
3458 push @comment, <$fd>;
3459 $tag{'comment'} = \
@comment;
3460 close $fd or return;
3461 if (!defined $tag{'name'}) {
3467 sub parse_commit_text
{
3468 my ($commit_text, $withparents) = @_;
3469 my @commit_lines = split '\n', $commit_text;
3472 pop @commit_lines; # Remove '\0'
3474 if (! @commit_lines) {
3478 my $header = shift @commit_lines;
3479 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3482 ($co{'id'}, my @parents) = split ' ', $header;
3483 while (my $line = shift @commit_lines) {
3484 last if $line eq "\n";
3485 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3487 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3489 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3490 $co{'author'} = to_utf8
($1);
3491 $co{'author_epoch'} = $2;
3492 $co{'author_tz'} = $3;
3493 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3494 $co{'author_name'} = $1;
3495 $co{'author_email'} = $2;
3497 $co{'author_name'} = $co{'author'};
3499 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3500 $co{'committer'} = to_utf8
($1);
3501 $co{'committer_epoch'} = $2;
3502 $co{'committer_tz'} = $3;
3503 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3504 $co{'committer_name'} = $1;
3505 $co{'committer_email'} = $2;
3507 $co{'committer_name'} = $co{'committer'};
3511 if (!defined $co{'tree'}) {
3514 $co{'parents'} = \
@parents;
3515 $co{'parent'} = $parents[0];
3517 foreach my $title (@commit_lines) {
3520 $co{'title'} = chop_str
($title, 80, 5);
3521 # remove leading stuff of merges to make the interesting part visible
3522 if (length($title) > 50) {
3523 $title =~ s/^Automatic //;
3524 $title =~ s/^merge (of|with) /Merge ... /i;
3525 if (length($title) > 50) {
3526 $title =~ s/(http|rsync):\/\///;
3528 if (length($title) > 50) {
3529 $title =~ s/(master|www|rsync)\.//;
3531 if (length($title) > 50) {
3532 $title =~ s/kernel.org:?//;
3534 if (length($title) > 50) {
3535 $title =~ s/\/pub\/scm//;
3538 $co{'title_short'} = chop_str
($title, 50, 5);
3542 if (! defined $co{'title'} || $co{'title'} eq "") {
3543 $co{'title'} = $co{'title_short'} = '(no commit message)';
3545 # remove added spaces
3546 foreach my $line (@commit_lines) {
3549 $co{'comment'} = \
@commit_lines;
3551 my $age = time - $co{'committer_epoch'};
3553 $co{'age_string'} = age_string
($age);
3554 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3555 if ($age > 60*60*24*7*2) {
3556 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3557 $co{'age_string_age'} = $co{'age_string'};
3559 $co{'age_string_date'} = $co{'age_string'};
3560 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3566 my ($commit_id) = @_;
3571 open my $fd, "-|", git_cmd
(), "rev-list",
3577 or die_error
(500, "Open git-rev-list failed");
3578 %co = parse_commit_text
(<$fd>, 1);
3585 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3593 open my $fd, "-|", git_cmd
(), "rev-list",
3596 ("--max-count=" . $maxcount),
3597 ("--skip=" . $skip),
3601 ($filename ?
($filename) : ())
3602 or die_error
(500, "Open git-rev-list failed");
3603 while (my $line = <$fd>) {
3604 my %co = parse_commit_text
($line);
3609 return wantarray ?
@cos : \
@cos;
3612 # parse line of git-diff-tree "raw" output
3613 sub parse_difftree_raw_line
{
3617 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3618 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3619 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3620 $res{'from_mode'} = $1;
3621 $res{'to_mode'} = $2;
3622 $res{'from_id'} = $3;
3624 $res{'status'} = $5;
3625 $res{'similarity'} = $6;
3626 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3627 ($res{'from_file'}, $res{'to_file'}) = map { unquote
($_) } split("\t", $7);
3629 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote
($7);
3632 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3633 # combined diff (for merge commit)
3634 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3635 $res{'nparents'} = length($1);
3636 $res{'from_mode'} = [ split(' ', $2) ];
3637 $res{'to_mode'} = pop @
{$res{'from_mode'}};
3638 $res{'from_id'} = [ split(' ', $3) ];
3639 $res{'to_id'} = pop @
{$res{'from_id'}};
3640 $res{'status'} = [ split('', $4) ];
3641 $res{'to_file'} = unquote
($5);
3643 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3644 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3645 $res{'commit'} = $1;
3648 return wantarray ?
%res : \
%res;
3651 # wrapper: return parsed line of git-diff-tree "raw" output
3652 # (the argument might be raw line, or parsed info)
3653 sub parsed_difftree_line
{
3654 my $line_or_ref = shift;
3656 if (ref($line_or_ref) eq "HASH") {
3657 # pre-parsed (or generated by hand)
3658 return $line_or_ref;
3660 return parse_difftree_raw_line
($line_or_ref);
3664 # parse line of git-ls-tree output
3665 sub parse_ls_tree_line
{
3671 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3672 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3681 $res{'name'} = unquote
($5);
3684 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3685 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3693 $res{'name'} = unquote
($4);
3697 return wantarray ?
%res : \
%res;
3700 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3701 sub parse_from_to_diffinfo
{
3702 my ($diffinfo, $from, $to, @parents) = @_;
3704 if ($diffinfo->{'nparents'}) {
3706 $from->{'file'} = [];
3707 $from->{'href'} = [];
3708 fill_from_file_info
($diffinfo, @parents)
3709 unless exists $diffinfo->{'from_file'};
3710 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3711 $from->{'file'}[$i] =
3712 defined $diffinfo->{'from_file'}[$i] ?
3713 $diffinfo->{'from_file'}[$i] :
3714 $diffinfo->{'to_file'};
3715 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3716 $from->{'href'}[$i] = href
(action
=>"blob",
3717 hash_base
=>$parents[$i],
3718 hash
=>$diffinfo->{'from_id'}[$i],
3719 file_name
=>$from->{'file'}[$i]);
3721 $from->{'href'}[$i] = undef;
3725 # ordinary (not combined) diff
3726 $from->{'file'} = $diffinfo->{'from_file'};
3727 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3728 $from->{'href'} = href
(action
=>"blob", hash_base
=>$hash_parent,
3729 hash
=>$diffinfo->{'from_id'},
3730 file_name
=>$from->{'file'});
3732 delete $from->{'href'};
3736 $to->{'file'} = $diffinfo->{'to_file'};
3737 if (!is_deleted
($diffinfo)) { # file exists in result
3738 $to->{'href'} = href
(action
=>"blob", hash_base
=>$hash,
3739 hash
=>$diffinfo->{'to_id'},
3740 file_name
=>$to->{'file'});
3742 delete $to->{'href'};
3746 ## ......................................................................
3747 ## parse to array of hashes functions
3749 sub git_get_heads_list
{
3750 my ($limit, @classes) = @_;
3751 @classes = get_branch_refs
() unless @classes;
3752 my @patterns = map { "refs/$_" } @classes;
3755 open my $fd, '-|', git_cmd
(), 'for-each-ref',
3756 ($limit ?
'--count='.($limit+1) : ()), '--sort=-committerdate',
3757 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3760 while (my $line = <$fd>) {
3764 my ($refinfo, $committerinfo) = split(/\0/, $line);
3765 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3766 my ($committer, $epoch, $tz) =
3767 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3768 $ref_item{'fullname'} = $name;
3769 my $strip_refs = join '|', map { quotemeta } get_branch_refs
();
3770 $name =~ s!^refs/($strip_refs|remotes)/!!;
3771 $ref_item{'name'} = $name;
3772 # for refs neither in 'heads' nor 'remotes' we want to
3773 # show their ref dir
3774 my $ref_dir = (defined $1) ?
$1 : '';
3775 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3776 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3779 $ref_item{'id'} = $hash;
3780 $ref_item{'title'} = $title || '(no commit message)';
3781 $ref_item{'epoch'} = $epoch;
3783 $ref_item{'age'} = age_string
(time - $ref_item{'epoch'});
3785 $ref_item{'age'} = "unknown";
3788 push @headslist, \
%ref_item;
3792 return wantarray ?
@headslist : \
@headslist;
3795 sub git_get_tags_list
{
3799 open my $fd, '-|', git_cmd
(), 'for-each-ref',
3800 ($limit ?
'--count='.($limit+1) : ()), '--sort=-creatordate',
3801 '--format=%(objectname) %(objecttype) %(refname) '.
3802 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3805 while (my $line = <$fd>) {
3809 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3810 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3811 my ($creator, $epoch, $tz) =
3812 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3813 $ref_item{'fullname'} = $name;
3814 $name =~ s!^refs/tags/!!;
3816 $ref_item{'type'} = $type;
3817 $ref_item{'id'} = $id;
3818 $ref_item{'name'} = $name;
3819 if ($type eq "tag") {
3820 $ref_item{'subject'} = $title;
3821 $ref_item{'reftype'} = $reftype;
3822 $ref_item{'refid'} = $refid;
3824 $ref_item{'reftype'} = $type;
3825 $ref_item{'refid'} = $id;
3828 if ($type eq "tag" || $type eq "commit") {
3829 $ref_item{'epoch'} = $epoch;
3831 $ref_item{'age'} = age_string
(time - $ref_item{'epoch'});
3833 $ref_item{'age'} = "unknown";
3837 push @tagslist, \
%ref_item;
3841 return wantarray ?
@tagslist : \
@tagslist;
3844 ## ----------------------------------------------------------------------
3845 ## filesystem-related functions
3847 sub get_file_owner
{
3850 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3851 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3852 if (!defined $gcos) {
3856 $owner =~ s/[,;].*$//;
3857 return to_utf8
($owner);
3860 # assume that file exists
3862 my $filename = shift;
3864 open my $fd, '<', $filename;
3865 print map { to_utf8
($_) } <$fd>;
3869 ## ......................................................................
3870 ## mimetype related functions
3872 sub mimetype_guess_file
{
3873 my $filename = shift;
3874 my $mimemap = shift;
3875 -r
$mimemap or return undef;
3878 open(my $mh, '<', $mimemap) or return undef;
3880 next if m/^#/; # skip comments
3881 my ($mimetype, @exts) = split(/\s+/);
3882 foreach my $ext (@exts) {
3883 $mimemap{$ext} = $mimetype;
3888 $filename =~ /\.([^.]*)$/;
3889 return $mimemap{$1};
3892 sub mimetype_guess
{
3893 my $filename = shift;
3895 $filename =~ /\./ or return undef;
3897 if ($mimetypes_file) {
3898 my $file = $mimetypes_file;
3899 if ($file !~ m!^/!) { # if it is relative path
3900 # it is relative to project
3901 $file = "$projectroot/$project/$file";
3903 $mime = mimetype_guess_file
($filename, $file);
3905 $mime ||= mimetype_guess_file
($filename, '/etc/mime.types');
3911 my $filename = shift;
3914 my $mime = mimetype_guess
($filename);
3915 $mime and return $mime;
3919 return $default_blob_plain_mimetype unless $fd;
3922 return 'text/plain';
3923 } elsif (! $filename) {
3924 return 'application/octet-stream';
3925 } elsif ($filename =~ m/\.png$/i) {
3927 } elsif ($filename =~ m/\.gif$/i) {
3929 } elsif ($filename =~ m/\.jpe?g$/i) {
3930 return 'image/jpeg';
3932 return 'application/octet-stream';
3936 sub blob_contenttype
{
3937 my ($fd, $file_name, $type) = @_;
3939 $type ||= blob_mimetype
($fd, $file_name);
3940 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3941 $type .= "; charset=$default_text_plain_charset";
3947 # guess file syntax for syntax highlighting; return undef if no highlighting
3948 # the name of syntax can (in the future) depend on syntax highlighter used
3949 sub guess_file_syntax
{
3950 my ($highlight, $mimetype, $file_name) = @_;
3951 return undef unless ($highlight && defined $file_name);
3952 my $basename = basename
($file_name, '.in');
3953 return $highlight_basename{$basename}
3954 if exists $highlight_basename{$basename};
3956 $basename =~ /\.([^.]*)$/;
3957 my $ext = $1 or return undef;
3958 return $highlight_ext{$ext}
3959 if exists $highlight_ext{$ext};
3964 # run highlighter and return FD of its output,
3965 # or return original FD if no highlighting
3966 sub run_highlighter
{
3967 my ($fd, $highlight, $syntax) = @_;
3968 return $fd unless ($highlight && defined $syntax);
3971 open $fd, quote_command
(git_cmd
(), "cat-file", "blob", $hash)." | ".
3972 quote_command
($highlight_bin).
3973 " --replace-tabs=8 --fragment --syntax $syntax |"
3974 or die_error
(500, "Couldn't open file or run syntax highlighter");
3978 ## ======================================================================
3979 ## functions printing HTML: header, footer, error page
3981 sub get_page_title
{
3982 my $title = to_utf8
($site_name);
3984 unless (defined $project) {
3985 if (defined $project_filter) {
3986 $title .= " - projects in '" . esc_path
($project_filter) . "'";
3990 $title .= " - " . to_utf8
($project);
3992 return $title unless (defined $action);
3993 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3995 return $title unless (defined $file_name);
3996 $title .= " - " . esc_path
($file_name);
3997 if ($action eq "tree" && $file_name !~ m
|/$|) {
4004 sub get_content_type_html
{
4005 # require explicit support from the UA if we are to send the page as
4006 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4007 # we have to do this because MSIE sometimes globs '*/*', pretending to
4008 # support xhtml+xml but choking when it gets what it asked for.
4009 if (defined $cgi->http('HTTP_ACCEPT') &&
4010 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\
+xml
(,|;|\s
|$)/ &&
4011 $cgi->Accept('application/xhtml+xml') != 0) {
4012 return 'application/xhtml+xml';
4018 sub print_feed_meta
{
4019 if (defined $project) {
4020 my %href_params = get_feed_info
();
4021 if (!exists $href_params{'-title'}) {
4022 $href_params{'-title'} = 'log';
4025 foreach my $format (qw(RSS Atom)) {
4026 my $type = lc($format);
4028 '-rel' => 'alternate',
4029 '-title' => esc_attr
("$project - $href_params{'-title'} - $format feed"),
4030 '-type' => "application/$type+xml"
4033 $href_params{'extra_options'} = undef;
4034 $href_params{'action'} = $type;
4035 $link_attr{'-href'} = href
(%href_params);
4037 "rel=\"$link_attr{'-rel'}\" ".
4038 "title=\"$link_attr{'-title'}\" ".
4039 "href=\"$link_attr{'-href'}\" ".
4040 "type=\"$link_attr{'-type'}\" ".
4043 $href_params{'extra_options'} = '--no-merges';
4044 $link_attr{'-href'} = href
(%href_params);
4045 $link_attr{'-title'} .= ' (no merges)';
4047 "rel=\"$link_attr{'-rel'}\" ".
4048 "title=\"$link_attr{'-title'}\" ".
4049 "href=\"$link_attr{'-href'}\" ".
4050 "type=\"$link_attr{'-type'}\" ".
4055 printf('<link rel="alternate" title="%s projects list" '.
4056 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4057 esc_attr
($site_name), href
(project
=>undef, action
=>"project_index"));
4058 printf('<link rel="alternate" title="%s projects feeds" '.
4059 'href="%s" type="text/x-opml" />'."\n",
4060 esc_attr
($site_name), href
(project
=>undef, action
=>"opml"));
4064 sub print_header_links
{
4067 # print out each stylesheet that exist, providing backwards capability
4068 # for those people who defined $stylesheet in a config file
4069 if (defined $stylesheet) {
4070 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
4072 foreach my $stylesheet (@stylesheets) {
4073 next unless $stylesheet;
4074 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
4078 if ($status eq '200 OK');
4079 if (defined $favicon) {
4080 print qq(<link rel
="shortcut icon" href
=").esc_url($favicon).qq(" type
="image/png" />\n);
4084 sub print_nav_breadcrumbs_path
{
4085 my $dirprefix = undef;
4086 while (my $part = shift) {
4087 $dirprefix .= "/" if defined $dirprefix;
4088 $dirprefix .= $part;
4089 print $cgi->a({-href
=> href
(project
=> undef,
4090 project_filter
=> $dirprefix,
4091 action
=> "project_list")},
4092 esc_html
($part)) . " / ";
4096 sub print_nav_breadcrumbs
{
4099 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4100 print $cgi->a({-href
=> esc_url
($crumb->[1])}, $crumb->[0]) . " / ";
4102 if (defined $project) {
4103 my @dirname = split '/', $project;
4104 my $projectbasename = pop @dirname;
4105 print_nav_breadcrumbs_path
(@dirname);
4106 print $cgi->a({-href
=> href
(action
=>"summary")}, esc_html
($projectbasename));
4107 if (defined $action) {
4108 my $action_print = $action ;
4109 if (defined $opts{-action_extra
}) {
4110 $action_print = $cgi->a({-href
=> href
(action
=>$action)},
4113 print " / $action_print";
4115 if (defined $opts{-action_extra
}) {
4116 print " / $opts{-action_extra}";
4119 } elsif (defined $project_filter) {
4120 print_nav_breadcrumbs_path
(split '/', $project_filter);
4124 sub print_search_form
{
4125 if (!defined $searchtext) {
4129 if (defined $hash_base) {
4130 $search_hash = $hash_base;
4131 } elsif (defined $hash) {
4132 $search_hash = $hash;
4134 $search_hash = "HEAD";
4136 my $action = $my_uri;
4137 my $use_pathinfo = gitweb_check_feature
('pathinfo');
4138 if ($use_pathinfo) {
4139 $action .= "/".esc_url
($project);
4141 print $cgi->start_form(-method
=> "get", -action
=> $action) .
4142 "<div class=\"search\">\n" .
4144 $cgi->input({-name
=>"p", -value
=>$project, -type
=>"hidden"}) . "\n") .
4145 $cgi->input({-name
=>"a", -value
=>"search", -type
=>"hidden"}) . "\n" .
4146 $cgi->input({-name
=>"h", -value
=>$search_hash, -type
=>"hidden"}) . "\n" .
4147 $cgi->popup_menu(-name
=> 'st', -default => 'commit',
4148 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4149 " " . $cgi->a({-href
=> href
(action
=>"search_help"),
4150 -title
=> "search help" }, "?") . " search:\n",
4151 $cgi->textfield(-name
=> "s", -value
=> $searchtext, -override
=> 1) . "\n" .
4152 "<span title=\"Extended regular expression\">" .
4153 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
4154 -checked
=> $search_use_regexp) .
4157 $cgi->end_form() . "\n";
4160 sub git_header_html
{
4161 my $status = shift || "200 OK";
4162 my $expires = shift;
4165 my $title = get_page_title
();
4166 my $content_type = get_content_type_html
();
4167 print $cgi->header(-type
=>$content_type, -charset
=> 'utf-8',
4168 -status
=> $status, -expires
=> $expires)
4169 unless ($opts{'-no_http_header'});
4170 my $mod_perl_version = $ENV{'MOD_PERL'} ?
" $ENV{'MOD_PERL'}" : '';
4172 <?xml version="1.0" encoding="utf-8"?>
4173 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4174 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4175 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4176 <!-- git core binaries version $git_version -->
4178 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4179 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4180 <meta name="robots" content="index, nofollow"/>
4181 <title>$title</title>
4183 # the stylesheet, favicon etc urls won't work correctly with path_info
4184 # unless we set the appropriate base URL
4185 if ($ENV{'PATH_INFO'}) {
4186 print "<base href=\"".esc_url
($base_url)."\" />\n";
4188 print_header_links
($status);
4190 if (defined $site_html_head_string) {
4191 print to_utf8
($site_html_head_string);
4197 if (defined $site_header && -f
$site_header) {
4198 insert_file
($site_header);
4201 print "<div class=\"page_header\">\n";
4202 if (defined $logo) {
4203 print $cgi->a({-href
=> esc_url
($logo_url),
4204 -title
=> $logo_label},
4205 $cgi->img({-src
=> esc_url
($logo),
4206 -width
=> 72, -height
=> 27,
4208 -class => "logo"}));
4210 print_nav_breadcrumbs
(%opts);
4213 my $have_search = gitweb_check_feature
('search');
4214 if (defined $project && $have_search) {
4215 print_search_form
();
4219 sub git_footer_html
{
4220 my $feed_class = 'rss_logo';
4222 print "<div class=\"page_footer\">\n";
4223 if (defined $project) {
4224 my $descr = git_get_project_description
($project);
4225 if (defined $descr) {
4226 print "<div class=\"page_footer_text\">" . esc_html
($descr) . "</div>\n";
4229 my %href_params = get_feed_info
();
4230 if (!%href_params) {
4231 $feed_class .= ' generic';
4233 $href_params{'-title'} ||= 'log';
4235 foreach my $format (qw(RSS Atom)) {
4236 $href_params{'action'} = lc($format);
4237 print $cgi->a({-href
=> href
(%href_params),
4238 -title
=> "$href_params{'-title'} $format feed",
4239 -class => $feed_class}, $format)."\n";
4243 print $cgi->a({-href
=> href
(project
=>undef, action
=>"opml",
4244 project_filter
=> $project_filter),
4245 -class => $feed_class}, "OPML") . " ";
4246 print $cgi->a({-href
=> href
(project
=>undef, action
=>"project_index",
4247 project_filter
=> $project_filter),
4248 -class => $feed_class}, "TXT") . "\n";
4250 print "</div>\n"; # class="page_footer"
4252 if (defined $t0 && gitweb_check_feature
('timed')) {
4253 print "<div id=\"generating_info\">\n";
4254 print 'This page took '.
4255 '<span id="generating_time" class="time_span">'.
4256 tv_interval
($t0, [ gettimeofday
() ]).
4259 '<span id="generating_cmd">'.
4260 $number_of_git_cmds.
4261 '</span> git commands '.
4263 print "</div>\n"; # class="page_footer"
4266 if (defined $site_footer && -f
$site_footer) {
4267 insert_file
($site_footer);
4270 print qq!<script type
="text/javascript" src
="!.esc_url($javascript).qq!"></script
>\n!;
4271 if (defined $action &&
4272 $action eq 'blame_incremental') {
4273 print qq!<script type
="text/javascript">\n!.
4274 qq!startBlame
("!. href(action=>"blame_data
", -replay=>1) .qq!",\n!.
4275 qq! "!. href() .qq!");\n!.
4278 my ($jstimezone, $tz_cookie, $datetime_class) =
4279 gitweb_get_feature
('javascript-timezone');
4281 print qq!<script type
="text/javascript">\n!.
4282 qq!window
.onload
= function
() {\n!;
4283 if (gitweb_check_feature
('javascript-actions')) {
4284 print qq! fixLinks
();\n!;
4286 if ($jstimezone && $tz_cookie && $datetime_class) {
4287 print qq! var tz_cookie
= { name
: '$tz_cookie', expires
: 14, path
: '/' };\n!. # in days
4288 qq! onloadTZSetup
('$jstimezone', tz_cookie
, '$datetime_class');\n!;
4298 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4299 # Example: die_error(404, 'Hash not found')
4300 # By convention, use the following status codes (as defined in RFC 2616):
4301 # 400: Invalid or missing CGI parameters, or
4302 # requested object exists but has wrong type.
4303 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4304 # this server or project.
4305 # 404: Requested object/revision/project doesn't exist.
4306 # 500: The server isn't configured properly, or
4307 # an internal error occurred (e.g. failed assertions caused by bugs), or
4308 # an unknown error occurred (e.g. the git binary died unexpectedly).
4309 # 503: The server is currently unavailable (because it is overloaded,
4310 # or down for maintenance). Generally, this is a temporary state.
4312 my $status = shift || 500;
4313 my $error = esc_html
(shift) || "Internal Server Error";
4317 my %http_responses = (
4318 400 => '400 Bad Request',
4319 403 => '403 Forbidden',
4320 404 => '404 Not Found',
4321 500 => '500 Internal Server Error',
4322 503 => '503 Service Unavailable',
4324 git_header_html
($http_responses{$status}, undef, %opts);
4326 <div class="page_body">
4331 if (defined $extra) {
4339 unless ($opts{'-error_handler'});
4342 ## ----------------------------------------------------------------------
4343 ## functions printing or outputting HTML: navigation
4345 sub git_print_page_nav
{
4346 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4347 $extra = '' if !defined $extra; # pager or formats
4349 my @navs = qw(summary shortlog log commit commitdiff tree);
4351 @navs = grep { $_ ne $suppress } @navs;
4354 my %arg = map { $_ => {action
=>$_} } @navs;
4355 if (defined $head) {
4356 for (qw(commit commitdiff)) {
4357 $arg{$_}{'hash'} = $head;
4359 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4360 for (qw(shortlog log)) {
4361 $arg{$_}{'hash'} = $head;
4366 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4367 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4369 my @actions = gitweb_get_feature
('actions');
4372 'n' => $project, # project name
4373 'f' => $git_dir, # project path within filesystem
4374 'h' => $treehead || '', # current hash ('h' parameter)
4375 'b' => $treebase || '', # hash base ('hb' parameter)
4378 my ($label, $link, $pos) = splice(@actions,0,3);
4380 @navs = map { $_ eq $pos ?
($_, $label) : $_ } @navs;
4382 $link =~ s/%([%nfhb])/$repl{$1}/g;
4383 $arg{$label}{'_href'} = $link;
4386 print "<div class=\"page_nav\">\n" .
4388 map { $_ eq $current ?
4389 $_ : $cgi->a({-href
=> ($arg{$_}{_href
} ?
$arg{$_}{_href
} : href
(%{$arg{$_}}))}, "$_")
4391 print "<br/>\n$extra<br/>\n" .
4395 # returns a submenu for the nagivation of the refs views (tags, heads,
4396 # remotes) with the current view disabled and the remotes view only
4397 # available if the feature is enabled
4398 sub format_ref_views
{
4400 my @ref_views = qw{tags heads
};
4401 push @ref_views, 'remotes' if gitweb_check_feature
('remote_heads');
4402 return join " | ", map {
4403 $_ eq $current ?
$_ :
4404 $cgi->a({-href
=> href
(action
=>$_)}, $_)
4408 sub format_paging_nav
{
4409 my ($action, $page, $has_next_link) = @_;
4415 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)}, "first") .
4417 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
4418 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
4420 $paging_nav .= "first ⋅ prev";
4423 if ($has_next_link) {
4424 $paging_nav .= " ⋅ " .
4425 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
4426 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
4428 $paging_nav .= " ⋅ next";
4434 ## ......................................................................
4435 ## functions printing or outputting HTML: div
4437 sub git_print_header_div
{
4438 my ($action, $title, $hash, $hash_base) = @_;
4441 $args{'action'} = $action;
4442 $args{'hash'} = $hash if $hash;
4443 $args{'hash_base'} = $hash_base if $hash_base;
4445 print "<div class=\"header\">\n" .
4446 $cgi->a({-href
=> href
(%args), -class => "title"},
4447 $title ?
$title : $action) .
4451 sub format_repo_url
{
4452 my ($name, $url) = @_;
4453 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4456 # Group output by placing it in a DIV element and adding a header.
4457 # Options for start_div() can be provided by passing a hash reference as the
4458 # first parameter to the function.
4459 # Options to git_print_header_div() can be provided by passing an array
4460 # reference. This must follow the options to start_div if they are present.
4461 # The content can be a scalar, which is output as-is, a scalar reference, which
4462 # is output after html escaping, an IO handle passed either as *handle or
4463 # *handle{IO}, or a function reference. In the latter case all following
4464 # parameters will be taken as argument to the content function call.
4465 sub git_print_section
{
4466 my ($div_args, $header_args, $content);
4468 if (ref($arg) eq 'HASH') {
4472 if (ref($arg) eq 'ARRAY') {
4473 $header_args = $arg;
4478 print $cgi->start_div($div_args);
4479 git_print_header_div
(@
$header_args);
4481 if (ref($content) eq 'CODE') {
4483 } elsif (ref($content) eq 'SCALAR') {
4484 print esc_html
($$content);
4485 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4487 } elsif (!ref($content) && defined($content)) {
4491 print $cgi->end_div;
4494 sub format_timestamp_html
{
4496 my $strtime = $date->{'rfc2822'};
4498 my (undef, undef, $datetime_class) =
4499 gitweb_get_feature
('javascript-timezone');
4500 if ($datetime_class) {
4501 $strtime = qq!<span
class="$datetime_class">$strtime</span
>!;
4504 my $localtime_format = '(%02d:%02d %s)';
4505 if ($date->{'hour_local'} < 6) {
4506 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4509 sprintf($localtime_format,
4510 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4515 # Outputs the author name and date in long form
4516 sub git_print_authorship
{
4519 my $tag = $opts{-tag
} || 'div';
4520 my $author = $co->{'author_name'};
4522 my %ad = parse_date
($co->{'author_epoch'}, $co->{'author_tz'});
4523 print "<$tag class=\"author_date\">" .
4524 format_search_author
($author, "author", esc_html
($author)) .
4525 " [".format_timestamp_html
(\
%ad)."]".
4526 git_get_avatar
($co->{'author_email'}, -pad_before
=> 1) .
4530 # Outputs table rows containing the full author or committer information,
4531 # in the format expected for 'commit' view (& similar).
4532 # Parameters are a commit hash reference, followed by the list of people
4533 # to output information for. If the list is empty it defaults to both
4534 # author and committer.
4535 sub git_print_authorship_rows
{
4537 # too bad we can't use @people = @_ || ('author', 'committer')
4539 @people = ('author', 'committer') unless @people;
4540 foreach my $who (@people) {
4541 my %wd = parse_date
($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4542 print "<tr><td>$who</td><td>" .
4543 format_search_author
($co->{"${who}_name"}, $who,
4544 esc_html
($co->{"${who}_name"})) . " " .
4545 format_search_author
($co->{"${who}_email"}, $who,
4546 esc_html
("<" . $co->{"${who}_email"} . ">")) .
4547 "</td><td rowspan=\"2\">" .
4548 git_get_avatar
($co->{"${who}_email"}, -size
=> 'double') .
4552 format_timestamp_html
(\
%wd) .
4558 sub git_print_page_path
{
4564 print "<div class=\"page_path\">";
4565 print $cgi->a({-href
=> href
(action
=>"tree", hash_base
=>$hb),
4566 -title
=> 'tree root'}, to_utf8
("[$project]"));
4568 if (defined $name) {
4569 my @dirname = split '/', $name;
4570 my $basename = pop @dirname;
4573 foreach my $dir (@dirname) {
4574 $fullname .= ($fullname ?
'/' : '') . $dir;
4575 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$fullname,
4577 -title
=> $fullname}, esc_path
($dir));
4580 if (defined $type && $type eq 'blob') {
4581 print $cgi->a({-href
=> href
(action
=>"blob_plain", file_name
=>$file_name,
4583 -title
=> $name}, esc_path
($basename));
4584 } elsif (defined $type && $type eq 'tree') {
4585 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$file_name,
4587 -title
=> $name}, esc_path
($basename));
4590 print esc_path
($basename);
4593 print "<br/></div>\n";
4600 if ($opts{'-remove_title'}) {
4601 # remove title, i.e. first line of log
4604 # remove leading empty lines
4605 while (defined $log->[0] && $log->[0] eq "") {
4610 my $skip_blank_line = 0;
4611 foreach my $line (@
$log) {
4612 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4613 if (! $opts{'-remove_signoff'}) {
4614 print "<span class=\"signoff\">" . esc_html
($line) . "</span><br/>\n";
4615 $skip_blank_line = 1;
4620 if ($line =~ m
,\s
*([a
-z
]*link): (https?
://\S
+),i
) {
4621 if (! $opts{'-remove_signoff'}) {
4622 print "<span class=\"signoff\">" . esc_html
($1) . ": " .
4623 "<a href=\"" . esc_html
($2) . "\">" . esc_html
($2) . "</a>" .
4625 $skip_blank_line = 1;
4630 # print only one empty line
4631 # do not print empty line after signoff
4633 next if ($skip_blank_line);
4634 $skip_blank_line = 1;
4636 $skip_blank_line = 0;
4639 print format_log_line_html
($line) . "<br/>\n";
4642 if ($opts{'-final_empty_line'}) {
4643 # end with single empty line
4644 print "<br/>\n" unless $skip_blank_line;
4648 # return link target (what link points to)
4649 sub git_get_link_target
{
4654 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
4658 $link_target = <$fd>;
4663 return $link_target;
4666 # given link target, and the directory (basedir) the link is in,
4667 # return target of link relative to top directory (top tree);
4668 # return undef if it is not possible (including absolute links).
4669 sub normalize_link_target
{
4670 my ($link_target, $basedir) = @_;
4672 # absolute symlinks (beginning with '/') cannot be normalized
4673 return if (substr($link_target, 0, 1) eq '/');
4675 # normalize link target to path from top (root) tree (dir)
4678 $path = $basedir . '/' . $link_target;
4680 # we are in top (root) tree (dir)
4681 $path = $link_target;
4684 # remove //, /./, and /../
4686 foreach my $part (split('/', $path)) {
4687 # discard '.' and ''
4688 next if (!$part || $part eq '.');
4690 if ($part eq '..') {
4694 # link leads outside repository (outside top dir)
4698 push @path_parts, $part;
4701 $path = join('/', @path_parts);
4706 # print tree entry (row of git_tree), but without encompassing <tr> element
4707 sub git_print_tree_entry
{
4708 my ($t, $basedir, $hash_base, $have_blame) = @_;
4711 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4713 # The format of a table row is: mode list link. Where mode is
4714 # the mode of the entry, list is the name of the entry, an href,
4715 # and link is the action links of the entry.
4717 print "<td class=\"mode\">" . mode_str
($t->{'mode'}) . "</td>\n";
4718 if (exists $t->{'size'}) {
4719 print "<td class=\"size\">$t->{'size'}</td>\n";
4721 if ($t->{'type'} eq "blob") {
4722 print "<td class=\"list\">" .
4723 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4724 file_name
=>"$basedir$t->{'name'}", %base_key),
4725 -class => "list"}, esc_path
($t->{'name'}));
4726 if (S_ISLNK
(oct $t->{'mode'})) {
4727 my $link_target = git_get_link_target
($t->{'hash'});
4729 my $norm_target = normalize_link_target
($link_target, $basedir);
4730 if (defined $norm_target) {
4732 $cgi->a({-href
=> href
(action
=>"object", hash_base
=>$hash_base,
4733 file_name
=>$norm_target),
4734 -title
=> $norm_target}, esc_path
($link_target));
4736 print " -> " . esc_path
($link_target);
4741 print "<td class=\"link\">";
4742 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4743 file_name
=>"$basedir$t->{'name'}", %base_key)},
4747 $cgi->a({-href
=> href
(action
=>"blame", hash
=>$t->{'hash'},
4748 file_name
=>"$basedir$t->{'name'}", %base_key)},
4751 if (defined $hash_base) {
4753 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4754 hash
=>$t->{'hash'}, file_name
=>"$basedir$t->{'name'}")},
4758 $cgi->a({-href
=> href
(action
=>"blob_plain", hash_base
=>$hash_base,
4759 file_name
=>"$basedir$t->{'name'}")},
4763 } elsif ($t->{'type'} eq "tree") {
4764 print "<td class=\"list\">";
4765 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4766 file_name
=>"$basedir$t->{'name'}",
4768 esc_path
($t->{'name'}));
4770 print "<td class=\"link\">";
4771 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4772 file_name
=>"$basedir$t->{'name'}",
4775 if (defined $hash_base) {
4777 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4778 file_name
=>"$basedir$t->{'name'}")},
4783 # unknown object: we can only present history for it
4784 # (this includes 'commit' object, i.e. submodule support)
4785 print "<td class=\"list\">" .
4786 esc_path
($t->{'name'}) .
4788 print "<td class=\"link\">";
4789 if (defined $hash_base) {
4790 print $cgi->a({-href
=> href
(action
=>"history",
4791 hash_base
=>$hash_base,
4792 file_name
=>"$basedir$t->{'name'}")},
4799 ## ......................................................................
4800 ## functions printing large fragments of HTML
4802 # get pre-image filenames for merge (combined) diff
4803 sub fill_from_file_info
{
4804 my ($diff, @parents) = @_;
4806 $diff->{'from_file'} = [ ];
4807 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4808 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4809 if ($diff->{'status'}[$i] eq 'R' ||
4810 $diff->{'status'}[$i] eq 'C') {
4811 $diff->{'from_file'}[$i] =
4812 git_get_path_by_hash
($parents[$i], $diff->{'from_id'}[$i]);
4819 # is current raw difftree line of file deletion
4821 my $diffinfo = shift;
4823 return $diffinfo->{'to_id'} eq ('0' x
40);
4826 # does patch correspond to [previous] difftree raw line
4827 # $diffinfo - hashref of parsed raw diff format
4828 # $patchinfo - hashref of parsed patch diff format
4829 # (the same keys as in $diffinfo)
4830 sub is_patch_split
{
4831 my ($diffinfo, $patchinfo) = @_;
4833 return defined $diffinfo && defined $patchinfo
4834 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4838 sub git_difftree_body
{
4839 my ($difftree, $hash, @parents) = @_;
4840 my ($parent) = $parents[0];
4841 my $have_blame = gitweb_check_feature
('blame');
4842 print "<div class=\"list_head\">\n";
4843 if ($#{$difftree} > 10) {
4844 print(($#{$difftree} + 1) . " files changed:\n");
4848 print "<table class=\"" .
4849 (@parents > 1 ?
"combined " : "") .
4852 # header only for combined diff in 'commitdiff' view
4853 my $has_header = @
$difftree && @parents > 1 && $action eq 'commitdiff';
4856 print "<thead><tr>\n" .
4857 "<th></th><th></th>\n"; # filename, patchN link
4858 for (my $i = 0; $i < @parents; $i++) {
4859 my $par = $parents[$i];
4861 $cgi->a({-href
=> href
(action
=>"commitdiff",
4862 hash
=>$hash, hash_parent
=>$par),
4863 -title
=> 'commitdiff to parent number ' .
4864 ($i+1) . ': ' . substr($par,0,7)},
4868 print "</tr></thead>\n<tbody>\n";
4873 foreach my $line (@
{$difftree}) {
4874 my $diff = parsed_difftree_line
($line);
4877 print "<tr class=\"dark\">\n";
4879 print "<tr class=\"light\">\n";
4883 if (exists $diff->{'nparents'}) { # combined diff
4885 fill_from_file_info
($diff, @parents)
4886 unless exists $diff->{'from_file'};
4888 if (!is_deleted
($diff)) {
4889 # file exists in the result (child) commit
4891 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4892 file_name
=>$diff->{'to_file'},
4894 -class => "list"}, esc_path
($diff->{'to_file'})) .
4898 esc_path
($diff->{'to_file'}) .
4902 if ($action eq 'commitdiff') {
4905 print "<td class=\"link\">" .
4906 $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4912 my $has_history = 0;
4913 my $not_deleted = 0;
4914 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4915 my $hash_parent = $parents[$i];
4916 my $from_hash = $diff->{'from_id'}[$i];
4917 my $from_path = $diff->{'from_file'}[$i];
4918 my $status = $diff->{'status'}[$i];
4920 $has_history ||= ($status ne 'A');
4921 $not_deleted ||= ($status ne 'D');
4923 if ($status eq 'A') {
4924 print "<td class=\"link\" align=\"right\"> | </td>\n";
4925 } elsif ($status eq 'D') {
4926 print "<td class=\"link\">" .
4927 $cgi->a({-href
=> href
(action
=>"blob",
4930 file_name
=>$from_path)},
4934 if ($diff->{'to_id'} eq $from_hash) {
4935 print "<td class=\"link nochange\">";
4937 print "<td class=\"link\">";
4939 print $cgi->a({-href
=> href
(action
=>"blobdiff",
4940 hash
=>$diff->{'to_id'},
4941 hash_parent
=>$from_hash,
4943 hash_parent_base
=>$hash_parent,
4944 file_name
=>$diff->{'to_file'},
4945 file_parent
=>$from_path)},
4951 print "<td class=\"link\">";
4953 print $cgi->a({-href
=> href
(action
=>"blob",
4954 hash
=>$diff->{'to_id'},
4955 file_name
=>$diff->{'to_file'},
4958 print " | " if ($has_history);
4961 print $cgi->a({-href
=> href
(action
=>"history",
4962 file_name
=>$diff->{'to_file'},
4969 next; # instead of 'else' clause, to avoid extra indent
4971 # else ordinary diff
4973 my ($to_mode_oct, $to_mode_str, $to_file_type);
4974 my ($from_mode_oct, $from_mode_str, $from_file_type);
4975 if ($diff->{'to_mode'} ne ('0' x
6)) {
4976 $to_mode_oct = oct $diff->{'to_mode'};
4977 if (S_ISREG
($to_mode_oct)) { # only for regular file
4978 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4980 $to_file_type = file_type
($diff->{'to_mode'});
4982 if ($diff->{'from_mode'} ne ('0' x
6)) {
4983 $from_mode_oct = oct $diff->{'from_mode'};
4984 if (S_ISREG
($from_mode_oct)) { # only for regular file
4985 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4987 $from_file_type = file_type
($diff->{'from_mode'});
4990 if ($diff->{'status'} eq "A") { # created
4991 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4992 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4993 $mode_chng .= "]</span>";
4995 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4996 hash_base
=>$hash, file_name
=>$diff->{'file'}),
4997 -class => "list"}, esc_path
($diff->{'file'}));
4999 print "<td>$mode_chng</td>\n";
5000 print "<td class=\"link\">";
5001 if ($action eq 'commitdiff') {
5004 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5008 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5009 hash_base
=>$hash, file_name
=>$diff->{'file'})},
5013 } elsif ($diff->{'status'} eq "D") { # deleted
5014 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5016 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
5017 hash_base
=>$parent, file_name
=>$diff->{'file'}),
5018 -class => "list"}, esc_path
($diff->{'file'}));
5020 print "<td>$mode_chng</td>\n";
5021 print "<td class=\"link\">";
5022 if ($action eq 'commitdiff') {
5025 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5029 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
5030 hash_base
=>$parent, file_name
=>$diff->{'file'})},
5033 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$parent,
5034 file_name
=>$diff->{'file'})},
5037 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$parent,
5038 file_name
=>$diff->{'file'})},
5042 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5043 my $mode_chnge = "";
5044 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5045 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5046 if ($from_file_type ne $to_file_type) {
5047 $mode_chnge .= " from $from_file_type to $to_file_type";
5049 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5050 if ($from_mode_str && $to_mode_str) {
5051 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5052 } elsif ($to_mode_str) {
5053 $mode_chnge .= " mode: $to_mode_str";
5056 $mode_chnge .= "]</span>\n";
5059 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5060 hash_base
=>$hash, file_name
=>$diff->{'file'}),
5061 -class => "list"}, esc_path
($diff->{'file'}));
5063 print "<td>$mode_chnge</td>\n";
5064 print "<td class=\"link\">";
5065 if ($action eq 'commitdiff') {
5068 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5071 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5072 # "commit" view and modified file (not onlu mode changed)
5073 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5074 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5075 hash_base
=>$hash, hash_parent_base
=>$parent,
5076 file_name
=>$diff->{'file'})},
5080 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5081 hash_base
=>$hash, file_name
=>$diff->{'file'})},
5084 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5085 file_name
=>$diff->{'file'})},
5088 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5089 file_name
=>$diff->{'file'})},
5093 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5094 my %status_name = ('R' => 'moved', 'C' => 'copied');
5095 my $nstatus = $status_name{$diff->{'status'}};
5097 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5098 # mode also for directories, so we cannot use $to_mode_str
5099 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5102 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$hash,
5103 hash
=>$diff->{'to_id'}, file_name
=>$diff->{'to_file'}),
5104 -class => "list"}, esc_path
($diff->{'to_file'})) . "</td>\n" .
5105 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5106 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$parent,
5107 hash
=>$diff->{'from_id'}, file_name
=>$diff->{'from_file'}),
5108 -class => "list"}, esc_path
($diff->{'from_file'})) .
5109 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5110 "<td class=\"link\">";
5111 if ($action eq 'commitdiff') {
5114 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5117 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5118 # "commit" view and modified file (not only pure rename or copy)
5119 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5120 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5121 hash_base
=>$hash, hash_parent_base
=>$parent,
5122 file_name
=>$diff->{'to_file'}, file_parent
=>$diff->{'from_file'})},
5126 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5127 hash_base
=>$parent, file_name
=>$diff->{'to_file'})},
5130 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5131 file_name
=>$diff->{'to_file'})},
5134 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5135 file_name
=>$diff->{'to_file'})},
5139 } # we should not encounter Unmerged (U) or Unknown (X) status
5142 print "</tbody>" if $has_header;
5146 # Print context lines and then rem/add lines in a side-by-side manner.
5147 sub print_sidebyside_diff_lines
{
5148 my ($ctx, $rem, $add) = @_;
5150 # print context block before add/rem block
5153 '<div class="chunk_block ctx">',
5154 '<div class="old">',
5157 '<div class="new">',
5166 '<div class="chunk_block rem">',
5167 '<div class="old">',
5174 '<div class="chunk_block add">',
5175 '<div class="new">',
5181 '<div class="chunk_block chg">',
5182 '<div class="old">',
5185 '<div class="new">',
5192 # Print context lines and then rem/add lines in inline manner.
5193 sub print_inline_diff_lines
{
5194 my ($ctx, $rem, $add) = @_;
5196 print @
$ctx, @
$rem, @
$add;
5199 # Format removed and added line, mark changed part and HTML-format them.
5200 # Implementation is based on contrib/diff-highlight
5201 sub format_rem_add_lines_pair
{
5202 my ($rem, $add, $num_parents) = @_;
5204 # We need to untabify lines before split()'ing them;
5205 # otherwise offsets would be invalid.
5208 $rem = untabify
($rem);
5209 $add = untabify
($add);
5211 my @rem = split(//, $rem);
5212 my @add = split(//, $add);
5213 my ($esc_rem, $esc_add);
5214 # Ignore leading +/- characters for each parent.
5215 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5216 my ($prefix_has_nonspace, $suffix_has_nonspace);
5218 my $shorter = (@rem < @add) ?
@rem : @add;
5219 while ($prefix_len < $shorter) {
5220 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5222 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5226 while ($prefix_len + $suffix_len < $shorter) {
5227 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5229 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5233 # Mark lines that are different from each other, but have some common
5234 # part that isn't whitespace. If lines are completely different, don't
5235 # mark them because that would make output unreadable, especially if
5236 # diff consists of multiple lines.
5237 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5238 $esc_rem = esc_html_hl_regions
($rem, 'marked',
5239 [$prefix_len, @rem - $suffix_len], -nbsp
=>1);
5240 $esc_add = esc_html_hl_regions
($add, 'marked',
5241 [$prefix_len, @add - $suffix_len], -nbsp
=>1);
5243 $esc_rem = esc_html
($rem, -nbsp
=>1);
5244 $esc_add = esc_html
($add, -nbsp
=>1);
5247 return format_diff_line
(\
$esc_rem, 'rem'),
5248 format_diff_line
(\
$esc_add, 'add');
5251 # HTML-format diff context, removed and added lines.
5252 sub format_ctx_rem_add_lines
{
5253 my ($ctx, $rem, $add, $num_parents) = @_;
5254 my (@new_ctx, @new_rem, @new_add);
5255 my $can_highlight = 0;
5256 my $is_combined = ($num_parents > 1);
5258 # Highlight if every removed line has a corresponding added line.
5259 if (@
$add > 0 && @
$add == @
$rem) {
5262 # Highlight lines in combined diff only if the chunk contains
5263 # diff between the same version, e.g.
5270 # Otherwise the highlightling would be confusing.
5272 for (my $i = 0; $i < @
$add; $i++) {
5273 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5274 my $prefix_add = substr($add->[$i], 0, $num_parents);
5276 $prefix_rem =~ s/-/+/g;
5278 if ($prefix_rem ne $prefix_add) {
5286 if ($can_highlight) {
5287 for (my $i = 0; $i < @
$add; $i++) {
5288 my ($line_rem, $line_add) = format_rem_add_lines_pair
(
5289 $rem->[$i], $add->[$i], $num_parents);
5290 push @new_rem, $line_rem;
5291 push @new_add, $line_add;
5294 @new_rem = map { format_diff_line
($_, 'rem') } @
$rem;
5295 @new_add = map { format_diff_line
($_, 'add') } @
$add;
5298 @new_ctx = map { format_diff_line
($_, 'ctx') } @
$ctx;
5300 return (\
@new_ctx, \
@new_rem, \
@new_add);
5303 # Print context lines and then rem/add lines.
5304 sub print_diff_lines
{
5305 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5306 my $is_combined = $num_parents > 1;
5308 ($ctx, $rem, $add) = format_ctx_rem_add_lines
($ctx, $rem, $add,
5311 if ($diff_style eq 'sidebyside' && !$is_combined) {
5312 print_sidebyside_diff_lines
($ctx, $rem, $add);
5314 # default 'inline' style and unknown styles
5315 print_inline_diff_lines
($ctx, $rem, $add);
5319 sub print_diff_chunk
{
5320 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5321 my (@ctx, @rem, @add);
5323 # The class of the previous line.
5324 my $prev_class = '';
5326 return unless @chunk;
5328 # incomplete last line might be among removed or added lines,
5329 # or both, or among context lines: find which
5330 for (my $i = 1; $i < @chunk; $i++) {
5331 if ($chunk[$i][0] eq 'incomplete') {
5332 $chunk[$i][0] = $chunk[$i-1][0];
5337 push @chunk, ["", ""];
5339 foreach my $line_info (@chunk) {
5340 my ($class, $line) = @
$line_info;
5342 # print chunk headers
5343 if ($class && $class eq 'chunk_header') {
5344 print format_diff_line
($line, $class, $from, $to);
5348 ## print from accumulator when have some add/rem lines or end
5349 # of chunk (flush context lines), or when have add and rem
5350 # lines and new block is reached (otherwise add/rem lines could
5352 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5353 (@rem && @add && $class ne $prev_class)) {
5354 print_diff_lines
(\
@ctx, \
@rem, \
@add,
5355 $diff_style, $num_parents);
5356 @ctx = @rem = @add = ();
5359 ## adding lines to accumulator
5362 # rem, add or change
5363 if ($class eq 'rem') {
5365 } elsif ($class eq 'add') {
5369 if ($class eq 'ctx') {
5373 $prev_class = $class;
5377 sub git_patchset_body
{
5378 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5379 my ($hash_parent) = $hash_parents[0];
5381 my $is_combined = (@hash_parents > 1);
5383 my $patch_number = 0;
5388 my @chunk; # for side-by-side diff
5390 print "<div class=\"patchset\">\n";
5392 # skip to first patch
5393 while ($patch_line = <$fd>) {
5396 last if ($patch_line =~ m/^diff /);
5400 while ($patch_line) {
5402 # parse "git diff" header line
5403 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5404 # $1 is from_name, which we do not use
5405 $to_name = unquote
($2);
5406 $to_name =~ s!^b/!!;
5407 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5408 # $1 is 'cc' or 'combined', which we do not use
5409 $to_name = unquote
($2);
5414 # check if current patch belong to current raw line
5415 # and parse raw git-diff line if needed
5416 if (is_patch_split
($diffinfo, { 'to_file' => $to_name })) {
5417 # this is continuation of a split patch
5418 print "<div class=\"patch cont\">\n";
5420 # advance raw git-diff output if needed
5421 $patch_idx++ if defined $diffinfo;
5423 # read and prepare patch information
5424 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5426 # compact combined diff output can have some patches skipped
5427 # find which patch (using pathname of result) we are at now;
5429 while ($to_name ne $diffinfo->{'to_file'}) {
5430 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5431 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5432 "</div>\n"; # class="patch"
5437 last if $patch_idx > $#$difftree;
5438 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5442 # modifies %from, %to hashes
5443 parse_from_to_diffinfo
($diffinfo, \
%from, \
%to, @hash_parents);
5445 # this is first patch for raw difftree line with $patch_idx index
5446 # we index @$difftree array from 0, but number patches from 1
5447 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5451 #assert($patch_line =~ m/^diff /) if DEBUG;
5452 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5454 # print "git diff" header
5455 print format_git_diff_header_line
($patch_line, $diffinfo,
5458 # print extended diff header
5459 print "<div class=\"diff extended_header\">\n";
5461 while ($patch_line = <$fd>) {
5464 last EXTENDED_HEADER
if ($patch_line =~ m/^--- |^diff /);
5466 print format_extended_diff_header_line
($patch_line, $diffinfo,
5469 print "</div>\n"; # class="diff extended_header"
5471 # from-file/to-file diff header
5472 if (! $patch_line) {
5473 print "</div>\n"; # class="patch"
5476 next PATCH
if ($patch_line =~ m/^diff /);
5477 #assert($patch_line =~ m/^---/) if DEBUG;
5479 my $last_patch_line = $patch_line;
5480 $patch_line = <$fd>;
5482 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5484 print format_diff_from_to_header
($last_patch_line, $patch_line,
5485 $diffinfo, \
%from, \
%to,
5490 while ($patch_line = <$fd>) {
5493 next PATCH
if ($patch_line =~ m/^diff /);
5495 my $class = diff_line_class
($patch_line, \
%from, \
%to);
5497 if ($class eq 'chunk_header') {
5498 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5502 push @chunk, [ $class, $patch_line ];
5507 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5510 print "</div>\n"; # class="patch"
5513 # for compact combined (--cc) format, with chunk and patch simplification
5514 # the patchset might be empty, but there might be unprocessed raw lines
5515 for (++$patch_idx if $patch_number > 0;
5516 $patch_idx < @
$difftree;
5518 # read and prepare patch information
5519 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5521 # generate anchor for "patch" links in difftree / whatchanged part
5522 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5523 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5524 "</div>\n"; # class="patch"
5529 if ($patch_number == 0) {
5530 if (@hash_parents > 1) {
5531 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5533 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5537 print "</div>\n"; # class="patchset"
5540 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5542 sub git_project_search_form
{
5543 my ($searchtext, $search_use_regexp) = @_;
5546 if ($project_filter) {
5547 $limit = " in '$project_filter/'";
5550 print "<div class=\"projsearch\">\n";
5551 print $cgi->start_form(-method
=> 'get', -action
=> $my_uri) .
5552 $cgi->hidden(-name
=> 'a', -value
=> 'project_list') . "\n";
5553 print $cgi->hidden(-name
=> 'pf', -value
=> $project_filter). "\n"
5554 if (defined $project_filter);
5555 print $cgi->textfield(-name
=> 's', -value
=> $searchtext,
5556 -title
=> "Search project by name and description$limit",
5557 -size
=> 60) . "\n" .
5558 "<span title=\"Extended regular expression\">" .
5559 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
5560 -checked
=> $search_use_regexp) .
5562 $cgi->submit(-name
=> 'btnS', -value
=> 'Search') .
5563 $cgi->end_form() . "\n" .
5564 $cgi->a({-href
=> href
(project
=> undef, searchtext
=> undef,
5565 project_filter
=> $project_filter)},
5566 esc_html
("List all projects$limit")) . "<br />\n";
5570 # entry for given @keys needs filling if at least one of keys in list
5571 # is not present in %$project_info
5572 sub project_info_needs_filling
{
5573 my ($project_info, @keys) = @_;
5575 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5576 foreach my $key (@keys) {
5577 if (!exists $project_info->{$key}) {
5584 # fills project list info (age, description, owner, category, forks, etc.)
5585 # for each project in the list, removing invalid projects from
5586 # returned list, or fill only specified info.
5588 # Invalid projects are removed from the returned list if and only if you
5589 # ask 'age' or 'age_string' to be filled, because they are the only fields
5590 # that run unconditionally git command that requires repository, and
5591 # therefore do always check if project repository is invalid.
5594 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5595 # ensures that 'descr_long' and 'ctags' fields are filled
5596 # * @project_list = fill_project_list_info(\@project_list)
5597 # ensures that all fields are filled (and invalid projects removed)
5599 # NOTE: modifies $projlist, but does not remove entries from it
5600 sub fill_project_list_info
{
5601 my ($projlist, @wanted_keys) = @_;
5603 my $filter_set = sub { return @_; };
5605 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5606 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5609 my $show_ctags = gitweb_check_feature
('ctags');
5611 foreach my $pr (@
$projlist) {
5612 if (project_info_needs_filling
($pr, $filter_set->('age', 'age_string'))) {
5613 my (@activity) = git_get_last_activity
($pr->{'path'});
5614 unless (@activity) {
5617 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5619 if (project_info_needs_filling
($pr, $filter_set->('descr', 'descr_long'))) {
5620 my $descr = git_get_project_description
($pr->{'path'}) || "";
5621 $descr = to_utf8
($descr);
5622 $pr->{'descr_long'} = $descr;
5623 $pr->{'descr'} = chop_str
($descr, $projects_list_description_width, 5);
5625 if (project_info_needs_filling
($pr, $filter_set->('owner'))) {
5626 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}") || "";
5629 project_info_needs_filling
($pr, $filter_set->('ctags'))) {
5630 $pr->{'ctags'} = git_get_project_ctags
($pr->{'path'});
5632 if ($projects_list_group_categories &&
5633 project_info_needs_filling
($pr, $filter_set->('category'))) {
5634 my $cat = git_get_project_category
($pr->{'path'}) ||
5635 $project_list_default_category;
5636 $pr->{'category'} = to_utf8
($cat);
5639 push @projects, $pr;
5645 sub sort_projects_list
{
5646 my ($projlist, $order) = @_;
5650 return sub { $a->{$key} cmp $b->{$key} };
5653 sub order_num_then_undef
{
5656 defined $a->{$key} ?
5657 (defined $b->{$key} ?
$a->{$key} <=> $b->{$key} : -1) :
5658 (defined $b->{$key} ?
1 : 0)
5663 project
=> order_str
('path'),
5664 descr
=> order_str
('descr_long'),
5665 owner
=> order_str
('owner'),
5666 age
=> order_num_then_undef
('age'),
5669 my $ordering = $orderings{$order};
5670 return defined $ordering ?
sort $ordering @
$projlist : @
$projlist;
5673 # returns a hash of categories, containing the list of project
5674 # belonging to each category
5675 sub build_projlist_by_category
{
5676 my ($projlist, $from, $to) = @_;
5679 $from = 0 unless defined $from;
5680 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5682 for (my $i = $from; $i <= $to; $i++) {
5683 my $pr = $projlist->[$i];
5684 push @
{$categories{ $pr->{'category'} }}, $pr;
5687 return wantarray ?
%categories : \
%categories;
5690 # print 'sort by' <th> element, generating 'sort by $name' replay link
5691 # if that order is not selected
5693 print format_sort_th
(@_);
5696 sub format_sort_th
{
5697 my ($name, $order, $header) = @_;
5699 $header ||= ucfirst($name);
5701 if ($order eq $name) {
5702 $sort_th .= "<th>$header</th>\n";
5704 $sort_th .= "<th>" .
5705 $cgi->a({-href
=> href
(-replay
=>1, order
=>$name),
5706 -class => "header"}, $header) .
5713 sub git_project_list_rows
{
5714 my ($projlist, $from, $to, $check_forks) = @_;
5716 $from = 0 unless defined $from;
5717 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5720 for (my $i = $from; $i <= $to; $i++) {
5721 my $pr = $projlist->[$i];
5724 print "<tr class=\"dark\">\n";
5726 print "<tr class=\"light\">\n";
5732 if ($pr->{'forks'}) {
5733 my $nforks = scalar @
{$pr->{'forks'}};
5735 print $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks"),
5736 -title
=> "$nforks forks"}, "+");
5738 print $cgi->span({-title
=> "$nforks forks"}, "+");
5743 print "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5745 esc_html_match_hl
($pr->{'path'}, $search_regexp)) .
5747 "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5749 -title
=> $pr->{'descr_long'}},
5751 ? esc_html_match_hl_chopped
($pr->{'descr_long'},
5752 $pr->{'descr'}, $search_regexp)
5753 : esc_html
($pr->{'descr'})) .
5755 unless ($omit_owner) {
5756 print "<td><i>" . chop_and_escape_str
($pr->{'owner'}, 15) . "</i></td>\n";
5758 unless ($omit_age_column) {
5759 print "<td class=\"". age_class
($pr->{'age'}) . "\">" .
5760 (defined $pr->{'age_string'} ?
$pr->{'age_string'} : "No commits") . "</td>\n";
5762 print"<td class=\"link\">" .
5763 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary")}, "summary") . " | " .
5764 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"shortlog")}, "shortlog") . " | " .
5765 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"log")}, "log") . " | " .
5766 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"tree")}, "tree") .
5767 ($pr->{'forks'} ?
" | " . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks")}, "forks") : '') .
5773 sub git_project_list_body
{
5774 # actually uses global variable $project
5775 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5776 my @projects = @
$projlist;
5778 my $check_forks = gitweb_check_feature
('forks');
5779 my $show_ctags = gitweb_check_feature
('ctags');
5780 my $tagfilter = $show_ctags ?
$input_params{'ctag'} : undef;
5781 $check_forks = undef
5782 if ($tagfilter || $search_regexp);
5784 # filtering out forks before filling info allows to do less work
5785 @projects = filter_forks_from_projects_list
(\
@projects)
5787 # search_projects_list pre-fills required info
5788 @projects = search_projects_list
(\
@projects,
5789 'search_regexp' => $search_regexp,
5790 'tagfilter' => $tagfilter)
5791 if ($tagfilter || $search_regexp);
5793 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5794 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5795 push @all_fields, 'owner' unless($omit_owner);
5796 @projects = fill_project_list_info
(\
@projects, @all_fields);
5798 $order ||= $default_projects_order;
5799 $from = 0 unless defined $from;
5800 $to = $#projects if (!defined $to || $#projects < $to);
5805 "<b>No such projects found</b><br />\n".
5806 "Click ".$cgi->a({-href
=>href
(project
=>undef)},"here")." to view all projects<br />\n".
5807 "</center>\n<br />\n";
5811 @projects = sort_projects_list
(\
@projects, $order);
5814 my $ctags = git_gather_all_ctags
(\
@projects);
5815 my $cloud = git_populate_project_tagcloud
($ctags);
5816 print git_show_project_tagcloud
($cloud, 64);
5819 print "<table class=\"project_list\">\n";
5820 unless ($no_header) {
5823 print "<th></th>\n";
5825 print_sort_th
('project', $order, 'Project');
5826 print_sort_th
('descr', $order, 'Description');
5827 print_sort_th
('owner', $order, 'Owner') unless $omit_owner;
5828 print_sort_th
('age', $order, 'Last Change') unless $omit_age_column;
5829 print "<th></th>\n" . # for links
5833 if ($projects_list_group_categories) {
5834 # only display categories with projects in the $from-$to window
5835 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5836 my %categories = build_projlist_by_category
(\
@projects, $from, $to);
5837 foreach my $cat (sort keys %categories) {
5838 unless ($cat eq "") {
5841 print "<td></td>\n";
5843 print "<td class=\"category\" colspan=\"5\">".esc_html
($cat)."</td>\n";
5847 git_project_list_rows
($categories{$cat}, undef, undef, $check_forks);
5850 git_project_list_rows
(\
@projects, $from, $to, $check_forks);
5853 if (defined $extra) {
5856 print "<td></td>\n";
5858 print "<td colspan=\"5\">$extra</td>\n" .
5865 # uses global variable $project
5866 my ($commitlist, $from, $to, $refs, $extra) = @_;
5868 $from = 0 unless defined $from;
5869 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5871 for (my $i = 0; $i <= $to; $i++) {
5872 my %co = %{$commitlist->[$i]};
5874 my $commit = $co{'id'};
5875 my $ref = format_ref_marker
($refs, $commit);
5876 git_print_header_div
('commit',
5877 "<span class=\"age\">$co{'age_string'}</span>" .
5878 esc_html
($co{'title'}) . $ref,
5880 print "<div class=\"title_text\">\n" .
5881 "<div class=\"log_link\">\n" .
5882 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") .
5884 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") .
5886 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree") .
5889 git_print_authorship
(\
%co, -tag
=> 'span');
5890 print "<br/>\n</div>\n";
5892 print "<div class=\"log_body\">\n";
5893 git_print_log
($co{'comment'}, -final_empty_line
=> 1);
5897 print "<div class=\"page_nav\">\n";
5903 sub git_shortlog_body
{
5904 # uses global variable $project
5905 my ($commitlist, $from, $to, $refs, $extra) = @_;
5907 $from = 0 unless defined $from;
5908 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5910 print "<table class=\"shortlog\">\n";
5912 for (my $i = $from; $i <= $to; $i++) {
5913 my %co = %{$commitlist->[$i]};
5914 my $commit = $co{'id'};
5915 my $ref = format_ref_marker
($refs, $commit);
5917 print "<tr class=\"dark\">\n";
5919 print "<tr class=\"light\">\n";
5922 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5923 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5924 format_author_html
('td', \
%co, 10) . "<td>";
5925 print format_subject_html
($co{'title'}, $co{'title_short'},
5926 href
(action
=>"commit", hash
=>$commit), $ref);
5928 "<td class=\"link\">" .
5929 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") . " | " .
5930 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") . " | " .
5931 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree");
5932 my $snapshot_links = format_snapshot_links
($commit);
5933 if (defined $snapshot_links) {
5934 print " | " . $snapshot_links;
5939 if (defined $extra) {
5941 "<td colspan=\"4\">$extra</td>\n" .
5947 sub git_history_body
{
5948 # Warning: assumes constant type (blob or tree) during history
5949 my ($commitlist, $from, $to, $refs, $extra,
5950 $file_name, $file_hash, $ftype) = @_;
5952 $from = 0 unless defined $from;
5953 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5955 print "<table class=\"history\">\n";
5957 for (my $i = $from; $i <= $to; $i++) {
5958 my %co = %{$commitlist->[$i]};
5962 my $commit = $co{'id'};
5964 my $ref = format_ref_marker
($refs, $commit);
5967 print "<tr class=\"dark\">\n";
5969 print "<tr class=\"light\">\n";
5972 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5973 # shortlog: format_author_html('td', \%co, 10)
5974 format_author_html
('td', \
%co, 15, 3) . "<td>";
5975 # originally git_history used chop_str($co{'title'}, 50)
5976 print format_subject_html
($co{'title'}, $co{'title_short'},
5977 href
(action
=>"commit", hash
=>$commit), $ref);
5979 "<td class=\"link\">" .
5980 $cgi->a({-href
=> href
(action
=>$ftype, hash_base
=>$commit, file_name
=>$file_name)}, $ftype) . " | " .
5981 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff");
5983 if ($ftype eq 'blob') {
5984 my $blob_current = $file_hash;
5985 my $blob_parent = git_get_hash_by_path
($commit, $file_name);
5986 if (defined $blob_current && defined $blob_parent &&
5987 $blob_current ne $blob_parent) {
5989 $cgi->a({-href
=> href
(action
=>"blobdiff",
5990 hash
=>$blob_current, hash_parent
=>$blob_parent,
5991 hash_base
=>$hash_base, hash_parent_base
=>$commit,
5992 file_name
=>$file_name)},
5999 if (defined $extra) {
6001 "<td colspan=\"4\">$extra</td>\n" .
6008 # uses global variable $project
6009 my ($taglist, $from, $to, $extra) = @_;
6010 $from = 0 unless defined $from;
6011 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6013 print "<table class=\"tags\">\n";
6015 for (my $i = $from; $i <= $to; $i++) {
6016 my $entry = $taglist->[$i];
6018 my $comment = $tag{'subject'};
6020 if (defined $comment) {
6021 $comment_short = chop_str
($comment, 30, 5);
6024 print "<tr class=\"dark\">\n";
6026 print "<tr class=\"light\">\n";
6029 if (defined $tag{'age'}) {
6030 print "<td><i>$tag{'age'}</i></td>\n";
6032 print "<td></td>\n";
6035 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'}),
6036 -class => "list name"}, esc_html
($tag{'name'})) .
6039 if (defined $comment) {
6040 print format_subject_html
($comment, $comment_short,
6041 href
(action
=>"tag", hash
=>$tag{'id'}));
6044 "<td class=\"selflink\">";
6045 if ($tag{'type'} eq "tag") {
6046 print $cgi->a({-href
=> href
(action
=>"tag", hash
=>$tag{'id'})}, "tag");
6051 "<td class=\"link\">" . " | " .
6052 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'})}, $tag{'reftype'});
6053 if ($tag{'reftype'} eq "commit") {
6054 print " | " . $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$tag{'fullname'})}, "shortlog") .
6055 " | " . $cgi->a({-href
=> href
(action
=>"log", hash
=>$tag{'fullname'})}, "log");
6056 } elsif ($tag{'reftype'} eq "blob") {
6057 print " | " . $cgi->a({-href
=> href
(action
=>"blob_plain", hash
=>$tag{'refid'})}, "raw");
6062 if (defined $extra) {
6064 "<td colspan=\"5\">$extra</td>\n" .
6070 sub git_heads_body
{
6071 # uses global variable $project
6072 my ($headlist, $head_at, $from, $to, $extra) = @_;
6073 $from = 0 unless defined $from;
6074 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6076 print "<table class=\"heads\">\n";
6078 for (my $i = $from; $i <= $to; $i++) {
6079 my $entry = $headlist->[$i];
6081 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6083 print "<tr class=\"dark\">\n";
6085 print "<tr class=\"light\">\n";
6088 print "<td><i>$ref{'age'}</i></td>\n" .
6089 ($curr ?
"<td class=\"current_head\">" : "<td>") .
6090 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'}),
6091 -class => "list name"},esc_html
($ref{'name'})) .
6093 "<td class=\"link\">" .
6094 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'})}, "shortlog") . " | " .
6095 $cgi->a({-href
=> href
(action
=>"log", hash
=>$ref{'fullname'})}, "log") . " | " .
6096 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$ref{'fullname'}, hash_base
=>$ref{'fullname'})}, "tree") .
6100 if (defined $extra) {
6102 "<td colspan=\"3\">$extra</td>\n" .
6108 # Display a single remote block
6109 sub git_remote_block
{
6110 my ($remote, $rdata, $limit, $head) = @_;
6112 my $heads = $rdata->{'heads'};
6113 my $fetch = $rdata->{'fetch'};
6114 my $push = $rdata->{'push'};
6116 my $urls_table = "<table class=\"projects_list\">\n" ;
6118 if (defined $fetch) {
6119 if ($fetch eq $push) {
6120 $urls_table .= format_repo_url
("URL", $fetch);
6122 $urls_table .= format_repo_url
("Fetch URL", $fetch);
6123 $urls_table .= format_repo_url
("Push URL", $push) if defined $push;
6125 } elsif (defined $push) {
6126 $urls_table .= format_repo_url
("Push URL", $push);
6128 $urls_table .= format_repo_url
("", "No remote URL");
6131 $urls_table .= "</table>\n";
6134 if (defined $limit && $limit < @
$heads) {
6135 $dots = $cgi->a({-href
=> href
(action
=>"remotes", hash
=>$remote)}, "...");
6139 git_heads_body
($heads, $head, 0, $limit, $dots);
6142 # Display a list of remote names with the respective fetch and push URLs
6143 sub git_remotes_list
{
6144 my ($remotedata, $limit) = @_;
6145 print "<table class=\"heads\">\n";
6147 my @remotes = sort keys %$remotedata;
6149 my $limited = $limit && $limit < @remotes;
6151 $#remotes = $limit - 1 if $limited;
6153 while (my $remote = shift @remotes) {
6154 my $rdata = $remotedata->{$remote};
6155 my $fetch = $rdata->{'fetch'};
6156 my $push = $rdata->{'push'};
6158 print "<tr class=\"dark\">\n";
6160 print "<tr class=\"light\">\n";
6164 $cgi->a({-href
=> href
(action
=>'remotes', hash
=>$remote),
6165 -class=> "list name"},esc_html
($remote)) .
6167 print "<td class=\"link\">" .
6168 (defined $fetch ?
$cgi->a({-href
=> $fetch}, "fetch") : "fetch") .
6170 (defined $push ?
$cgi->a({-href
=> $push}, "push") : "push") .
6178 "<td colspan=\"3\">" .
6179 $cgi->a({-href
=> href
(action
=>"remotes")}, "...") .
6180 "</td>\n" . "</tr>\n";
6186 # Display remote heads grouped by remote, unless there are too many
6187 # remotes, in which case we only display the remote names
6188 sub git_remotes_body
{
6189 my ($remotedata, $limit, $head) = @_;
6190 if ($limit and $limit < keys %$remotedata) {
6191 git_remotes_list
($remotedata, $limit);
6193 fill_remote_heads
($remotedata);
6194 while (my ($remote, $rdata) = each %$remotedata) {
6195 git_print_section
({-class=>"remote", -id
=>$remote},
6196 ["remotes", $remote, $remote], sub {
6197 git_remote_block
($remote, $rdata, $limit, $head);
6203 sub git_search_message
{
6207 if ($searchtype eq 'commit') {
6208 $greptype = "--grep=";
6209 } elsif ($searchtype eq 'author') {
6210 $greptype = "--author=";
6211 } elsif ($searchtype eq 'committer') {
6212 $greptype = "--committer=";
6214 $greptype .= $searchtext;
6215 my @commitlist = parse_commits
($hash, 101, (100 * $page), undef,
6216 $greptype, '--regexp-ignore-case',
6217 $search_use_regexp ?
'--extended-regexp' : '--fixed-strings');
6219 my $paging_nav = '';
6222 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)},
6225 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
6226 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
6228 $paging_nav .= "first ⋅ prev";
6231 if ($#commitlist >= 100) {
6233 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
6234 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
6235 $paging_nav .= " ⋅ $next_link";
6237 $paging_nav .= " ⋅ next";
6242 git_print_page_nav
('','', $hash,$co{'tree'},$hash, $paging_nav);
6243 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6244 if ($page == 0 && !@commitlist) {
6245 print "<p>No match.</p>\n";
6247 git_search_grep_body
(\
@commitlist, 0, 99, $next_link);
6253 sub git_search_changes
{
6257 open my $fd, '-|', git_cmd
(), '--no-pager', 'log', @diff_opts,
6258 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6259 ($search_use_regexp ?
'--pickaxe-regex' : ())
6260 or die_error
(500, "Open git-log failed");
6264 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6265 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6267 print "<table class=\"pickaxe search\">\n";
6271 while (my $line = <$fd>) {
6275 my %set = parse_difftree_raw_line
($line);
6276 if (defined $set{'commit'}) {
6277 # finish previous commit
6280 "<td class=\"link\">" .
6281 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6284 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6285 hash_base
=>$co{'id'})},
6292 print "<tr class=\"dark\">\n";
6294 print "<tr class=\"light\">\n";
6297 %co = parse_commit
($set{'commit'});
6298 my $author = chop_and_escape_str
($co{'author_name'}, 15, 5);
6299 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6300 "<td><i>$author</i></td>\n" .
6302 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6303 -class => "list subject"},
6304 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6305 } elsif (defined $set{'to_id'}) {
6306 next if ($set{'to_id'} =~ m/^0{40}$/);
6308 print $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$co{'id'},
6309 hash
=>$set{'to_id'}, file_name
=>$set{'to_file'}),
6311 "<span class=\"match\">" . esc_path
($set{'file'}) . "</span>") .
6317 # finish last commit (warning: repetition!)
6320 "<td class=\"link\">" .
6321 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6324 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6325 hash_base
=>$co{'id'})},
6336 sub git_search_files
{
6340 open my $fd, "-|", git_cmd
(), 'grep', '-n', '-z',
6341 $search_use_regexp ?
('-E', '-i') : '-F',
6342 $searchtext, $co{'tree'}
6343 or die_error
(500, "Open git-grep failed");
6347 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6348 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6350 print "<table class=\"grep_search\">\n";
6355 while (my $line = <$fd>) {
6357 my ($file, $lno, $ltext, $binary);
6358 last if ($matches++ > 1000);
6359 if ($line =~ /^Binary file (.+) matches$/) {
6363 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6364 $file =~ s/^$co{'tree'}://;
6366 if ($file ne $lastfile) {
6367 $lastfile and print "</td></tr>\n";
6369 print "<tr class=\"dark\">\n";
6371 print "<tr class=\"light\">\n";
6373 $file_href = href
(action
=>"blob", hash_base
=>$co{'id'},
6375 print "<td class=\"list\">".
6376 $cgi->a({-href
=> $file_href, -class => "list"}, esc_path
($file));
6377 print "</td><td>\n";
6381 print "<div class=\"binary\">Binary file</div>\n";
6383 $ltext = untabify
($ltext);
6384 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6385 $ltext = esc_html
($1, -nbsp
=>1);
6386 $ltext .= '<span class="match">';
6387 $ltext .= esc_html
($2, -nbsp
=>1);
6388 $ltext .= '</span>';
6389 $ltext .= esc_html
($3, -nbsp
=>1);
6391 $ltext = esc_html
($ltext, -nbsp
=>1);
6393 print "<div class=\"pre\">" .
6394 $cgi->a({-href
=> $file_href.'#l'.$lno,
6395 -class => "linenr"}, sprintf('%4i', $lno)) .
6396 ' ' . $ltext . "</div>\n";
6400 print "</td></tr>\n";
6401 if ($matches > 1000) {
6402 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6405 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6414 sub git_search_grep_body
{
6415 my ($commitlist, $from, $to, $extra) = @_;
6416 $from = 0 unless defined $from;
6417 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6419 print "<table class=\"commit_search\">\n";
6421 for (my $i = $from; $i <= $to; $i++) {
6422 my %co = %{$commitlist->[$i]};
6426 my $commit = $co{'id'};
6428 print "<tr class=\"dark\">\n";
6430 print "<tr class=\"light\">\n";
6433 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6434 format_author_html
('td', \
%co, 15, 5) .
6436 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6437 -class => "list subject"},
6438 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6439 my $comment = $co{'comment'};
6440 foreach my $line (@
$comment) {
6441 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6442 my ($lead, $match, $trail) = ($1, $2, $3);
6443 $match = chop_str
($match, 70, 5, 'center');
6444 my $contextlen = int((80 - length($match))/2);
6445 $contextlen = 30 if ($contextlen > 30);
6446 $lead = chop_str
($lead, $contextlen, 10, 'left');
6447 $trail = chop_str
($trail, $contextlen, 10, 'right');
6449 $lead = esc_html
($lead);
6450 $match = esc_html
($match);
6451 $trail = esc_html
($trail);
6453 print "$lead<span class=\"match\">$match</span>$trail<br />";
6457 "<td class=\"link\">" .
6458 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})}, "commit") .
6460 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$co{'id'})}, "commitdiff") .
6462 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$co{'id'})}, "tree");
6466 if (defined $extra) {
6468 "<td colspan=\"3\">$extra</td>\n" .
6474 ## ======================================================================
6475 ## ======================================================================
6478 sub git_project_list
{
6479 my $order = $input_params{'order'};
6480 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6481 die_error
(400, "Unknown order parameter");
6484 my @list = git_get_projects_list
($project_filter, $strict_export);
6486 die_error
(404, "No projects found");
6490 if (defined $home_text && -f
$home_text) {
6491 print "<div class=\"index_include\">\n";
6492 insert_file
($home_text);
6496 git_project_search_form
($searchtext, $search_use_regexp);
6497 git_project_list_body
(\
@list, $order);
6502 my $order = $input_params{'order'};
6503 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6504 die_error
(400, "Unknown order parameter");
6507 my $filter = $project;
6508 $filter =~ s/\.git$//;
6509 my @list = git_get_projects_list
($filter);
6511 die_error
(404, "No forks found");
6515 git_print_page_nav
('','');
6516 git_print_header_div
('summary', "$project forks");
6517 git_project_list_body
(\
@list, $order);
6521 sub git_project_index
{
6522 my @projects = git_get_projects_list
($project_filter, $strict_export);
6524 die_error
(404, "No projects found");
6528 -type
=> 'text/plain',
6529 -charset
=> 'utf-8',
6530 -content_disposition
=> 'inline; filename="index.aux"');
6532 foreach my $pr (@projects) {
6533 if (!exists $pr->{'owner'}) {
6534 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}");
6537 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6538 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6539 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6540 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6544 print "$path $owner\n";
6549 my $descr = git_get_project_description
($project) || "none";
6550 my %co = parse_commit
("HEAD");
6551 my %cd = %co ? parse_date
($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6552 my $head = $co{'id'};
6553 my $remote_heads = gitweb_check_feature
('remote_heads');
6555 my $owner = git_get_project_owner
($project);
6557 my $refs = git_get_references
();
6558 # These get_*_list functions return one more to allow us to see if
6559 # there are more ...
6560 my @taglist = git_get_tags_list
(16);
6561 my @headlist = git_get_heads_list
(16);
6562 my %remotedata = $remote_heads ? git_get_remotes_list
() : ();
6564 my $check_forks = gitweb_check_feature
('forks');
6567 # find forks of a project
6568 my $filter = $project;
6569 $filter =~ s/\.git$//;
6570 @forklist = git_get_projects_list
($filter);
6571 # filter out forks of forks
6572 @forklist = filter_forks_from_projects_list
(\
@forklist)
6577 git_print_page_nav
('summary','', $head);
6579 print "<div class=\"title\"> </div>\n";
6580 print "<table class=\"projects_list\">\n" .
6581 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html
($descr) . "</td></tr>\n";
6582 if ($owner and not $omit_owner) {
6583 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html
($owner) . "</td></tr>\n";
6585 if (defined $cd{'rfc2822'}) {
6586 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6587 "<td>".format_timestamp_html
(\
%cd)."</td></tr>\n";
6590 # use per project git URL list in $projectroot/$project/cloneurl
6591 # or make project git URL from git base URL and project name
6592 my $url_tag = "URL";
6593 my @url_list = git_get_project_url_list
($project);
6594 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6595 foreach my $git_url (@url_list) {
6596 next unless $git_url;
6597 print format_repo_url
($url_tag, $git_url);
6602 my $show_ctags = gitweb_check_feature
('ctags');
6604 my $ctags = git_get_project_ctags
($project);
6606 # without ability to add tags, don't show if there are none
6607 my $cloud = git_populate_project_tagcloud
($ctags);
6608 print "<tr id=\"metadata_ctags\">" .
6609 "<td>content tags</td>" .
6610 "<td>".git_show_project_tagcloud
($cloud, 48)."</td>" .
6617 # If XSS prevention is on, we don't include README.html.
6618 # TODO: Allow a readme in some safe format.
6619 if (!$prevent_xss && -s
"$projectroot/$project/README.html") {
6620 print "<div class=\"title\">readme</div>\n" .
6621 "<div class=\"readme\">\n";
6622 insert_file
("$projectroot/$project/README.html");
6623 print "\n</div>\n"; # class="readme"
6626 # we need to request one more than 16 (0..15) to check if
6628 my @commitlist = $head ? parse_commits
($head, 17) : ();
6630 git_print_header_div
('shortlog');
6631 git_shortlog_body
(\
@commitlist, 0, 15, $refs,
6632 $#commitlist <= 15 ?
undef :
6633 $cgi->a({-href
=> href
(action
=>"shortlog")}, "..."));
6637 git_print_header_div
('tags');
6638 git_tags_body
(\
@taglist, 0, 15,
6639 $#taglist <= 15 ?
undef :
6640 $cgi->a({-href
=> href
(action
=>"tags")}, "..."));
6644 git_print_header_div
('heads');
6645 git_heads_body
(\
@headlist, $head, 0, 15,
6646 $#headlist <= 15 ?
undef :
6647 $cgi->a({-href
=> href
(action
=>"heads")}, "..."));
6651 git_print_header_div
('remotes');
6652 git_remotes_body
(\
%remotedata, 15, $head);
6656 git_print_header_div
('forks');
6657 git_project_list_body
(\
@forklist, 'age', 0, 15,
6658 $#forklist <= 15 ?
undef :
6659 $cgi->a({-href
=> href
(action
=>"forks")}, "..."),
6667 my %tag = parse_tag
($hash);
6670 die_error
(404, "Unknown tag object");
6673 my $head = git_get_head_hash
($project);
6675 git_print_page_nav
('','', $head,undef,$head);
6676 git_print_header_div
('commit', esc_html
($tag{'name'}), $hash);
6677 print "<div class=\"title_text\">\n" .
6678 "<table class=\"object_header\">\n" .
6680 "<td>object</td>\n" .
6681 "<td>" . $cgi->a({-class => "list", -href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6682 $tag{'object'}) . "</td>\n" .
6683 "<td class=\"link\">" . $cgi->a({-href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6684 $tag{'type'}) . "</td>\n" .
6686 if (defined($tag{'author'})) {
6687 git_print_authorship_rows
(\
%tag, 'author');
6689 print "</table>\n\n" .
6691 print "<div class=\"page_body\">";
6692 my $comment = $tag{'comment'};
6693 foreach my $line (@
$comment) {
6695 print esc_html
($line, -nbsp
=>1) . "<br/>\n";
6701 sub git_blame_common
{
6702 my $format = shift || 'porcelain';
6703 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6704 $format = 'incremental';
6705 $action = 'blame_incremental'; # for page title etc
6709 gitweb_check_feature
('blame')
6710 or die_error
(403, "Blame view not allowed");
6713 die_error
(400, "No file name given") unless $file_name;
6714 $hash_base ||= git_get_head_hash
($project);
6715 die_error
(404, "Couldn't find base commit") unless $hash_base;
6716 my %co = parse_commit
($hash_base)
6717 or die_error
(404, "Commit not found");
6719 if (!defined $hash) {
6720 $hash = git_get_hash_by_path
($hash_base, $file_name, "blob")
6721 or die_error
(404, "Error looking up file");
6723 $ftype = git_get_type
($hash);
6724 if ($ftype !~ "blob") {
6725 die_error
(400, "Object is not a blob");
6730 if ($format eq 'incremental') {
6731 # get file contents (as base)
6732 open $fd, "-|", git_cmd
(), 'cat-file', 'blob', $hash
6733 or die_error
(500, "Open git-cat-file failed");
6734 } elsif ($format eq 'data') {
6735 # run git-blame --incremental
6736 open $fd, "-|", git_cmd
(), "blame", "--incremental",
6737 $hash_base, "--", $file_name
6738 or die_error
(500, "Open git-blame --incremental failed");
6740 # run git-blame --porcelain
6741 open $fd, "-|", git_cmd
(), "blame", '-p',
6742 $hash_base, '--', $file_name
6743 or die_error
(500, "Open git-blame --porcelain failed");
6745 binmode $fd, ':utf8';
6747 # incremental blame data returns early
6748 if ($format eq 'data') {
6750 -type
=>"text/plain", -charset
=> "utf-8",
6751 -status
=> "200 OK");
6752 local $| = 1; # output autoflush
6753 while (my $line = <$fd>) {
6754 print to_utf8
($line);
6757 or print "ERROR $!\n";
6760 if (defined $t0 && gitweb_check_feature
('timed')) {
6762 tv_interval
($t0, [ gettimeofday
() ]).
6763 ' '.$number_of_git_cmds;
6773 $cgi->a({-href
=> href
(action
=>"blob", -replay
=>1)},
6776 if ($format eq 'incremental') {
6778 $cgi->a({-href
=> href
(action
=>"blame", javascript
=>0, -replay
=>1)},
6779 "blame") . " (non-incremental)";
6782 $cgi->a({-href
=> href
(action
=>"blame_incremental", -replay
=>1)},
6783 "blame") . " (incremental)";
6787 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
6790 $cgi->a({-href
=> href
(action
=>$action, file_name
=>$file_name)},
6792 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6793 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
6794 git_print_page_path
($file_name, $ftype, $hash_base);
6797 if ($format eq 'incremental') {
6798 print "<noscript>\n<div class=\"error\"><center><b>\n".
6799 "This page requires JavaScript to run.\n Use ".
6800 $cgi->a({-href
=> href
(action
=>'blame',javascript
=>0,-replay
=>1)},
6803 "</b></center></div>\n</noscript>\n";
6805 print qq!<div id
="progress_bar" style
="width: 100%; background-color: yellow"></div
>\n!;
6808 print qq!<div
class="page_body">\n!;
6809 print qq!<div id
="progress_info">... / ...</div
>\n!
6810 if ($format eq 'incremental');
6811 print qq!<table id
="blame_table" class="blame" width
="100%">\n!.
6812 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6814 qq!<tr
><th
>Commit
</th><th>Line</th
><th
>Data
</th></tr
>\n!.
6818 my @rev_color = qw(light dark);
6819 my $num_colors = scalar(@rev_color);
6820 my $current_color = 0;
6822 if ($format eq 'incremental') {
6823 my $color_class = $rev_color[$current_color];
6828 while (my $line = <$fd>) {
6832 print qq!<tr id
="l$linenr" class="$color_class">!.
6833 qq!<td
class="sha1"><a href
=""> </a></td
>!.
6834 qq!<td
class="linenr">!.
6835 qq!<a
class="linenr" href
="">$linenr</a></td
>!;
6836 print qq!<td
class="pre">! . esc_html
($line) . "</td>\n";
6840 } else { # porcelain, i.e. ordinary blame
6841 my %metainfo = (); # saves information about commits
6845 while (my $line = <$fd>) {
6847 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6848 # no <lines in group> for subsequent lines in group of lines
6849 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6850 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6851 if (!exists $metainfo{$full_rev}) {
6852 $metainfo{$full_rev} = { 'nprevious' => 0 };
6854 my $meta = $metainfo{$full_rev};
6856 while ($data = <$fd>) {
6858 last if ($data =~ s/^\t//); # contents of line
6859 if ($data =~ /^(\S+)(?: (.*))?$/) {
6860 $meta->{$1} = $2 unless exists $meta->{$1};
6862 if ($data =~ /^previous /) {
6863 $meta->{'nprevious'}++;
6866 my $short_rev = substr($full_rev, 0, 8);
6867 my $author = $meta->{'author'};
6869 parse_date
($meta->{'author-time'}, $meta->{'author-tz'});
6870 my $date = $date{'iso-tz'};
6872 $current_color = ($current_color + 1) % $num_colors;
6874 my $tr_class = $rev_color[$current_color];
6875 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6876 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6877 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6878 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6880 print "<td class=\"sha1\"";
6881 print " title=\"". esc_html
($author) . ", $date\"";
6882 print " rowspan=\"$group_size\"" if ($group_size > 1);
6884 print $cgi->a({-href
=> href
(action
=>"commit",
6886 file_name
=>$file_name)},
6887 esc_html
($short_rev));
6888 if ($group_size >= 2) {
6889 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6890 if (@author_initials) {
6892 esc_html
(join('', @author_initials));
6898 # 'previous' <sha1 of parent commit> <filename at commit>
6899 if (exists $meta->{'previous'} &&
6900 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6901 $meta->{'parent'} = $1;
6902 $meta->{'file_parent'} = unquote
($2);
6905 exists($meta->{'parent'}) ?
6906 $meta->{'parent'} : $full_rev;
6907 my $linenr_filename =
6908 exists($meta->{'file_parent'}) ?
6909 $meta->{'file_parent'} : unquote
($meta->{'filename'});
6910 my $blamed = href
(action
=> 'blame',
6911 file_name
=> $linenr_filename,
6912 hash_base
=> $linenr_commit);
6913 print "<td class=\"linenr\">";
6914 print $cgi->a({ -href
=> "$blamed#l$orig_lineno",
6915 -class => "linenr" },
6918 print "<td class=\"pre\">" . esc_html
($data) . "</td>\n";
6926 "</table>\n"; # class="blame"
6927 print "</div>\n"; # class="blame_body"
6929 or print "Reading blob failed\n";
6938 sub git_blame_incremental
{
6939 git_blame_common
('incremental');
6942 sub git_blame_data
{
6943 git_blame_common
('data');
6947 my $head = git_get_head_hash
($project);
6949 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('tags'));
6950 git_print_header_div
('summary', $project);
6952 my @tagslist = git_get_tags_list
();
6954 git_tags_body
(\
@tagslist);
6960 my $head = git_get_head_hash
($project);
6962 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('heads'));
6963 git_print_header_div
('summary', $project);
6965 my @headslist = git_get_heads_list
();
6967 git_heads_body
(\
@headslist, $head);
6972 # used both for single remote view and for list of all the remotes
6974 gitweb_check_feature
('remote_heads')
6975 or die_error
(403, "Remote heads view is disabled");
6977 my $head = git_get_head_hash
($project);
6978 my $remote = $input_params{'hash'};
6980 my $remotedata = git_get_remotes_list
($remote);
6981 die_error
(500, "Unable to get remote information") unless defined $remotedata;
6983 unless (%$remotedata) {
6984 die_error
(404, defined $remote ?
6985 "Remote $remote not found" :
6986 "No remotes found");
6989 git_header_html
(undef, undef, -action_extra
=> $remote);
6990 git_print_page_nav
('', '', $head, undef, $head,
6991 format_ref_views
($remote ?
'' : 'remotes'));
6993 fill_remote_heads
($remotedata);
6994 if (defined $remote) {
6995 git_print_header_div
('remotes', "$remote remote for $project");
6996 git_remote_block
($remote, $remotedata->{$remote}, undef, $head);
6998 git_print_header_div
('summary', "$project remotes");
6999 git_remotes_body
($remotedata, undef, $head);
7005 sub git_blob_plain
{
7009 if (!defined $hash) {
7010 if (defined $file_name) {
7011 my $base = $hash_base || git_get_head_hash
($project);
7012 $hash = git_get_hash_by_path
($base, $file_name, "blob")
7013 or die_error
(404, "Cannot find file");
7015 die_error
(400, "No file name defined");
7017 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7018 # blobs defined by non-textual hash id's can be cached
7022 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
7023 or die_error
(500, "Open git-cat-file blob '$hash' failed");
7025 # content-type (can include charset)
7026 $type = blob_contenttype
($fd, $file_name, $type);
7028 # "save as" filename, even when no $file_name is given
7029 my $save_as = "$hash";
7030 if (defined $file_name) {
7031 $save_as = $file_name;
7032 } elsif ($type =~ m/^text\//) {
7036 # With XSS prevention on, blobs of all types except a few known safe
7037 # ones are served with "Content-Disposition: attachment" to make sure
7038 # they don't run in our security domain. For certain image types,
7039 # blob view writes an <img> tag referring to blob_plain view, and we
7040 # want to be sure not to break that by serving the image as an
7041 # attachment (though Firefox 3 doesn't seem to care).
7042 my $sandbox = $prevent_xss &&
7043 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7045 # serve text/* as text/plain
7047 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7048 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T
$fd))) {
7050 $rest = defined $rest ?
$rest : '';
7051 $type = "text/plain$rest";
7056 -expires
=> $expires,
7057 -content_disposition
=>
7058 ($sandbox ?
'attachment' : 'inline')
7059 . '; filename="' . $save_as . '"');
7061 binmode STDOUT
, ':raw';
7063 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7070 if (!defined $hash) {
7071 if (defined $file_name) {
7072 my $base = $hash_base || git_get_head_hash
($project);
7073 $hash = git_get_hash_by_path
($base, $file_name, "blob")
7074 or die_error
(404, "Cannot find file");
7076 die_error
(400, "No file name defined");
7078 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7079 # blobs defined by non-textual hash id's can be cached
7083 my $have_blame = gitweb_check_feature
('blame');
7084 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
7085 or die_error
(500, "Couldn't cat $file_name, $hash");
7086 my $mimetype = blob_mimetype
($fd, $file_name);
7087 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7088 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B
$fd) {
7090 return git_blob_plain
($mimetype);
7092 # we can have blame only for text/* mimetype
7093 $have_blame &&= ($mimetype =~ m!^text/!);
7095 my $highlight = gitweb_check_feature
('highlight');
7096 my $syntax = guess_file_syntax
($highlight, $mimetype, $file_name);
7097 $fd = run_highlighter
($fd, $highlight, $syntax)
7100 git_header_html
(undef, $expires);
7101 my $formats_nav = '';
7102 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7103 if (defined $file_name) {
7106 $cgi->a({-href
=> href
(action
=>"blame", -replay
=>1)},
7111 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7114 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7117 $cgi->a({-href
=> href
(action
=>"blob",
7118 hash_base
=>"HEAD", file_name
=>$file_name)},
7122 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7125 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7126 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7128 print "<div class=\"page_nav\">\n" .
7129 "<br/><br/></div>\n" .
7130 "<div class=\"title\">".esc_html
($hash)."</div>\n";
7132 git_print_page_path
($file_name, "blob", $hash_base);
7133 print "<div class=\"page_body\">\n";
7134 if ($mimetype =~ m!^image/!) {
7135 print qq!<img
class="blob" type
="!.esc_attr($mimetype).qq!"!;
7137 print qq! alt
="!.esc_attr($file_name).qq!" title
="!.esc_attr($file_name).qq!"!;
7140 href(action=>"blob_plain
", hash=>$hash,
7141 hash_base=>$hash_base, file_name=>$file_name) .
7145 while (my $line = <$fd>) {
7148 $line = untabify
($line);
7149 printf qq!<div
class="pre"><a id
="l%i" href
="%s#l%i" class="linenr">%4i</a> %s</div
>\n!,
7150 $nr, esc_attr
(href
(-replay
=> 1)), $nr, $nr,
7151 $syntax ? sanitize
($line) : esc_html
($line, -nbsp
=>1);
7155 or print "Reading blob failed.\n";
7161 if (!defined $hash_base) {
7162 $hash_base = "HEAD";
7164 if (!defined $hash) {
7165 if (defined $file_name) {
7166 $hash = git_get_hash_by_path
($hash_base, $file_name, "tree");
7171 die_error
(404, "No such tree") unless defined($hash);
7173 my $show_sizes = gitweb_check_feature
('show-sizes');
7174 my $have_blame = gitweb_check_feature
('blame');
7179 open my $fd, "-|", git_cmd
(), "ls-tree", '-z',
7180 ($show_sizes ?
'-l' : ()), @extra_options, $hash
7181 or die_error
(500, "Open git-ls-tree failed");
7182 @entries = map { chomp; $_ } <$fd>;
7184 or die_error
(404, "Reading tree failed");
7187 my $refs = git_get_references
();
7188 my $ref = format_ref_marker
($refs, $hash_base);
7191 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7193 if (defined $file_name) {
7195 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7197 $cgi->a({-href
=> href
(action
=>"tree",
7198 hash_base
=>"HEAD", file_name
=>$file_name)},
7201 my $snapshot_links = format_snapshot_links
($hash);
7202 if (defined $snapshot_links) {
7203 # FIXME: Should be available when we have no hash base as well.
7204 push @views_nav, $snapshot_links;
7206 git_print_page_nav
('tree','', $hash_base, undef, undef,
7207 join(' | ', @views_nav));
7208 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash_base);
7211 print "<div class=\"page_nav\">\n";
7212 print "<br/><br/></div>\n";
7213 print "<div class=\"title\">".esc_html
($hash)."</div>\n";
7215 if (defined $file_name) {
7216 $basedir = $file_name;
7217 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7220 git_print_page_path
($file_name, 'tree', $hash_base);
7222 print "<div class=\"page_body\">\n";
7223 print "<table class=\"tree\">\n";
7225 # '..' (top directory) link if possible
7226 if (defined $hash_base &&
7227 defined $file_name && $file_name =~ m![^/]+$!) {
7229 print "<tr class=\"dark\">\n";
7231 print "<tr class=\"light\">\n";
7235 my $up = $file_name;
7236 $up =~ s!/?[^/]+$!!;
7237 undef $up unless $up;
7238 # based on git_print_tree_entry
7239 print '<td class="mode">' . mode_str
('040000') . "</td>\n";
7240 print '<td class="size"> </td>'."\n" if $show_sizes;
7241 print '<td class="list">';
7242 print $cgi->a({-href
=> href
(action
=>"tree",
7243 hash_base
=>$hash_base,
7247 print "<td class=\"link\"></td>\n";
7251 foreach my $line (@entries) {
7252 my %t = parse_ls_tree_line
($line, -z
=> 1, -l
=> $show_sizes);
7255 print "<tr class=\"dark\">\n";
7257 print "<tr class=\"light\">\n";
7261 git_print_tree_entry
(\
%t, $basedir, $hash_base, $have_blame);
7265 print "</table>\n" .
7270 sub sanitize_for_filename
{
7274 $name =~ s/[^[:alnum:]_.-]//g;
7280 my ($project, $hash) = @_;
7282 # path/to/project.git -> project
7283 # path/to/project/.git -> project
7284 my $name = to_utf8
($project);
7285 $name =~ s
,([^/])/*\
.git
$,$1,;
7286 $name = sanitize_for_filename
(basename
($name));
7289 if ($hash =~ /^[0-9a-fA-F]+$/) {
7290 # shorten SHA-1 hash
7291 my $full_hash = git_get_full_hash
($project, $hash);
7292 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7293 $ver = git_get_short_hash
($project, $hash);
7295 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7296 # tags don't need shortened SHA-1 hash
7299 # branches and other need shortened SHA-1 hash
7300 my $strip_refs = join '|', map { quotemeta } get_branch_refs
();
7301 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7302 my $ref_dir = (defined $1) ?
$1 : '';
7305 $ref_dir = sanitize_for_filename
($ref_dir);
7306 # for refs neither in heads nor remotes we want to
7307 # add a ref dir to archive name
7308 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7309 $ver = $ref_dir . '-' . $ver;
7312 $ver .= '-' . git_get_short_hash
($project, $hash);
7314 # special case of sanitization for filename - we change
7315 # slashes to dots instead of dashes
7316 # in case of hierarchical branch names
7318 $ver =~ s/[^[:alnum:]_.-]//g;
7320 # name = project-version_string
7321 $name = "$name-$ver";
7323 return wantarray ?
($name, $name) : $name;
7326 sub exit_if_unmodified_since
{
7327 my ($latest_epoch) = @_;
7330 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7331 if (defined $if_modified) {
7333 if (eval { require HTTP
::Date
; 1; }) {
7334 $since = HTTP
::Date
::str2time
($if_modified);
7335 } elsif (eval { require Time
::ParseDate
; 1; }) {
7336 $since = Time
::ParseDate
::parsedate
($if_modified, GMT
=> 1);
7338 if (defined $since && $latest_epoch <= $since) {
7339 my %latest_date = parse_date
($latest_epoch);
7341 -last_modified
=> $latest_date{'rfc2822'},
7342 -status
=> '304 Not Modified');
7349 my $format = $input_params{'snapshot_format'};
7350 if (!@snapshot_fmts) {
7351 die_error
(403, "Snapshots not allowed");
7353 # default to first supported snapshot format
7354 $format ||= $snapshot_fmts[0];
7355 if ($format !~ m/^[a-z0-9]+$/) {
7356 die_error
(400, "Invalid snapshot format parameter");
7357 } elsif (!exists($known_snapshot_formats{$format})) {
7358 die_error
(400, "Unknown snapshot format");
7359 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7360 die_error
(403, "Snapshot format not allowed");
7361 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7362 die_error
(403, "Unsupported snapshot format");
7365 my $type = git_get_type
("$hash^{}");
7367 die_error
(404, 'Object does not exist');
7368 } elsif ($type eq 'blob') {
7369 die_error
(400, 'Object is not a tree-ish');
7372 my ($name, $prefix) = snapshot_name
($project, $hash);
7373 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7375 my %co = parse_commit
($hash);
7376 exit_if_unmodified_since
($co{'committer_epoch'}) if %co;
7378 my $cmd = quote_command
(
7379 git_cmd
(), 'archive',
7380 "--format=$known_snapshot_formats{$format}{'format'}",
7381 "--prefix=$prefix/", $hash);
7382 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7383 $cmd .= ' | ' . quote_command
(@
{$known_snapshot_formats{$format}{'compressor'}});
7386 $filename =~ s/(["\\])/\\$1/g;
7389 %latest_date = parse_date
($co{'committer_epoch'}, $co{'committer_tz'});
7393 -type
=> $known_snapshot_formats{$format}{'type'},
7394 -content_disposition
=> 'inline; filename="' . $filename . '"',
7395 %co ?
(-last_modified
=> $latest_date{'rfc2822'}) : (),
7396 -status
=> '200 OK');
7398 open my $fd, "-|", $cmd
7399 or die_error
(500, "Execute git-archive failed");
7400 binmode STDOUT
, ':raw';
7402 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7406 sub git_log_generic
{
7407 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7409 my $head = git_get_head_hash
($project);
7410 if (!defined $base) {
7413 if (!defined $page) {
7416 my $refs = git_get_references
();
7418 my $commit_hash = $base;
7419 if (defined $parent) {
7420 $commit_hash = "$parent..$base";
7423 parse_commits
($commit_hash, 101, (100 * $page),
7424 defined $file_name ?
($file_name, "--full-history") : ());
7427 if (!defined $file_hash && defined $file_name) {
7428 # some commits could have deleted file in question,
7429 # and not have it in tree, but one of them has to have it
7430 for (my $i = 0; $i < @commitlist; $i++) {
7431 $file_hash = git_get_hash_by_path
($commitlist[$i]{'id'}, $file_name);
7432 last if defined $file_hash;
7435 if (defined $file_hash) {
7436 $ftype = git_get_type
($file_hash);
7438 if (defined $file_name && !defined $ftype) {
7439 die_error
(500, "Unknown type of object");
7442 if (defined $file_name) {
7443 %co = parse_commit
($base)
7444 or die_error
(404, "Unknown commit object");
7448 my $paging_nav = format_paging_nav
($fmt_name, $page, $#commitlist >= 100);
7450 if ($#commitlist >= 100) {
7452 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
7453 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
7455 my $patch_max = gitweb_get_feature
('patches');
7456 if ($patch_max && !defined $file_name) {
7457 if ($patch_max < 0 || @commitlist <= $patch_max) {
7458 $paging_nav .= " ⋅ " .
7459 $cgi->a({-href
=> href
(action
=>"patches", -replay
=>1)},
7465 git_print_page_nav
($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7466 if (defined $file_name) {
7467 git_print_header_div
('commit', esc_html
($co{'title'}), $base);
7469 git_print_header_div
('summary', $project)
7471 git_print_page_path
($file_name, $ftype, $hash_base)
7472 if (defined $file_name);
7474 $body_subr->(\
@commitlist, 0, 99, $refs, $next_link,
7475 $file_name, $file_hash, $ftype);
7481 git_log_generic
('log', \
&git_log_body
,
7482 $hash, $hash_parent);
7486 $hash ||= $hash_base || "HEAD";
7487 my %co = parse_commit
($hash)
7488 or die_error
(404, "Unknown commit object");
7490 my $parent = $co{'parent'};
7491 my $parents = $co{'parents'}; # listref
7493 # we need to prepare $formats_nav before any parameter munging
7495 if (!defined $parent) {
7497 $formats_nav .= '(initial)';
7498 } elsif (@
$parents == 1) {
7499 # single parent commit
7502 $cgi->a({-href
=> href
(action
=>"commit",
7504 esc_html
(substr($parent, 0, 7))) .
7511 $cgi->a({-href
=> href
(action
=>"commit",
7513 esc_html
(substr($_, 0, 7)));
7517 if (gitweb_check_feature
('patches') && @
$parents <= 1) {
7518 $formats_nav .= " | " .
7519 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7523 if (!defined $parent) {
7527 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', "--no-commit-id",
7529 (@
$parents <= 1 ?
$parent : '-c'),
7531 or die_error
(500, "Open git-diff-tree failed");
7532 @difftree = map { chomp; $_ } <$fd>;
7533 close $fd or die_error
(404, "Reading git-diff-tree failed");
7535 # non-textual hash id's can be cached
7537 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7540 my $refs = git_get_references
();
7541 my $ref = format_ref_marker
($refs, $co{'id'});
7543 git_header_html
(undef, $expires);
7544 git_print_page_nav
('commit', '',
7545 $hash, $co{'tree'}, $hash,
7548 if (defined $co{'parent'}) {
7549 git_print_header_div
('commitdiff', esc_html
($co{'title'}) . $ref, $hash);
7551 git_print_header_div
('tree', esc_html
($co{'title'}) . $ref, $co{'tree'}, $hash);
7553 print "<div class=\"title_text\">\n" .
7554 "<table class=\"object_header\">\n";
7555 git_print_authorship_rows
(\
%co);
7556 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7559 "<td class=\"sha1\">" .
7560 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash),
7561 class => "list"}, $co{'tree'}) .
7563 "<td class=\"link\">" .
7564 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash)},
7566 my $snapshot_links = format_snapshot_links
($hash);
7567 if (defined $snapshot_links) {
7568 print " | " . $snapshot_links;
7573 foreach my $par (@
$parents) {
7576 "<td class=\"sha1\">" .
7577 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par),
7578 class => "list"}, $par) .
7580 "<td class=\"link\">" .
7581 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par)}, "commit") .
7583 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$hash, hash_parent
=>$par)}, "diff") .
7590 print "<div class=\"page_body\">\n";
7591 git_print_log
($co{'comment'});
7594 git_difftree_body
(\
@difftree, $hash, @
$parents);
7600 # object is defined by:
7601 # - hash or hash_base alone
7602 # - hash_base and file_name
7605 # - hash or hash_base alone
7606 if ($hash || ($hash_base && !defined $file_name)) {
7607 my $object_id = $hash || $hash_base;
7609 open my $fd, "-|", quote_command
(
7610 git_cmd
(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7611 or die_error
(404, "Object does not exist");
7615 or die_error
(404, "Object does not exist");
7617 # - hash_base and file_name
7618 } elsif ($hash_base && defined $file_name) {
7619 $file_name =~ s
,/+$,,;
7621 system(git_cmd
(), "cat-file", '-e', $hash_base) == 0
7622 or die_error
(404, "Base object does not exist");
7624 # here errors should not happen
7625 open my $fd, "-|", git_cmd
(), "ls-tree", $hash_base, "--", $file_name
7626 or die_error
(500, "Open git-ls-tree failed");
7630 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7631 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7632 die_error
(404, "File or directory for given base does not exist");
7637 die_error
(400, "Not enough information to find object");
7640 print $cgi->redirect(-uri
=> href
(action
=>$type, -full
=>1,
7641 hash
=>$hash, hash_base
=>$hash_base,
7642 file_name
=>$file_name),
7643 -status
=> '302 Found');
7647 my $format = shift || 'html';
7648 my $diff_style = $input_params{'diff_style'} || 'inline';
7655 # preparing $fd and %diffinfo for git_patchset_body
7657 if (defined $hash_base && defined $hash_parent_base) {
7658 if (defined $file_name) {
7660 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7661 $hash_parent_base, $hash_base,
7662 "--", (defined $file_parent ?
$file_parent : ()), $file_name
7663 or die_error
(500, "Open git-diff-tree failed");
7664 @difftree = map { chomp; $_ } <$fd>;
7666 or die_error
(404, "Reading git-diff-tree failed");
7668 or die_error
(404, "Blob diff not found");
7670 } elsif (defined $hash &&
7671 $hash =~ /[0-9a-fA-F]{40}/) {
7672 # try to find filename from $hash
7674 # read filtered raw output
7675 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7676 $hash_parent_base, $hash_base, "--"
7677 or die_error
(500, "Open git-diff-tree failed");
7679 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7681 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7682 map { chomp; $_ } <$fd>;
7684 or die_error
(404, "Reading git-diff-tree failed");
7686 or die_error
(404, "Blob diff not found");
7689 die_error
(400, "Missing one of the blob diff parameters");
7692 if (@difftree > 1) {
7693 die_error
(400, "Ambiguous blob diff specification");
7696 %diffinfo = parse_difftree_raw_line
($difftree[0]);
7697 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7698 $file_name ||= $diffinfo{'to_file'};
7700 $hash_parent ||= $diffinfo{'from_id'};
7701 $hash ||= $diffinfo{'to_id'};
7703 # non-textual hash id's can be cached
7704 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7705 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7710 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7711 '-p', ($format eq 'html' ?
"--full-index" : ()),
7712 $hash_parent_base, $hash_base,
7713 "--", (defined $file_parent ?
$file_parent : ()), $file_name
7714 or die_error
(500, "Open git-diff-tree failed");
7717 # old/legacy style URI -- not generated anymore since 1.4.3.
7719 die_error
('404 Not Found', "Missing one of the blob diff parameters")
7723 if ($format eq 'html') {
7725 $cgi->a({-href
=> href
(action
=>"blobdiff_plain", -replay
=>1)},
7727 $formats_nav .= diff_style_nav
($diff_style);
7728 git_header_html
(undef, $expires);
7729 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7730 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7731 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7733 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7734 print "<div class=\"title\">".esc_html
("$hash vs $hash_parent")."</div>\n";
7736 if (defined $file_name) {
7737 git_print_page_path
($file_name, "blob", $hash_base);
7739 print "<div class=\"page_path\"></div>\n";
7742 } elsif ($format eq 'plain') {
7744 -type
=> 'text/plain',
7745 -charset
=> 'utf-8',
7746 -expires
=> $expires,
7747 -content_disposition
=> 'inline; filename="' . "$file_name" . '.patch"');
7749 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7752 die_error
(400, "Unknown blobdiff format");
7756 if ($format eq 'html') {
7757 print "<div class=\"page_body\">\n";
7759 git_patchset_body
($fd, $diff_style,
7760 [ \
%diffinfo ], $hash_base, $hash_parent_base);
7763 print "</div>\n"; # class="page_body"
7767 while (my $line = <$fd>) {
7768 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7769 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7773 last if $line =~ m!^\+\+\+!;
7781 sub git_blobdiff_plain
{
7782 git_blobdiff
('plain');
7785 # assumes that it is added as later part of already existing navigation,
7786 # so it returns "| foo | bar" rather than just "foo | bar"
7787 sub diff_style_nav
{
7788 my ($diff_style, $is_combined) = @_;
7789 $diff_style ||= 'inline';
7791 return "" if ($is_combined);
7793 my @styles = (inline
=> 'inline', 'sidebyside' => 'side by side');
7794 my %styles = @styles;
7796 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7801 $_ eq $diff_style ?
$styles{$_} :
7802 $cgi->a({-href
=> href
(-replay
=>1, diff_style
=> $_)}, $styles{$_})
7806 sub git_commitdiff
{
7808 my $format = $params{-format
} || 'html';
7809 my $diff_style = $input_params{'diff_style'} || 'inline';
7811 my ($patch_max) = gitweb_get_feature
('patches');
7812 if ($format eq 'patch') {
7813 die_error
(403, "Patch view not allowed") unless $patch_max;
7816 $hash ||= $hash_base || "HEAD";
7817 my %co = parse_commit
($hash)
7818 or die_error
(404, "Unknown commit object");
7820 # choose format for commitdiff for merge
7821 if (! defined $hash_parent && @
{$co{'parents'}} > 1) {
7822 $hash_parent = '--cc';
7824 # we need to prepare $formats_nav before almost any parameter munging
7826 if ($format eq 'html') {
7828 $cgi->a({-href
=> href
(action
=>"commitdiff_plain", -replay
=>1)},
7830 if ($patch_max && @
{$co{'parents'}} <= 1) {
7831 $formats_nav .= " | " .
7832 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7835 $formats_nav .= diff_style_nav
($diff_style, @
{$co{'parents'}} > 1);
7837 if (defined $hash_parent &&
7838 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7839 # commitdiff with two commits given
7840 my $hash_parent_short = $hash_parent;
7841 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7842 $hash_parent_short = substr($hash_parent, 0, 7);
7846 for (my $i = 0; $i < @
{$co{'parents'}}; $i++) {
7847 if ($co{'parents'}[$i] eq $hash_parent) {
7848 $formats_nav .= ' parent ' . ($i+1);
7852 $formats_nav .= ': ' .
7853 $cgi->a({-href
=> href
(-replay
=>1,
7854 hash
=>$hash_parent, hash_base
=>undef)},
7855 esc_html
($hash_parent_short)) .
7857 } elsif (!$co{'parent'}) {
7859 $formats_nav .= ' (initial)';
7860 } elsif (scalar @
{$co{'parents'}} == 1) {
7861 # single parent commit
7864 $cgi->a({-href
=> href
(-replay
=>1,
7865 hash
=>$co{'parent'}, hash_base
=>undef)},
7866 esc_html
(substr($co{'parent'}, 0, 7))) .
7870 if ($hash_parent eq '--cc') {
7871 $formats_nav .= ' | ' .
7872 $cgi->a({-href
=> href
(-replay
=>1,
7873 hash
=>$hash, hash_parent
=>'-c')},
7875 } else { # $hash_parent eq '-c'
7876 $formats_nav .= ' | ' .
7877 $cgi->a({-href
=> href
(-replay
=>1,
7878 hash
=>$hash, hash_parent
=>'--cc')},
7884 $cgi->a({-href
=> href
(-replay
=>1,
7885 hash
=>$_, hash_base
=>undef)},
7886 esc_html
(substr($_, 0, 7)));
7887 } @
{$co{'parents'}} ) .
7892 my $hash_parent_param = $hash_parent;
7893 if (!defined $hash_parent_param) {
7894 # --cc for multiple parents, --root for parentless
7895 $hash_parent_param =
7896 @
{$co{'parents'}} > 1 ?
'--cc' : $co{'parent'} || '--root';
7902 if ($format eq 'html') {
7903 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7904 "--no-commit-id", "--patch-with-raw", "--full-index",
7905 $hash_parent_param, $hash, "--"
7906 or die_error
(500, "Open git-diff-tree failed");
7908 while (my $line = <$fd>) {
7910 # empty line ends raw part of diff-tree output
7912 push @difftree, scalar parse_difftree_raw_line
($line);
7915 } elsif ($format eq 'plain') {
7916 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7917 '-p', $hash_parent_param, $hash, "--"
7918 or die_error
(500, "Open git-diff-tree failed");
7919 } elsif ($format eq 'patch') {
7920 # For commit ranges, we limit the output to the number of
7921 # patches specified in the 'patches' feature.
7922 # For single commits, we limit the output to a single patch,
7923 # diverging from the git-format-patch default.
7924 my @commit_spec = ();
7926 if ($patch_max > 0) {
7927 push @commit_spec, "-$patch_max";
7929 push @commit_spec, '-n', "$hash_parent..$hash";
7931 if ($params{-single
}) {
7932 push @commit_spec, '-1';
7934 if ($patch_max > 0) {
7935 push @commit_spec, "-$patch_max";
7937 push @commit_spec, "-n";
7939 push @commit_spec, '--root', $hash;
7941 open $fd, "-|", git_cmd
(), "format-patch", @diff_opts,
7942 '--encoding=utf8', '--stdout', @commit_spec
7943 or die_error
(500, "Open git-format-patch failed");
7945 die_error
(400, "Unknown commitdiff format");
7948 # non-textual hash id's can be cached
7950 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7954 # write commit message
7955 if ($format eq 'html') {
7956 my $refs = git_get_references
();
7957 my $ref = format_ref_marker
($refs, $co{'id'});
7959 git_header_html
(undef, $expires);
7960 git_print_page_nav
('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7961 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash);
7962 print "<div class=\"title_text\">\n" .
7963 "<table class=\"object_header\">\n";
7964 git_print_authorship_rows
(\
%co);
7967 print "<div class=\"page_body\">\n";
7968 if (@
{$co{'comment'}} > 1) {
7969 print "<div class=\"log\">\n";
7970 git_print_log
($co{'comment'}, -final_empty_line
=> 1, -remove_title
=> 1);
7971 print "</div>\n"; # class="log"
7974 } elsif ($format eq 'plain') {
7975 my $refs = git_get_references
("tags");
7976 my $tagname = git_get_rev_name_tags
($hash);
7977 my $filename = basename
($project) . "-$hash.patch";
7980 -type
=> 'text/plain',
7981 -charset
=> 'utf-8',
7982 -expires
=> $expires,
7983 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
7984 my %ad = parse_date
($co{'author_epoch'}, $co{'author_tz'});
7985 print "From: " . to_utf8
($co{'author'}) . "\n";
7986 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7987 print "Subject: " . to_utf8
($co{'title'}) . "\n";
7989 print "X-Git-Tag: $tagname\n" if $tagname;
7990 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7992 foreach my $line (@
{$co{'comment'}}) {
7993 print to_utf8
($line) . "\n";
7996 } elsif ($format eq 'patch') {
7997 my $filename = basename
($project) . "-$hash.patch";
8000 -type
=> 'text/plain',
8001 -charset
=> 'utf-8',
8002 -expires
=> $expires,
8003 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
8007 if ($format eq 'html') {
8008 my $use_parents = !defined $hash_parent ||
8009 $hash_parent eq '-c' || $hash_parent eq '--cc';
8010 git_difftree_body
(\
@difftree, $hash,
8011 $use_parents ? @
{$co{'parents'}} : $hash_parent);
8014 git_patchset_body
($fd, $diff_style,
8016 $use_parents ? @
{$co{'parents'}} : $hash_parent);
8018 print "</div>\n"; # class="page_body"
8021 } elsif ($format eq 'plain') {
8025 or print "Reading git-diff-tree failed\n";
8026 } elsif ($format eq 'patch') {
8030 or print "Reading git-format-patch failed\n";
8034 sub git_commitdiff_plain
{
8035 git_commitdiff
(-format
=> 'plain');
8038 # format-patch-style patches
8040 git_commitdiff
(-format
=> 'patch', -single
=> 1);
8044 git_commitdiff
(-format
=> 'patch');
8048 git_log_generic
('history', \
&git_history_body
,
8049 $hash_base, $hash_parent_base,
8054 $searchtype ||= 'commit';
8056 # check if appropriate features are enabled
8057 gitweb_check_feature
('search')
8058 or die_error
(403, "Search is disabled");
8059 if ($searchtype eq 'pickaxe') {
8060 # pickaxe may take all resources of your box and run for several minutes
8061 # with every query - so decide by yourself how public you make this feature
8062 gitweb_check_feature
('pickaxe')
8063 or die_error
(403, "Pickaxe search is disabled");
8065 if ($searchtype eq 'grep') {
8066 # grep search might be potentially CPU-intensive, too
8067 gitweb_check_feature
('grep')
8068 or die_error
(403, "Grep search is disabled");
8071 if (!defined $searchtext) {
8072 die_error
(400, "Text field is empty");
8074 if (!defined $hash) {
8075 $hash = git_get_head_hash
($project);
8077 my %co = parse_commit
($hash);
8079 die_error
(404, "Unknown commit object");
8081 if (!defined $page) {
8085 if ($searchtype eq 'commit' ||
8086 $searchtype eq 'author' ||
8087 $searchtype eq 'committer') {
8088 git_search_message
(%co);
8089 } elsif ($searchtype eq 'pickaxe') {
8090 git_search_changes
(%co);
8091 } elsif ($searchtype eq 'grep') {
8092 git_search_files
(%co);
8094 die_error
(400, "Unknown search type");
8098 sub git_search_help
{
8100 git_print_page_nav
('','', $hash,$hash,$hash);
8102 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8103 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8104 the pattern entered is recognized as the POSIX extended
8105 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8108 <dt><b>commit</b></dt>
8109 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8111 my $have_grep = gitweb_check_feature
('grep');
8114 <dt><b>grep</b></dt>
8115 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8116 a different one) are searched for the given pattern. On large trees, this search can take
8117 a while and put some strain on the server, so please use it with some consideration. Note that
8118 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8119 case-sensitive.</dd>
8123 <dt><b>author</b></dt>
8124 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8125 <dt><b>committer</b></dt>
8126 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8128 my $have_pickaxe = gitweb_check_feature
('pickaxe');
8129 if ($have_pickaxe) {
8131 <dt><b>pickaxe</b></dt>
8132 <dd>All commits that caused the string to appear or disappear from any file (changes that
8133 added, removed or "modified" the string) will be listed. This search can take a while and
8134 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8135 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8143 git_log_generic
('shortlog', \
&git_shortlog_body
,
8144 $hash, $hash_parent);
8147 ## ......................................................................
8148 ## feeds (RSS, Atom; OPML)
8151 my $format = shift || 'atom';
8152 my $have_blame = gitweb_check_feature
('blame');
8154 # Atom: http://www.atomenabled.org/developers/syndication/
8155 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8156 if ($format ne 'rss' && $format ne 'atom') {
8157 die_error
(400, "Unknown web feed format");
8160 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8161 my $head = $hash || 'HEAD';
8162 my @commitlist = parse_commits
($head, 150, 0, $file_name);
8166 my $content_type = "application/$format+xml";
8167 if (defined $cgi->http('HTTP_ACCEPT') &&
8168 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8169 # browser (feed reader) prefers text/xml
8170 $content_type = 'text/xml';
8172 if (defined($commitlist[0])) {
8173 %latest_commit = %{$commitlist[0]};
8174 my $latest_epoch = $latest_commit{'committer_epoch'};
8175 exit_if_unmodified_since
($latest_epoch);
8176 %latest_date = parse_date
($latest_epoch, $latest_commit{'committer_tz'});
8179 -type
=> $content_type,
8180 -charset
=> 'utf-8',
8181 %latest_date ?
(-last_modified
=> $latest_date{'rfc2822'}) : (),
8182 -status
=> '200 OK');
8184 # Optimization: skip generating the body if client asks only
8185 # for Last-Modified date.
8186 return if ($cgi->request_method() eq 'HEAD');
8189 my $title = "$site_name - $project/$action";
8190 my $feed_type = 'log';
8191 if (defined $hash) {
8192 $title .= " - '$hash'";
8193 $feed_type = 'branch log';
8194 if (defined $file_name) {
8195 $title .= " :: $file_name";
8196 $feed_type = 'history';
8198 } elsif (defined $file_name) {
8199 $title .= " - $file_name";
8200 $feed_type = 'history';
8202 $title .= " $feed_type";
8203 $title = esc_html
($title);
8204 my $descr = git_get_project_description
($project);
8205 if (defined $descr) {
8206 $descr = esc_html
($descr);
8208 $descr = "$project " .
8209 ($format eq 'rss' ?
'RSS' : 'Atom') .
8212 my $owner = git_get_project_owner
($project);
8213 $owner = esc_html
($owner);
8217 if (defined $file_name) {
8218 $alt_url = href
(-full
=>1, action
=>"history", hash
=>$hash, file_name
=>$file_name);
8219 } elsif (defined $hash) {
8220 $alt_url = href
(-full
=>1, action
=>"log", hash
=>$hash);
8222 $alt_url = href
(-full
=>1, action
=>"summary");
8224 print qq!<?xml version
="1.0" encoding
="utf-8"?
>\n!;
8225 if ($format eq 'rss') {
8227 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8230 print "<title>$title</title>\n" .
8231 "<link>$alt_url</link>\n" .
8232 "<description>$descr</description>\n" .
8233 "<language>en</language>\n" .
8234 # project owner is responsible for 'editorial' content
8235 "<managingEditor>$owner</managingEditor>\n";
8236 if (defined $logo || defined $favicon) {
8237 # prefer the logo to the favicon, since RSS
8238 # doesn't allow both
8239 my $img = esc_url
($logo || $favicon);
8241 "<url>$img</url>\n" .
8242 "<title>$title</title>\n" .
8243 "<link>$alt_url</link>\n" .
8247 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8248 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8250 print "<generator>gitweb v.$version/$git_version</generator>\n";
8251 } elsif ($format eq 'atom') {
8253 <feed xmlns="http://www.w3.org/2005/Atom">
8255 print "<title>$title</title>\n" .
8256 "<subtitle>$descr</subtitle>\n" .
8257 '<link rel="alternate" type="text/html" href="' .
8258 $alt_url . '" />' . "\n" .
8259 '<link rel="self" type="' . $content_type . '" href="' .
8260 $cgi->self_url() . '" />' . "\n" .
8261 "<id>" . href
(-full
=>1) . "</id>\n" .
8262 # use project owner for feed author
8263 "<author><name>$owner</name></author>\n";
8264 if (defined $favicon) {
8265 print "<icon>" . esc_url
($favicon) . "</icon>\n";
8267 if (defined $logo) {
8268 # not twice as wide as tall: 72 x 27 pixels
8269 print "<logo>" . esc_url
($logo) . "</logo>\n";
8271 if (! %latest_date) {
8272 # dummy date to keep the feed valid until commits trickle in:
8273 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8275 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8277 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8281 for (my $i = 0; $i <= $#commitlist; $i++) {
8282 my %co = %{$commitlist[$i]};
8283 my $commit = $co{'id'};
8284 # we read 150, we always show 30 and the ones more recent than 48 hours
8285 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8288 my %cd = parse_date
($co{'author_epoch'}, $co{'author_tz'});
8290 # get list of changed files
8291 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
8292 $co{'parent'} || "--root",
8293 $co{'id'}, "--", (defined $file_name ?
$file_name : ())
8295 my @difftree = map { chomp; $_ } <$fd>;
8299 # print element (entry, item)
8300 my $co_url = href
(-full
=>1, action
=>"commitdiff", hash
=>$commit);
8301 if ($format eq 'rss') {
8303 "<title>" . esc_html
($co{'title'}) . "</title>\n" .
8304 "<author>" . esc_html
($co{'author'}) . "</author>\n" .
8305 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8306 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8307 "<link>$co_url</link>\n" .
8308 "<description>" . esc_html
($co{'title'}) . "</description>\n" .
8309 "<content:encoded>" .
8311 } elsif ($format eq 'atom') {
8313 "<title type=\"html\">" . esc_html
($co{'title'}) . "</title>\n" .
8314 "<updated>$cd{'iso-8601'}</updated>\n" .
8316 " <name>" . esc_html
($co{'author_name'}) . "</name>\n";
8317 if ($co{'author_email'}) {
8318 print " <email>" . esc_html
($co{'author_email'}) . "</email>\n";
8320 print "</author>\n" .
8321 # use committer for contributor
8323 " <name>" . esc_html
($co{'committer_name'}) . "</name>\n";
8324 if ($co{'committer_email'}) {
8325 print " <email>" . esc_html
($co{'committer_email'}) . "</email>\n";
8327 print "</contributor>\n" .
8328 "<published>$cd{'iso-8601'}</published>\n" .
8329 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8330 "<id>$co_url</id>\n" .
8331 "<content type=\"xhtml\" xml:base=\"" . esc_url
($my_url) . "\">\n" .
8332 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8334 my $comment = $co{'comment'};
8336 foreach my $line (@
$comment) {
8337 $line = esc_html
($line);
8340 print "</pre><ul>\n";
8341 foreach my $difftree_line (@difftree) {
8342 my %difftree = parse_difftree_raw_line
($difftree_line);
8343 next if !$difftree{'from_id'};
8345 my $file = $difftree{'file'} || $difftree{'to_file'};
8349 $cgi->a({-href
=> href
(-full
=>1, action
=>"blobdiff",
8350 hash
=>$difftree{'to_id'}, hash_parent
=>$difftree{'from_id'},
8351 hash_base
=>$co{'id'}, hash_parent_base
=>$co{'parent'},
8352 file_name
=>$file, file_parent
=>$difftree{'from_file'}),
8353 -title
=> "diff"}, 'D');
8355 print $cgi->a({-href
=> href
(-full
=>1, action
=>"blame",
8356 file_name
=>$file, hash_base
=>$commit),
8357 -title
=> "blame"}, 'B');
8359 # if this is not a feed of a file history
8360 if (!defined $file_name || $file_name ne $file) {
8361 print $cgi->a({-href
=> href
(-full
=>1, action
=>"history",
8362 file_name
=>$file, hash
=>$commit),
8363 -title
=> "history"}, 'H');
8365 $file = esc_path
($file);
8369 if ($format eq 'rss') {
8370 print "</ul>]]>\n" .
8371 "</content:encoded>\n" .
8373 } elsif ($format eq 'atom') {
8374 print "</ul>\n</div>\n" .
8381 if ($format eq 'rss') {
8382 print "</channel>\n</rss>\n";
8383 } elsif ($format eq 'atom') {
8397 my @list = git_get_projects_list
($project_filter, $strict_export);
8399 die_error
(404, "No projects found");
8403 -type
=> 'text/xml',
8404 -charset
=> 'utf-8',
8405 -content_disposition
=> 'inline; filename="opml.xml"');
8407 my $title = esc_html
($site_name);
8408 my $filter = " within subdirectory ";
8409 if (defined $project_filter) {
8410 $filter .= esc_html
($project_filter);
8415 <?xml version="1.0" encoding="utf-8"?>
8416 <opml version="1.0">
8418 <title>$title OPML Export$filter</title>
8421 <outline text="git RSS feeds">
8424 foreach my $pr (@list) {
8426 my $head = git_get_head_hash
($proj{'path'});
8427 if (!defined $head) {
8430 $git_dir = "$projectroot/$proj{'path'}";
8431 my %co = parse_commit
($head);
8436 my $path = esc_html
(chop_str
($proj{'path'}, 25, 5));
8437 my $rss = href
('project' => $proj{'path'}, 'action' => 'rss', -full
=> 1);
8438 my $html = href
('project' => $proj{'path'}, 'action' => 'summary', -full
=> 1);
8439 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";