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.
413 # Make gitweb consider projects in project root subdirectories
414 # to be forks of existing projects. Given project $projname.git,
415 # projects matching $projname/*.git will not be shown in the main
416 # projects list, instead a '+' mark will be added to $projname
417 # there and a 'forks' view will be enabled for the project, listing
418 # all the forks. If project list is taken from a file, forks have
419 # to be listed after the main project.
421 # To enable system wide have in $GITWEB_CONFIG
422 # $feature{'forks'}{'default'} = [1];
423 # Project specific override is not supported.
428 # Insert custom links to the action bar of all project pages.
429 # This enables you mainly to link to third-party scripts integrating
430 # into gitweb; e.g. git-browser for graphical history representation
431 # or custom web-based repository administration interface.
433 # The 'default' value consists of a list of triplets in the form
434 # (label, link, position) where position is the label after which
435 # to insert the link and link is a format string where %n expands
436 # to the project name, %f to the project path within the filesystem,
437 # %h to the current hash (h gitweb parameter) and %b to the current
438 # hash base (hb gitweb parameter); %% expands to %.
440 # To enable system wide have in $GITWEB_CONFIG e.g.
441 # $feature{'actions'}{'default'} = [('graphiclog',
442 # '/git-browser/by-commit.html?r=%n', 'summary')];
443 # Project specific override is not supported.
448 # Allow gitweb scan project content tags of project repository,
449 # and display the popular Web 2.0-ish "tag cloud" near the projects
450 # list. Note that this is something COMPLETELY different from the
453 # gitweb by itself can show existing tags, but it does not handle
454 # tagging itself; you need to do it externally, outside gitweb.
455 # The format is described in git_get_project_ctags() subroutine.
456 # You may want to install the HTML::TagCloud Perl module to get
457 # a pretty tag cloud instead of just a list of tags.
459 # To enable system wide have in $GITWEB_CONFIG
460 # $feature{'ctags'}{'default'} = [1];
461 # Project specific override is not supported.
463 # A value of 0 means no ctags display or editing. A value of
464 # 1 enables ctags display but never editing. A non-empty value
465 # that is not a string of digits enables ctags display AND the
466 # ability to add tags using a form that uses method POST and
467 # an action value set to the configured 'ctags' value.
472 # The maximum number of patches in a patchset generated in patch
473 # view. Set this to 0 or undef to disable patch view, or to a
474 # negative number to remove any limit.
476 # To disable system wide have in $GITWEB_CONFIG
477 # $feature{'patches'}{'default'} = [0];
478 # To have project specific config enable override in $GITWEB_CONFIG
479 # $feature{'patches'}{'override'} = 1;
480 # and in project config gitweb.patches = 0|n;
481 # where n is the maximum number of patches allowed in a patchset.
483 'sub' => \
&feature_patches
,
487 # Avatar support. When this feature is enabled, views such as
488 # shortlog or commit will display an avatar associated with
489 # the email of the committer(s) and/or author(s).
491 # Currently available providers are gravatar and picon.
492 # If an unknown provider is specified, the feature is disabled.
494 # Gravatar depends on Digest::MD5.
495 # Picon currently relies on the indiana.edu database.
497 # To enable system wide have in $GITWEB_CONFIG
498 # $feature{'avatar'}{'default'} = ['<provider>'];
499 # where <provider> is either gravatar or picon.
500 # To have project specific config enable override in $GITWEB_CONFIG
501 # $feature{'avatar'}{'override'} = 1;
502 # and in project config gitweb.avatar = <provider>;
504 'sub' => \
&feature_avatar
,
508 # Enable displaying how much time and how many git commands
509 # it took to generate and display page. Disabled by default.
510 # Project specific override is not supported.
515 # Enable turning some links into links to actions which require
516 # JavaScript to run (like 'blame_incremental'). Not enabled by
517 # default. Project specific override is currently not supported.
518 'javascript-actions' => {
522 # Enable and configure ability to change common timezone for dates
523 # in gitweb output via JavaScript. Enabled by default.
524 # Project specific override is not supported.
525 'javascript-timezone' => {
528 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
529 # or undef to turn off this feature
530 'gitweb_tz', # name of cookie where to store selected timezone
531 'datetime', # CSS class used to mark up dates for manipulation
534 # Syntax highlighting support. This is based on Daniel Svensson's
535 # and Sham Chukoury's work in gitweb-xmms2.git.
536 # It requires the 'highlight' program present in $PATH,
537 # and therefore is disabled by default.
539 # To enable system wide have in $GITWEB_CONFIG
540 # $feature{'highlight'}{'default'} = [1];
543 'sub' => sub { feature_bool
('highlight', @_) },
547 # Enable displaying of remote heads in the heads list
549 # To enable system wide have in $GITWEB_CONFIG
550 # $feature{'remote_heads'}{'default'} = [1];
551 # To have project specific config enable override in $GITWEB_CONFIG
552 # $feature{'remote_heads'}{'override'} = 1;
553 # and in project config gitweb.remoteheads = 0|1;
555 'sub' => sub { feature_bool
('remote_heads', @_) },
559 # Enable showing branches under other refs in addition to heads
561 # To set system wide extra branch refs have in $GITWEB_CONFIG
562 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
563 # To have project specific config enable override in $GITWEB_CONFIG
564 # $feature{'extra-branch-refs'}{'override'} = 1;
565 # and in project config gitweb.extrabranchrefs = dirs of choice
566 # Every directory is separated with whitespace.
568 'extra-branch-refs' => {
569 'sub' => \
&feature_extra_branch_refs
,
574 sub gitweb_get_feature
{
576 return unless exists $feature{$name};
577 my ($sub, $override, @defaults) = (
578 $feature{$name}{'sub'},
579 $feature{$name}{'override'},
580 @
{$feature{$name}{'default'}});
581 # project specific override is possible only if we have project
582 our $git_dir; # global variable, declared later
583 if (!$override || !defined $git_dir) {
587 warn "feature $name is not overridable";
590 return $sub->(@defaults);
593 # A wrapper to check if a given feature is enabled.
594 # With this, you can say
596 # my $bool_feat = gitweb_check_feature('bool_feat');
597 # gitweb_check_feature('bool_feat') or somecode;
601 # my ($bool_feat) = gitweb_get_feature('bool_feat');
602 # (gitweb_get_feature('bool_feat'))[0] or somecode;
604 sub gitweb_check_feature
{
605 return (gitweb_get_feature
(@_))[0];
611 my ($val) = git_get_project_config
($key, '--bool');
615 } elsif ($val eq 'true') {
617 } elsif ($val eq 'false') {
622 sub feature_snapshot
{
625 my ($val) = git_get_project_config
('snapshot');
628 @fmts = ($val eq 'none' ?
() : split /\s*[,\s]\s*/, $val);
634 sub feature_patches
{
635 my @val = (git_get_project_config
('patches', '--int'));
645 my @val = (git_get_project_config
('avatar'));
647 return @val ?
@val : @_;
650 sub feature_extra_branch_refs
{
651 my (@branch_refs) = @_;
652 my $values = git_get_project_config
('extrabranchrefs');
655 $values = config_to_multi
($values);
657 foreach my $value (@
{$values}) {
658 push @branch_refs, split /\s+/, $value;
665 # checking HEAD file with -e is fragile if the repository was
666 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
668 sub check_head_link
{
670 my $headfile = "$dir/HEAD";
671 return ((-e
$headfile) ||
672 (-l
$headfile && readlink($headfile) =~ /^refs\/heads\
//));
675 sub check_export_ok
{
677 return (check_head_link
($dir) &&
678 (!$export_ok || -e
"$dir/$export_ok") &&
679 (!$export_auth_hook || $export_auth_hook->($dir)));
682 # process alternate names for backward compatibility
683 # filter out unsupported (unknown) snapshot formats
684 sub filter_snapshot_fmts
{
688 exists $known_snapshot_format_aliases{$_} ?
689 $known_snapshot_format_aliases{$_} : $_} @fmts;
691 exists $known_snapshot_formats{$_} &&
692 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
695 sub filter_and_validate_refs
{
697 my %unique_refs = ();
699 foreach my $ref (@refs) {
700 die_error
(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format
($ref));
701 # 'heads' are added implicitly in get_branch_refs().
702 $unique_refs{$ref} = 1 if ($ref ne 'heads');
704 return sort keys %unique_refs;
707 # If it is set to code reference, it is code that it is to be run once per
708 # request, allowing updating configurations that change with each request,
709 # while running other code in config file only once.
711 # Otherwise, if it is false then gitweb would process config file only once;
712 # if it is true then gitweb config would be run for each request.
713 our $per_request_config = 1;
715 # read and parse gitweb config file given by its parameter.
716 # returns true on success, false on recoverable error, allowing
717 # to chain this subroutine, using first file that exists.
718 # dies on errors during parsing config file, as it is unrecoverable.
719 sub read_config_file
{
720 my $filename = shift;
721 return unless defined $filename;
722 # die if there are errors parsing config file
731 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
732 sub evaluate_gitweb_config
{
733 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
734 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
735 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
737 # Protect against duplications of file names, to not read config twice.
738 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
739 # there possibility of duplication of filename there doesn't matter.
740 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
741 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
743 # Common system-wide settings for convenience.
744 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
745 read_config_file
($GITWEB_CONFIG_COMMON);
747 # Use first config file that exists. This means use the per-instance
748 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
749 read_config_file
($GITWEB_CONFIG) and return;
750 read_config_file
($GITWEB_CONFIG_SYSTEM);
753 # Get loadavg of system, to compare against $maxload.
754 # Currently it requires '/proc/loadavg' present to get loadavg;
755 # if it is not present it returns 0, which means no load checking.
757 if( -e
'/proc/loadavg' ){
758 open my $fd, '<', '/proc/loadavg'
760 my @load = split(/\s+/, scalar <$fd>);
763 # The first three columns measure CPU and IO utilization of the last one,
764 # five, and 10 minute periods. The fourth column shows the number of
765 # currently running processes and the total number of processes in the m/n
766 # format. The last column displays the last process ID used.
767 return $load[0] || 0;
769 # additional checks for load average should go here for things that don't export
775 # version of the core git binary
777 sub evaluate_git_version
{
778 our $git_version = qx("$GIT" --version
) =~ m/git version (.*)$/ ?
$1 : "unknown";
779 $number_of_git_cmds++;
783 if (defined $maxload && get_loadavg
() > $maxload) {
784 die_error
(503, "The load average on the server is too high");
788 # ======================================================================
789 # input validation and dispatch
791 # input parameters can be collected from a variety of sources (presently, CGI
792 # and PATH_INFO), so we define an %input_params hash that collects them all
793 # together during validation: this allows subsequent uses (e.g. href()) to be
794 # agnostic of the parameter origin
796 our %input_params = ();
798 # input parameters are stored with the long parameter name as key. This will
799 # also be used in the href subroutine to convert parameters to their CGI
800 # equivalent, and since the href() usage is the most frequent one, we store
801 # the name -> CGI key mapping here, instead of the reverse.
803 # XXX: Warning: If you touch this, check the search form for updating,
806 our @cgi_param_mapping = (
814 hash_parent_base
=> "hpb",
819 snapshot_format
=> "sf",
821 extra_options
=> "opt",
822 search_use_regexp
=> "sr",
825 project_filter
=> "pf",
826 # this must be last entry (for manipulation from JavaScript)
829 our %cgi_param_mapping = @cgi_param_mapping;
831 # we will also need to know the possible actions, for validation
833 "blame" => \
&git_blame
,
834 "blame_incremental" => \
&git_blame_incremental
,
835 "blame_data" => \
&git_blame_data
,
836 "blobdiff" => \
&git_blobdiff
,
837 "blobdiff_plain" => \
&git_blobdiff_plain
,
838 "blob" => \
&git_blob
,
839 "blob_plain" => \
&git_blob_plain
,
840 "commitdiff" => \
&git_commitdiff
,
841 "commitdiff_plain" => \
&git_commitdiff_plain
,
842 "commit" => \
&git_commit
,
843 "forks" => \
&git_forks
,
844 "heads" => \
&git_heads
,
845 "history" => \
&git_history
,
847 "patch" => \
&git_patch
,
848 "patches" => \
&git_patches
,
849 "remotes" => \
&git_remotes
,
851 "atom" => \
&git_atom
,
852 "search" => \
&git_search
,
853 "search_help" => \
&git_search_help
,
854 "shortlog" => \
&git_shortlog
,
855 "summary" => \
&git_summary
,
857 "tags" => \
&git_tags
,
858 "tree" => \
&git_tree
,
859 "snapshot" => \
&git_snapshot
,
860 "object" => \
&git_object
,
861 # those below don't need $project
862 "opml" => \
&git_opml
,
863 "project_list" => \
&git_project_list
,
864 "project_index" => \
&git_project_index
,
867 # finally, we have the hash of allowed extra_options for the commands that
869 our %allowed_options = (
870 "--no-merges" => [ qw(rss atom log shortlog history) ],
873 # fill %input_params with the CGI parameters. All values except for 'opt'
874 # should be single values, but opt can be an array. We should probably
875 # build an array of parameters that can be multi-valued, but since for the time
876 # being it's only this one, we just single it out
877 sub evaluate_query_params
{
880 while (my ($name, $symbol) = each %cgi_param_mapping) {
881 if ($symbol eq 'opt') {
882 $input_params{$name} = [ map { decode_utf8
($_) } $cgi->multi_param($symbol) ];
884 $input_params{$name} = decode_utf8
($cgi->param($symbol));
888 # Backwards compatibility - by_tag= <=> t=
889 if ($input_params{'ctag'}) {
890 $input_params{'ctag_filter'} = $input_params{'ctag'};
894 # now read PATH_INFO and update the parameter list for missing parameters
895 sub evaluate_path_info
{
896 return if defined $input_params{'project'};
897 return if !$path_info;
898 $path_info =~ s
,^/+,,;
899 return if !$path_info;
901 # find which part of PATH_INFO is project
902 my $project = $path_info;
904 while ($project && !check_head_link
("$projectroot/$project")) {
905 $project =~ s
,/*[^/]*$,,;
907 return unless $project;
908 $input_params{'project'} = $project;
910 # do not change any parameters if an action is given using the query string
911 return if $input_params{'action'};
912 $path_info =~ s
,^\Q
$project\E
/*,,;
914 # next, check if we have an action
915 my $action = $path_info;
917 if (exists $actions{$action}) {
918 $path_info =~ s
,^$action/*,,;
919 $input_params{'action'} = $action;
922 # list of actions that want hash_base instead of hash, but can have no
923 # pathname (f) parameter
929 # we want to catch, among others
930 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
931 my ($parentrefname, $parentpathname, $refname, $pathname) =
932 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
934 # first, analyze the 'current' part
935 if (defined $pathname) {
936 # we got "branch:filename" or "branch:dir/"
937 # we could use git_get_type(branch:pathname), but:
938 # - it needs $git_dir
939 # - it does a git() call
940 # - the convention of terminating directories with a slash
941 # makes it superfluous
942 # - embedding the action in the PATH_INFO would make it even
944 $pathname =~ s
,^/+,,;
945 if (!$pathname || substr($pathname, -1) eq "/") {
946 $input_params{'action'} ||= "tree";
949 # the default action depends on whether we had parent info
951 if ($parentrefname) {
952 $input_params{'action'} ||= "blobdiff_plain";
954 $input_params{'action'} ||= "blob_plain";
957 $input_params{'hash_base'} ||= $refname;
958 $input_params{'file_name'} ||= $pathname;
959 } elsif (defined $refname) {
960 # we got "branch". In this case we have to choose if we have to
961 # set hash or hash_base.
963 # Most of the actions without a pathname only want hash to be
964 # set, except for the ones specified in @wants_base that want
965 # hash_base instead. It should also be noted that hand-crafted
966 # links having 'history' as an action and no pathname or hash
967 # set will fail, but that happens regardless of PATH_INFO.
968 if (defined $parentrefname) {
969 # if there is parent let the default be 'shortlog' action
970 # (for http://git.example.com/repo.git/A..B links); if there
971 # is no parent, dispatch will detect type of object and set
972 # action appropriately if required (if action is not set)
973 $input_params{'action'} ||= "shortlog";
975 if ($input_params{'action'} &&
976 grep { $_ eq $input_params{'action'} } @wants_base) {
977 $input_params{'hash_base'} ||= $refname;
979 $input_params{'hash'} ||= $refname;
983 # next, handle the 'parent' part, if present
984 if (defined $parentrefname) {
985 # a missing pathspec defaults to the 'current' filename, allowing e.g.
986 # someproject/blobdiff/oldrev..newrev:/filename
987 if ($parentpathname) {
988 $parentpathname =~ s
,^/+,,;
989 $parentpathname =~ s
,/$,,;
990 $input_params{'file_parent'} ||= $parentpathname;
992 $input_params{'file_parent'} ||= $input_params{'file_name'};
994 # we assume that hash_parent_base is wanted if a path was specified,
995 # or if the action wants hash_base instead of hash
996 if (defined $input_params{'file_parent'} ||
997 grep { $_ eq $input_params{'action'} } @wants_base) {
998 $input_params{'hash_parent_base'} ||= $parentrefname;
1000 $input_params{'hash_parent'} ||= $parentrefname;
1004 # for the snapshot action, we allow URLs in the form
1005 # $project/snapshot/$hash.ext
1006 # where .ext determines the snapshot and gets removed from the
1007 # passed $refname to provide the $hash.
1009 # To be able to tell that $refname includes the format extension, we
1010 # require the following two conditions to be satisfied:
1011 # - the hash input parameter MUST have been set from the $refname part
1012 # of the URL (i.e. they must be equal)
1013 # - the snapshot format MUST NOT have been defined already (e.g. from
1015 # It's also useless to try any matching unless $refname has a dot,
1016 # so we check for that too
1017 if (defined $input_params{'action'} &&
1018 $input_params{'action'} eq 'snapshot' &&
1019 defined $refname && index($refname, '.') != -1 &&
1020 $refname eq $input_params{'hash'} &&
1021 !defined $input_params{'snapshot_format'}) {
1022 # We loop over the known snapshot formats, checking for
1023 # extensions. Allowed extensions are both the defined suffix
1024 # (which includes the initial dot already) and the snapshot
1025 # format key itself, with a prepended dot
1026 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1027 my $hash = $refname;
1028 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1032 # a valid suffix was found, so set the snapshot format
1033 # and reset the hash parameter
1034 $input_params{'snapshot_format'} = $fmt;
1035 $input_params{'hash'} = $hash;
1036 # we also set the format suffix to the one requested
1037 # in the URL: this way a request for e.g. .tgz returns
1038 # a .tgz instead of a .tar.gz
1039 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1045 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1046 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1047 $searchtext, $search_regexp, $project_filter);
1048 sub evaluate_and_validate_params
{
1049 our $action = $input_params{'action'};
1050 if (defined $action) {
1051 if (!is_valid_action
($action)) {
1052 die_error
(400, "Invalid action parameter");
1056 # parameters which are pathnames
1057 our $project = $input_params{'project'};
1058 if (defined $project) {
1059 if (!is_valid_project
($project)) {
1061 die_error
(404, "No such project");
1065 our $project_filter = $input_params{'project_filter'};
1066 if (defined $project_filter) {
1067 if (!is_valid_pathname
($project_filter)) {
1068 die_error
(404, "Invalid project_filter parameter");
1072 our $file_name = $input_params{'file_name'};
1073 if (defined $file_name) {
1074 if (!is_valid_pathname
($file_name)) {
1075 die_error
(400, "Invalid file parameter");
1079 our $file_parent = $input_params{'file_parent'};
1080 if (defined $file_parent) {
1081 if (!is_valid_pathname
($file_parent)) {
1082 die_error
(400, "Invalid file parent parameter");
1086 # parameters which are refnames
1087 our $hash = $input_params{'hash'};
1088 if (defined $hash) {
1089 if (!is_valid_refname
($hash)) {
1090 die_error
(400, "Invalid hash parameter");
1094 our $hash_parent = $input_params{'hash_parent'};
1095 if (defined $hash_parent) {
1096 if (!is_valid_refname
($hash_parent)) {
1097 die_error
(400, "Invalid hash parent parameter");
1101 our $hash_base = $input_params{'hash_base'};
1102 if (defined $hash_base) {
1103 if (!is_valid_refname
($hash_base)) {
1104 die_error
(400, "Invalid hash base parameter");
1108 our @extra_options = @
{$input_params{'extra_options'}};
1109 # @extra_options is always defined, since it can only be (currently) set from
1110 # CGI, and $cgi->param() returns the empty array in array context if the param
1112 foreach my $opt (@extra_options) {
1113 if (not exists $allowed_options{$opt}) {
1114 die_error
(400, "Invalid option parameter");
1116 if (not grep(/^$action$/, @
{$allowed_options{$opt}})) {
1117 die_error
(400, "Invalid option parameter for this action");
1121 our $hash_parent_base = $input_params{'hash_parent_base'};
1122 if (defined $hash_parent_base) {
1123 if (!is_valid_refname
($hash_parent_base)) {
1124 die_error
(400, "Invalid hash parent base parameter");
1129 our $page = $input_params{'page'};
1130 if (defined $page) {
1131 if ($page =~ m/[^0-9]/) {
1132 die_error
(400, "Invalid page parameter");
1136 our $searchtype = $input_params{'searchtype'};
1137 if (defined $searchtype) {
1138 if ($searchtype =~ m/[^a-z]/) {
1139 die_error
(400, "Invalid searchtype parameter");
1143 our $search_use_regexp = $input_params{'search_use_regexp'};
1145 our $searchtext = $input_params{'searchtext'};
1146 our $search_regexp = undef;
1147 if (defined $searchtext) {
1148 if (length($searchtext) < 2) {
1149 die_error
(403, "At least two characters are required for search parameter");
1151 if ($search_use_regexp) {
1152 $search_regexp = $searchtext;
1153 if (!eval { qr/$search_regexp/; 1; }) {
1154 (my $error = $@
) =~ s/ at \S+ line \d+.*\n?//;
1155 die_error
(400, "Invalid search regexp '$search_regexp'",
1159 $search_regexp = quotemeta $searchtext;
1164 # path to the current git repository
1166 sub evaluate_git_dir
{
1167 our $git_dir = "$projectroot/$project" if $project;
1170 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1171 sub configure_gitweb_features
{
1172 # list of supported snapshot formats
1173 our @snapshot_fmts = gitweb_get_feature
('snapshot');
1174 @snapshot_fmts = filter_snapshot_fmts
(@snapshot_fmts);
1176 # check that the avatar feature is set to a known provider name,
1177 # and for each provider check if the dependencies are satisfied.
1178 # if the provider name is invalid or the dependencies are not met,
1179 # reset $git_avatar to the empty string.
1180 our ($git_avatar) = gitweb_get_feature
('avatar');
1181 if ($git_avatar eq 'gravatar') {
1182 $git_avatar = '' unless (eval { require Digest
::MD5
; 1; });
1183 } elsif ($git_avatar eq 'picon') {
1189 our @extra_branch_refs = gitweb_get_feature
('extra-branch-refs');
1190 @extra_branch_refs = filter_and_validate_refs
(@extra_branch_refs);
1193 sub get_branch_refs
{
1194 return ('heads', @extra_branch_refs);
1197 # custom error handler: 'die <message>' is Internal Server Error
1198 sub handle_errors_html
{
1199 my $msg = shift; # it is already HTML escaped
1201 # to avoid infinite loop where error occurs in die_error,
1202 # change handler to default handler, disabling handle_errors_html
1203 set_message
("Error occurred when inside die_error:\n$msg");
1205 # you cannot jump out of die_error when called as error handler;
1206 # the subroutine set via CGI::Carp::set_message is called _after_
1207 # HTTP headers are already written, so it cannot write them itself
1208 die_error
(undef, undef, $msg, -error_handler
=> 1, -no_http_header
=> 1);
1210 set_message
(\
&handle_errors_html
);
1214 if (!defined $action) {
1215 if (defined $hash) {
1216 $action = git_get_type
($hash);
1217 $action or die_error
(404, "Object does not exist");
1218 } elsif (defined $hash_base && defined $file_name) {
1219 $action = git_get_type
("$hash_base:$file_name");
1220 $action or die_error
(404, "File or directory does not exist");
1221 } elsif (defined $project) {
1222 $action = 'summary';
1224 $action = 'project_list';
1227 if (!defined($actions{$action})) {
1228 die_error
(400, "Unknown action");
1230 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1232 die_error
(400, "Project needed");
1234 $actions{$action}->();
1238 our $t0 = [ gettimeofday
() ]
1240 our $number_of_git_cmds = 0;
1243 our $first_request = 1;
1248 if ($first_request) {
1249 evaluate_gitweb_config
();
1250 evaluate_git_version
();
1252 if ($per_request_config) {
1253 if (ref($per_request_config) eq 'CODE') {
1254 $per_request_config->();
1255 } elsif (!$first_request) {
1256 evaluate_gitweb_config
();
1261 # $projectroot and $projects_list might be set in gitweb config file
1262 $projects_list ||= $projectroot;
1264 evaluate_query_params
();
1265 evaluate_path_info
();
1266 evaluate_and_validate_params
();
1269 configure_gitweb_features
();
1274 our $is_last_request = sub { 1 };
1275 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1278 sub configure_as_fcgi
{
1280 our $CGI = 'CGI::Fast';
1282 my $request_number = 0;
1283 # let each child service 100 requests
1284 our $is_last_request = sub { ++$request_number > 100 };
1287 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__
;
1289 if $script_name =~ /\.fcgi$/;
1291 return unless (@ARGV);
1293 require Getopt
::Long
;
1294 Getopt
::Long
::GetOptions
(
1295 'fastcgi|fcgi|f' => \
&configure_as_fcgi
,
1296 'nproc|n=i' => sub {
1297 my ($arg, $val) = @_;
1298 return unless eval { require FCGI
::ProcManager
; 1; };
1299 my $proc_manager = FCGI
::ProcManager
->new({
1300 n_processes
=> $val,
1302 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1303 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1304 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1313 $pre_listen_hook->()
1314 if $pre_listen_hook;
1317 while ($cgi = $CGI->new()) {
1318 $pre_dispatch_hook->()
1319 if $pre_dispatch_hook;
1323 $post_dispatch_hook->()
1324 if $post_dispatch_hook;
1327 last REQUEST
if ($is_last_request->());
1336 if (defined caller) {
1337 # wrapped in a subroutine processing requests,
1338 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1341 # pure CGI script, serving single request
1345 ## ======================================================================
1348 # possible values of extra options
1349 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1350 # -replay => 1 - start from a current view (replay with modifications)
1351 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1352 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1355 # default is to use -absolute url() i.e. $my_uri
1356 my $href = $params{-full
} ?
$my_url : $my_uri;
1358 # implicit -replay, must be first of implicit params
1359 $params{-replay
} = 1 if (keys %params == 1 && $params{-anchor
});
1361 $params{'project'} = $project unless exists $params{'project'};
1363 if ($params{-replay
}) {
1364 while (my ($name, $symbol) = each %cgi_param_mapping) {
1365 if (!exists $params{$name}) {
1366 $params{$name} = $input_params{$name};
1371 my $use_pathinfo = gitweb_check_feature
('pathinfo');
1372 if (defined $params{'project'} &&
1373 (exists $params{-path_info
} ?
$params{-path_info
} : $use_pathinfo)) {
1374 # try to put as many parameters as possible in PATH_INFO:
1377 # - hash_parent or hash_parent_base:/file_parent
1378 # - hash or hash_base:/filename
1379 # - the snapshot_format as an appropriate suffix
1381 # When the script is the root DirectoryIndex for the domain,
1382 # $href here would be something like http://gitweb.example.com/
1383 # Thus, we strip any trailing / from $href, to spare us double
1384 # slashes in the final URL
1387 # Then add the project name, if present
1388 $href .= "/".esc_path_info
($params{'project'});
1389 delete $params{'project'};
1391 # since we destructively absorb parameters, we keep this
1392 # boolean that remembers if we're handling a snapshot
1393 my $is_snapshot = $params{'action'} eq 'snapshot';
1395 # Summary just uses the project path URL, any other action is
1397 if (defined $params{'action'}) {
1398 $href .= "/".esc_path_info
($params{'action'})
1399 unless $params{'action'} eq 'summary';
1400 delete $params{'action'};
1403 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1404 # stripping nonexistent or useless pieces
1405 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1406 || $params{'hash_parent'} || $params{'hash'});
1407 if (defined $params{'hash_base'}) {
1408 if (defined $params{'hash_parent_base'}) {
1409 $href .= esc_path_info
($params{'hash_parent_base'});
1410 # skip the file_parent if it's the same as the file_name
1411 if (defined $params{'file_parent'}) {
1412 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1413 delete $params{'file_parent'};
1414 } elsif ($params{'file_parent'} !~ /\.\./) {
1415 $href .= ":/".esc_path_info
($params{'file_parent'});
1416 delete $params{'file_parent'};
1420 delete $params{'hash_parent'};
1421 delete $params{'hash_parent_base'};
1422 } elsif (defined $params{'hash_parent'}) {
1423 $href .= esc_path_info
($params{'hash_parent'}). "..";
1424 delete $params{'hash_parent'};
1427 $href .= esc_path_info
($params{'hash_base'});
1428 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1429 $href .= ":/".esc_path_info
($params{'file_name'});
1430 delete $params{'file_name'};
1432 delete $params{'hash'};
1433 delete $params{'hash_base'};
1434 } elsif (defined $params{'hash'}) {
1435 $href .= esc_path_info
($params{'hash'});
1436 delete $params{'hash'};
1439 # If the action was a snapshot, we can absorb the
1440 # snapshot_format parameter too
1442 my $fmt = $params{'snapshot_format'};
1443 # snapshot_format should always be defined when href()
1444 # is called, but just in case some code forgets, we
1445 # fall back to the default
1446 $fmt ||= $snapshot_fmts[0];
1447 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1448 delete $params{'snapshot_format'};
1452 # now encode the parameters explicitly
1454 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1455 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1456 if (defined $params{$name}) {
1457 if (ref($params{$name}) eq "ARRAY") {
1458 foreach my $par (@
{$params{$name}}) {
1459 push @result, $symbol . "=" . esc_param
($par);
1462 push @result, $symbol . "=" . esc_param
($params{$name});
1466 $href .= "?" . join(';', @result) if scalar @result;
1468 # final transformation: trailing spaces must be escaped (URI-encoded)
1469 $href =~ s/(\s+)$/CGI::escape($1)/e;
1471 if ($params{-anchor
}) {
1472 $href .= "#".esc_param
($params{-anchor
});
1479 ## ======================================================================
1480 ## validation, quoting/unquoting and escaping
1482 sub is_valid_action
{
1484 return undef unless exists $actions{$input};
1488 sub is_valid_project
{
1491 return unless defined $input;
1492 if (!is_valid_pathname
($input) ||
1493 !(-d
"$projectroot/$input") ||
1494 !check_export_ok
("$projectroot/$input") ||
1495 ($strict_export && !project_in_list
($input))) {
1502 sub is_valid_pathname
{
1505 return undef unless defined $input;
1506 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1507 # at the beginning, at the end, and between slashes.
1508 # also this catches doubled slashes
1509 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1512 # no null characters
1513 if ($input =~ m!\0!) {
1519 sub is_valid_ref_format
{
1522 return undef unless defined $input;
1523 # restrictions on ref name according to git-check-ref-format
1524 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1530 sub is_valid_refname
{
1533 return undef unless defined $input;
1534 # textual hashes are O.K.
1535 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1538 # it must be correct pathname
1539 is_valid_pathname
($input) or return undef;
1540 # check git-check-ref-format restrictions
1541 is_valid_ref_format
($input) or return undef;
1545 # decode sequences of octets in utf8 into Perl's internal form,
1546 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1547 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1550 return undef unless defined $str;
1552 if (utf8
::is_utf8
($str) || utf8
::decode
($str)) {
1555 return decode
($fallback_encoding, $str, Encode
::FB_DEFAULT
);
1559 # quote unsafe chars, but keep the slash, even when it's not
1560 # correct, but quoted slashes look too horrible in bookmarks
1563 return undef unless defined $str;
1564 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI
::escape
($1)/eg
;
1569 # the quoting rules for path_info fragment are slightly different
1572 return undef unless defined $str;
1574 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1575 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI
::escape
($1)/eg
;
1580 # quote unsafe chars in whole URL, so some characters cannot be quoted
1583 return undef unless defined $str;
1584 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI
::escape
($1)/eg
;
1589 # quote unsafe characters in HTML attributes
1592 # for XHTML conformance escaping '"' to '"' is not enough
1593 return esc_html
(@_);
1596 # replace invalid utf8 character with SUBSTITUTION sequence
1601 return undef unless defined $str;
1603 $str = to_utf8
($str);
1604 $str = $cgi->escapeHTML($str);
1605 if ($opts{'-nbsp'}) {
1606 $str =~ s/ / /g;
1608 $str =~ s
|([[:cntrl
:]])|(($1 ne "\t") ? quot_cec
($1) : $1)|eg
;
1612 # quote control characters and escape filename to HTML
1617 return undef unless defined $str;
1619 $str = to_utf8
($str);
1620 $str = $cgi->escapeHTML($str);
1621 if ($opts{'-nbsp'}) {
1622 $str =~ s/ / /g;
1624 $str =~ s
|([[:cntrl
:]])|quot_cec
($1)|eg
;
1628 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1632 return undef unless defined $str;
1634 $str = to_utf8
($str);
1635 $str =~ s
|([[:cntrl
:]])|(index("\t\n\r", $1) != -1 ?
$1 : quot_cec
($1))|eg
;
1639 # Make control characters "printable", using character escape codes (CEC)
1643 my %es = ( # character escape codes, aka escape sequences
1644 "\t" => '\t', # tab (HT)
1645 "\n" => '\n', # line feed (LF)
1646 "\r" => '\r', # carrige return (CR)
1647 "\f" => '\f', # form feed (FF)
1648 "\b" => '\b', # backspace (BS)
1649 "\a" => '\a', # alarm (bell) (BEL)
1650 "\e" => '\e', # escape (ESC)
1651 "\013" => '\v', # vertical tab (VT)
1652 "\000" => '\0', # nul character (NUL)
1654 my $chr = ( (exists $es{$cntrl})
1656 : sprintf('\%2x', ord($cntrl)) );
1657 if ($opts{-nohtml
}) {
1660 return "<span class=\"cntrl\">$chr</span>";
1664 # Alternatively use unicode control pictures codepoints,
1665 # Unicode "printable representation" (PR)
1670 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1671 if ($opts{-nohtml
}) {
1674 return "<span class=\"cntrl\">$chr</span>";
1678 # git may return quoted and escaped filenames
1684 my %es = ( # character escape codes, aka escape sequences
1685 't' => "\t", # tab (HT, TAB)
1686 'n' => "\n", # newline (NL)
1687 'r' => "\r", # return (CR)
1688 'f' => "\f", # form feed (FF)
1689 'b' => "\b", # backspace (BS)
1690 'a' => "\a", # alarm (bell) (BEL)
1691 'e' => "\e", # escape (ESC)
1692 'v' => "\013", # vertical tab (VT)
1695 if ($seq =~ m/^[0-7]{1,3}$/) {
1696 # octal char sequence
1697 return chr(oct($seq));
1698 } elsif (exists $es{$seq}) {
1699 # C escape sequence, aka character escape code
1702 # quoted ordinary character
1706 if ($str =~ m/^"(.*)"$/) {
1709 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1714 # escape tabs (convert tabs to spaces)
1718 while ((my $pos = index($line, "\t")) != -1) {
1719 if (my $count = (8 - ($pos % 8))) {
1720 my $spaces = ' ' x
$count;
1721 $line =~ s/\t/$spaces/;
1728 sub project_in_list
{
1729 my $project = shift;
1730 my @list = git_get_projects_list
();
1731 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1734 ## ----------------------------------------------------------------------
1735 ## HTML aware string manipulation
1737 # Try to chop given string on a word boundary between position
1738 # $len and $len+$add_len. If there is no word boundary there,
1739 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1740 # (marking chopped part) would be longer than given string.
1744 my $add_len = shift || 10;
1745 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1747 # Make sure perl knows it is utf8 encoded so we don't
1748 # cut in the middle of a utf8 multibyte char.
1749 $str = to_utf8
($str);
1751 # allow only $len chars, but don't cut a word if it would fit in $add_len
1752 # if it doesn't fit, cut it if it's still longer than the dots we would add
1753 # remove chopped character entities entirely
1755 # when chopping in the middle, distribute $len into left and right part
1756 # return early if chopping wouldn't make string shorter
1757 if ($where eq 'center') {
1758 return $str if ($len + 5 >= length($str)); # filler is length 5
1761 return $str if ($len + 4 >= length($str)); # filler is length 4
1764 # regexps: ending and beginning with word part up to $add_len
1765 my $endre = qr/.{$len}\w{0,$add_len}/;
1766 my $begre = qr/\w{0,$add_len}.{$len}/;
1768 if ($where eq 'left') {
1769 $str =~ m/^(.*?)($begre)$/;
1770 my ($lead, $body) = ($1, $2);
1771 if (length($lead) > 4) {
1774 return "$lead$body";
1776 } elsif ($where eq 'center') {
1777 $str =~ m/^($endre)(.*)$/;
1778 my ($left, $str) = ($1, $2);
1779 $str =~ m/^(.*?)($begre)$/;
1780 my ($mid, $right) = ($1, $2);
1781 if (length($mid) > 5) {
1784 return "$left$mid$right";
1787 $str =~ m/^($endre)(.*)$/;
1790 if (length($tail) > 4) {
1793 return "$body$tail";
1797 # takes the same arguments as chop_str, but also wraps a <span> around the
1798 # result with a title attribute if it does get chopped. Additionally, the
1799 # string is HTML-escaped.
1800 sub chop_and_escape_str
{
1803 my $chopped = chop_str
(@_);
1804 $str = to_utf8
($str);
1805 if ($chopped eq $str) {
1806 return esc_html
($chopped);
1808 $str =~ s/[[:cntrl:]]/?/g;
1809 return $cgi->span({-title
=>$str}, esc_html
($chopped));
1813 # Highlight selected fragments of string, using given CSS class,
1814 # and escape HTML. It is assumed that fragments do not overlap.
1815 # Regions are passed as list of pairs (array references).
1817 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1818 # '<span class="mark">foo</span>bar'
1819 sub esc_html_hl_regions
{
1820 my ($str, $css_class, @sel) = @_;
1821 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1822 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1823 return esc_html
($str, %opts) unless @sel;
1829 my ($begin, $end) = @
$s;
1831 # Don't create empty <span> elements.
1832 next if $end <= $begin;
1834 my $escaped = esc_html
(substr($str, $begin, $end - $begin),
1837 $out .= esc_html
(substr($str, $pos, $begin - $pos), %opts)
1838 if ($begin - $pos > 0);
1839 $out .= $cgi->span({-class => $css_class}, $escaped);
1843 $out .= esc_html
(substr($str, $pos), %opts)
1844 if ($pos < length($str));
1849 # return positions of beginning and end of each match
1851 my ($str, $regexp) = @_;
1852 return unless (defined $str && defined $regexp);
1855 while ($str =~ /$regexp/g) {
1856 push @matches, [$-[0], $+[0]];
1861 # highlight match (if any), and escape HTML
1862 sub esc_html_match_hl
{
1863 my ($str, $regexp) = @_;
1864 return esc_html
($str) unless defined $regexp;
1866 my @matches = matchpos_list
($str, $regexp);
1867 return esc_html
($str) unless @matches;
1869 return esc_html_hl_regions
($str, 'match', @matches);
1873 # highlight match (if any) of shortened string, and escape HTML
1874 sub esc_html_match_hl_chopped
{
1875 my ($str, $chopped, $regexp) = @_;
1876 return esc_html_match_hl
($str, $regexp) unless defined $chopped;
1878 my @matches = matchpos_list
($str, $regexp);
1879 return esc_html
($chopped) unless @matches;
1881 # filter matches so that we mark chopped string
1882 my $tail = "... "; # see chop_str
1883 unless ($chopped =~ s/\Q$tail\E$//) {
1886 my $chop_len = length($chopped);
1887 my $tail_len = length($tail);
1890 for my $m (@matches) {
1891 if ($m->[0] > $chop_len) {
1892 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1894 } elsif ($m->[1] > $chop_len) {
1895 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1901 return esc_html_hl_regions
($chopped . $tail, 'match', @filtered);
1904 ## ----------------------------------------------------------------------
1905 ## functions returning short strings
1907 # CSS class for given age value (in seconds)
1911 if (!defined $age) {
1913 } elsif ($age < 60*60*2) {
1915 } elsif ($age < 60*60*24*2) {
1922 # convert age in seconds to "nn units ago" string
1927 if ($age > 60*60*24*365*2) {
1928 $age_str = (int $age/60/60/24/365);
1929 $age_str .= " years ago";
1930 } elsif ($age > 60*60*24*(365/12)*2) {
1931 $age_str = int $age/60/60/24/(365/12);
1932 $age_str .= " months ago";
1933 } elsif ($age > 60*60*24*7*2) {
1934 $age_str = int $age/60/60/24/7;
1935 $age_str .= " weeks ago";
1936 } elsif ($age > 60*60*24*2) {
1937 $age_str = int $age/60/60/24;
1938 $age_str .= " days ago";
1939 } elsif ($age > 60*60*2) {
1940 $age_str = int $age/60/60;
1941 $age_str .= " hours ago";
1942 } elsif ($age > 60*2) {
1943 $age_str = int $age/60;
1944 $age_str .= " min ago";
1945 } elsif ($age > 2) {
1946 $age_str = int $age;
1947 $age_str .= " sec ago";
1949 $age_str .= " right now";
1955 S_IFINVALID
=> 0030000,
1956 S_IFGITLINK
=> 0160000,
1959 # submodule/subproject, a commit object reference
1963 return (($mode & S_IFMT
) == S_IFGITLINK
)
1966 # convert file mode in octal to symbolic file mode string
1968 my $mode = oct shift;
1970 if (S_ISGITLINK
($mode)) {
1971 return 'm---------';
1972 } elsif (S_ISDIR
($mode & S_IFMT
)) {
1973 return 'drwxr-xr-x';
1974 } elsif (S_ISLNK
($mode)) {
1975 return 'lrwxrwxrwx';
1976 } elsif (S_ISREG
($mode)) {
1977 # git cares only about the executable bit
1978 if ($mode & S_IXUSR
) {
1979 return '-rwxr-xr-x';
1981 return '-rw-r--r--';
1984 return '----------';
1988 # convert file mode in octal to file type string
1992 if ($mode !~ m/^[0-7]+$/) {
1998 if (S_ISGITLINK
($mode)) {
2000 } elsif (S_ISDIR
($mode & S_IFMT
)) {
2002 } elsif (S_ISLNK
($mode)) {
2004 } elsif (S_ISREG
($mode)) {
2011 # convert file mode in octal to file type description string
2012 sub file_type_long
{
2015 if ($mode !~ m/^[0-7]+$/) {
2021 if (S_ISGITLINK
($mode)) {
2023 } elsif (S_ISDIR
($mode & S_IFMT
)) {
2025 } elsif (S_ISLNK
($mode)) {
2027 } elsif (S_ISREG
($mode)) {
2028 if ($mode & S_IXUSR
) {
2029 return "executable";
2039 ## ----------------------------------------------------------------------
2040 ## functions returning short HTML fragments, or transforming HTML fragments
2041 ## which don't belong to other sections
2043 # format line of commit message.
2044 sub format_log_line_html
{
2047 $line = esc_html
($line, -nbsp
=>1);
2048 $line =~ s
{\b([0-9a
-fA
-F
]{8,40})\b}{
2049 $cgi->a({-href
=> href
(action
=>"object", hash
=>$1),
2050 -class => "text"}, $1);
2056 # format marker of refs pointing to given object
2058 # the destination action is chosen based on object type and current context:
2059 # - for annotated tags, we choose the tag view unless it's the current view
2060 # already, in which case we go to shortlog view
2061 # - for other refs, we keep the current view if we're in history, shortlog or
2062 # log view, and select shortlog otherwise
2063 sub format_ref_marker
{
2064 my ($refs, $id) = @_;
2067 if (defined $refs->{$id}) {
2068 foreach my $ref (@
{$refs->{$id}}) {
2069 # this code exploits the fact that non-lightweight tags are the
2070 # only indirect objects, and that they are the only objects for which
2071 # we want to use tag instead of shortlog as action
2072 my ($type, $name) = qw();
2073 my $indirect = ($ref =~ s/\^\{\}$//);
2074 # e.g. tags/v2.6.11 or heads/next
2075 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2084 $class .= " indirect" if $indirect;
2086 my $dest_action = "shortlog";
2089 $dest_action = "tag" unless $action eq "tag";
2090 } elsif ($action =~ /^(history|(short)?log)$/) {
2091 $dest_action = $action;
2095 $dest .= "refs/" unless $ref =~ m
!^refs
/!;
2098 my $link = $cgi->a({
2100 action
=>$dest_action,
2104 $markers .= " <span class=\"".esc_attr
($class)."\" title=\"".esc_attr
($ref)."\">" .
2110 return ' <span class="refs">'. $markers . '</span>';
2116 # format, perhaps shortened and with markers, title line
2117 sub format_subject_html
{
2118 my ($long, $short, $href, $extra) = @_;
2119 $extra = '' unless defined($extra);
2121 if (length($short) < length($long)) {
2122 $long =~ s/[[:cntrl:]]/?/g;
2123 return $cgi->a({-href
=> $href, -class => "list subject",
2124 -title
=> to_utf8
($long)},
2125 esc_html
($short)) . $extra;
2127 return $cgi->a({-href
=> $href, -class => "list subject"},
2128 esc_html
($long)) . $extra;
2132 # Rather than recomputing the url for an email multiple times, we cache it
2133 # after the first hit. This gives a visible benefit in views where the avatar
2134 # for the same email is used repeatedly (e.g. shortlog).
2135 # The cache is shared by all avatar engines (currently gravatar only), which
2136 # are free to use it as preferred. Since only one avatar engine is used for any
2137 # given page, there's no risk for cache conflicts.
2138 our %avatar_cache = ();
2140 # Compute the picon url for a given email, by using the picon search service over at
2141 # http://www.cs.indiana.edu/picons/search.html
2143 my $email = lc shift;
2144 if (!$avatar_cache{$email}) {
2145 my ($user, $domain) = split('@', $email);
2146 $avatar_cache{$email} =
2147 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2149 "users+domains+unknown/up/single";
2151 return $avatar_cache{$email};
2154 # Compute the gravatar url for a given email, if it's not in the cache already.
2155 # Gravatar stores only the part of the URL before the size, since that's the
2156 # one computationally more expensive. This also allows reuse of the cache for
2157 # different sizes (for this particular engine).
2159 my $email = lc shift;
2161 $avatar_cache{$email} ||=
2162 "//www.gravatar.com/avatar/" .
2163 Digest
::MD5
::md5_hex
($email) . "?s=";
2164 return $avatar_cache{$email} . $size;
2167 # Insert an avatar for the given $email at the given $size if the feature
2169 sub git_get_avatar
{
2170 my ($email, %opts) = @_;
2171 my $pre_white = ($opts{-pad_before
} ?
" " : "");
2172 my $post_white = ($opts{-pad_after
} ?
" " : "");
2173 $opts{-size
} ||= 'default';
2174 my $size = $avatar_size{$opts{-size
}} || $avatar_size{'default'};
2176 if ($git_avatar eq 'gravatar') {
2177 $url = gravatar_url
($email, $size);
2178 } elsif ($git_avatar eq 'picon') {
2179 $url = picon_url
($email);
2181 # Other providers can be added by extending the if chain, defining $url
2182 # as needed. If no variant puts something in $url, we assume avatars
2183 # are completely disabled/unavailable.
2186 "<img width=\"$size\" " .
2187 "class=\"avatar\" " .
2188 "src=\"".esc_url
($url)."\" " .
2196 sub format_search_author
{
2197 my ($author, $searchtype, $displaytext) = @_;
2198 my $have_search = gitweb_check_feature
('search');
2202 if ($searchtype eq 'author') {
2203 $performed = "authored";
2204 } elsif ($searchtype eq 'committer') {
2205 $performed = "committed";
2208 return $cgi->a({-href
=> href
(action
=>"search", hash
=>$hash,
2209 searchtext
=>$author,
2210 searchtype
=>$searchtype), class=>"list",
2211 title
=>"Search for commits $performed by $author"},
2215 return $displaytext;
2219 # format the author name of the given commit with the given tag
2220 # the author name is chopped and escaped according to the other
2221 # optional parameters (see chop_str).
2222 sub format_author_html
{
2225 my $author = chop_and_escape_str
($co->{'author_name'}, @_);
2226 return "<$tag class=\"author\">" .
2227 format_search_author
($co->{'author_name'}, "author",
2228 git_get_avatar
($co->{'author_email'}, -pad_after
=> 1) .
2233 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2234 sub format_git_diff_header_line
{
2236 my $diffinfo = shift;
2237 my ($from, $to) = @_;
2239 if ($diffinfo->{'nparents'}) {
2241 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2242 if ($to->{'href'}) {
2243 $line .= $cgi->a({-href
=> $to->{'href'}, -class => "path"},
2244 esc_path
($to->{'file'}));
2245 } else { # file was deleted (no href)
2246 $line .= esc_path
($to->{'file'});
2250 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2251 if ($from->{'href'}) {
2252 $line .= $cgi->a({-href
=> $from->{'href'}, -class => "path"},
2253 'a/' . esc_path
($from->{'file'}));
2254 } else { # file was added (no href)
2255 $line .= 'a/' . esc_path
($from->{'file'});
2258 if ($to->{'href'}) {
2259 $line .= $cgi->a({-href
=> $to->{'href'}, -class => "path"},
2260 'b/' . esc_path
($to->{'file'}));
2261 } else { # file was deleted
2262 $line .= 'b/' . esc_path
($to->{'file'});
2266 return "<div class=\"diff header\">$line</div>\n";
2269 # format extended diff header line, before patch itself
2270 sub format_extended_diff_header_line
{
2272 my $diffinfo = shift;
2273 my ($from, $to) = @_;
2276 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2277 $line .= $cgi->a({-href
=>$from->{'href'}, -class=>"path"},
2278 esc_path
($from->{'file'}));
2280 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2281 $line .= $cgi->a({-href
=>$to->{'href'}, -class=>"path"},
2282 esc_path
($to->{'file'}));
2284 # match single <mode>
2285 if ($line =~ m/\s(\d{6})$/) {
2286 $line .= '<span class="info"> (' .
2287 file_type_long
($1) .
2291 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2292 # can match only for combined diff
2294 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2295 if ($from->{'href'}[$i]) {
2296 $line .= $cgi->a({-href
=>$from->{'href'}[$i],
2298 substr($diffinfo->{'from_id'}[$i],0,7));
2303 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2306 if ($to->{'href'}) {
2307 $line .= $cgi->a({-href
=>$to->{'href'}, -class=>"hash"},
2308 substr($diffinfo->{'to_id'},0,7));
2313 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2314 # can match only for ordinary diff
2315 my ($from_link, $to_link);
2316 if ($from->{'href'}) {
2317 $from_link = $cgi->a({-href
=>$from->{'href'}, -class=>"hash"},
2318 substr($diffinfo->{'from_id'},0,7));
2320 $from_link = '0' x
7;
2322 if ($to->{'href'}) {
2323 $to_link = $cgi->a({-href
=>$to->{'href'}, -class=>"hash"},
2324 substr($diffinfo->{'to_id'},0,7));
2328 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2329 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2332 return $line . "<br/>\n";
2335 # format from-file/to-file diff header
2336 sub format_diff_from_to_header
{
2337 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2342 #assert($line =~ m/^---/) if DEBUG;
2343 # no extra formatting for "^--- /dev/null"
2344 if (! $diffinfo->{'nparents'}) {
2345 # ordinary (single parent) diff
2346 if ($line =~ m!^--- "?a/!) {
2347 if ($from->{'href'}) {
2349 $cgi->a({-href
=>$from->{'href'}, -class=>"path"},
2350 esc_path
($from->{'file'}));
2353 esc_path
($from->{'file'});
2356 $result .= qq!<div
class="diff from_file">$line</div
>\n!;
2359 # combined diff (merge commit)
2360 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2361 if ($from->{'href'}[$i]) {
2363 $cgi->a({-href
=>href
(action
=>"blobdiff",
2364 hash_parent
=>$diffinfo->{'from_id'}[$i],
2365 hash_parent_base
=>$parents[$i],
2366 file_parent
=>$from->{'file'}[$i],
2367 hash
=>$diffinfo->{'to_id'},
2369 file_name
=>$to->{'file'}),
2371 -title
=>"diff" . ($i+1)},
2374 $cgi->a({-href
=>$from->{'href'}[$i], -class=>"path"},
2375 esc_path
($from->{'file'}[$i]));
2377 $line = '--- /dev/null';
2379 $result .= qq!<div
class="diff from_file">$line</div
>\n!;
2384 #assert($line =~ m/^\+\+\+/) if DEBUG;
2385 # no extra formatting for "^+++ /dev/null"
2386 if ($line =~ m!^\+\+\+ "?b/!) {
2387 if ($to->{'href'}) {
2389 $cgi->a({-href
=>$to->{'href'}, -class=>"path"},
2390 esc_path
($to->{'file'}));
2393 esc_path
($to->{'file'});
2396 $result .= qq!<div
class="diff to_file">$line</div
>\n!;
2401 # create note for patch simplified by combined diff
2402 sub format_diff_cc_simplified
{
2403 my ($diffinfo, @parents) = @_;
2406 $result .= "<div class=\"diff header\">" .
2408 if (!is_deleted
($diffinfo)) {
2409 $result .= $cgi->a({-href
=> href
(action
=>"blob",
2411 hash
=>$diffinfo->{'to_id'},
2412 file_name
=>$diffinfo->{'to_file'}),
2414 esc_path
($diffinfo->{'to_file'}));
2416 $result .= esc_path
($diffinfo->{'to_file'});
2418 $result .= "</div>\n" . # class="diff header"
2419 "<div class=\"diff nodifferences\">" .
2421 "</div>\n"; # class="diff nodifferences"
2426 sub diff_line_class
{
2427 my ($line, $from, $to) = @_;
2432 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2433 $num_sign = scalar @
{$from->{'href'}};
2436 my @diff_line_classifier = (
2437 { regexp
=> qr/^\@\@{$num_sign} /, class => "chunk_header"},
2438 { regexp
=> qr/^\\/, class => "incomplete" },
2439 { regexp
=> qr/^ {$num_sign}/, class => "ctx" },
2440 # classifier for context must come before classifier add/rem,
2441 # or we would have to use more complicated regexp, for example
2442 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2443 { regexp
=> qr/^[+ ]{$num_sign}/, class => "add" },
2444 { regexp
=> qr/^[- ]{$num_sign}/, class => "rem" },
2446 for my $clsfy (@diff_line_classifier) {
2447 return $clsfy->{'class'}
2448 if ($line =~ $clsfy->{'regexp'});
2455 # assumes that $from and $to are defined and correctly filled,
2456 # and that $line holds a line of chunk header for unified diff
2457 sub format_unidiff_chunk_header
{
2458 my ($line, $from, $to) = @_;
2460 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2461 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2463 $from_lines = 0 unless defined $from_lines;
2464 $to_lines = 0 unless defined $to_lines;
2466 if ($from->{'href'}) {
2467 $from_text = $cgi->a({-href
=>"$from->{'href'}#l$from_start",
2468 -class=>"list"}, $from_text);
2470 if ($to->{'href'}) {
2471 $to_text = $cgi->a({-href
=>"$to->{'href'}#l$to_start",
2472 -class=>"list"}, $to_text);
2474 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2475 "<span class=\"section\">" . esc_html
($section, -nbsp
=>1) . "</span>";
2479 # assumes that $from and $to are defined and correctly filled,
2480 # and that $line holds a line of chunk header for combined diff
2481 sub format_cc_diff_chunk_header
{
2482 my ($line, $from, $to) = @_;
2484 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2485 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2487 @from_text = split(' ', $ranges);
2488 for (my $i = 0; $i < @from_text; ++$i) {
2489 ($from_start[$i], $from_nlines[$i]) =
2490 (split(',', substr($from_text[$i], 1)), 0);
2493 $to_text = pop @from_text;
2494 $to_start = pop @from_start;
2495 $to_nlines = pop @from_nlines;
2497 $line = "<span class=\"chunk_info\">$prefix ";
2498 for (my $i = 0; $i < @from_text; ++$i) {
2499 if ($from->{'href'}[$i]) {
2500 $line .= $cgi->a({-href
=>"$from->{'href'}[$i]#l$from_start[$i]",
2501 -class=>"list"}, $from_text[$i]);
2503 $line .= $from_text[$i];
2507 if ($to->{'href'}) {
2508 $line .= $cgi->a({-href
=>"$to->{'href'}#l$to_start",
2509 -class=>"list"}, $to_text);
2513 $line .= " $prefix</span>" .
2514 "<span class=\"section\">" . esc_html
($section, -nbsp
=>1) . "</span>";
2518 # process patch (diff) line (not to be used for diff headers),
2519 # returning HTML-formatted (but not wrapped) line.
2520 # If the line is passed as a reference, it is treated as HTML and not
2522 sub format_diff_line
{
2523 my ($line, $diff_class, $from, $to) = @_;
2529 $line = untabify
($line);
2531 if ($from && $to && $line =~ m/^\@{2} /) {
2532 $line = format_unidiff_chunk_header
($line, $from, $to);
2533 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2534 $line = format_cc_diff_chunk_header
($line, $from, $to);
2536 $line = esc_html
($line, -nbsp
=>1);
2540 my $diff_classes = "diff";
2541 $diff_classes .= " $diff_class" if ($diff_class);
2542 $line = "<div class=\"$diff_classes\">$line</div>\n";
2547 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2548 # linked. Pass the hash of the tree/commit to snapshot.
2549 sub format_snapshot_links
{
2551 my $num_fmts = @snapshot_fmts;
2552 if ($num_fmts > 1) {
2553 # A parenthesized list of links bearing format names.
2554 # e.g. "snapshot (_tar.gz_ _zip_)"
2555 return "snapshot (" . join(' ', map
2562 }, $known_snapshot_formats{$_}{'display'})
2563 , @snapshot_fmts) . ")";
2564 } elsif ($num_fmts == 1) {
2565 # A single "snapshot" link whose tooltip bears the format name.
2567 my ($fmt) = @snapshot_fmts;
2573 snapshot_format
=>$fmt
2575 -title
=> "in format: $known_snapshot_formats{$fmt}{'display'}"
2577 } else { # $num_fmts == 0
2582 ## ......................................................................
2583 ## functions returning values to be passed, perhaps after some
2584 ## transformation, to other functions; e.g. returning arguments to href()
2586 # returns hash to be passed to href to generate gitweb URL
2587 # in -title key it returns description of link
2589 my $format = shift || 'Atom';
2590 my %res = (action
=> lc($format));
2591 my $matched_ref = 0;
2593 # feed links are possible only for project views
2594 return unless (defined $project);
2595 # some views should link to OPML, or to generic project feed,
2596 # or don't have specific feed yet (so they should use generic)
2597 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2600 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2601 # (fullname) to differentiate from tag links; this also makes
2602 # possible to detect branch links
2603 for my $ref (get_branch_refs
()) {
2604 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2605 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2607 $matched_ref = $ref;
2611 # find log type for feed description (title)
2613 if (defined $file_name) {
2614 $type = "history of $file_name";
2615 $type .= "/" if ($action eq 'tree');
2616 $type .= " on '$branch'" if (defined $branch);
2618 $type = "log of $branch" if (defined $branch);
2621 $res{-title
} = $type;
2622 $res{'hash'} = (defined $branch ?
"refs/$matched_ref/$branch" : undef);
2623 $res{'file_name'} = $file_name;
2628 ## ----------------------------------------------------------------------
2629 ## git utility subroutines, invoking git commands
2631 # returns path to the core git executable and the --git-dir parameter as list
2633 $number_of_git_cmds++;
2634 return $GIT, '--git-dir='.$git_dir;
2637 # quote the given arguments for passing them to the shell
2638 # quote_command("command", "arg 1", "arg with ' and ! characters")
2639 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2640 # Try to avoid using this function wherever possible.
2643 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2646 # get HEAD ref of given project as hash
2647 sub git_get_head_hash
{
2648 return git_get_full_hash
(shift, 'HEAD');
2651 sub git_get_full_hash
{
2652 return git_get_hash
(@_);
2655 sub git_get_short_hash
{
2656 return git_get_hash
(@_, '--short=7');
2660 my ($project, $hash, @options) = @_;
2661 my $o_git_dir = $git_dir;
2663 $git_dir = "$projectroot/$project";
2664 if (open my $fd, '-|', git_cmd
(), 'rev-parse',
2665 '--verify', '-q', @options, $hash) {
2667 chomp $retval if defined $retval;
2670 if (defined $o_git_dir) {
2671 $git_dir = $o_git_dir;
2676 # get type of given object
2680 open my $fd, "-|", git_cmd
(), "cat-file", '-t', $hash or return;
2682 close $fd or return;
2687 # repository configuration
2688 our $config_file = '';
2691 # store multiple values for single key as anonymous array reference
2692 # single values stored directly in the hash, not as [ <value> ]
2693 sub hash_set_multi
{
2694 my ($hash, $key, $value) = @_;
2696 if (!exists $hash->{$key}) {
2697 $hash->{$key} = $value;
2698 } elsif (!ref $hash->{$key}) {
2699 $hash->{$key} = [ $hash->{$key}, $value ];
2701 push @
{$hash->{$key}}, $value;
2705 # return hash of git project configuration
2706 # optionally limited to some section, e.g. 'gitweb'
2707 sub git_parse_project_config
{
2708 my $section_regexp = shift;
2713 open my $fh, "-|", git_cmd
(), "config", '-z', '-l',
2716 while (my $keyval = <$fh>) {
2718 my ($key, $value) = split(/\n/, $keyval, 2);
2720 hash_set_multi
(\
%config, $key, $value)
2721 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2728 # convert config value to boolean: 'true' or 'false'
2729 # no value, number > 0, 'true' and 'yes' values are true
2730 # rest of values are treated as false (never as error)
2731 sub config_to_bool
{
2734 return 1 if !defined $val; # section.key
2736 # strip leading and trailing whitespace
2740 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2741 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2744 # convert config value to simple decimal number
2745 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2746 # to be multiplied by 1024, 1048576, or 1073741824
2750 # strip leading and trailing whitespace
2754 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2756 # unknown unit is treated as 1
2757 return $num * ($unit eq 'g' ?
1073741824 :
2758 $unit eq 'm' ?
1048576 :
2759 $unit eq 'k' ?
1024 : 1);
2764 # convert config value to array reference, if needed
2765 sub config_to_multi
{
2768 return ref($val) ?
$val : (defined($val) ?
[ $val ] : []);
2771 sub git_get_project_config
{
2772 my ($key, $type) = @_;
2774 return unless defined $git_dir;
2777 return unless ($key);
2778 # only subsection, if exists, is case sensitive,
2779 # and not lowercased by 'git config -z -l'
2780 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2782 $key = join(".", lc($hi), $mi, lc($lo));
2783 return if ($lo =~ /\W/ || $hi =~ /\W/);
2787 return if ($key =~ /\W/);
2789 $key =~ s/^gitweb\.//;
2792 if (defined $type) {
2795 unless ($type eq 'bool' || $type eq 'int');
2799 if (!defined $config_file ||
2800 $config_file ne "$git_dir/config") {
2801 %config = git_parse_project_config
('gitweb');
2802 $config_file = "$git_dir/config";
2805 # check if config variable (key) exists
2806 return unless exists $config{"gitweb.$key"};
2809 if (!defined $type) {
2810 return $config{"gitweb.$key"};
2811 } elsif ($type eq 'bool') {
2812 # backward compatibility: 'git config --bool' returns true/false
2813 return config_to_bool
($config{"gitweb.$key"}) ?
'true' : 'false';
2814 } elsif ($type eq 'int') {
2815 return config_to_int
($config{"gitweb.$key"});
2817 return $config{"gitweb.$key"};
2820 # get hash of given path at given ref
2821 sub git_get_hash_by_path
{
2823 my $path = shift || return undef;
2828 open my $fd, "-|", git_cmd
(), "ls-tree", $base, "--", $path
2829 or die_error
(500, "Open git-ls-tree failed");
2831 close $fd or return undef;
2833 if (!defined $line) {
2834 # there is no tree or hash given by $path at $base
2838 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2839 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2840 if (defined $type && $type ne $2) {
2841 # type doesn't match
2847 # get path of entry with given hash at given tree-ish (ref)
2848 # used to get 'from' filename for combined diff (merge commit) for renames
2849 sub git_get_path_by_hash
{
2850 my $base = shift || return;
2851 my $hash = shift || return;
2855 open my $fd, "-|", git_cmd
(), "ls-tree", '-r', '-t', '-z', $base
2857 while (my $line = <$fd>) {
2860 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2861 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2862 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2871 ## ......................................................................
2872 ## git utility functions, directly accessing git repository
2874 # get the value of config variable either from file named as the variable
2875 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2876 # configuration variable in the repository config file.
2877 sub git_get_file_or_project_config
{
2878 my ($path, $name) = @_;
2880 $git_dir = "$projectroot/$path";
2881 open my $fd, '<', "$git_dir/$name"
2882 or return git_get_project_config
($name);
2885 if (defined $conf) {
2891 sub git_get_project_description
{
2893 return git_get_file_or_project_config
($path, 'description');
2896 sub git_get_project_category
{
2898 return git_get_file_or_project_config
($path, 'category');
2902 # supported formats:
2903 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2904 # - if its contents is a number, use it as tag weight,
2905 # - otherwise add a tag with weight 1
2906 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2907 # the same value multiple times increases tag weight
2908 # * `gitweb.ctag' multi-valued repo config variable
2909 sub git_get_project_ctags
{
2910 my $project = shift;
2913 $git_dir = "$projectroot/$project";
2914 if (opendir my $dh, "$git_dir/ctags") {
2915 my @files = grep { -f
$_ } map { "$git_dir/ctags/$_" } readdir($dh);
2916 foreach my $tagfile (@files) {
2917 open my $ct, '<', $tagfile
2923 (my $ctag = $tagfile) =~ s
#.*/##;
2924 if ($val =~ /^\d+$/) {
2925 $ctags->{$ctag} = $val;
2927 $ctags->{$ctag} = 1;
2932 } elsif (open my $fh, '<', "$git_dir/ctags") {
2933 while (my $line = <$fh>) {
2935 $ctags->{$line}++ if $line;
2940 my $taglist = config_to_multi
(git_get_project_config
('ctag'));
2941 foreach my $tag (@
$taglist) {
2949 # return hash, where keys are content tags ('ctags'),
2950 # and values are sum of weights of given tag in every project
2951 sub git_gather_all_ctags
{
2952 my $projects = shift;
2955 foreach my $p (@
$projects) {
2956 foreach my $ct (keys %{$p->{'ctags'}}) {
2957 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2964 sub git_populate_project_tagcloud
{
2965 my ($ctags, $action) = @_;
2967 # First, merge different-cased tags; tags vote on casing
2969 foreach (keys %$ctags) {
2970 $ctags_lc{lc $_}->{count
} += $ctags->{$_};
2971 if (not $ctags_lc{lc $_}->{topcount
}
2972 or $ctags_lc{lc $_}->{topcount
} < $ctags->{$_}) {
2973 $ctags_lc{lc $_}->{topcount
} = $ctags->{$_};
2974 $ctags_lc{lc $_}->{topname
} = $_;
2979 my $matched = $input_params{'ctag_filter'};
2980 if (eval { require HTML
::TagCloud
; 1; }) {
2981 $cloud = HTML
::TagCloud
->new;
2982 foreach my $ctag (sort keys %ctags_lc) {
2983 # Pad the title with spaces so that the cloud looks
2985 my $title = esc_html
($ctags_lc{$ctag}->{topname
});
2986 $title =~ s/ / /g;
2987 $title =~ s/^/ /g;
2988 $title =~ s/$/ /g;
2989 if (defined $matched && $matched eq $ctag) {
2990 $title = qq(<span
class="match">$title</span
>);
2992 $cloud->add($title, href
(-replay
=>1, action
=>$action, ctag_filter
=>$ctag),
2993 $ctags_lc{$ctag}->{count
});
2997 foreach my $ctag (keys %ctags_lc) {
2998 my $title = esc_html
($ctags_lc{$ctag}->{topname
}, -nbsp
=>1);
2999 if (defined $matched && $matched eq $ctag) {
3000 $title = qq(<span
class="match">$title</span
>);
3002 $cloud->{$ctag}{count
} = $ctags_lc{$ctag}->{count
};
3003 $cloud->{$ctag}{ctag
} =
3004 $cgi->a({-href
=>href
(-replay
=>1, action
=>$action, ctag_filter
=>$ctag)}, $title);
3010 sub git_show_project_tagcloud
{
3011 my ($cloud, $count) = @_;
3012 if (ref $cloud eq 'HTML::TagCloud') {
3013 return $cloud->html_and_css($count);
3015 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3017 '<div id="htmltagcloud"'.($project ?
'' : ' align="center"').'>' .
3019 $cloud->{$_}->{'ctag'}
3020 } splice(@tags, 0, $count)) .
3025 sub git_get_project_url_list
{
3028 $git_dir = "$projectroot/$path";
3029 open my $fd, '<', "$git_dir/cloneurl"
3030 or return wantarray ?
3031 @
{ config_to_multi
(git_get_project_config
('url')) } :
3032 config_to_multi
(git_get_project_config
('url'));
3033 my @git_project_url_list = map { chomp; $_ } <$fd>;
3036 return wantarray ?
@git_project_url_list : \
@git_project_url_list;
3039 sub git_get_projects_list
{
3040 my $filter = shift || '';
3041 my $paranoid = shift;
3044 if (-d
$projects_list) {
3045 # search in directory
3046 my $dir = $projects_list;
3047 # remove the trailing "/"
3049 my $pfxlen = length("$dir");
3050 my $pfxdepth = ($dir =~ tr!/!!);
3051 # when filtering, search only given subdirectory
3052 if ($filter && !$paranoid) {
3058 follow_fast
=> 1, # follow symbolic links
3059 follow_skip
=> 2, # ignore duplicates
3060 dangling_symlinks
=> 0, # ignore dangling symlinks, silently
3063 our $project_maxdepth;
3065 # skip project-list toplevel, if we get it.
3066 return if (m!^[/.]$!);
3067 # only directories can be git repositories
3068 return unless (-d
$_);
3069 # don't traverse too deep (Find is super slow on os x)
3070 # $project_maxdepth excludes depth of $projectroot
3071 if (($File::Find
::name
=~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3072 $File::Find
::prune
= 1;
3076 my $path = substr($File::Find
::name
, $pfxlen + 1);
3077 # paranoidly only filter here
3078 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3081 # we check related file in $projectroot
3082 if (check_export_ok
("$projectroot/$path")) {
3083 push @list, { path
=> $path };
3084 $File::Find
::prune
= 1;
3089 } elsif (-f
$projects_list) {
3090 # read from file(url-encoded):
3091 # 'git%2Fgit.git Linus+Torvalds'
3092 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3093 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3094 open my $fd, '<', $projects_list or return;
3096 while (my $line = <$fd>) {
3098 my ($path, $owner) = split ' ', $line;
3099 $path = unescape
($path);
3100 $owner = unescape
($owner);
3101 if (!defined $path) {
3104 # if $filter is rpovided, check if $path begins with $filter
3105 if ($filter && $path !~ m!^\Q$filter\E/!) {
3108 if (check_export_ok
("$projectroot/$path")) {
3113 $pr->{'owner'} = to_utf8
($owner);
3123 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3124 # as side effects it sets 'forks' field to list of forks for forked projects
3125 sub filter_forks_from_projects_list
{
3126 my $projects = shift;
3128 my %trie; # prefix tree of directories (path components)
3129 # generate trie out of those directories that might contain forks
3130 foreach my $pr (@
$projects) {
3131 my $path = $pr->{'path'};
3132 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3133 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3134 next unless ($path); # skip '.git' repository: tests, git-instaweb
3135 next unless (-d
"$projectroot/$path"); # containing directory exists
3136 $pr->{'forks'} = []; # there can be 0 or more forks of project
3139 my @dirs = split('/', $path);
3140 # walk the trie, until either runs out of components or out of trie
3142 while (scalar @dirs &&
3143 exists($ref->{$dirs[0]})) {
3144 $ref = $ref->{shift @dirs};
3146 # create rest of trie structure from rest of components
3147 foreach my $dir (@dirs) {
3148 $ref = $ref->{$dir} = {};
3150 # create end marker, store $pr as a data
3151 $ref->{''} = $pr if (!exists $ref->{''});
3154 # filter out forks, by finding shortest prefix match for paths
3157 foreach my $pr (@
$projects) {
3161 foreach my $dir (split('/', $pr->{'path'})) {
3162 if (exists $ref->{''}) {
3163 # found [shortest] prefix, is a fork - skip it
3164 push @
{$ref->{''}{'forks'}}, $pr;
3167 if (!exists $ref->{$dir}) {
3168 # not in trie, cannot have prefix, not a fork
3169 push @filtered, $pr;
3172 # If the dir is there, we just walk one step down the trie.
3173 $ref = $ref->{$dir};
3175 # we ran out of trie
3176 # (shouldn't happen: it's either no match, or end marker)
3177 push @filtered, $pr;
3183 # note: fill_project_list_info must be run first,
3184 # for 'descr_long' and 'ctags' to be filled
3185 sub search_projects_list
{
3186 my ($projlist, %opts) = @_;
3187 my $tagfilter = $opts{'tagfilter'};
3188 my $search_re = $opts{'search_regexp'};
3191 unless ($tagfilter || $search_re);
3193 # searching projects require filling to be run before it;
3194 fill_project_list_info
($projlist,
3195 $tagfilter ?
'ctags' : (),
3196 $search_re ?
('path', 'descr') : ());
3199 foreach my $pr (@
$projlist) {
3202 next unless ref($pr->{'ctags'}) eq 'HASH';
3204 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3209 $pr->{'path'} =~ /$search_re/ ||
3210 $pr->{'descr_long'} =~ /$search_re/;
3213 push @projects, $pr;
3219 our $gitweb_project_owner = undef;
3220 sub git_get_project_list_from_file
{
3222 return if (defined $gitweb_project_owner);
3224 $gitweb_project_owner = {};
3225 # read from file (url-encoded):
3226 # 'git%2Fgit.git Linus+Torvalds'
3227 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3228 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3229 if (-f
$projects_list) {
3230 open(my $fd, '<', $projects_list);
3231 while (my $line = <$fd>) {
3233 my ($pr, $ow) = split ' ', $line;
3234 $pr = unescape
($pr);
3235 $ow = unescape
($ow);
3236 $gitweb_project_owner->{$pr} = to_utf8
($ow);
3242 sub git_get_project_owner
{
3243 my $project = shift;
3246 return undef unless $project;
3247 $git_dir = "$projectroot/$project";
3249 if (!defined $gitweb_project_owner) {
3250 git_get_project_list_from_file
();
3253 if (exists $gitweb_project_owner->{$project}) {
3254 $owner = $gitweb_project_owner->{$project};
3256 if (!defined $owner){
3257 $owner = git_get_project_config
('owner');
3259 if (!defined $owner) {
3260 $owner = get_file_owner
("$git_dir");
3266 sub git_get_last_activity
{
3270 $git_dir = "$projectroot/$path";
3271 open($fd, "-|", git_cmd
(), 'for-each-ref',
3272 '--format=%(committer)',
3273 '--sort=-committerdate',
3275 map { "refs/$_" } get_branch_refs
()) or return;
3276 my $most_recent = <$fd>;
3277 close $fd or return;
3278 if (defined $most_recent &&
3279 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3281 my $age = time - $timestamp;
3282 return ($age, age_string
($age));
3284 return (undef, undef);
3287 # Implementation note: when a single remote is wanted, we cannot use 'git
3288 # remote show -n' because that command always work (assuming it's a remote URL
3289 # if it's not defined), and we cannot use 'git remote show' because that would
3290 # try to make a network roundtrip. So the only way to find if that particular
3291 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3292 # and when we find what we want.
3293 sub git_get_remotes_list
{
3297 open my $fd, '-|' , git_cmd
(), 'remote', '-v';
3299 while (my $remote = <$fd>) {
3301 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3302 next if $wanted and not $remote eq $wanted;
3303 my ($url, $key) = ($1, $2);
3305 $remotes{$remote} ||= { 'heads' => () };
3306 $remotes{$remote}{$key} = $url;
3308 close $fd or return;
3309 return wantarray ?
%remotes : \
%remotes;
3312 # Takes a hash of remotes as first parameter and fills it by adding the
3313 # available remote heads for each of the indicated remotes.
3314 sub fill_remote_heads
{
3315 my $remotes = shift;
3316 my @heads = map { "remotes/$_" } keys %$remotes;
3317 my @remoteheads = git_get_heads_list
(undef, @heads);
3318 foreach my $remote (keys %$remotes) {
3319 $remotes->{$remote}{'heads'} = [ grep {
3320 $_->{'name'} =~ s!^$remote/!!
3325 sub git_get_references
{
3326 my $type = shift || "";
3328 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3329 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3330 open my $fd, "-|", git_cmd
(), "show-ref", "--dereference",
3331 ($type ?
("--", "refs/$type") : ()) # use -- <pattern> if $type
3334 while (my $line = <$fd>) {
3336 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3337 if (defined $refs{$1}) {
3338 push @
{$refs{$1}}, $2;
3344 close $fd or return;
3348 sub git_get_rev_name_tags
{
3349 my $hash = shift || return undef;
3351 open my $fd, "-|", git_cmd
(), "name-rev", "--tags", $hash
3353 my $name_rev = <$fd>;
3356 if ($name_rev =~ m
|^$hash tags
/(.*)$|) {
3359 # catches also '$hash undefined' output
3364 ## ----------------------------------------------------------------------
3365 ## parse to hash functions
3369 my $tz = shift || "-0000";
3372 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3373 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3374 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3375 $date{'hour'} = $hour;
3376 $date{'minute'} = $min;
3377 $date{'mday'} = $mday;
3378 $date{'day'} = $days[$wday];
3379 $date{'month'} = $months[$mon];
3380 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3381 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3382 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3383 $mday, $months[$mon], $hour ,$min;
3384 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3385 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3387 my ($tz_sign, $tz_hour, $tz_min) =
3388 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3389 $tz_sign = ($tz_sign eq '-' ?
-1 : +1);
3390 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3391 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3392 $date{'hour_local'} = $hour;
3393 $date{'minute_local'} = $min;
3394 $date{'tz_local'} = $tz;
3395 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3396 1900+$year, $mon+1, $mday,
3397 $hour, $min, $sec, $tz);
3406 open my $fd, "-|", git_cmd
(), "cat-file", "tag", $tag_id or return;
3407 $tag{'id'} = $tag_id;
3408 while (my $line = <$fd>) {
3410 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3411 $tag{'object'} = $1;
3412 } elsif ($line =~ m/^type (.+)$/) {
3414 } elsif ($line =~ m/^tag (.+)$/) {
3416 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3417 $tag{'author'} = $1;
3418 $tag{'author_epoch'} = $2;
3419 $tag{'author_tz'} = $3;
3420 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3421 $tag{'author_name'} = $1;
3422 $tag{'author_email'} = $2;
3424 $tag{'author_name'} = $tag{'author'};
3426 } elsif ($line =~ m/--BEGIN/) {
3427 push @comment, $line;
3429 } elsif ($line eq "") {
3433 push @comment, <$fd>;
3434 $tag{'comment'} = \
@comment;
3435 close $fd or return;
3436 if (!defined $tag{'name'}) {
3442 sub parse_commit_text
{
3443 my ($commit_text, $withparents) = @_;
3444 my @commit_lines = split '\n', $commit_text;
3447 pop @commit_lines; # Remove '\0'
3449 if (! @commit_lines) {
3453 my $header = shift @commit_lines;
3454 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3457 ($co{'id'}, my @parents) = split ' ', $header;
3458 while (my $line = shift @commit_lines) {
3459 last if $line eq "\n";
3460 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3462 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3464 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3465 $co{'author'} = to_utf8
($1);
3466 $co{'author_epoch'} = $2;
3467 $co{'author_tz'} = $3;
3468 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3469 $co{'author_name'} = $1;
3470 $co{'author_email'} = $2;
3472 $co{'author_name'} = $co{'author'};
3474 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3475 $co{'committer'} = to_utf8
($1);
3476 $co{'committer_epoch'} = $2;
3477 $co{'committer_tz'} = $3;
3478 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3479 $co{'committer_name'} = $1;
3480 $co{'committer_email'} = $2;
3482 $co{'committer_name'} = $co{'committer'};
3486 if (!defined $co{'tree'}) {
3489 $co{'parents'} = \
@parents;
3490 $co{'parent'} = $parents[0];
3492 foreach my $title (@commit_lines) {
3495 $co{'title'} = chop_str
($title, 80, 5);
3496 # remove leading stuff of merges to make the interesting part visible
3497 if (length($title) > 50) {
3498 $title =~ s/^Automatic //;
3499 $title =~ s/^merge (of|with) /Merge ... /i;
3500 if (length($title) > 50) {
3501 $title =~ s/(http|rsync):\/\///;
3503 if (length($title) > 50) {
3504 $title =~ s/(master|www|rsync)\.//;
3506 if (length($title) > 50) {
3507 $title =~ s/kernel.org:?//;
3509 if (length($title) > 50) {
3510 $title =~ s/\/pub\/scm//;
3513 $co{'title_short'} = chop_str
($title, 50, 5);
3517 if (! defined $co{'title'} || $co{'title'} eq "") {
3518 $co{'title'} = $co{'title_short'} = '(no commit message)';
3520 # remove added spaces
3521 foreach my $line (@commit_lines) {
3524 $co{'comment'} = \
@commit_lines;
3526 my $age = time - $co{'committer_epoch'};
3528 $co{'age_string'} = age_string
($age);
3529 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3530 if ($age > 60*60*24*7*2) {
3531 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3532 $co{'age_string_age'} = $co{'age_string'};
3534 $co{'age_string_date'} = $co{'age_string'};
3535 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3541 my ($commit_id) = @_;
3546 open my $fd, "-|", git_cmd
(), "rev-list",
3552 or die_error
(500, "Open git-rev-list failed");
3553 %co = parse_commit_text
(<$fd>, 1);
3560 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3568 open my $fd, "-|", git_cmd
(), "rev-list",
3571 ("--max-count=" . $maxcount),
3572 ("--skip=" . $skip),
3576 ($filename ?
($filename) : ())
3577 or die_error
(500, "Open git-rev-list failed");
3578 while (my $line = <$fd>) {
3579 my %co = parse_commit_text
($line);
3584 return wantarray ?
@cos : \
@cos;
3587 # parse line of git-diff-tree "raw" output
3588 sub parse_difftree_raw_line
{
3592 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3593 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3594 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3595 $res{'from_mode'} = $1;
3596 $res{'to_mode'} = $2;
3597 $res{'from_id'} = $3;
3599 $res{'status'} = $5;
3600 $res{'similarity'} = $6;
3601 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3602 ($res{'from_file'}, $res{'to_file'}) = map { unquote
($_) } split("\t", $7);
3604 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote
($7);
3607 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3608 # combined diff (for merge commit)
3609 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3610 $res{'nparents'} = length($1);
3611 $res{'from_mode'} = [ split(' ', $2) ];
3612 $res{'to_mode'} = pop @
{$res{'from_mode'}};
3613 $res{'from_id'} = [ split(' ', $3) ];
3614 $res{'to_id'} = pop @
{$res{'from_id'}};
3615 $res{'status'} = [ split('', $4) ];
3616 $res{'to_file'} = unquote
($5);
3618 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3619 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3620 $res{'commit'} = $1;
3623 return wantarray ?
%res : \
%res;
3626 # wrapper: return parsed line of git-diff-tree "raw" output
3627 # (the argument might be raw line, or parsed info)
3628 sub parsed_difftree_line
{
3629 my $line_or_ref = shift;
3631 if (ref($line_or_ref) eq "HASH") {
3632 # pre-parsed (or generated by hand)
3633 return $line_or_ref;
3635 return parse_difftree_raw_line
($line_or_ref);
3639 # parse line of git-ls-tree output
3640 sub parse_ls_tree_line
{
3646 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3647 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3656 $res{'name'} = unquote
($5);
3659 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3660 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3668 $res{'name'} = unquote
($4);
3672 return wantarray ?
%res : \
%res;
3675 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3676 sub parse_from_to_diffinfo
{
3677 my ($diffinfo, $from, $to, @parents) = @_;
3679 if ($diffinfo->{'nparents'}) {
3681 $from->{'file'} = [];
3682 $from->{'href'} = [];
3683 fill_from_file_info
($diffinfo, @parents)
3684 unless exists $diffinfo->{'from_file'};
3685 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3686 $from->{'file'}[$i] =
3687 defined $diffinfo->{'from_file'}[$i] ?
3688 $diffinfo->{'from_file'}[$i] :
3689 $diffinfo->{'to_file'};
3690 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3691 $from->{'href'}[$i] = href
(action
=>"blob",
3692 hash_base
=>$parents[$i],
3693 hash
=>$diffinfo->{'from_id'}[$i],
3694 file_name
=>$from->{'file'}[$i]);
3696 $from->{'href'}[$i] = undef;
3700 # ordinary (not combined) diff
3701 $from->{'file'} = $diffinfo->{'from_file'};
3702 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3703 $from->{'href'} = href
(action
=>"blob", hash_base
=>$hash_parent,
3704 hash
=>$diffinfo->{'from_id'},
3705 file_name
=>$from->{'file'});
3707 delete $from->{'href'};
3711 $to->{'file'} = $diffinfo->{'to_file'};
3712 if (!is_deleted
($diffinfo)) { # file exists in result
3713 $to->{'href'} = href
(action
=>"blob", hash_base
=>$hash,
3714 hash
=>$diffinfo->{'to_id'},
3715 file_name
=>$to->{'file'});
3717 delete $to->{'href'};
3721 ## ......................................................................
3722 ## parse to array of hashes functions
3724 sub git_get_heads_list
{
3725 my ($limit, @classes) = @_;
3726 @classes = get_branch_refs
() unless @classes;
3727 my @patterns = map { "refs/$_" } @classes;
3730 open my $fd, '-|', git_cmd
(), 'for-each-ref',
3731 ($limit ?
'--count='.($limit+1) : ()), '--sort=-committerdate',
3732 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3735 while (my $line = <$fd>) {
3739 my ($refinfo, $committerinfo) = split(/\0/, $line);
3740 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3741 my ($committer, $epoch, $tz) =
3742 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3743 $ref_item{'fullname'} = $name;
3744 my $strip_refs = join '|', map { quotemeta } get_branch_refs
();
3745 $name =~ s!^refs/($strip_refs|remotes)/!!;
3746 $ref_item{'name'} = $name;
3747 # for refs neither in 'heads' nor 'remotes' we want to
3748 # show their ref dir
3749 my $ref_dir = (defined $1) ?
$1 : '';
3750 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3751 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3754 $ref_item{'id'} = $hash;
3755 $ref_item{'title'} = $title || '(no commit message)';
3756 $ref_item{'epoch'} = $epoch;
3758 $ref_item{'age'} = age_string
(time - $ref_item{'epoch'});
3760 $ref_item{'age'} = "unknown";
3763 push @headslist, \
%ref_item;
3767 return wantarray ?
@headslist : \
@headslist;
3770 sub git_get_tags_list
{
3774 open my $fd, '-|', git_cmd
(), 'for-each-ref',
3775 ($limit ?
'--count='.($limit+1) : ()), '--sort=-creatordate',
3776 '--format=%(objectname) %(objecttype) %(refname) '.
3777 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3780 while (my $line = <$fd>) {
3784 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3785 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3786 my ($creator, $epoch, $tz) =
3787 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3788 $ref_item{'fullname'} = $name;
3789 $name =~ s!^refs/tags/!!;
3791 $ref_item{'type'} = $type;
3792 $ref_item{'id'} = $id;
3793 $ref_item{'name'} = $name;
3794 if ($type eq "tag") {
3795 $ref_item{'subject'} = $title;
3796 $ref_item{'reftype'} = $reftype;
3797 $ref_item{'refid'} = $refid;
3799 $ref_item{'reftype'} = $type;
3800 $ref_item{'refid'} = $id;
3803 if ($type eq "tag" || $type eq "commit") {
3804 $ref_item{'epoch'} = $epoch;
3806 $ref_item{'age'} = age_string
(time - $ref_item{'epoch'});
3808 $ref_item{'age'} = "unknown";
3812 push @tagslist, \
%ref_item;
3816 return wantarray ?
@tagslist : \
@tagslist;
3819 ## ----------------------------------------------------------------------
3820 ## filesystem-related functions
3822 sub get_file_owner
{
3825 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3826 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3827 if (!defined $gcos) {
3831 $owner =~ s/[,;].*$//;
3832 return to_utf8
($owner);
3835 # assume that file exists
3837 my $filename = shift;
3839 open my $fd, '<', $filename;
3840 print map { to_utf8
($_) } <$fd>;
3844 ## ......................................................................
3845 ## mimetype related functions
3847 sub mimetype_guess_file
{
3848 my $filename = shift;
3849 my $mimemap = shift;
3850 -r
$mimemap or return undef;
3853 open(my $mh, '<', $mimemap) or return undef;
3855 next if m/^#/; # skip comments
3856 my ($mimetype, @exts) = split(/\s+/);
3857 foreach my $ext (@exts) {
3858 $mimemap{$ext} = $mimetype;
3863 $filename =~ /\.([^.]*)$/;
3864 return $mimemap{$1};
3867 sub mimetype_guess
{
3868 my $filename = shift;
3870 $filename =~ /\./ or return undef;
3872 if ($mimetypes_file) {
3873 my $file = $mimetypes_file;
3874 if ($file !~ m!^/!) { # if it is relative path
3875 # it is relative to project
3876 $file = "$projectroot/$project/$file";
3878 $mime = mimetype_guess_file
($filename, $file);
3880 $mime ||= mimetype_guess_file
($filename, '/etc/mime.types');
3886 my $filename = shift;
3889 my $mime = mimetype_guess
($filename);
3890 $mime and return $mime;
3894 return $default_blob_plain_mimetype unless $fd;
3897 return 'text/plain';
3898 } elsif (! $filename) {
3899 return 'application/octet-stream';
3900 } elsif ($filename =~ m/\.png$/i) {
3902 } elsif ($filename =~ m/\.gif$/i) {
3904 } elsif ($filename =~ m/\.jpe?g$/i) {
3905 return 'image/jpeg';
3907 return 'application/octet-stream';
3911 sub blob_contenttype
{
3912 my ($fd, $file_name, $type) = @_;
3914 $type ||= blob_mimetype
($fd, $file_name);
3915 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3916 $type .= "; charset=$default_text_plain_charset";
3922 # guess file syntax for syntax highlighting; return undef if no highlighting
3923 # the name of syntax can (in the future) depend on syntax highlighter used
3924 sub guess_file_syntax
{
3925 my ($highlight, $mimetype, $file_name) = @_;
3926 return undef unless ($highlight && defined $file_name);
3927 my $basename = basename
($file_name, '.in');
3928 return $highlight_basename{$basename}
3929 if exists $highlight_basename{$basename};
3931 $basename =~ /\.([^.]*)$/;
3932 my $ext = $1 or return undef;
3933 return $highlight_ext{$ext}
3934 if exists $highlight_ext{$ext};
3939 # run highlighter and return FD of its output,
3940 # or return original FD if no highlighting
3941 sub run_highlighter
{
3942 my ($fd, $highlight, $syntax) = @_;
3943 return $fd unless ($highlight && defined $syntax);
3946 open $fd, quote_command
(git_cmd
(), "cat-file", "blob", $hash)." | ".
3947 quote_command
($highlight_bin).
3948 " --replace-tabs=8 --fragment --syntax $syntax |"
3949 or die_error
(500, "Couldn't open file or run syntax highlighter");
3953 ## ======================================================================
3954 ## functions printing HTML: header, footer, error page
3956 sub get_page_title
{
3957 my $title = to_utf8
($site_name);
3959 unless (defined $project) {
3960 if (defined $project_filter) {
3961 $title .= " - projects in '" . esc_path
($project_filter) . "'";
3965 $title .= " - " . to_utf8
($project);
3967 return $title unless (defined $action);
3968 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3970 return $title unless (defined $file_name);
3971 $title .= " - " . esc_path
($file_name);
3972 if ($action eq "tree" && $file_name !~ m
|/$|) {
3979 sub get_content_type_html
{
3980 # require explicit support from the UA if we are to send the page as
3981 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3982 # we have to do this because MSIE sometimes globs '*/*', pretending to
3983 # support xhtml+xml but choking when it gets what it asked for.
3984 if (defined $cgi->http('HTTP_ACCEPT') &&
3985 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\
+xml
(,|;|\s
|$)/ &&
3986 $cgi->Accept('application/xhtml+xml') != 0) {
3987 return 'application/xhtml+xml';
3993 sub print_feed_meta
{
3994 if (defined $project) {
3995 my %href_params = get_feed_info
();
3996 if (!exists $href_params{'-title'}) {
3997 $href_params{'-title'} = 'log';
4000 foreach my $format (qw(RSS Atom)) {
4001 my $type = lc($format);
4003 '-rel' => 'alternate',
4004 '-title' => esc_attr
("$project - $href_params{'-title'} - $format feed"),
4005 '-type' => "application/$type+xml"
4008 $href_params{'extra_options'} = undef;
4009 $href_params{'action'} = $type;
4010 $link_attr{'-href'} = href
(%href_params);
4012 "rel=\"$link_attr{'-rel'}\" ".
4013 "title=\"$link_attr{'-title'}\" ".
4014 "href=\"$link_attr{'-href'}\" ".
4015 "type=\"$link_attr{'-type'}\" ".
4018 $href_params{'extra_options'} = '--no-merges';
4019 $link_attr{'-href'} = href
(%href_params);
4020 $link_attr{'-title'} .= ' (no merges)';
4022 "rel=\"$link_attr{'-rel'}\" ".
4023 "title=\"$link_attr{'-title'}\" ".
4024 "href=\"$link_attr{'-href'}\" ".
4025 "type=\"$link_attr{'-type'}\" ".
4030 printf('<link rel="alternate" title="%s projects list" '.
4031 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4032 esc_attr
($site_name), href
(project
=>undef, action
=>"project_index"));
4033 printf('<link rel="alternate" title="%s projects feeds" '.
4034 'href="%s" type="text/x-opml" />'."\n",
4035 esc_attr
($site_name), href
(project
=>undef, action
=>"opml"));
4039 sub print_header_links
{
4042 # print out each stylesheet that exist, providing backwards capability
4043 # for those people who defined $stylesheet in a config file
4044 if (defined $stylesheet) {
4045 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
4047 foreach my $stylesheet (@stylesheets) {
4048 next unless $stylesheet;
4049 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
4053 if ($status eq '200 OK');
4054 if (defined $favicon) {
4055 print qq(<link rel
="shortcut icon" href
=").esc_url($favicon).qq(" type
="image/png" />\n);
4059 sub print_nav_breadcrumbs_path
{
4060 my $dirprefix = undef;
4061 while (my $part = shift) {
4062 $dirprefix .= "/" if defined $dirprefix;
4063 $dirprefix .= $part;
4064 print $cgi->a({-href
=> href
(project
=> undef,
4065 project_filter
=> $dirprefix,
4066 action
=> "project_list")},
4067 esc_html
($part)) . " / ";
4071 sub print_nav_breadcrumbs
{
4074 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4075 print $cgi->a({-href
=> esc_url
($crumb->[1])}, $crumb->[0]) . " / ";
4077 if (defined $project) {
4078 my @dirname = split '/', $project;
4079 my $projectbasename = pop @dirname;
4080 print_nav_breadcrumbs_path
(@dirname);
4081 print $cgi->a({-href
=> href
(action
=>"summary")}, esc_html
($projectbasename));
4082 if (defined $action) {
4083 my $action_print = $action ;
4084 if (defined $opts{-action_extra
}) {
4085 $action_print = $cgi->a({-href
=> href
(action
=>$action)},
4088 print " / $action_print";
4090 if (defined $opts{-action_extra
}) {
4091 print " / $opts{-action_extra}";
4094 } elsif (defined $project_filter) {
4095 print_nav_breadcrumbs_path
(split '/', $project_filter);
4099 sub print_search_form
{
4100 if (!defined $searchtext) {
4104 if (defined $hash_base) {
4105 $search_hash = $hash_base;
4106 } elsif (defined $hash) {
4107 $search_hash = $hash;
4109 $search_hash = "HEAD";
4111 my $action = $my_uri;
4112 my $use_pathinfo = gitweb_check_feature
('pathinfo');
4113 if ($use_pathinfo) {
4114 $action .= "/".esc_url
($project);
4116 print $cgi->start_form(-method
=> "get", -action
=> $action) .
4117 "<div class=\"search\">\n" .
4119 $cgi->input({-name
=>"p", -value
=>$project, -type
=>"hidden"}) . "\n") .
4120 $cgi->input({-name
=>"a", -value
=>"search", -type
=>"hidden"}) . "\n" .
4121 $cgi->input({-name
=>"h", -value
=>$search_hash, -type
=>"hidden"}) . "\n" .
4122 $cgi->popup_menu(-name
=> 'st', -default => 'commit',
4123 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4124 " " . $cgi->a({-href
=> href
(action
=>"search_help"),
4125 -title
=> "search help" }, "?") . " search:\n",
4126 $cgi->textfield(-name
=> "s", -value
=> $searchtext, -override
=> 1) . "\n" .
4127 "<span title=\"Extended regular expression\">" .
4128 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
4129 -checked
=> $search_use_regexp) .
4132 $cgi->end_form() . "\n";
4135 sub git_header_html
{
4136 my $status = shift || "200 OK";
4137 my $expires = shift;
4140 my $title = get_page_title
();
4141 my $content_type = get_content_type_html
();
4142 print $cgi->header(-type
=>$content_type, -charset
=> 'utf-8',
4143 -status
=> $status, -expires
=> $expires)
4144 unless ($opts{'-no_http_header'});
4145 my $mod_perl_version = $ENV{'MOD_PERL'} ?
" $ENV{'MOD_PERL'}" : '';
4147 <?xml version="1.0" encoding="utf-8"?>
4148 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4149 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4150 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4151 <!-- git core binaries version $git_version -->
4153 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4154 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4155 <meta name="robots" content="index, nofollow"/>
4156 <title>$title</title>
4158 # the stylesheet, favicon etc urls won't work correctly with path_info
4159 # unless we set the appropriate base URL
4160 if ($ENV{'PATH_INFO'}) {
4161 print "<base href=\"".esc_url
($base_url)."\" />\n";
4163 print_header_links
($status);
4165 if (defined $site_html_head_string) {
4166 print to_utf8
($site_html_head_string);
4172 if (defined $site_header && -f
$site_header) {
4173 insert_file
($site_header);
4176 print "<div class=\"page_header\">\n";
4177 if (defined $logo) {
4178 print $cgi->a({-href
=> esc_url
($logo_url),
4179 -title
=> $logo_label},
4180 $cgi->img({-src
=> esc_url
($logo),
4181 -width
=> 72, -height
=> 27,
4183 -class => "logo"}));
4185 print_nav_breadcrumbs
(%opts);
4188 my $have_search = gitweb_check_feature
('search');
4189 if (defined $project && $have_search) {
4190 print_search_form
();
4194 sub git_footer_html
{
4195 my $feed_class = 'rss_logo';
4197 print "<div class=\"page_footer\">\n";
4198 if (defined $project) {
4199 my $descr = git_get_project_description
($project);
4200 if (defined $descr) {
4201 print "<div class=\"page_footer_text\">" . esc_html
($descr) . "</div>\n";
4204 my %href_params = get_feed_info
();
4205 if (!%href_params) {
4206 $feed_class .= ' generic';
4208 $href_params{'-title'} ||= 'log';
4210 foreach my $format (qw(RSS Atom)) {
4211 $href_params{'action'} = lc($format);
4212 print $cgi->a({-href
=> href
(%href_params),
4213 -title
=> "$href_params{'-title'} $format feed",
4214 -class => $feed_class}, $format)."\n";
4218 print $cgi->a({-href
=> href
(project
=>undef, action
=>"opml",
4219 project_filter
=> $project_filter),
4220 -class => $feed_class}, "OPML") . " ";
4221 print $cgi->a({-href
=> href
(project
=>undef, action
=>"project_index",
4222 project_filter
=> $project_filter),
4223 -class => $feed_class}, "TXT") . "\n";
4225 print "</div>\n"; # class="page_footer"
4227 if (defined $t0 && gitweb_check_feature
('timed')) {
4228 print "<div id=\"generating_info\">\n";
4229 print 'This page took '.
4230 '<span id="generating_time" class="time_span">'.
4231 tv_interval
($t0, [ gettimeofday
() ]).
4234 '<span id="generating_cmd">'.
4235 $number_of_git_cmds.
4236 '</span> git commands '.
4238 print "</div>\n"; # class="page_footer"
4241 if (defined $site_footer && -f
$site_footer) {
4242 insert_file
($site_footer);
4245 print qq!<script type
="text/javascript" src
="!.esc_url($javascript).qq!"></script
>\n!;
4246 if (defined $action &&
4247 $action eq 'blame_incremental') {
4248 print qq!<script type
="text/javascript">\n!.
4249 qq!startBlame
("!. href(action=>"blame_data
", -replay=>1) .qq!",\n!.
4250 qq! "!. href() .qq!");\n!.
4253 my ($jstimezone, $tz_cookie, $datetime_class) =
4254 gitweb_get_feature
('javascript-timezone');
4256 print qq!<script type
="text/javascript">\n!.
4257 qq!window
.onload
= function
() {\n!;
4258 if (gitweb_check_feature
('javascript-actions')) {
4259 print qq! fixLinks
();\n!;
4261 if ($jstimezone && $tz_cookie && $datetime_class) {
4262 print qq! var tz_cookie
= { name
: '$tz_cookie', expires
: 14, path
: '/' };\n!. # in days
4263 qq! onloadTZSetup
('$jstimezone', tz_cookie
, '$datetime_class');\n!;
4273 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4274 # Example: die_error(404, 'Hash not found')
4275 # By convention, use the following status codes (as defined in RFC 2616):
4276 # 400: Invalid or missing CGI parameters, or
4277 # requested object exists but has wrong type.
4278 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4279 # this server or project.
4280 # 404: Requested object/revision/project doesn't exist.
4281 # 500: The server isn't configured properly, or
4282 # an internal error occurred (e.g. failed assertions caused by bugs), or
4283 # an unknown error occurred (e.g. the git binary died unexpectedly).
4284 # 503: The server is currently unavailable (because it is overloaded,
4285 # or down for maintenance). Generally, this is a temporary state.
4287 my $status = shift || 500;
4288 my $error = esc_html
(shift) || "Internal Server Error";
4292 my %http_responses = (
4293 400 => '400 Bad Request',
4294 403 => '403 Forbidden',
4295 404 => '404 Not Found',
4296 500 => '500 Internal Server Error',
4297 503 => '503 Service Unavailable',
4299 git_header_html
($http_responses{$status}, undef, %opts);
4301 <div class="page_body">
4306 if (defined $extra) {
4314 unless ($opts{'-error_handler'});
4317 ## ----------------------------------------------------------------------
4318 ## functions printing or outputting HTML: navigation
4320 sub git_print_page_nav
{
4321 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4322 $extra = '' if !defined $extra; # pager or formats
4324 my @navs = qw(summary shortlog log commit commitdiff tree);
4326 @navs = grep { $_ ne $suppress } @navs;
4329 my %arg = map { $_ => {action
=>$_} } @navs;
4330 if (defined $head) {
4331 for (qw(commit commitdiff)) {
4332 $arg{$_}{'hash'} = $head;
4334 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4335 for (qw(shortlog log)) {
4336 $arg{$_}{'hash'} = $head;
4341 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4342 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4344 my @actions = gitweb_get_feature
('actions');
4347 'n' => $project, # project name
4348 'f' => $git_dir, # project path within filesystem
4349 'h' => $treehead || '', # current hash ('h' parameter)
4350 'b' => $treebase || '', # hash base ('hb' parameter)
4353 my ($label, $link, $pos) = splice(@actions,0,3);
4355 @navs = map { $_ eq $pos ?
($_, $label) : $_ } @navs;
4357 $link =~ s/%([%nfhb])/$repl{$1}/g;
4358 $arg{$label}{'_href'} = $link;
4361 print "<div class=\"page_nav\">\n" .
4363 map { $_ eq $current ?
4364 $_ : $cgi->a({-href
=> ($arg{$_}{_href
} ?
$arg{$_}{_href
} : href
(%{$arg{$_}}))}, "$_")
4366 print "<br/>\n$extra<br/>\n" .
4370 # returns a submenu for the nagivation of the refs views (tags, heads,
4371 # remotes) with the current view disabled and the remotes view only
4372 # available if the feature is enabled
4373 sub format_ref_views
{
4375 my @ref_views = qw{tags heads
};
4376 push @ref_views, 'remotes' if gitweb_check_feature
('remote_heads');
4377 return join " | ", map {
4378 $_ eq $current ?
$_ :
4379 $cgi->a({-href
=> href
(action
=>$_)}, $_)
4383 sub format_paging_nav
{
4384 my ($action, $page, $has_next_link) = @_;
4390 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)}, "first") .
4392 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
4393 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
4395 $paging_nav .= "first ⋅ prev";
4398 if ($has_next_link) {
4399 $paging_nav .= " ⋅ " .
4400 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
4401 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
4403 $paging_nav .= " ⋅ next";
4409 ## ......................................................................
4410 ## functions printing or outputting HTML: div
4412 sub git_print_header_div
{
4413 my ($action, $title, $hash, $hash_base) = @_;
4416 $args{'action'} = $action;
4417 $args{'hash'} = $hash if $hash;
4418 $args{'hash_base'} = $hash_base if $hash_base;
4420 print "<div class=\"header\">\n" .
4421 $cgi->a({-href
=> href
(%args), -class => "title"},
4422 $title ?
$title : $action) .
4426 sub format_repo_url
{
4427 my ($name, $url) = @_;
4428 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4431 # Group output by placing it in a DIV element and adding a header.
4432 # Options for start_div() can be provided by passing a hash reference as the
4433 # first parameter to the function.
4434 # Options to git_print_header_div() can be provided by passing an array
4435 # reference. This must follow the options to start_div if they are present.
4436 # The content can be a scalar, which is output as-is, a scalar reference, which
4437 # is output after html escaping, an IO handle passed either as *handle or
4438 # *handle{IO}, or a function reference. In the latter case all following
4439 # parameters will be taken as argument to the content function call.
4440 sub git_print_section
{
4441 my ($div_args, $header_args, $content);
4443 if (ref($arg) eq 'HASH') {
4447 if (ref($arg) eq 'ARRAY') {
4448 $header_args = $arg;
4453 print $cgi->start_div($div_args);
4454 git_print_header_div
(@
$header_args);
4456 if (ref($content) eq 'CODE') {
4458 } elsif (ref($content) eq 'SCALAR') {
4459 print esc_html
($$content);
4460 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4462 } elsif (!ref($content) && defined($content)) {
4466 print $cgi->end_div;
4469 sub format_timestamp_html
{
4471 my $strtime = $date->{'rfc2822'};
4473 my (undef, undef, $datetime_class) =
4474 gitweb_get_feature
('javascript-timezone');
4475 if ($datetime_class) {
4476 $strtime = qq!<span
class="$datetime_class">$strtime</span
>!;
4479 my $localtime_format = '(%02d:%02d %s)';
4480 if ($date->{'hour_local'} < 6) {
4481 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4484 sprintf($localtime_format,
4485 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4490 # Outputs the author name and date in long form
4491 sub git_print_authorship
{
4494 my $tag = $opts{-tag
} || 'div';
4495 my $author = $co->{'author_name'};
4497 my %ad = parse_date
($co->{'author_epoch'}, $co->{'author_tz'});
4498 print "<$tag class=\"author_date\">" .
4499 format_search_author
($author, "author", esc_html
($author)) .
4500 " [".format_timestamp_html
(\
%ad)."]".
4501 git_get_avatar
($co->{'author_email'}, -pad_before
=> 1) .
4505 # Outputs table rows containing the full author or committer information,
4506 # in the format expected for 'commit' view (& similar).
4507 # Parameters are a commit hash reference, followed by the list of people
4508 # to output information for. If the list is empty it defaults to both
4509 # author and committer.
4510 sub git_print_authorship_rows
{
4512 # too bad we can't use @people = @_ || ('author', 'committer')
4514 @people = ('author', 'committer') unless @people;
4515 foreach my $who (@people) {
4516 my %wd = parse_date
($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4517 print "<tr><td>$who</td><td>" .
4518 format_search_author
($co->{"${who}_name"}, $who,
4519 esc_html
($co->{"${who}_name"})) . " " .
4520 format_search_author
($co->{"${who}_email"}, $who,
4521 esc_html
("<" . $co->{"${who}_email"} . ">")) .
4522 "</td><td rowspan=\"2\">" .
4523 git_get_avatar
($co->{"${who}_email"}, -size
=> 'double') .
4527 format_timestamp_html
(\
%wd) .
4533 sub git_print_page_path
{
4539 print "<div class=\"page_path\">";
4540 print $cgi->a({-href
=> href
(action
=>"tree", hash_base
=>$hb),
4541 -title
=> 'tree root'}, to_utf8
("[$project]"));
4543 if (defined $name) {
4544 my @dirname = split '/', $name;
4545 my $basename = pop @dirname;
4548 foreach my $dir (@dirname) {
4549 $fullname .= ($fullname ?
'/' : '') . $dir;
4550 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$fullname,
4552 -title
=> $fullname}, esc_path
($dir));
4555 if (defined $type && $type eq 'blob') {
4556 print $cgi->a({-href
=> href
(action
=>"blob_plain", file_name
=>$file_name,
4558 -title
=> $name}, esc_path
($basename));
4559 } elsif (defined $type && $type eq 'tree') {
4560 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$file_name,
4562 -title
=> $name}, esc_path
($basename));
4565 print esc_path
($basename);
4568 print "<br/></div>\n";
4575 if ($opts{'-remove_title'}) {
4576 # remove title, i.e. first line of log
4579 # remove leading empty lines
4580 while (defined $log->[0] && $log->[0] eq "") {
4585 my $skip_blank_line = 0;
4586 foreach my $line (@
$log) {
4587 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4588 if (! $opts{'-remove_signoff'}) {
4589 print "<span class=\"signoff\">" . esc_html
($line) . "</span><br/>\n";
4590 $skip_blank_line = 1;
4595 if ($line =~ m
,\s
*([a
-z
]*link): (https?
://\S
+),i
) {
4596 if (! $opts{'-remove_signoff'}) {
4597 print "<span class=\"signoff\">" . esc_html
($1) . ": " .
4598 "<a href=\"" . esc_html
($2) . "\">" . esc_html
($2) . "</a>" .
4600 $skip_blank_line = 1;
4605 # print only one empty line
4606 # do not print empty line after signoff
4608 next if ($skip_blank_line);
4609 $skip_blank_line = 1;
4611 $skip_blank_line = 0;
4614 print format_log_line_html
($line) . "<br/>\n";
4617 if ($opts{'-final_empty_line'}) {
4618 # end with single empty line
4619 print "<br/>\n" unless $skip_blank_line;
4623 # return link target (what link points to)
4624 sub git_get_link_target
{
4629 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
4633 $link_target = <$fd>;
4638 return $link_target;
4641 # given link target, and the directory (basedir) the link is in,
4642 # return target of link relative to top directory (top tree);
4643 # return undef if it is not possible (including absolute links).
4644 sub normalize_link_target
{
4645 my ($link_target, $basedir) = @_;
4647 # absolute symlinks (beginning with '/') cannot be normalized
4648 return if (substr($link_target, 0, 1) eq '/');
4650 # normalize link target to path from top (root) tree (dir)
4653 $path = $basedir . '/' . $link_target;
4655 # we are in top (root) tree (dir)
4656 $path = $link_target;
4659 # remove //, /./, and /../
4661 foreach my $part (split('/', $path)) {
4662 # discard '.' and ''
4663 next if (!$part || $part eq '.');
4665 if ($part eq '..') {
4669 # link leads outside repository (outside top dir)
4673 push @path_parts, $part;
4676 $path = join('/', @path_parts);
4681 # print tree entry (row of git_tree), but without encompassing <tr> element
4682 sub git_print_tree_entry
{
4683 my ($t, $basedir, $hash_base, $have_blame) = @_;
4686 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4688 # The format of a table row is: mode list link. Where mode is
4689 # the mode of the entry, list is the name of the entry, an href,
4690 # and link is the action links of the entry.
4692 print "<td class=\"mode\">" . mode_str
($t->{'mode'}) . "</td>\n";
4693 if (exists $t->{'size'}) {
4694 print "<td class=\"size\">$t->{'size'}</td>\n";
4696 if ($t->{'type'} eq "blob") {
4697 print "<td class=\"list\">" .
4698 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4699 file_name
=>"$basedir$t->{'name'}", %base_key),
4700 -class => "list"}, esc_path
($t->{'name'}));
4701 if (S_ISLNK
(oct $t->{'mode'})) {
4702 my $link_target = git_get_link_target
($t->{'hash'});
4704 my $norm_target = normalize_link_target
($link_target, $basedir);
4705 if (defined $norm_target) {
4707 $cgi->a({-href
=> href
(action
=>"object", hash_base
=>$hash_base,
4708 file_name
=>$norm_target),
4709 -title
=> $norm_target}, esc_path
($link_target));
4711 print " -> " . esc_path
($link_target);
4716 print "<td class=\"link\">";
4717 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4718 file_name
=>"$basedir$t->{'name'}", %base_key)},
4722 $cgi->a({-href
=> href
(action
=>"blame", hash
=>$t->{'hash'},
4723 file_name
=>"$basedir$t->{'name'}", %base_key)},
4726 if (defined $hash_base) {
4728 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4729 hash
=>$t->{'hash'}, file_name
=>"$basedir$t->{'name'}")},
4733 $cgi->a({-href
=> href
(action
=>"blob_plain", hash_base
=>$hash_base,
4734 file_name
=>"$basedir$t->{'name'}")},
4738 } elsif ($t->{'type'} eq "tree") {
4739 print "<td class=\"list\">";
4740 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4741 file_name
=>"$basedir$t->{'name'}",
4743 esc_path
($t->{'name'}));
4745 print "<td class=\"link\">";
4746 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4747 file_name
=>"$basedir$t->{'name'}",
4750 if (defined $hash_base) {
4752 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4753 file_name
=>"$basedir$t->{'name'}")},
4758 # unknown object: we can only present history for it
4759 # (this includes 'commit' object, i.e. submodule support)
4760 print "<td class=\"list\">" .
4761 esc_path
($t->{'name'}) .
4763 print "<td class=\"link\">";
4764 if (defined $hash_base) {
4765 print $cgi->a({-href
=> href
(action
=>"history",
4766 hash_base
=>$hash_base,
4767 file_name
=>"$basedir$t->{'name'}")},
4774 ## ......................................................................
4775 ## functions printing large fragments of HTML
4777 # get pre-image filenames for merge (combined) diff
4778 sub fill_from_file_info
{
4779 my ($diff, @parents) = @_;
4781 $diff->{'from_file'} = [ ];
4782 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4783 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4784 if ($diff->{'status'}[$i] eq 'R' ||
4785 $diff->{'status'}[$i] eq 'C') {
4786 $diff->{'from_file'}[$i] =
4787 git_get_path_by_hash
($parents[$i], $diff->{'from_id'}[$i]);
4794 # is current raw difftree line of file deletion
4796 my $diffinfo = shift;
4798 return $diffinfo->{'to_id'} eq ('0' x
40);
4801 # does patch correspond to [previous] difftree raw line
4802 # $diffinfo - hashref of parsed raw diff format
4803 # $patchinfo - hashref of parsed patch diff format
4804 # (the same keys as in $diffinfo)
4805 sub is_patch_split
{
4806 my ($diffinfo, $patchinfo) = @_;
4808 return defined $diffinfo && defined $patchinfo
4809 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4813 sub git_difftree_body
{
4814 my ($difftree, $hash, @parents) = @_;
4815 my ($parent) = $parents[0];
4816 my $have_blame = gitweb_check_feature
('blame');
4817 print "<div class=\"list_head\">\n";
4818 if ($#{$difftree} > 10) {
4819 print(($#{$difftree} + 1) . " files changed:\n");
4823 print "<table class=\"" .
4824 (@parents > 1 ?
"combined " : "") .
4827 # header only for combined diff in 'commitdiff' view
4828 my $has_header = @
$difftree && @parents > 1 && $action eq 'commitdiff';
4831 print "<thead><tr>\n" .
4832 "<th></th><th></th>\n"; # filename, patchN link
4833 for (my $i = 0; $i < @parents; $i++) {
4834 my $par = $parents[$i];
4836 $cgi->a({-href
=> href
(action
=>"commitdiff",
4837 hash
=>$hash, hash_parent
=>$par),
4838 -title
=> 'commitdiff to parent number ' .
4839 ($i+1) . ': ' . substr($par,0,7)},
4843 print "</tr></thead>\n<tbody>\n";
4848 foreach my $line (@
{$difftree}) {
4849 my $diff = parsed_difftree_line
($line);
4852 print "<tr class=\"dark\">\n";
4854 print "<tr class=\"light\">\n";
4858 if (exists $diff->{'nparents'}) { # combined diff
4860 fill_from_file_info
($diff, @parents)
4861 unless exists $diff->{'from_file'};
4863 if (!is_deleted
($diff)) {
4864 # file exists in the result (child) commit
4866 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4867 file_name
=>$diff->{'to_file'},
4869 -class => "list"}, esc_path
($diff->{'to_file'})) .
4873 esc_path
($diff->{'to_file'}) .
4877 if ($action eq 'commitdiff') {
4880 print "<td class=\"link\">" .
4881 $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4887 my $has_history = 0;
4888 my $not_deleted = 0;
4889 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4890 my $hash_parent = $parents[$i];
4891 my $from_hash = $diff->{'from_id'}[$i];
4892 my $from_path = $diff->{'from_file'}[$i];
4893 my $status = $diff->{'status'}[$i];
4895 $has_history ||= ($status ne 'A');
4896 $not_deleted ||= ($status ne 'D');
4898 if ($status eq 'A') {
4899 print "<td class=\"link\" align=\"right\"> | </td>\n";
4900 } elsif ($status eq 'D') {
4901 print "<td class=\"link\">" .
4902 $cgi->a({-href
=> href
(action
=>"blob",
4905 file_name
=>$from_path)},
4909 if ($diff->{'to_id'} eq $from_hash) {
4910 print "<td class=\"link nochange\">";
4912 print "<td class=\"link\">";
4914 print $cgi->a({-href
=> href
(action
=>"blobdiff",
4915 hash
=>$diff->{'to_id'},
4916 hash_parent
=>$from_hash,
4918 hash_parent_base
=>$hash_parent,
4919 file_name
=>$diff->{'to_file'},
4920 file_parent
=>$from_path)},
4926 print "<td class=\"link\">";
4928 print $cgi->a({-href
=> href
(action
=>"blob",
4929 hash
=>$diff->{'to_id'},
4930 file_name
=>$diff->{'to_file'},
4933 print " | " if ($has_history);
4936 print $cgi->a({-href
=> href
(action
=>"history",
4937 file_name
=>$diff->{'to_file'},
4944 next; # instead of 'else' clause, to avoid extra indent
4946 # else ordinary diff
4948 my ($to_mode_oct, $to_mode_str, $to_file_type);
4949 my ($from_mode_oct, $from_mode_str, $from_file_type);
4950 if ($diff->{'to_mode'} ne ('0' x
6)) {
4951 $to_mode_oct = oct $diff->{'to_mode'};
4952 if (S_ISREG
($to_mode_oct)) { # only for regular file
4953 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4955 $to_file_type = file_type
($diff->{'to_mode'});
4957 if ($diff->{'from_mode'} ne ('0' x
6)) {
4958 $from_mode_oct = oct $diff->{'from_mode'};
4959 if (S_ISREG
($from_mode_oct)) { # only for regular file
4960 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4962 $from_file_type = file_type
($diff->{'from_mode'});
4965 if ($diff->{'status'} eq "A") { # created
4966 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4967 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4968 $mode_chng .= "]</span>";
4970 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4971 hash_base
=>$hash, file_name
=>$diff->{'file'}),
4972 -class => "list"}, esc_path
($diff->{'file'}));
4974 print "<td>$mode_chng</td>\n";
4975 print "<td class=\"link\">";
4976 if ($action eq 'commitdiff') {
4979 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4983 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4984 hash_base
=>$hash, file_name
=>$diff->{'file'})},
4988 } elsif ($diff->{'status'} eq "D") { # deleted
4989 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4991 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
4992 hash_base
=>$parent, file_name
=>$diff->{'file'}),
4993 -class => "list"}, esc_path
($diff->{'file'}));
4995 print "<td>$mode_chng</td>\n";
4996 print "<td class=\"link\">";
4997 if ($action eq 'commitdiff') {
5000 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5004 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
5005 hash_base
=>$parent, file_name
=>$diff->{'file'})},
5008 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$parent,
5009 file_name
=>$diff->{'file'})},
5012 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$parent,
5013 file_name
=>$diff->{'file'})},
5017 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5018 my $mode_chnge = "";
5019 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5020 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5021 if ($from_file_type ne $to_file_type) {
5022 $mode_chnge .= " from $from_file_type to $to_file_type";
5024 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5025 if ($from_mode_str && $to_mode_str) {
5026 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5027 } elsif ($to_mode_str) {
5028 $mode_chnge .= " mode: $to_mode_str";
5031 $mode_chnge .= "]</span>\n";
5034 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5035 hash_base
=>$hash, file_name
=>$diff->{'file'}),
5036 -class => "list"}, esc_path
($diff->{'file'}));
5038 print "<td>$mode_chnge</td>\n";
5039 print "<td class=\"link\">";
5040 if ($action eq 'commitdiff') {
5043 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5046 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5047 # "commit" view and modified file (not onlu mode changed)
5048 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5049 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5050 hash_base
=>$hash, hash_parent_base
=>$parent,
5051 file_name
=>$diff->{'file'})},
5055 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5056 hash_base
=>$hash, file_name
=>$diff->{'file'})},
5059 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5060 file_name
=>$diff->{'file'})},
5063 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5064 file_name
=>$diff->{'file'})},
5068 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5069 my %status_name = ('R' => 'moved', 'C' => 'copied');
5070 my $nstatus = $status_name{$diff->{'status'}};
5072 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5073 # mode also for directories, so we cannot use $to_mode_str
5074 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5077 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$hash,
5078 hash
=>$diff->{'to_id'}, file_name
=>$diff->{'to_file'}),
5079 -class => "list"}, esc_path
($diff->{'to_file'})) . "</td>\n" .
5080 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5081 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$parent,
5082 hash
=>$diff->{'from_id'}, file_name
=>$diff->{'from_file'}),
5083 -class => "list"}, esc_path
($diff->{'from_file'})) .
5084 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5085 "<td class=\"link\">";
5086 if ($action eq 'commitdiff') {
5089 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5092 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5093 # "commit" view and modified file (not only pure rename or copy)
5094 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5095 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5096 hash_base
=>$hash, hash_parent_base
=>$parent,
5097 file_name
=>$diff->{'to_file'}, file_parent
=>$diff->{'from_file'})},
5101 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5102 hash_base
=>$parent, file_name
=>$diff->{'to_file'})},
5105 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5106 file_name
=>$diff->{'to_file'})},
5109 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5110 file_name
=>$diff->{'to_file'})},
5114 } # we should not encounter Unmerged (U) or Unknown (X) status
5117 print "</tbody>" if $has_header;
5121 # Print context lines and then rem/add lines in a side-by-side manner.
5122 sub print_sidebyside_diff_lines
{
5123 my ($ctx, $rem, $add) = @_;
5125 # print context block before add/rem block
5128 '<div class="chunk_block ctx">',
5129 '<div class="old">',
5132 '<div class="new">',
5141 '<div class="chunk_block rem">',
5142 '<div class="old">',
5149 '<div class="chunk_block add">',
5150 '<div class="new">',
5156 '<div class="chunk_block chg">',
5157 '<div class="old">',
5160 '<div class="new">',
5167 # Print context lines and then rem/add lines in inline manner.
5168 sub print_inline_diff_lines
{
5169 my ($ctx, $rem, $add) = @_;
5171 print @
$ctx, @
$rem, @
$add;
5174 # Format removed and added line, mark changed part and HTML-format them.
5175 # Implementation is based on contrib/diff-highlight
5176 sub format_rem_add_lines_pair
{
5177 my ($rem, $add, $num_parents) = @_;
5179 # We need to untabify lines before split()'ing them;
5180 # otherwise offsets would be invalid.
5183 $rem = untabify
($rem);
5184 $add = untabify
($add);
5186 my @rem = split(//, $rem);
5187 my @add = split(//, $add);
5188 my ($esc_rem, $esc_add);
5189 # Ignore leading +/- characters for each parent.
5190 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5191 my ($prefix_has_nonspace, $suffix_has_nonspace);
5193 my $shorter = (@rem < @add) ?
@rem : @add;
5194 while ($prefix_len < $shorter) {
5195 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5197 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5201 while ($prefix_len + $suffix_len < $shorter) {
5202 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5204 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5208 # Mark lines that are different from each other, but have some common
5209 # part that isn't whitespace. If lines are completely different, don't
5210 # mark them because that would make output unreadable, especially if
5211 # diff consists of multiple lines.
5212 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5213 $esc_rem = esc_html_hl_regions
($rem, 'marked',
5214 [$prefix_len, @rem - $suffix_len], -nbsp
=>1);
5215 $esc_add = esc_html_hl_regions
($add, 'marked',
5216 [$prefix_len, @add - $suffix_len], -nbsp
=>1);
5218 $esc_rem = esc_html
($rem, -nbsp
=>1);
5219 $esc_add = esc_html
($add, -nbsp
=>1);
5222 return format_diff_line
(\
$esc_rem, 'rem'),
5223 format_diff_line
(\
$esc_add, 'add');
5226 # HTML-format diff context, removed and added lines.
5227 sub format_ctx_rem_add_lines
{
5228 my ($ctx, $rem, $add, $num_parents) = @_;
5229 my (@new_ctx, @new_rem, @new_add);
5230 my $can_highlight = 0;
5231 my $is_combined = ($num_parents > 1);
5233 # Highlight if every removed line has a corresponding added line.
5234 if (@
$add > 0 && @
$add == @
$rem) {
5237 # Highlight lines in combined diff only if the chunk contains
5238 # diff between the same version, e.g.
5245 # Otherwise the highlightling would be confusing.
5247 for (my $i = 0; $i < @
$add; $i++) {
5248 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5249 my $prefix_add = substr($add->[$i], 0, $num_parents);
5251 $prefix_rem =~ s/-/+/g;
5253 if ($prefix_rem ne $prefix_add) {
5261 if ($can_highlight) {
5262 for (my $i = 0; $i < @
$add; $i++) {
5263 my ($line_rem, $line_add) = format_rem_add_lines_pair
(
5264 $rem->[$i], $add->[$i], $num_parents);
5265 push @new_rem, $line_rem;
5266 push @new_add, $line_add;
5269 @new_rem = map { format_diff_line
($_, 'rem') } @
$rem;
5270 @new_add = map { format_diff_line
($_, 'add') } @
$add;
5273 @new_ctx = map { format_diff_line
($_, 'ctx') } @
$ctx;
5275 return (\
@new_ctx, \
@new_rem, \
@new_add);
5278 # Print context lines and then rem/add lines.
5279 sub print_diff_lines
{
5280 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5281 my $is_combined = $num_parents > 1;
5283 ($ctx, $rem, $add) = format_ctx_rem_add_lines
($ctx, $rem, $add,
5286 if ($diff_style eq 'sidebyside' && !$is_combined) {
5287 print_sidebyside_diff_lines
($ctx, $rem, $add);
5289 # default 'inline' style and unknown styles
5290 print_inline_diff_lines
($ctx, $rem, $add);
5294 sub print_diff_chunk
{
5295 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5296 my (@ctx, @rem, @add);
5298 # The class of the previous line.
5299 my $prev_class = '';
5301 return unless @chunk;
5303 # incomplete last line might be among removed or added lines,
5304 # or both, or among context lines: find which
5305 for (my $i = 1; $i < @chunk; $i++) {
5306 if ($chunk[$i][0] eq 'incomplete') {
5307 $chunk[$i][0] = $chunk[$i-1][0];
5312 push @chunk, ["", ""];
5314 foreach my $line_info (@chunk) {
5315 my ($class, $line) = @
$line_info;
5317 # print chunk headers
5318 if ($class && $class eq 'chunk_header') {
5319 print format_diff_line
($line, $class, $from, $to);
5323 ## print from accumulator when have some add/rem lines or end
5324 # of chunk (flush context lines), or when have add and rem
5325 # lines and new block is reached (otherwise add/rem lines could
5327 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5328 (@rem && @add && $class ne $prev_class)) {
5329 print_diff_lines
(\
@ctx, \
@rem, \
@add,
5330 $diff_style, $num_parents);
5331 @ctx = @rem = @add = ();
5334 ## adding lines to accumulator
5337 # rem, add or change
5338 if ($class eq 'rem') {
5340 } elsif ($class eq 'add') {
5344 if ($class eq 'ctx') {
5348 $prev_class = $class;
5352 sub git_patchset_body
{
5353 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5354 my ($hash_parent) = $hash_parents[0];
5356 my $is_combined = (@hash_parents > 1);
5358 my $patch_number = 0;
5363 my @chunk; # for side-by-side diff
5365 print "<div class=\"patchset\">\n";
5367 # skip to first patch
5368 while ($patch_line = <$fd>) {
5371 last if ($patch_line =~ m/^diff /);
5375 while ($patch_line) {
5377 # parse "git diff" header line
5378 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5379 # $1 is from_name, which we do not use
5380 $to_name = unquote
($2);
5381 $to_name =~ s!^b/!!;
5382 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5383 # $1 is 'cc' or 'combined', which we do not use
5384 $to_name = unquote
($2);
5389 # check if current patch belong to current raw line
5390 # and parse raw git-diff line if needed
5391 if (is_patch_split
($diffinfo, { 'to_file' => $to_name })) {
5392 # this is continuation of a split patch
5393 print "<div class=\"patch cont\">\n";
5395 # advance raw git-diff output if needed
5396 $patch_idx++ if defined $diffinfo;
5398 # read and prepare patch information
5399 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5401 # compact combined diff output can have some patches skipped
5402 # find which patch (using pathname of result) we are at now;
5404 while ($to_name ne $diffinfo->{'to_file'}) {
5405 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5406 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5407 "</div>\n"; # class="patch"
5412 last if $patch_idx > $#$difftree;
5413 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5417 # modifies %from, %to hashes
5418 parse_from_to_diffinfo
($diffinfo, \
%from, \
%to, @hash_parents);
5420 # this is first patch for raw difftree line with $patch_idx index
5421 # we index @$difftree array from 0, but number patches from 1
5422 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5426 #assert($patch_line =~ m/^diff /) if DEBUG;
5427 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5429 # print "git diff" header
5430 print format_git_diff_header_line
($patch_line, $diffinfo,
5433 # print extended diff header
5434 print "<div class=\"diff extended_header\">\n";
5436 while ($patch_line = <$fd>) {
5439 last EXTENDED_HEADER
if ($patch_line =~ m/^--- |^diff /);
5441 print format_extended_diff_header_line
($patch_line, $diffinfo,
5444 print "</div>\n"; # class="diff extended_header"
5446 # from-file/to-file diff header
5447 if (! $patch_line) {
5448 print "</div>\n"; # class="patch"
5451 next PATCH
if ($patch_line =~ m/^diff /);
5452 #assert($patch_line =~ m/^---/) if DEBUG;
5454 my $last_patch_line = $patch_line;
5455 $patch_line = <$fd>;
5457 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5459 print format_diff_from_to_header
($last_patch_line, $patch_line,
5460 $diffinfo, \
%from, \
%to,
5465 while ($patch_line = <$fd>) {
5468 next PATCH
if ($patch_line =~ m/^diff /);
5470 my $class = diff_line_class
($patch_line, \
%from, \
%to);
5472 if ($class eq 'chunk_header') {
5473 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5477 push @chunk, [ $class, $patch_line ];
5482 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5485 print "</div>\n"; # class="patch"
5488 # for compact combined (--cc) format, with chunk and patch simplification
5489 # the patchset might be empty, but there might be unprocessed raw lines
5490 for (++$patch_idx if $patch_number > 0;
5491 $patch_idx < @
$difftree;
5493 # read and prepare patch information
5494 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5496 # generate anchor for "patch" links in difftree / whatchanged part
5497 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5498 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5499 "</div>\n"; # class="patch"
5504 if ($patch_number == 0) {
5505 if (@hash_parents > 1) {
5506 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5508 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5512 print "</div>\n"; # class="patchset"
5515 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5517 sub git_project_search_form
{
5518 my ($searchtext, $search_use_regexp) = @_;
5521 if ($project_filter) {
5522 $limit = " in '$project_filter/'";
5525 print "<div class=\"projsearch\">\n";
5526 print $cgi->start_form(-method
=> 'get', -action
=> $my_uri) .
5527 $cgi->hidden(-name
=> 'a', -value
=> 'project_list') . "\n";
5528 print $cgi->hidden(-name
=> 'pf', -value
=> $project_filter). "\n"
5529 if (defined $project_filter);
5530 print $cgi->textfield(-name
=> 's', -value
=> $searchtext,
5531 -title
=> "Search project by name and description$limit",
5532 -size
=> 60) . "\n" .
5533 "<span title=\"Extended regular expression\">" .
5534 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
5535 -checked
=> $search_use_regexp) .
5537 $cgi->submit(-name
=> 'btnS', -value
=> 'Search') .
5538 $cgi->end_form() . "\n" .
5539 $cgi->a({-href
=> href
(project
=> undef, searchtext
=> undef,
5540 project_filter
=> $project_filter)},
5541 esc_html
("List all projects$limit")) . "<br />\n";
5545 # entry for given @keys needs filling if at least one of keys in list
5546 # is not present in %$project_info
5547 sub project_info_needs_filling
{
5548 my ($project_info, @keys) = @_;
5550 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5551 foreach my $key (@keys) {
5552 if (!exists $project_info->{$key}) {
5559 # fills project list info (age, description, owner, category, forks, etc.)
5560 # for each project in the list, removing invalid projects from
5561 # returned list, or fill only specified info.
5563 # Invalid projects are removed from the returned list if and only if you
5564 # ask 'age' or 'age_string' to be filled, because they are the only fields
5565 # that run unconditionally git command that requires repository, and
5566 # therefore do always check if project repository is invalid.
5569 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5570 # ensures that 'descr_long' and 'ctags' fields are filled
5571 # * @project_list = fill_project_list_info(\@project_list)
5572 # ensures that all fields are filled (and invalid projects removed)
5574 # NOTE: modifies $projlist, but does not remove entries from it
5575 sub fill_project_list_info
{
5576 my ($projlist, @wanted_keys) = @_;
5578 my $filter_set = sub { return @_; };
5580 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5581 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5584 my $show_ctags = gitweb_check_feature
('ctags');
5586 foreach my $pr (@
$projlist) {
5587 if (project_info_needs_filling
($pr, $filter_set->('age', 'age_string'))) {
5588 my (@activity) = git_get_last_activity
($pr->{'path'});
5589 unless (@activity) {
5592 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5594 if (project_info_needs_filling
($pr, $filter_set->('descr', 'descr_long'))) {
5595 my $descr = git_get_project_description
($pr->{'path'}) || "";
5596 $descr = to_utf8
($descr);
5597 $pr->{'descr_long'} = $descr;
5598 $pr->{'descr'} = chop_str
($descr, $projects_list_description_width, 5);
5600 if (project_info_needs_filling
($pr, $filter_set->('owner'))) {
5601 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}") || "";
5604 project_info_needs_filling
($pr, $filter_set->('ctags'))) {
5605 $pr->{'ctags'} = git_get_project_ctags
($pr->{'path'});
5607 if ($projects_list_group_categories &&
5608 project_info_needs_filling
($pr, $filter_set->('category'))) {
5609 my $cat = git_get_project_category
($pr->{'path'}) ||
5610 $project_list_default_category;
5611 $pr->{'category'} = to_utf8
($cat);
5614 push @projects, $pr;
5620 sub sort_projects_list
{
5621 my ($projlist, $order) = @_;
5625 return sub { $a->{$key} cmp $b->{$key} };
5628 sub order_num_then_undef
{
5631 defined $a->{$key} ?
5632 (defined $b->{$key} ?
$a->{$key} <=> $b->{$key} : -1) :
5633 (defined $b->{$key} ?
1 : 0)
5638 project
=> order_str
('path'),
5639 descr
=> order_str
('descr_long'),
5640 owner
=> order_str
('owner'),
5641 age
=> order_num_then_undef
('age'),
5644 my $ordering = $orderings{$order};
5645 return defined $ordering ?
sort $ordering @
$projlist : @
$projlist;
5648 # returns a hash of categories, containing the list of project
5649 # belonging to each category
5650 sub build_projlist_by_category
{
5651 my ($projlist, $from, $to) = @_;
5654 $from = 0 unless defined $from;
5655 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5657 for (my $i = $from; $i <= $to; $i++) {
5658 my $pr = $projlist->[$i];
5659 push @
{$categories{ $pr->{'category'} }}, $pr;
5662 return wantarray ?
%categories : \
%categories;
5665 # print 'sort by' <th> element, generating 'sort by $name' replay link
5666 # if that order is not selected
5668 print format_sort_th
(@_);
5671 sub format_sort_th
{
5672 my ($name, $order, $header) = @_;
5674 $header ||= ucfirst($name);
5676 if ($order eq $name) {
5677 $sort_th .= "<th>$header</th>\n";
5679 $sort_th .= "<th>" .
5680 $cgi->a({-href
=> href
(-replay
=>1, order
=>$name),
5681 -class => "header"}, $header) .
5688 sub git_project_list_rows
{
5689 my ($projlist, $from, $to, $check_forks) = @_;
5691 $from = 0 unless defined $from;
5692 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5695 for (my $i = $from; $i <= $to; $i++) {
5696 my $pr = $projlist->[$i];
5699 print "<tr class=\"dark\">\n";
5701 print "<tr class=\"light\">\n";
5707 if ($pr->{'forks'}) {
5708 my $nforks = scalar @
{$pr->{'forks'}};
5710 print $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks"),
5711 -title
=> "$nforks forks"}, "+");
5713 print $cgi->span({-title
=> "$nforks forks"}, "+");
5718 print "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5720 esc_html_match_hl
($pr->{'path'}, $search_regexp)) .
5722 "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5724 -title
=> $pr->{'descr_long'}},
5726 ? esc_html_match_hl_chopped
($pr->{'descr_long'},
5727 $pr->{'descr'}, $search_regexp)
5728 : esc_html
($pr->{'descr'})) .
5730 unless ($omit_owner) {
5731 print "<td><i>" . chop_and_escape_str
($pr->{'owner'}, 15) . "</i></td>\n";
5733 unless ($omit_age_column) {
5734 print "<td class=\"". age_class
($pr->{'age'}) . "\">" .
5735 (defined $pr->{'age_string'} ?
$pr->{'age_string'} : "No commits") . "</td>\n";
5737 print"<td class=\"link\">" .
5738 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary")}, "summary") . " | " .
5739 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"shortlog")}, "shortlog") . " | " .
5740 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"log")}, "log") . " | " .
5741 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"tree")}, "tree") .
5742 ($pr->{'forks'} ?
" | " . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks")}, "forks") : '') .
5748 sub git_project_list_body
{
5749 # actually uses global variable $project
5750 my ($projlist, $order, $from, $to, $extra, $no_header, $ctags_action) = @_;
5751 my @projects = @
$projlist;
5753 my $check_forks = gitweb_check_feature
('forks');
5754 my $show_ctags = gitweb_check_feature
('ctags');
5755 my $tagfilter = $show_ctags ?
$input_params{'ctag_filter'} : undef;
5756 $check_forks = undef
5757 if ($tagfilter || $search_regexp);
5759 # filtering out forks before filling info allows to do less work
5760 @projects = filter_forks_from_projects_list
(\
@projects)
5762 # search_projects_list pre-fills required info
5763 @projects = search_projects_list
(\
@projects,
5764 'search_regexp' => $search_regexp,
5765 'tagfilter' => $tagfilter)
5766 if ($tagfilter || $search_regexp);
5768 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5769 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5770 push @all_fields, 'owner' unless($omit_owner);
5771 @projects = fill_project_list_info
(\
@projects, @all_fields);
5773 $order ||= $default_projects_order;
5774 $from = 0 unless defined $from;
5775 $to = $#projects if (!defined $to || $#projects < $to);
5780 "<b>No such projects found</b><br />\n".
5781 "Click ".$cgi->a({-href
=>href
(project
=>undef)},"here")." to view all projects<br />\n".
5782 "</center>\n<br />\n";
5786 @projects = sort_projects_list
(\
@projects, $order);
5789 my $ctags = git_gather_all_ctags
(\
@projects);
5790 my $cloud = git_populate_project_tagcloud
($ctags, $ctags_action||'project_list');
5791 print git_show_project_tagcloud
($cloud, 64);
5794 print "<table class=\"project_list\">\n";
5795 unless ($no_header) {
5798 print "<th></th>\n";
5800 print_sort_th
('project', $order, 'Project');
5801 print_sort_th
('descr', $order, 'Description');
5802 print_sort_th
('owner', $order, 'Owner') unless $omit_owner;
5803 print_sort_th
('age', $order, 'Last Change') unless $omit_age_column;
5804 print "<th></th>\n" . # for links
5808 if ($projects_list_group_categories) {
5809 # only display categories with projects in the $from-$to window
5810 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5811 my %categories = build_projlist_by_category
(\
@projects, $from, $to);
5812 foreach my $cat (sort keys %categories) {
5813 unless ($cat eq "") {
5816 print "<td></td>\n";
5818 print "<td class=\"category\" colspan=\"5\">".esc_html
($cat)."</td>\n";
5822 git_project_list_rows
($categories{$cat}, undef, undef, $check_forks);
5825 git_project_list_rows
(\
@projects, $from, $to, $check_forks);
5828 if (defined $extra) {
5831 print "<td></td>\n";
5833 print "<td colspan=\"5\">$extra</td>\n" .
5840 # uses global variable $project
5841 my ($commitlist, $from, $to, $refs, $extra) = @_;
5843 $from = 0 unless defined $from;
5844 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5846 for (my $i = 0; $i <= $to; $i++) {
5847 my %co = %{$commitlist->[$i]};
5849 my $commit = $co{'id'};
5850 my $ref = format_ref_marker
($refs, $commit);
5851 git_print_header_div
('commit',
5852 "<span class=\"age\">$co{'age_string'}</span>" .
5853 esc_html
($co{'title'}) . $ref,
5855 print "<div class=\"title_text\">\n" .
5856 "<div class=\"log_link\">\n" .
5857 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") .
5859 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") .
5861 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree") .
5864 git_print_authorship
(\
%co, -tag
=> 'span');
5865 print "<br/>\n</div>\n";
5867 print "<div class=\"log_body\">\n";
5868 git_print_log
($co{'comment'}, -final_empty_line
=> 1);
5872 print "<div class=\"page_nav\">\n";
5878 sub git_shortlog_body
{
5879 # uses global variable $project
5880 my ($commitlist, $from, $to, $refs, $extra) = @_;
5882 $from = 0 unless defined $from;
5883 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5885 print "<table class=\"shortlog\">\n";
5887 for (my $i = $from; $i <= $to; $i++) {
5888 my %co = %{$commitlist->[$i]};
5889 my $commit = $co{'id'};
5890 my $ref = format_ref_marker
($refs, $commit);
5892 print "<tr class=\"dark\">\n";
5894 print "<tr class=\"light\">\n";
5897 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5898 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5899 format_author_html
('td', \
%co, 10) . "<td>";
5900 print format_subject_html
($co{'title'}, $co{'title_short'},
5901 href
(action
=>"commit", hash
=>$commit), $ref);
5903 "<td class=\"link\">" .
5904 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") . " | " .
5905 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") . " | " .
5906 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree");
5907 my $snapshot_links = format_snapshot_links
($commit);
5908 if (defined $snapshot_links) {
5909 print " | " . $snapshot_links;
5914 if (defined $extra) {
5916 "<td colspan=\"4\">$extra</td>\n" .
5922 sub git_history_body
{
5923 # Warning: assumes constant type (blob or tree) during history
5924 my ($commitlist, $from, $to, $refs, $extra,
5925 $file_name, $file_hash, $ftype) = @_;
5927 $from = 0 unless defined $from;
5928 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5930 print "<table class=\"history\">\n";
5932 for (my $i = $from; $i <= $to; $i++) {
5933 my %co = %{$commitlist->[$i]};
5937 my $commit = $co{'id'};
5939 my $ref = format_ref_marker
($refs, $commit);
5942 print "<tr class=\"dark\">\n";
5944 print "<tr class=\"light\">\n";
5947 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5948 # shortlog: format_author_html('td', \%co, 10)
5949 format_author_html
('td', \
%co, 15, 3) . "<td>";
5950 # originally git_history used chop_str($co{'title'}, 50)
5951 print format_subject_html
($co{'title'}, $co{'title_short'},
5952 href
(action
=>"commit", hash
=>$commit), $ref);
5954 "<td class=\"link\">" .
5955 $cgi->a({-href
=> href
(action
=>$ftype, hash_base
=>$commit, file_name
=>$file_name)}, $ftype) . " | " .
5956 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff");
5958 if ($ftype eq 'blob') {
5959 my $blob_current = $file_hash;
5960 my $blob_parent = git_get_hash_by_path
($commit, $file_name);
5961 if (defined $blob_current && defined $blob_parent &&
5962 $blob_current ne $blob_parent) {
5964 $cgi->a({-href
=> href
(action
=>"blobdiff",
5965 hash
=>$blob_current, hash_parent
=>$blob_parent,
5966 hash_base
=>$hash_base, hash_parent_base
=>$commit,
5967 file_name
=>$file_name)},
5974 if (defined $extra) {
5976 "<td colspan=\"4\">$extra</td>\n" .
5983 # uses global variable $project
5984 my ($taglist, $from, $to, $extra) = @_;
5985 $from = 0 unless defined $from;
5986 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5988 print "<table class=\"tags\">\n";
5990 for (my $i = $from; $i <= $to; $i++) {
5991 my $entry = $taglist->[$i];
5993 my $comment = $tag{'subject'};
5995 if (defined $comment) {
5996 $comment_short = chop_str
($comment, 30, 5);
5999 print "<tr class=\"dark\">\n";
6001 print "<tr class=\"light\">\n";
6004 if (defined $tag{'age'}) {
6005 print "<td><i>$tag{'age'}</i></td>\n";
6007 print "<td></td>\n";
6010 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'}),
6011 -class => "list name"}, esc_html
($tag{'name'})) .
6014 if (defined $comment) {
6015 print format_subject_html
($comment, $comment_short,
6016 href
(action
=>"tag", hash
=>$tag{'id'}));
6019 "<td class=\"selflink\">";
6020 if ($tag{'type'} eq "tag") {
6021 print $cgi->a({-href
=> href
(action
=>"tag", hash
=>$tag{'id'})}, "tag");
6026 "<td class=\"link\">" . " | " .
6027 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'})}, $tag{'reftype'});
6028 if ($tag{'reftype'} eq "commit") {
6029 print " | " . $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$tag{'fullname'})}, "shortlog") .
6030 " | " . $cgi->a({-href
=> href
(action
=>"log", hash
=>$tag{'fullname'})}, "log");
6031 } elsif ($tag{'reftype'} eq "blob") {
6032 print " | " . $cgi->a({-href
=> href
(action
=>"blob_plain", hash
=>$tag{'refid'})}, "raw");
6037 if (defined $extra) {
6039 "<td colspan=\"5\">$extra</td>\n" .
6045 sub git_heads_body
{
6046 # uses global variable $project
6047 my ($headlist, $head_at, $from, $to, $extra) = @_;
6048 $from = 0 unless defined $from;
6049 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6051 print "<table class=\"heads\">\n";
6053 for (my $i = $from; $i <= $to; $i++) {
6054 my $entry = $headlist->[$i];
6056 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6058 print "<tr class=\"dark\">\n";
6060 print "<tr class=\"light\">\n";
6063 print "<td><i>$ref{'age'}</i></td>\n" .
6064 ($curr ?
"<td class=\"current_head\">" : "<td>") .
6065 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'}),
6066 -class => "list name"},esc_html
($ref{'name'})) .
6068 "<td class=\"link\">" .
6069 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'})}, "shortlog") . " | " .
6070 $cgi->a({-href
=> href
(action
=>"log", hash
=>$ref{'fullname'})}, "log") . " | " .
6071 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$ref{'fullname'}, hash_base
=>$ref{'fullname'})}, "tree") .
6075 if (defined $extra) {
6077 "<td colspan=\"3\">$extra</td>\n" .
6083 # Display a single remote block
6084 sub git_remote_block
{
6085 my ($remote, $rdata, $limit, $head) = @_;
6087 my $heads = $rdata->{'heads'};
6088 my $fetch = $rdata->{'fetch'};
6089 my $push = $rdata->{'push'};
6091 my $urls_table = "<table class=\"projects_list\">\n" ;
6093 if (defined $fetch) {
6094 if ($fetch eq $push) {
6095 $urls_table .= format_repo_url
("URL", $fetch);
6097 $urls_table .= format_repo_url
("Fetch URL", $fetch);
6098 $urls_table .= format_repo_url
("Push URL", $push) if defined $push;
6100 } elsif (defined $push) {
6101 $urls_table .= format_repo_url
("Push URL", $push);
6103 $urls_table .= format_repo_url
("", "No remote URL");
6106 $urls_table .= "</table>\n";
6109 if (defined $limit && $limit < @
$heads) {
6110 $dots = $cgi->a({-href
=> href
(action
=>"remotes", hash
=>$remote)}, "...");
6114 git_heads_body
($heads, $head, 0, $limit, $dots);
6117 # Display a list of remote names with the respective fetch and push URLs
6118 sub git_remotes_list
{
6119 my ($remotedata, $limit) = @_;
6120 print "<table class=\"heads\">\n";
6122 my @remotes = sort keys %$remotedata;
6124 my $limited = $limit && $limit < @remotes;
6126 $#remotes = $limit - 1 if $limited;
6128 while (my $remote = shift @remotes) {
6129 my $rdata = $remotedata->{$remote};
6130 my $fetch = $rdata->{'fetch'};
6131 my $push = $rdata->{'push'};
6133 print "<tr class=\"dark\">\n";
6135 print "<tr class=\"light\">\n";
6139 $cgi->a({-href
=> href
(action
=>'remotes', hash
=>$remote),
6140 -class=> "list name"},esc_html
($remote)) .
6142 print "<td class=\"link\">" .
6143 (defined $fetch ?
$cgi->a({-href
=> $fetch}, "fetch") : "fetch") .
6145 (defined $push ?
$cgi->a({-href
=> $push}, "push") : "push") .
6153 "<td colspan=\"3\">" .
6154 $cgi->a({-href
=> href
(action
=>"remotes")}, "...") .
6155 "</td>\n" . "</tr>\n";
6161 # Display remote heads grouped by remote, unless there are too many
6162 # remotes, in which case we only display the remote names
6163 sub git_remotes_body
{
6164 my ($remotedata, $limit, $head) = @_;
6165 if ($limit and $limit < keys %$remotedata) {
6166 git_remotes_list
($remotedata, $limit);
6168 fill_remote_heads
($remotedata);
6169 while (my ($remote, $rdata) = each %$remotedata) {
6170 git_print_section
({-class=>"remote", -id
=>$remote},
6171 ["remotes", $remote, $remote], sub {
6172 git_remote_block
($remote, $rdata, $limit, $head);
6178 sub git_search_message
{
6182 if ($searchtype eq 'commit') {
6183 $greptype = "--grep=";
6184 } elsif ($searchtype eq 'author') {
6185 $greptype = "--author=";
6186 } elsif ($searchtype eq 'committer') {
6187 $greptype = "--committer=";
6189 $greptype .= $searchtext;
6190 my @commitlist = parse_commits
($hash, 101, (100 * $page), undef,
6191 $greptype, '--regexp-ignore-case',
6192 $search_use_regexp ?
'--extended-regexp' : '--fixed-strings');
6194 my $paging_nav = '';
6197 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)},
6200 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
6201 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
6203 $paging_nav .= "first ⋅ prev";
6206 if ($#commitlist >= 100) {
6208 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
6209 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
6210 $paging_nav .= " ⋅ $next_link";
6212 $paging_nav .= " ⋅ next";
6217 git_print_page_nav
('','', $hash,$co{'tree'},$hash, $paging_nav);
6218 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6219 if ($page == 0 && !@commitlist) {
6220 print "<p>No match.</p>\n";
6222 git_search_grep_body
(\
@commitlist, 0, 99, $next_link);
6228 sub git_search_changes
{
6232 open my $fd, '-|', git_cmd
(), '--no-pager', 'log', @diff_opts,
6233 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6234 ($search_use_regexp ?
'--pickaxe-regex' : ())
6235 or die_error
(500, "Open git-log failed");
6239 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6240 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6242 print "<table class=\"pickaxe search\">\n";
6246 while (my $line = <$fd>) {
6250 my %set = parse_difftree_raw_line
($line);
6251 if (defined $set{'commit'}) {
6252 # finish previous commit
6255 "<td class=\"link\">" .
6256 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6259 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6260 hash_base
=>$co{'id'})},
6267 print "<tr class=\"dark\">\n";
6269 print "<tr class=\"light\">\n";
6272 %co = parse_commit
($set{'commit'});
6273 my $author = chop_and_escape_str
($co{'author_name'}, 15, 5);
6274 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6275 "<td><i>$author</i></td>\n" .
6277 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6278 -class => "list subject"},
6279 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6280 } elsif (defined $set{'to_id'}) {
6281 next if ($set{'to_id'} =~ m/^0{40}$/);
6283 print $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$co{'id'},
6284 hash
=>$set{'to_id'}, file_name
=>$set{'to_file'}),
6286 "<span class=\"match\">" . esc_path
($set{'file'}) . "</span>") .
6292 # finish last commit (warning: repetition!)
6295 "<td class=\"link\">" .
6296 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6299 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6300 hash_base
=>$co{'id'})},
6311 sub git_search_files
{
6315 open my $fd, "-|", git_cmd
(), 'grep', '-n', '-z',
6316 $search_use_regexp ?
('-E', '-i') : '-F',
6317 $searchtext, $co{'tree'}
6318 or die_error
(500, "Open git-grep failed");
6322 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6323 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6325 print "<table class=\"grep_search\">\n";
6330 while (my $line = <$fd>) {
6332 my ($file, $lno, $ltext, $binary);
6333 last if ($matches++ > 1000);
6334 if ($line =~ /^Binary file (.+) matches$/) {
6338 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6339 $file =~ s/^$co{'tree'}://;
6341 if ($file ne $lastfile) {
6342 $lastfile and print "</td></tr>\n";
6344 print "<tr class=\"dark\">\n";
6346 print "<tr class=\"light\">\n";
6348 $file_href = href
(action
=>"blob", hash_base
=>$co{'id'},
6350 print "<td class=\"list\">".
6351 $cgi->a({-href
=> $file_href, -class => "list"}, esc_path
($file));
6352 print "</td><td>\n";
6356 print "<div class=\"binary\">Binary file</div>\n";
6358 $ltext = untabify
($ltext);
6359 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6360 $ltext = esc_html
($1, -nbsp
=>1);
6361 $ltext .= '<span class="match">';
6362 $ltext .= esc_html
($2, -nbsp
=>1);
6363 $ltext .= '</span>';
6364 $ltext .= esc_html
($3, -nbsp
=>1);
6366 $ltext = esc_html
($ltext, -nbsp
=>1);
6368 print "<div class=\"pre\">" .
6369 $cgi->a({-href
=> $file_href.'#l'.$lno,
6370 -class => "linenr"}, sprintf('%4i', $lno)) .
6371 ' ' . $ltext . "</div>\n";
6375 print "</td></tr>\n";
6376 if ($matches > 1000) {
6377 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6380 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6389 sub git_search_grep_body
{
6390 my ($commitlist, $from, $to, $extra) = @_;
6391 $from = 0 unless defined $from;
6392 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6394 print "<table class=\"commit_search\">\n";
6396 for (my $i = $from; $i <= $to; $i++) {
6397 my %co = %{$commitlist->[$i]};
6401 my $commit = $co{'id'};
6403 print "<tr class=\"dark\">\n";
6405 print "<tr class=\"light\">\n";
6408 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6409 format_author_html
('td', \
%co, 15, 5) .
6411 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6412 -class => "list subject"},
6413 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6414 my $comment = $co{'comment'};
6415 foreach my $line (@
$comment) {
6416 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6417 my ($lead, $match, $trail) = ($1, $2, $3);
6418 $match = chop_str
($match, 70, 5, 'center');
6419 my $contextlen = int((80 - length($match))/2);
6420 $contextlen = 30 if ($contextlen > 30);
6421 $lead = chop_str
($lead, $contextlen, 10, 'left');
6422 $trail = chop_str
($trail, $contextlen, 10, 'right');
6424 $lead = esc_html
($lead);
6425 $match = esc_html
($match);
6426 $trail = esc_html
($trail);
6428 print "$lead<span class=\"match\">$match</span>$trail<br />";
6432 "<td class=\"link\">" .
6433 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})}, "commit") .
6435 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$co{'id'})}, "commitdiff") .
6437 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$co{'id'})}, "tree");
6441 if (defined $extra) {
6443 "<td colspan=\"3\">$extra</td>\n" .
6449 ## ======================================================================
6450 ## ======================================================================
6453 sub git_project_list
{
6454 my $order = $input_params{'order'};
6455 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6456 die_error
(400, "Unknown order parameter");
6459 my @list = git_get_projects_list
($project_filter, $strict_export);
6461 die_error
(404, "No projects found");
6465 if (defined $home_text && -f
$home_text) {
6466 print "<div class=\"index_include\">\n";
6467 insert_file
($home_text);
6471 git_project_search_form
($searchtext, $search_use_regexp);
6472 git_project_list_body
(\
@list, $order);
6477 my $order = $input_params{'order'};
6478 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6479 die_error
(400, "Unknown order parameter");
6482 my $filter = $project;
6483 $filter =~ s/\.git$//;
6484 my @list = git_get_projects_list
($filter);
6486 die_error
(404, "No forks found");
6490 git_print_page_nav
('','');
6491 git_print_header_div
('summary', "$project forks");
6492 git_project_list_body
(\
@list, $order, undef, undef, undef, undef, 'forks');
6496 sub git_project_index
{
6497 my @projects = git_get_projects_list
($project_filter, $strict_export);
6499 die_error
(404, "No projects found");
6503 -type
=> 'text/plain',
6504 -charset
=> 'utf-8',
6505 -content_disposition
=> 'inline; filename="index.aux"');
6507 foreach my $pr (@projects) {
6508 if (!exists $pr->{'owner'}) {
6509 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}");
6512 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6513 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6514 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6515 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6519 print "$path $owner\n";
6524 my $descr = git_get_project_description
($project) || "none";
6525 my %co = parse_commit
("HEAD");
6526 my %cd = %co ? parse_date
($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6527 my $head = $co{'id'};
6528 my $remote_heads = gitweb_check_feature
('remote_heads');
6530 my $owner = git_get_project_owner
($project);
6532 my $refs = git_get_references
();
6533 # These get_*_list functions return one more to allow us to see if
6534 # there are more ...
6535 my @taglist = git_get_tags_list
(16);
6536 my @headlist = git_get_heads_list
(16);
6537 my %remotedata = $remote_heads ? git_get_remotes_list
() : ();
6539 my $check_forks = gitweb_check_feature
('forks');
6542 # find forks of a project
6543 my $filter = $project;
6544 $filter =~ s/\.git$//;
6545 @forklist = git_get_projects_list
($filter);
6546 # filter out forks of forks
6547 @forklist = filter_forks_from_projects_list
(\
@forklist)
6552 git_print_page_nav
('summary','', $head);
6554 print "<div class=\"title\"> </div>\n";
6555 print "<table class=\"projects_list\">\n" .
6556 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html
($descr) . "</td></tr>\n";
6557 if ($owner and not $omit_owner) {
6558 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html
($owner) . "</td></tr>\n";
6560 if (defined $cd{'rfc2822'}) {
6561 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6562 "<td>".format_timestamp_html
(\
%cd)."</td></tr>\n";
6565 # use per project git URL list in $projectroot/$project/cloneurl
6566 # or make project git URL from git base URL and project name
6567 my $url_tag = "URL";
6568 my @url_list = git_get_project_url_list
($project);
6569 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6570 foreach my $git_url (@url_list) {
6571 next unless $git_url;
6572 print format_repo_url
($url_tag, $git_url);
6577 my $show_ctags = gitweb_check_feature
('ctags');
6579 my $ctags = git_get_project_ctags
($project);
6580 if (%$ctags || $show_ctags !~ /^\d+$/) {
6581 # without ability to add tags, don't show if there are none
6582 my $cloud = git_populate_project_tagcloud
($ctags, 'project_list');
6583 print "<tr id=\"metadata_ctags\">" .
6584 "<td style=\"vertical-align:middle\">content tags<br />";
6585 print "</td>\n<td>" unless %$ctags;
6586 print "<form action=\"$show_ctags\" method=\"post\">" .
6587 "<input type=\"hidden\" name=\"p\" value=\"$project\"/>" .
6588 "add: <input type=\"text\" name=\"t\" size=\"10\" /></form>"
6589 unless $show_ctags =~ /^\d+$/;
6590 print "</td>\n<td>" if %$ctags;
6591 print git_show_project_tagcloud
($cloud, 48)."</td>" .
6598 # If XSS prevention is on, we don't include README.html.
6599 # TODO: Allow a readme in some safe format.
6600 if (!$prevent_xss && -s
"$projectroot/$project/README.html") {
6601 print "<div class=\"title\">readme</div>\n" .
6602 "<div class=\"readme\">\n";
6603 insert_file
("$projectroot/$project/README.html");
6604 print "\n</div>\n"; # class="readme"
6607 # we need to request one more than 16 (0..15) to check if
6609 my @commitlist = $head ? parse_commits
($head, 17) : ();
6611 git_print_header_div
('shortlog');
6612 git_shortlog_body
(\
@commitlist, 0, 15, $refs,
6613 $#commitlist <= 15 ?
undef :
6614 $cgi->a({-href
=> href
(action
=>"shortlog")}, "..."));
6618 git_print_header_div
('tags');
6619 git_tags_body
(\
@taglist, 0, 15,
6620 $#taglist <= 15 ?
undef :
6621 $cgi->a({-href
=> href
(action
=>"tags")}, "..."));
6625 git_print_header_div
('heads');
6626 git_heads_body
(\
@headlist, $head, 0, 15,
6627 $#headlist <= 15 ?
undef :
6628 $cgi->a({-href
=> href
(action
=>"heads")}, "..."));
6632 git_print_header_div
('remotes');
6633 git_remotes_body
(\
%remotedata, 15, $head);
6637 git_print_header_div
('forks');
6638 git_project_list_body
(\
@forklist, 'age', 0, 15,
6639 $#forklist <= 15 ?
undef :
6640 $cgi->a({-href
=> href
(action
=>"forks")}, "..."),
6641 'no_header', 'forks');
6648 my %tag = parse_tag
($hash);
6651 die_error
(404, "Unknown tag object");
6654 my $head = git_get_head_hash
($project);
6656 git_print_page_nav
('','', $head,undef,$head);
6657 git_print_header_div
('commit', esc_html
($tag{'name'}), $hash);
6658 print "<div class=\"title_text\">\n" .
6659 "<table class=\"object_header\">\n" .
6661 "<td>object</td>\n" .
6662 "<td>" . $cgi->a({-class => "list", -href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6663 $tag{'object'}) . "</td>\n" .
6664 "<td class=\"link\">" . $cgi->a({-href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6665 $tag{'type'}) . "</td>\n" .
6667 if (defined($tag{'author'})) {
6668 git_print_authorship_rows
(\
%tag, 'author');
6670 print "</table>\n\n" .
6672 print "<div class=\"page_body\">";
6673 my $comment = $tag{'comment'};
6674 foreach my $line (@
$comment) {
6676 print esc_html
($line, -nbsp
=>1) . "<br/>\n";
6682 sub git_blame_common
{
6683 my $format = shift || 'porcelain';
6684 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6685 $format = 'incremental';
6686 $action = 'blame_incremental'; # for page title etc
6690 gitweb_check_feature
('blame')
6691 or die_error
(403, "Blame view not allowed");
6694 die_error
(400, "No file name given") unless $file_name;
6695 $hash_base ||= git_get_head_hash
($project);
6696 die_error
(404, "Couldn't find base commit") unless $hash_base;
6697 my %co = parse_commit
($hash_base)
6698 or die_error
(404, "Commit not found");
6700 if (!defined $hash) {
6701 $hash = git_get_hash_by_path
($hash_base, $file_name, "blob")
6702 or die_error
(404, "Error looking up file");
6704 $ftype = git_get_type
($hash);
6705 if ($ftype !~ "blob") {
6706 die_error
(400, "Object is not a blob");
6711 if ($format eq 'incremental') {
6712 # get file contents (as base)
6713 open $fd, "-|", git_cmd
(), 'cat-file', 'blob', $hash
6714 or die_error
(500, "Open git-cat-file failed");
6715 } elsif ($format eq 'data') {
6716 # run git-blame --incremental
6717 open $fd, "-|", git_cmd
(), "blame", "--incremental",
6718 $hash_base, "--", $file_name
6719 or die_error
(500, "Open git-blame --incremental failed");
6721 # run git-blame --porcelain
6722 open $fd, "-|", git_cmd
(), "blame", '-p',
6723 $hash_base, '--', $file_name
6724 or die_error
(500, "Open git-blame --porcelain failed");
6726 binmode $fd, ':utf8';
6728 # incremental blame data returns early
6729 if ($format eq 'data') {
6731 -type
=>"text/plain", -charset
=> "utf-8",
6732 -status
=> "200 OK");
6733 local $| = 1; # output autoflush
6734 while (my $line = <$fd>) {
6735 print to_utf8
($line);
6738 or print "ERROR $!\n";
6741 if (defined $t0 && gitweb_check_feature
('timed')) {
6743 tv_interval
($t0, [ gettimeofday
() ]).
6744 ' '.$number_of_git_cmds;
6754 $cgi->a({-href
=> href
(action
=>"blob", -replay
=>1)},
6757 if ($format eq 'incremental') {
6759 $cgi->a({-href
=> href
(action
=>"blame", javascript
=>0, -replay
=>1)},
6760 "blame") . " (non-incremental)";
6763 $cgi->a({-href
=> href
(action
=>"blame_incremental", -replay
=>1)},
6764 "blame") . " (incremental)";
6768 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
6771 $cgi->a({-href
=> href
(action
=>$action, file_name
=>$file_name)},
6773 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6774 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
6775 git_print_page_path
($file_name, $ftype, $hash_base);
6778 if ($format eq 'incremental') {
6779 print "<noscript>\n<div class=\"error\"><center><b>\n".
6780 "This page requires JavaScript to run.\n Use ".
6781 $cgi->a({-href
=> href
(action
=>'blame',javascript
=>0,-replay
=>1)},
6784 "</b></center></div>\n</noscript>\n";
6786 print qq!<div id
="progress_bar" style
="width: 100%; background-color: yellow"></div
>\n!;
6789 print qq!<div
class="page_body">\n!;
6790 print qq!<div id
="progress_info">... / ...</div
>\n!
6791 if ($format eq 'incremental');
6792 print qq!<table id
="blame_table" class="blame" width
="100%">\n!.
6793 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6795 qq!<tr
><th
>Commit
</th><th>Line</th
><th
>Data
</th></tr
>\n!.
6799 my @rev_color = qw(light dark);
6800 my $num_colors = scalar(@rev_color);
6801 my $current_color = 0;
6803 if ($format eq 'incremental') {
6804 my $color_class = $rev_color[$current_color];
6809 while (my $line = <$fd>) {
6813 print qq!<tr id
="l$linenr" class="$color_class">!.
6814 qq!<td
class="sha1"><a href
=""> </a></td
>!.
6815 qq!<td
class="linenr">!.
6816 qq!<a
class="linenr" href
="">$linenr</a></td
>!;
6817 print qq!<td
class="pre">! . esc_html
($line) . "</td>\n";
6821 } else { # porcelain, i.e. ordinary blame
6822 my %metainfo = (); # saves information about commits
6826 while (my $line = <$fd>) {
6828 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6829 # no <lines in group> for subsequent lines in group of lines
6830 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6831 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6832 if (!exists $metainfo{$full_rev}) {
6833 $metainfo{$full_rev} = { 'nprevious' => 0 };
6835 my $meta = $metainfo{$full_rev};
6837 while ($data = <$fd>) {
6839 last if ($data =~ s/^\t//); # contents of line
6840 if ($data =~ /^(\S+)(?: (.*))?$/) {
6841 $meta->{$1} = $2 unless exists $meta->{$1};
6843 if ($data =~ /^previous /) {
6844 $meta->{'nprevious'}++;
6847 my $short_rev = substr($full_rev, 0, 8);
6848 my $author = $meta->{'author'};
6850 parse_date
($meta->{'author-time'}, $meta->{'author-tz'});
6851 my $date = $date{'iso-tz'};
6853 $current_color = ($current_color + 1) % $num_colors;
6855 my $tr_class = $rev_color[$current_color];
6856 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6857 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6858 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6859 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6861 print "<td class=\"sha1\"";
6862 print " title=\"". esc_html
($author) . ", $date\"";
6863 print " rowspan=\"$group_size\"" if ($group_size > 1);
6865 print $cgi->a({-href
=> href
(action
=>"commit",
6867 file_name
=>$file_name)},
6868 esc_html
($short_rev));
6869 if ($group_size >= 2) {
6870 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6871 if (@author_initials) {
6873 esc_html
(join('', @author_initials));
6879 # 'previous' <sha1 of parent commit> <filename at commit>
6880 if (exists $meta->{'previous'} &&
6881 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6882 $meta->{'parent'} = $1;
6883 $meta->{'file_parent'} = unquote
($2);
6886 exists($meta->{'parent'}) ?
6887 $meta->{'parent'} : $full_rev;
6888 my $linenr_filename =
6889 exists($meta->{'file_parent'}) ?
6890 $meta->{'file_parent'} : unquote
($meta->{'filename'});
6891 my $blamed = href
(action
=> 'blame',
6892 file_name
=> $linenr_filename,
6893 hash_base
=> $linenr_commit);
6894 print "<td class=\"linenr\">";
6895 print $cgi->a({ -href
=> "$blamed#l$orig_lineno",
6896 -class => "linenr" },
6899 print "<td class=\"pre\">" . esc_html
($data) . "</td>\n";
6907 "</table>\n"; # class="blame"
6908 print "</div>\n"; # class="blame_body"
6910 or print "Reading blob failed\n";
6919 sub git_blame_incremental
{
6920 git_blame_common
('incremental');
6923 sub git_blame_data
{
6924 git_blame_common
('data');
6928 my $head = git_get_head_hash
($project);
6930 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('tags'));
6931 git_print_header_div
('summary', $project);
6933 my @tagslist = git_get_tags_list
();
6935 git_tags_body
(\
@tagslist);
6941 my $head = git_get_head_hash
($project);
6943 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('heads'));
6944 git_print_header_div
('summary', $project);
6946 my @headslist = git_get_heads_list
();
6948 git_heads_body
(\
@headslist, $head);
6953 # used both for single remote view and for list of all the remotes
6955 gitweb_check_feature
('remote_heads')
6956 or die_error
(403, "Remote heads view is disabled");
6958 my $head = git_get_head_hash
($project);
6959 my $remote = $input_params{'hash'};
6961 my $remotedata = git_get_remotes_list
($remote);
6962 die_error
(500, "Unable to get remote information") unless defined $remotedata;
6964 unless (%$remotedata) {
6965 die_error
(404, defined $remote ?
6966 "Remote $remote not found" :
6967 "No remotes found");
6970 git_header_html
(undef, undef, -action_extra
=> $remote);
6971 git_print_page_nav
('', '', $head, undef, $head,
6972 format_ref_views
($remote ?
'' : 'remotes'));
6974 fill_remote_heads
($remotedata);
6975 if (defined $remote) {
6976 git_print_header_div
('remotes', "$remote remote for $project");
6977 git_remote_block
($remote, $remotedata->{$remote}, undef, $head);
6979 git_print_header_div
('summary', "$project remotes");
6980 git_remotes_body
($remotedata, undef, $head);
6986 sub git_blob_plain
{
6990 if (!defined $hash) {
6991 if (defined $file_name) {
6992 my $base = $hash_base || git_get_head_hash
($project);
6993 $hash = git_get_hash_by_path
($base, $file_name, "blob")
6994 or die_error
(404, "Cannot find file");
6996 die_error
(400, "No file name defined");
6998 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6999 # blobs defined by non-textual hash id's can be cached
7003 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
7004 or die_error
(500, "Open git-cat-file blob '$hash' failed");
7006 # content-type (can include charset)
7007 $type = blob_contenttype
($fd, $file_name, $type);
7009 # "save as" filename, even when no $file_name is given
7010 my $save_as = "$hash";
7011 if (defined $file_name) {
7012 $save_as = $file_name;
7013 } elsif ($type =~ m/^text\//) {
7017 # With XSS prevention on, blobs of all types except a few known safe
7018 # ones are served with "Content-Disposition: attachment" to make sure
7019 # they don't run in our security domain. For certain image types,
7020 # blob view writes an <img> tag referring to blob_plain view, and we
7021 # want to be sure not to break that by serving the image as an
7022 # attachment (though Firefox 3 doesn't seem to care).
7023 my $sandbox = $prevent_xss &&
7024 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7026 # serve text/* as text/plain
7028 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7029 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T
$fd))) {
7031 $rest = defined $rest ?
$rest : '';
7032 $type = "text/plain$rest";
7037 -expires
=> $expires,
7038 -content_disposition
=>
7039 ($sandbox ?
'attachment' : 'inline')
7040 . '; filename="' . $save_as . '"');
7042 binmode STDOUT
, ':raw';
7044 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7051 if (!defined $hash) {
7052 if (defined $file_name) {
7053 my $base = $hash_base || git_get_head_hash
($project);
7054 $hash = git_get_hash_by_path
($base, $file_name, "blob")
7055 or die_error
(404, "Cannot find file");
7057 die_error
(400, "No file name defined");
7059 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7060 # blobs defined by non-textual hash id's can be cached
7064 my $have_blame = gitweb_check_feature
('blame');
7065 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
7066 or die_error
(500, "Couldn't cat $file_name, $hash");
7067 my $mimetype = blob_mimetype
($fd, $file_name);
7068 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7069 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B
$fd) {
7071 return git_blob_plain
($mimetype);
7073 # we can have blame only for text/* mimetype
7074 $have_blame &&= ($mimetype =~ m!^text/!);
7076 my $highlight = gitweb_check_feature
('highlight');
7077 my $syntax = guess_file_syntax
($highlight, $mimetype, $file_name);
7078 $fd = run_highlighter
($fd, $highlight, $syntax)
7081 git_header_html
(undef, $expires);
7082 my $formats_nav = '';
7083 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7084 if (defined $file_name) {
7087 $cgi->a({-href
=> href
(action
=>"blame", -replay
=>1)},
7092 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7095 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7098 $cgi->a({-href
=> href
(action
=>"blob",
7099 hash_base
=>"HEAD", file_name
=>$file_name)},
7103 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7106 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7107 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7109 print "<div class=\"page_nav\">\n" .
7110 "<br/><br/></div>\n" .
7111 "<div class=\"title\">".esc_html
($hash)."</div>\n";
7113 git_print_page_path
($file_name, "blob", $hash_base);
7114 print "<div class=\"page_body\">\n";
7115 if ($mimetype =~ m!^image/!) {
7116 print qq!<img
class="blob" type
="!.esc_attr($mimetype).qq!"!;
7118 print qq! alt
="!.esc_attr($file_name).qq!" title
="!.esc_attr($file_name).qq!"!;
7121 href(action=>"blob_plain
", hash=>$hash,
7122 hash_base=>$hash_base, file_name=>$file_name) .
7126 while (my $line = <$fd>) {
7129 $line = untabify
($line);
7130 printf qq!<div
class="pre"><a id
="l%i" href
="%s#l%i" class="linenr">%4i</a> %s</div
>\n!,
7131 $nr, esc_attr
(href
(-replay
=> 1)), $nr, $nr,
7132 $syntax ? sanitize
($line) : esc_html
($line, -nbsp
=>1);
7136 or print "Reading blob failed.\n";
7142 if (!defined $hash_base) {
7143 $hash_base = "HEAD";
7145 if (!defined $hash) {
7146 if (defined $file_name) {
7147 $hash = git_get_hash_by_path
($hash_base, $file_name, "tree");
7152 die_error
(404, "No such tree") unless defined($hash);
7154 my $show_sizes = gitweb_check_feature
('show-sizes');
7155 my $have_blame = gitweb_check_feature
('blame');
7160 open my $fd, "-|", git_cmd
(), "ls-tree", '-z',
7161 ($show_sizes ?
'-l' : ()), @extra_options, $hash
7162 or die_error
(500, "Open git-ls-tree failed");
7163 @entries = map { chomp; $_ } <$fd>;
7165 or die_error
(404, "Reading tree failed");
7168 my $refs = git_get_references
();
7169 my $ref = format_ref_marker
($refs, $hash_base);
7172 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7174 if (defined $file_name) {
7176 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7178 $cgi->a({-href
=> href
(action
=>"tree",
7179 hash_base
=>"HEAD", file_name
=>$file_name)},
7182 my $snapshot_links = format_snapshot_links
($hash);
7183 if (defined $snapshot_links) {
7184 # FIXME: Should be available when we have no hash base as well.
7185 push @views_nav, $snapshot_links;
7187 git_print_page_nav
('tree','', $hash_base, undef, undef,
7188 join(' | ', @views_nav));
7189 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash_base);
7192 print "<div class=\"page_nav\">\n";
7193 print "<br/><br/></div>\n";
7194 print "<div class=\"title\">".esc_html
($hash)."</div>\n";
7196 if (defined $file_name) {
7197 $basedir = $file_name;
7198 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7201 git_print_page_path
($file_name, 'tree', $hash_base);
7203 print "<div class=\"page_body\">\n";
7204 print "<table class=\"tree\">\n";
7206 # '..' (top directory) link if possible
7207 if (defined $hash_base &&
7208 defined $file_name && $file_name =~ m![^/]+$!) {
7210 print "<tr class=\"dark\">\n";
7212 print "<tr class=\"light\">\n";
7216 my $up = $file_name;
7217 $up =~ s!/?[^/]+$!!;
7218 undef $up unless $up;
7219 # based on git_print_tree_entry
7220 print '<td class="mode">' . mode_str
('040000') . "</td>\n";
7221 print '<td class="size"> </td>'."\n" if $show_sizes;
7222 print '<td class="list">';
7223 print $cgi->a({-href
=> href
(action
=>"tree",
7224 hash_base
=>$hash_base,
7228 print "<td class=\"link\"></td>\n";
7232 foreach my $line (@entries) {
7233 my %t = parse_ls_tree_line
($line, -z
=> 1, -l
=> $show_sizes);
7236 print "<tr class=\"dark\">\n";
7238 print "<tr class=\"light\">\n";
7242 git_print_tree_entry
(\
%t, $basedir, $hash_base, $have_blame);
7246 print "</table>\n" .
7251 sub sanitize_for_filename
{
7255 $name =~ s/[^[:alnum:]_.-]//g;
7261 my ($project, $hash) = @_;
7263 # path/to/project.git -> project
7264 # path/to/project/.git -> project
7265 my $name = to_utf8
($project);
7266 $name =~ s
,([^/])/*\
.git
$,$1,;
7267 $name = sanitize_for_filename
(basename
($name));
7270 if ($hash =~ /^[0-9a-fA-F]+$/) {
7271 # shorten SHA-1 hash
7272 my $full_hash = git_get_full_hash
($project, $hash);
7273 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7274 $ver = git_get_short_hash
($project, $hash);
7276 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7277 # tags don't need shortened SHA-1 hash
7280 # branches and other need shortened SHA-1 hash
7281 my $strip_refs = join '|', map { quotemeta } get_branch_refs
();
7282 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7283 my $ref_dir = (defined $1) ?
$1 : '';
7286 $ref_dir = sanitize_for_filename
($ref_dir);
7287 # for refs neither in heads nor remotes we want to
7288 # add a ref dir to archive name
7289 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7290 $ver = $ref_dir . '-' . $ver;
7293 $ver .= '-' . git_get_short_hash
($project, $hash);
7295 # special case of sanitization for filename - we change
7296 # slashes to dots instead of dashes
7297 # in case of hierarchical branch names
7299 $ver =~ s/[^[:alnum:]_.-]//g;
7301 # name = project-version_string
7302 $name = "$name-$ver";
7304 return wantarray ?
($name, $name) : $name;
7307 sub exit_if_unmodified_since
{
7308 my ($latest_epoch) = @_;
7311 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7312 if (defined $if_modified) {
7314 if (eval { require HTTP
::Date
; 1; }) {
7315 $since = HTTP
::Date
::str2time
($if_modified);
7316 } elsif (eval { require Time
::ParseDate
; 1; }) {
7317 $since = Time
::ParseDate
::parsedate
($if_modified, GMT
=> 1);
7319 if (defined $since && $latest_epoch <= $since) {
7320 my %latest_date = parse_date
($latest_epoch);
7322 -last_modified
=> $latest_date{'rfc2822'},
7323 -status
=> '304 Not Modified');
7330 my $format = $input_params{'snapshot_format'};
7331 if (!@snapshot_fmts) {
7332 die_error
(403, "Snapshots not allowed");
7334 # default to first supported snapshot format
7335 $format ||= $snapshot_fmts[0];
7336 if ($format !~ m/^[a-z0-9]+$/) {
7337 die_error
(400, "Invalid snapshot format parameter");
7338 } elsif (!exists($known_snapshot_formats{$format})) {
7339 die_error
(400, "Unknown snapshot format");
7340 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7341 die_error
(403, "Snapshot format not allowed");
7342 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7343 die_error
(403, "Unsupported snapshot format");
7346 my $type = git_get_type
("$hash^{}");
7348 die_error
(404, 'Object does not exist');
7349 } elsif ($type eq 'blob') {
7350 die_error
(400, 'Object is not a tree-ish');
7353 my ($name, $prefix) = snapshot_name
($project, $hash);
7354 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7356 my %co = parse_commit
($hash);
7357 exit_if_unmodified_since
($co{'committer_epoch'}) if %co;
7359 my $cmd = quote_command
(
7360 git_cmd
(), 'archive',
7361 "--format=$known_snapshot_formats{$format}{'format'}",
7362 "--prefix=$prefix/", $hash);
7363 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7364 $cmd .= ' | ' . quote_command
(@
{$known_snapshot_formats{$format}{'compressor'}});
7367 $filename =~ s/(["\\])/\\$1/g;
7370 %latest_date = parse_date
($co{'committer_epoch'}, $co{'committer_tz'});
7374 -type
=> $known_snapshot_formats{$format}{'type'},
7375 -content_disposition
=> 'inline; filename="' . $filename . '"',
7376 %co ?
(-last_modified
=> $latest_date{'rfc2822'}) : (),
7377 -status
=> '200 OK');
7379 open my $fd, "-|", $cmd
7380 or die_error
(500, "Execute git-archive failed");
7381 binmode STDOUT
, ':raw';
7383 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7387 sub git_log_generic
{
7388 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7390 my $head = git_get_head_hash
($project);
7391 if (!defined $base) {
7394 if (!defined $page) {
7397 my $refs = git_get_references
();
7399 my $commit_hash = $base;
7400 if (defined $parent) {
7401 $commit_hash = "$parent..$base";
7404 parse_commits
($commit_hash, 101, (100 * $page),
7405 defined $file_name ?
($file_name, "--full-history") : ());
7408 if (!defined $file_hash && defined $file_name) {
7409 # some commits could have deleted file in question,
7410 # and not have it in tree, but one of them has to have it
7411 for (my $i = 0; $i < @commitlist; $i++) {
7412 $file_hash = git_get_hash_by_path
($commitlist[$i]{'id'}, $file_name);
7413 last if defined $file_hash;
7416 if (defined $file_hash) {
7417 $ftype = git_get_type
($file_hash);
7419 if (defined $file_name && !defined $ftype) {
7420 die_error
(500, "Unknown type of object");
7423 if (defined $file_name) {
7424 %co = parse_commit
($base)
7425 or die_error
(404, "Unknown commit object");
7429 my $paging_nav = format_paging_nav
($fmt_name, $page, $#commitlist >= 100);
7431 if ($#commitlist >= 100) {
7433 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
7434 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
7436 my $patch_max = gitweb_get_feature
('patches');
7437 if ($patch_max && !defined $file_name) {
7438 if ($patch_max < 0 || @commitlist <= $patch_max) {
7439 $paging_nav .= " ⋅ " .
7440 $cgi->a({-href
=> href
(action
=>"patches", -replay
=>1)},
7446 git_print_page_nav
($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7447 if (defined $file_name) {
7448 git_print_header_div
('commit', esc_html
($co{'title'}), $base);
7450 git_print_header_div
('summary', $project)
7452 git_print_page_path
($file_name, $ftype, $hash_base)
7453 if (defined $file_name);
7455 $body_subr->(\
@commitlist, 0, 99, $refs, $next_link,
7456 $file_name, $file_hash, $ftype);
7462 git_log_generic
('log', \
&git_log_body
,
7463 $hash, $hash_parent);
7467 $hash ||= $hash_base || "HEAD";
7468 my %co = parse_commit
($hash)
7469 or die_error
(404, "Unknown commit object");
7471 my $parent = $co{'parent'};
7472 my $parents = $co{'parents'}; # listref
7474 # we need to prepare $formats_nav before any parameter munging
7476 if (!defined $parent) {
7478 $formats_nav .= '(initial)';
7479 } elsif (@
$parents == 1) {
7480 # single parent commit
7483 $cgi->a({-href
=> href
(action
=>"commit",
7485 esc_html
(substr($parent, 0, 7))) .
7492 $cgi->a({-href
=> href
(action
=>"commit",
7494 esc_html
(substr($_, 0, 7)));
7498 if (gitweb_check_feature
('patches') && @
$parents <= 1) {
7499 $formats_nav .= " | " .
7500 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7504 if (!defined $parent) {
7508 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', "--no-commit-id",
7510 (@
$parents <= 1 ?
$parent : '-c'),
7512 or die_error
(500, "Open git-diff-tree failed");
7513 @difftree = map { chomp; $_ } <$fd>;
7514 close $fd or die_error
(404, "Reading git-diff-tree failed");
7516 # non-textual hash id's can be cached
7518 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7521 my $refs = git_get_references
();
7522 my $ref = format_ref_marker
($refs, $co{'id'});
7524 git_header_html
(undef, $expires);
7525 git_print_page_nav
('commit', '',
7526 $hash, $co{'tree'}, $hash,
7529 if (defined $co{'parent'}) {
7530 git_print_header_div
('commitdiff', esc_html
($co{'title'}) . $ref, $hash);
7532 git_print_header_div
('tree', esc_html
($co{'title'}) . $ref, $co{'tree'}, $hash);
7534 print "<div class=\"title_text\">\n" .
7535 "<table class=\"object_header\">\n";
7536 git_print_authorship_rows
(\
%co);
7537 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7540 "<td class=\"sha1\">" .
7541 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash),
7542 class => "list"}, $co{'tree'}) .
7544 "<td class=\"link\">" .
7545 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash)},
7547 my $snapshot_links = format_snapshot_links
($hash);
7548 if (defined $snapshot_links) {
7549 print " | " . $snapshot_links;
7554 foreach my $par (@
$parents) {
7557 "<td class=\"sha1\">" .
7558 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par),
7559 class => "list"}, $par) .
7561 "<td class=\"link\">" .
7562 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par)}, "commit") .
7564 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$hash, hash_parent
=>$par)}, "diff") .
7571 print "<div class=\"page_body\">\n";
7572 git_print_log
($co{'comment'});
7575 git_difftree_body
(\
@difftree, $hash, @
$parents);
7581 # object is defined by:
7582 # - hash or hash_base alone
7583 # - hash_base and file_name
7586 # - hash or hash_base alone
7587 if ($hash || ($hash_base && !defined $file_name)) {
7588 my $object_id = $hash || $hash_base;
7590 open my $fd, "-|", quote_command
(
7591 git_cmd
(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7592 or die_error
(404, "Object does not exist");
7596 or die_error
(404, "Object does not exist");
7598 # - hash_base and file_name
7599 } elsif ($hash_base && defined $file_name) {
7600 $file_name =~ s
,/+$,,;
7602 system(git_cmd
(), "cat-file", '-e', $hash_base) == 0
7603 or die_error
(404, "Base object does not exist");
7605 # here errors should not happen
7606 open my $fd, "-|", git_cmd
(), "ls-tree", $hash_base, "--", $file_name
7607 or die_error
(500, "Open git-ls-tree failed");
7611 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7612 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7613 die_error
(404, "File or directory for given base does not exist");
7618 die_error
(400, "Not enough information to find object");
7621 print $cgi->redirect(-uri
=> href
(action
=>$type, -full
=>1,
7622 hash
=>$hash, hash_base
=>$hash_base,
7623 file_name
=>$file_name),
7624 -status
=> '302 Found');
7628 my $format = shift || 'html';
7629 my $diff_style = $input_params{'diff_style'} || 'inline';
7636 # preparing $fd and %diffinfo for git_patchset_body
7638 if (defined $hash_base && defined $hash_parent_base) {
7639 if (defined $file_name) {
7641 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7642 $hash_parent_base, $hash_base,
7643 "--", (defined $file_parent ?
$file_parent : ()), $file_name
7644 or die_error
(500, "Open git-diff-tree failed");
7645 @difftree = map { chomp; $_ } <$fd>;
7647 or die_error
(404, "Reading git-diff-tree failed");
7649 or die_error
(404, "Blob diff not found");
7651 } elsif (defined $hash &&
7652 $hash =~ /[0-9a-fA-F]{40}/) {
7653 # try to find filename from $hash
7655 # read filtered raw output
7656 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7657 $hash_parent_base, $hash_base, "--"
7658 or die_error
(500, "Open git-diff-tree failed");
7660 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7662 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7663 map { chomp; $_ } <$fd>;
7665 or die_error
(404, "Reading git-diff-tree failed");
7667 or die_error
(404, "Blob diff not found");
7670 die_error
(400, "Missing one of the blob diff parameters");
7673 if (@difftree > 1) {
7674 die_error
(400, "Ambiguous blob diff specification");
7677 %diffinfo = parse_difftree_raw_line
($difftree[0]);
7678 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7679 $file_name ||= $diffinfo{'to_file'};
7681 $hash_parent ||= $diffinfo{'from_id'};
7682 $hash ||= $diffinfo{'to_id'};
7684 # non-textual hash id's can be cached
7685 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7686 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7691 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7692 '-p', ($format eq 'html' ?
"--full-index" : ()),
7693 $hash_parent_base, $hash_base,
7694 "--", (defined $file_parent ?
$file_parent : ()), $file_name
7695 or die_error
(500, "Open git-diff-tree failed");
7698 # old/legacy style URI -- not generated anymore since 1.4.3.
7700 die_error
('404 Not Found', "Missing one of the blob diff parameters")
7704 if ($format eq 'html') {
7706 $cgi->a({-href
=> href
(action
=>"blobdiff_plain", -replay
=>1)},
7708 $formats_nav .= diff_style_nav
($diff_style);
7709 git_header_html
(undef, $expires);
7710 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7711 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7712 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7714 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7715 print "<div class=\"title\">".esc_html
("$hash vs $hash_parent")."</div>\n";
7717 if (defined $file_name) {
7718 git_print_page_path
($file_name, "blob", $hash_base);
7720 print "<div class=\"page_path\"></div>\n";
7723 } elsif ($format eq 'plain') {
7725 -type
=> 'text/plain',
7726 -charset
=> 'utf-8',
7727 -expires
=> $expires,
7728 -content_disposition
=> 'inline; filename="' . "$file_name" . '.patch"');
7730 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7733 die_error
(400, "Unknown blobdiff format");
7737 if ($format eq 'html') {
7738 print "<div class=\"page_body\">\n";
7740 git_patchset_body
($fd, $diff_style,
7741 [ \
%diffinfo ], $hash_base, $hash_parent_base);
7744 print "</div>\n"; # class="page_body"
7748 while (my $line = <$fd>) {
7749 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7750 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7754 last if $line =~ m!^\+\+\+!;
7762 sub git_blobdiff_plain
{
7763 git_blobdiff
('plain');
7766 # assumes that it is added as later part of already existing navigation,
7767 # so it returns "| foo | bar" rather than just "foo | bar"
7768 sub diff_style_nav
{
7769 my ($diff_style, $is_combined) = @_;
7770 $diff_style ||= 'inline';
7772 return "" if ($is_combined);
7774 my @styles = (inline
=> 'inline', 'sidebyside' => 'side by side');
7775 my %styles = @styles;
7777 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7782 $_ eq $diff_style ?
$styles{$_} :
7783 $cgi->a({-href
=> href
(-replay
=>1, diff_style
=> $_)}, $styles{$_})
7787 sub git_commitdiff
{
7789 my $format = $params{-format
} || 'html';
7790 my $diff_style = $input_params{'diff_style'} || 'inline';
7792 my ($patch_max) = gitweb_get_feature
('patches');
7793 if ($format eq 'patch') {
7794 die_error
(403, "Patch view not allowed") unless $patch_max;
7797 $hash ||= $hash_base || "HEAD";
7798 my %co = parse_commit
($hash)
7799 or die_error
(404, "Unknown commit object");
7801 # choose format for commitdiff for merge
7802 if (! defined $hash_parent && @
{$co{'parents'}} > 1) {
7803 $hash_parent = '--cc';
7805 # we need to prepare $formats_nav before almost any parameter munging
7807 if ($format eq 'html') {
7809 $cgi->a({-href
=> href
(action
=>"commitdiff_plain", -replay
=>1)},
7811 if ($patch_max && @
{$co{'parents'}} <= 1) {
7812 $formats_nav .= " | " .
7813 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7816 $formats_nav .= diff_style_nav
($diff_style, @
{$co{'parents'}} > 1);
7818 if (defined $hash_parent &&
7819 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7820 # commitdiff with two commits given
7821 my $hash_parent_short = $hash_parent;
7822 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7823 $hash_parent_short = substr($hash_parent, 0, 7);
7827 for (my $i = 0; $i < @
{$co{'parents'}}; $i++) {
7828 if ($co{'parents'}[$i] eq $hash_parent) {
7829 $formats_nav .= ' parent ' . ($i+1);
7833 $formats_nav .= ': ' .
7834 $cgi->a({-href
=> href
(-replay
=>1,
7835 hash
=>$hash_parent, hash_base
=>undef)},
7836 esc_html
($hash_parent_short)) .
7838 } elsif (!$co{'parent'}) {
7840 $formats_nav .= ' (initial)';
7841 } elsif (scalar @
{$co{'parents'}} == 1) {
7842 # single parent commit
7845 $cgi->a({-href
=> href
(-replay
=>1,
7846 hash
=>$co{'parent'}, hash_base
=>undef)},
7847 esc_html
(substr($co{'parent'}, 0, 7))) .
7851 if ($hash_parent eq '--cc') {
7852 $formats_nav .= ' | ' .
7853 $cgi->a({-href
=> href
(-replay
=>1,
7854 hash
=>$hash, hash_parent
=>'-c')},
7856 } else { # $hash_parent eq '-c'
7857 $formats_nav .= ' | ' .
7858 $cgi->a({-href
=> href
(-replay
=>1,
7859 hash
=>$hash, hash_parent
=>'--cc')},
7865 $cgi->a({-href
=> href
(-replay
=>1,
7866 hash
=>$_, hash_base
=>undef)},
7867 esc_html
(substr($_, 0, 7)));
7868 } @
{$co{'parents'}} ) .
7873 my $hash_parent_param = $hash_parent;
7874 if (!defined $hash_parent_param) {
7875 # --cc for multiple parents, --root for parentless
7876 $hash_parent_param =
7877 @
{$co{'parents'}} > 1 ?
'--cc' : $co{'parent'} || '--root';
7883 if ($format eq 'html') {
7884 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7885 "--no-commit-id", "--patch-with-raw", "--full-index",
7886 $hash_parent_param, $hash, "--"
7887 or die_error
(500, "Open git-diff-tree failed");
7889 while (my $line = <$fd>) {
7891 # empty line ends raw part of diff-tree output
7893 push @difftree, scalar parse_difftree_raw_line
($line);
7896 } elsif ($format eq 'plain') {
7897 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7898 '-p', $hash_parent_param, $hash, "--"
7899 or die_error
(500, "Open git-diff-tree failed");
7900 } elsif ($format eq 'patch') {
7901 # For commit ranges, we limit the output to the number of
7902 # patches specified in the 'patches' feature.
7903 # For single commits, we limit the output to a single patch,
7904 # diverging from the git-format-patch default.
7905 my @commit_spec = ();
7907 if ($patch_max > 0) {
7908 push @commit_spec, "-$patch_max";
7910 push @commit_spec, '-n', "$hash_parent..$hash";
7912 if ($params{-single
}) {
7913 push @commit_spec, '-1';
7915 if ($patch_max > 0) {
7916 push @commit_spec, "-$patch_max";
7918 push @commit_spec, "-n";
7920 push @commit_spec, '--root', $hash;
7922 open $fd, "-|", git_cmd
(), "format-patch", @diff_opts,
7923 '--encoding=utf8', '--stdout', @commit_spec
7924 or die_error
(500, "Open git-format-patch failed");
7926 die_error
(400, "Unknown commitdiff format");
7929 # non-textual hash id's can be cached
7931 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7935 # write commit message
7936 if ($format eq 'html') {
7937 my $refs = git_get_references
();
7938 my $ref = format_ref_marker
($refs, $co{'id'});
7940 git_header_html
(undef, $expires);
7941 git_print_page_nav
('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7942 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash);
7943 print "<div class=\"title_text\">\n" .
7944 "<table class=\"object_header\">\n";
7945 git_print_authorship_rows
(\
%co);
7948 print "<div class=\"page_body\">\n";
7949 if (@
{$co{'comment'}} > 1) {
7950 print "<div class=\"log\">\n";
7951 git_print_log
($co{'comment'}, -final_empty_line
=> 1, -remove_title
=> 1);
7952 print "</div>\n"; # class="log"
7955 } elsif ($format eq 'plain') {
7956 my $refs = git_get_references
("tags");
7957 my $tagname = git_get_rev_name_tags
($hash);
7958 my $filename = basename
($project) . "-$hash.patch";
7961 -type
=> 'text/plain',
7962 -charset
=> 'utf-8',
7963 -expires
=> $expires,
7964 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
7965 my %ad = parse_date
($co{'author_epoch'}, $co{'author_tz'});
7966 print "From: " . to_utf8
($co{'author'}) . "\n";
7967 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7968 print "Subject: " . to_utf8
($co{'title'}) . "\n";
7970 print "X-Git-Tag: $tagname\n" if $tagname;
7971 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7973 foreach my $line (@
{$co{'comment'}}) {
7974 print to_utf8
($line) . "\n";
7977 } elsif ($format eq 'patch') {
7978 my $filename = basename
($project) . "-$hash.patch";
7981 -type
=> 'text/plain',
7982 -charset
=> 'utf-8',
7983 -expires
=> $expires,
7984 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
7988 if ($format eq 'html') {
7989 my $use_parents = !defined $hash_parent ||
7990 $hash_parent eq '-c' || $hash_parent eq '--cc';
7991 git_difftree_body
(\
@difftree, $hash,
7992 $use_parents ? @
{$co{'parents'}} : $hash_parent);
7995 git_patchset_body
($fd, $diff_style,
7997 $use_parents ? @
{$co{'parents'}} : $hash_parent);
7999 print "</div>\n"; # class="page_body"
8002 } elsif ($format eq 'plain') {
8006 or print "Reading git-diff-tree failed\n";
8007 } elsif ($format eq 'patch') {
8011 or print "Reading git-format-patch failed\n";
8015 sub git_commitdiff_plain
{
8016 git_commitdiff
(-format
=> 'plain');
8019 # format-patch-style patches
8021 git_commitdiff
(-format
=> 'patch', -single
=> 1);
8025 git_commitdiff
(-format
=> 'patch');
8029 git_log_generic
('history', \
&git_history_body
,
8030 $hash_base, $hash_parent_base,
8035 $searchtype ||= 'commit';
8037 # check if appropriate features are enabled
8038 gitweb_check_feature
('search')
8039 or die_error
(403, "Search is disabled");
8040 if ($searchtype eq 'pickaxe') {
8041 # pickaxe may take all resources of your box and run for several minutes
8042 # with every query - so decide by yourself how public you make this feature
8043 gitweb_check_feature
('pickaxe')
8044 or die_error
(403, "Pickaxe search is disabled");
8046 if ($searchtype eq 'grep') {
8047 # grep search might be potentially CPU-intensive, too
8048 gitweb_check_feature
('grep')
8049 or die_error
(403, "Grep search is disabled");
8052 if (!defined $searchtext) {
8053 die_error
(400, "Text field is empty");
8055 if (!defined $hash) {
8056 $hash = git_get_head_hash
($project);
8058 my %co = parse_commit
($hash);
8060 die_error
(404, "Unknown commit object");
8062 if (!defined $page) {
8066 if ($searchtype eq 'commit' ||
8067 $searchtype eq 'author' ||
8068 $searchtype eq 'committer') {
8069 git_search_message
(%co);
8070 } elsif ($searchtype eq 'pickaxe') {
8071 git_search_changes
(%co);
8072 } elsif ($searchtype eq 'grep') {
8073 git_search_files
(%co);
8075 die_error
(400, "Unknown search type");
8079 sub git_search_help
{
8081 git_print_page_nav
('','', $hash,$hash,$hash);
8083 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8084 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8085 the pattern entered is recognized as the POSIX extended
8086 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8089 <dt><b>commit</b></dt>
8090 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8092 my $have_grep = gitweb_check_feature
('grep');
8095 <dt><b>grep</b></dt>
8096 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8097 a different one) are searched for the given pattern. On large trees, this search can take
8098 a while and put some strain on the server, so please use it with some consideration. Note that
8099 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8100 case-sensitive.</dd>
8104 <dt><b>author</b></dt>
8105 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8106 <dt><b>committer</b></dt>
8107 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8109 my $have_pickaxe = gitweb_check_feature
('pickaxe');
8110 if ($have_pickaxe) {
8112 <dt><b>pickaxe</b></dt>
8113 <dd>All commits that caused the string to appear or disappear from any file (changes that
8114 added, removed or "modified" the string) will be listed. This search can take a while and
8115 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8116 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8124 git_log_generic
('shortlog', \
&git_shortlog_body
,
8125 $hash, $hash_parent);
8128 ## ......................................................................
8129 ## feeds (RSS, Atom; OPML)
8132 my $format = shift || 'atom';
8133 my $have_blame = gitweb_check_feature
('blame');
8135 # Atom: http://www.atomenabled.org/developers/syndication/
8136 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8137 if ($format ne 'rss' && $format ne 'atom') {
8138 die_error
(400, "Unknown web feed format");
8141 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8142 my $head = $hash || 'HEAD';
8143 my @commitlist = parse_commits
($head, 150, 0, $file_name);
8147 my $content_type = "application/$format+xml";
8148 if (defined $cgi->http('HTTP_ACCEPT') &&
8149 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8150 # browser (feed reader) prefers text/xml
8151 $content_type = 'text/xml';
8153 if (defined($commitlist[0])) {
8154 %latest_commit = %{$commitlist[0]};
8155 my $latest_epoch = $latest_commit{'committer_epoch'};
8156 exit_if_unmodified_since
($latest_epoch);
8157 %latest_date = parse_date
($latest_epoch, $latest_commit{'committer_tz'});
8160 -type
=> $content_type,
8161 -charset
=> 'utf-8',
8162 %latest_date ?
(-last_modified
=> $latest_date{'rfc2822'}) : (),
8163 -status
=> '200 OK');
8165 # Optimization: skip generating the body if client asks only
8166 # for Last-Modified date.
8167 return if ($cgi->request_method() eq 'HEAD');
8170 my $title = "$site_name - $project/$action";
8171 my $feed_type = 'log';
8172 if (defined $hash) {
8173 $title .= " - '$hash'";
8174 $feed_type = 'branch log';
8175 if (defined $file_name) {
8176 $title .= " :: $file_name";
8177 $feed_type = 'history';
8179 } elsif (defined $file_name) {
8180 $title .= " - $file_name";
8181 $feed_type = 'history';
8183 $title .= " $feed_type";
8184 $title = esc_html
($title);
8185 my $descr = git_get_project_description
($project);
8186 if (defined $descr) {
8187 $descr = esc_html
($descr);
8189 $descr = "$project " .
8190 ($format eq 'rss' ?
'RSS' : 'Atom') .
8193 my $owner = git_get_project_owner
($project);
8194 $owner = esc_html
($owner);
8198 if (defined $file_name) {
8199 $alt_url = href
(-full
=>1, action
=>"history", hash
=>$hash, file_name
=>$file_name);
8200 } elsif (defined $hash) {
8201 $alt_url = href
(-full
=>1, action
=>"log", hash
=>$hash);
8203 $alt_url = href
(-full
=>1, action
=>"summary");
8205 print qq!<?xml version
="1.0" encoding
="utf-8"?
>\n!;
8206 if ($format eq 'rss') {
8208 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8211 print "<title>$title</title>\n" .
8212 "<link>$alt_url</link>\n" .
8213 "<description>$descr</description>\n" .
8214 "<language>en</language>\n" .
8215 # project owner is responsible for 'editorial' content
8216 "<managingEditor>$owner</managingEditor>\n";
8217 if (defined $logo || defined $favicon) {
8218 # prefer the logo to the favicon, since RSS
8219 # doesn't allow both
8220 my $img = esc_url
($logo || $favicon);
8222 "<url>$img</url>\n" .
8223 "<title>$title</title>\n" .
8224 "<link>$alt_url</link>\n" .
8228 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8229 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8231 print "<generator>gitweb v.$version/$git_version</generator>\n";
8232 } elsif ($format eq 'atom') {
8234 <feed xmlns="http://www.w3.org/2005/Atom">
8236 print "<title>$title</title>\n" .
8237 "<subtitle>$descr</subtitle>\n" .
8238 '<link rel="alternate" type="text/html" href="' .
8239 $alt_url . '" />' . "\n" .
8240 '<link rel="self" type="' . $content_type . '" href="' .
8241 $cgi->self_url() . '" />' . "\n" .
8242 "<id>" . href
(-full
=>1) . "</id>\n" .
8243 # use project owner for feed author
8244 "<author><name>$owner</name></author>\n";
8245 if (defined $favicon) {
8246 print "<icon>" . esc_url
($favicon) . "</icon>\n";
8248 if (defined $logo) {
8249 # not twice as wide as tall: 72 x 27 pixels
8250 print "<logo>" . esc_url
($logo) . "</logo>\n";
8252 if (! %latest_date) {
8253 # dummy date to keep the feed valid until commits trickle in:
8254 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8256 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8258 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8262 for (my $i = 0; $i <= $#commitlist; $i++) {
8263 my %co = %{$commitlist[$i]};
8264 my $commit = $co{'id'};
8265 # we read 150, we always show 30 and the ones more recent than 48 hours
8266 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8269 my %cd = parse_date
($co{'author_epoch'}, $co{'author_tz'});
8271 # get list of changed files
8272 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
8273 $co{'parent'} || "--root",
8274 $co{'id'}, "--", (defined $file_name ?
$file_name : ())
8276 my @difftree = map { chomp; $_ } <$fd>;
8280 # print element (entry, item)
8281 my $co_url = href
(-full
=>1, action
=>"commitdiff", hash
=>$commit);
8282 if ($format eq 'rss') {
8284 "<title>" . esc_html
($co{'title'}) . "</title>\n" .
8285 "<author>" . esc_html
($co{'author'}) . "</author>\n" .
8286 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8287 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8288 "<link>$co_url</link>\n" .
8289 "<description>" . esc_html
($co{'title'}) . "</description>\n" .
8290 "<content:encoded>" .
8292 } elsif ($format eq 'atom') {
8294 "<title type=\"html\">" . esc_html
($co{'title'}) . "</title>\n" .
8295 "<updated>$cd{'iso-8601'}</updated>\n" .
8297 " <name>" . esc_html
($co{'author_name'}) . "</name>\n";
8298 if ($co{'author_email'}) {
8299 print " <email>" . esc_html
($co{'author_email'}) . "</email>\n";
8301 print "</author>\n" .
8302 # use committer for contributor
8304 " <name>" . esc_html
($co{'committer_name'}) . "</name>\n";
8305 if ($co{'committer_email'}) {
8306 print " <email>" . esc_html
($co{'committer_email'}) . "</email>\n";
8308 print "</contributor>\n" .
8309 "<published>$cd{'iso-8601'}</published>\n" .
8310 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8311 "<id>$co_url</id>\n" .
8312 "<content type=\"xhtml\" xml:base=\"" . esc_url
($my_url) . "\">\n" .
8313 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8315 my $comment = $co{'comment'};
8317 foreach my $line (@
$comment) {
8318 $line = esc_html
($line);
8321 print "</pre><ul>\n";
8322 foreach my $difftree_line (@difftree) {
8323 my %difftree = parse_difftree_raw_line
($difftree_line);
8324 next if !$difftree{'from_id'};
8326 my $file = $difftree{'file'} || $difftree{'to_file'};
8330 $cgi->a({-href
=> href
(-full
=>1, action
=>"blobdiff",
8331 hash
=>$difftree{'to_id'}, hash_parent
=>$difftree{'from_id'},
8332 hash_base
=>$co{'id'}, hash_parent_base
=>$co{'parent'},
8333 file_name
=>$file, file_parent
=>$difftree{'from_file'}),
8334 -title
=> "diff"}, 'D');
8336 print $cgi->a({-href
=> href
(-full
=>1, action
=>"blame",
8337 file_name
=>$file, hash_base
=>$commit),
8338 -title
=> "blame"}, 'B');
8340 # if this is not a feed of a file history
8341 if (!defined $file_name || $file_name ne $file) {
8342 print $cgi->a({-href
=> href
(-full
=>1, action
=>"history",
8343 file_name
=>$file, hash
=>$commit),
8344 -title
=> "history"}, 'H');
8346 $file = esc_path
($file);
8350 if ($format eq 'rss') {
8351 print "</ul>]]>\n" .
8352 "</content:encoded>\n" .
8354 } elsif ($format eq 'atom') {
8355 print "</ul>\n</div>\n" .
8362 if ($format eq 'rss') {
8363 print "</channel>\n</rss>\n";
8364 } elsif ($format eq 'atom') {
8378 my @list = git_get_projects_list
($project_filter, $strict_export);
8380 die_error
(404, "No projects found");
8384 -type
=> 'text/xml',
8385 -charset
=> 'utf-8',
8386 -content_disposition
=> 'inline; filename="opml.xml"');
8388 my $title = esc_html
($site_name);
8389 my $filter = " within subdirectory ";
8390 if (defined $project_filter) {
8391 $filter .= esc_html
($project_filter);
8396 <?xml version="1.0" encoding="utf-8"?>
8397 <opml version="1.0">
8399 <title>$title OPML Export$filter</title>
8402 <outline text="git RSS feeds">
8405 foreach my $pr (@list) {
8407 my $head = git_get_head_hash
($proj{'path'});
8408 if (!defined $head) {
8411 $git_dir = "$projectroot/$proj{'path'}";
8412 my %co = parse_commit
($head);
8417 my $path = esc_html
(chop_str
($proj{'path'}, 25, 5));
8418 my $rss = href
('project' => $proj{'path'}, 'action' => 'rss', -full
=> 1);
8419 my $html = href
('project' => $proj{'path'}, 'action' => 'summary', -full
=> 1);
8420 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";