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 our $t0 = [ gettimeofday
() ];
24 our $number_of_git_cmds = 0;
27 CGI-
>compile() if $ENV{'MOD_PERL'};
30 our $version = "++GIT_VERSION++";
32 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
36 our $my_url = $cgi->url();
37 our $my_uri = $cgi->url(-absolute
=> 1);
39 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
40 # needed and used only for URLs with nonempty PATH_INFO
41 our $base_url = $my_url;
43 # When the script is used as DirectoryIndex, the URL does not contain the name
44 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
45 # have to do it ourselves. We make $path_info global because it's also used
48 # Another issue with the script being the DirectoryIndex is that the resulting
49 # $my_url data is not the full script URL: this is good, because we want
50 # generated links to keep implying the script name if it wasn't explicitly
51 # indicated in the URL we're handling, but it means that $my_url cannot be used
53 # Therefore, if we needed to strip PATH_INFO, then we know that we have
54 # to build the base URL ourselves:
55 our $path_info = decode_utf8
($ENV{"PATH_INFO"});
57 # $path_info has already been URL-decoded by the web server, but
58 # $my_url and $my_uri have not. URL-decode them so we can properly
60 $my_url = unescape
($my_url);
61 $my_uri = unescape
($my_uri);
62 if ($my_url =~ s
,\Q
$path_info\E
$,, &&
63 $my_uri =~ s
,\Q
$path_info\E
$,, &&
64 defined $ENV{'SCRIPT_NAME'}) {
65 $base_url = $cgi->url(-base
=> 1) . $ENV{'SCRIPT_NAME'};
69 # target of the home link on top of all pages
70 our $home_link = $my_uri || "/";
73 # core git executable to use
74 # this can just be "git" if your webserver has a sensible PATH
75 our $GIT = "++GIT_BINDIR++/git";
77 # absolute fs-path which will be prepended to the project path
78 #our $projectroot = "/pub/scm";
79 our $projectroot = "++GITWEB_PROJECTROOT++";
81 # fs traversing limit for getting project list
82 # the number is relative to the projectroot
83 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
85 # string of the home link on top of all pages
86 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
88 # extra breadcrumbs preceding the home link
89 our @extra_breadcrumbs = ();
91 # name of your site or organization to appear in page titles
92 # replace this with something more descriptive for clearer bookmarks
93 our $site_name = "++GITWEB_SITENAME++"
94 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
96 # html snippet to include in the <head> section of each page
97 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
98 # filename of html text to include at top of each page
99 our $site_header = "++GITWEB_SITE_HEADER++";
100 # html text to include at home page
101 our $home_text = "++GITWEB_HOMETEXT++";
102 # filename of html text to include at bottom of each page
103 our $site_footer = "++GITWEB_SITE_FOOTER++";
106 our @stylesheets = ("++GITWEB_CSS++");
107 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
108 our $stylesheet = undef;
110 # URI of GIT logo (72x27 size)
111 our $logo = "++GITWEB_LOGO++";
112 # URI of GIT favicon, assumed to be image/png type
113 our $favicon = "++GITWEB_FAVICON++";
114 # URI of gitweb.js (JavaScript code for gitweb)
115 our $javascript = "++GITWEB_JS++";
117 # URI and label (title) of GIT logo link
118 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
119 #our $logo_label = "git documentation";
120 our $logo_url = "http://git-scm.com/";
121 our $logo_label = "git homepage";
123 # source of projects list
124 our $projects_list = "++GITWEB_LIST++";
126 # the width (in characters) of the projects list "Description" column
127 our $projects_list_description_width = 25;
129 # group projects by category on the projects list
130 # (enabled if this variable evaluates to true)
131 our $projects_list_group_categories = 0;
133 # default category if none specified
134 # (leave the empty string for no category)
135 our $project_list_default_category = "";
137 # default order of projects list
138 # valid values are none, project, descr, owner, and age
139 our $default_projects_order = "project";
141 # show repository only if this file exists
142 # (only effective if this variable evaluates to true)
143 our $export_ok = "++GITWEB_EXPORT_OK++";
145 # don't generate age column on the projects list page
146 our $omit_age_column = 0;
148 # don't generate information about owners of repositories
151 # show repository only if this subroutine returns true
152 # when given the path to the project, for example:
153 # sub { return -e "$_[0]/git-daemon-export-ok"; }
154 our $export_auth_hook = undef;
156 # only allow viewing of repositories also shown on the overview page
157 our $strict_export = "++GITWEB_STRICT_EXPORT++";
159 # list of git base URLs used for URL to where fetch project from,
160 # i.e. full URL is "$git_base_url/$project"
161 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
163 # default blob_plain mimetype and default charset for text/plain blob
164 our $default_blob_plain_mimetype = 'text/plain';
165 our $default_text_plain_charset = undef;
167 # file to use for guessing MIME types before trying /etc/mime.types
168 # (relative to the current git repository)
169 our $mimetypes_file = undef;
171 # assume this charset if line contains non-UTF-8 characters;
172 # it should be valid encoding (see Encoding::Supported(3pm) for list),
173 # for which encoding all byte sequences are valid, for example
174 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
175 # could be even 'utf-8' for the old behavior)
176 our $fallback_encoding = 'latin1';
178 # rename detection options for git-diff and git-diff-tree
179 # - default is '-M', with the cost proportional to
180 # (number of removed files) * (number of new files).
181 # - more costly is '-C' (which implies '-M'), with the cost proportional to
182 # (number of changed files + number of removed files) * (number of new files)
183 # - even more costly is '-C', '--find-copies-harder' with cost
184 # (number of files in the original tree) * (number of new files)
185 # - one might want to include '-B' option, e.g. '-B', '-M'
186 our @diff_opts = ('-M'); # taken from git_commit
188 # Disables features that would allow repository owners to inject script into
190 our $prevent_xss = 0;
192 # Path to the highlight executable to use (must be the one from
193 # http://www.andre-simon.de due to assumptions about parameters and output).
194 # Useful if highlight is not installed on your webserver's PATH.
195 # [Default: highlight]
196 our $highlight_bin = "++HIGHLIGHT_BIN++";
198 # information about snapshot formats that gitweb is capable of serving
199 our %known_snapshot_formats = (
201 # 'display' => display name,
202 # 'type' => mime type,
203 # 'suffix' => filename suffix,
204 # 'format' => --format for git-archive,
205 # 'compressor' => [compressor command and arguments]
206 # (array reference, optional)
207 # 'disabled' => boolean (optional)}
210 'display' => 'tar.gz',
211 'type' => 'application/x-gzip',
212 'suffix' => '.tar.gz',
214 'compressor' => ['gzip', '-n']},
217 'display' => 'tar.bz2',
218 'type' => 'application/x-bzip2',
219 'suffix' => '.tar.bz2',
221 'compressor' => ['bzip2']},
224 'display' => 'tar.xz',
225 'type' => 'application/x-xz',
226 'suffix' => '.tar.xz',
228 'compressor' => ['xz'],
233 'type' => 'application/x-zip',
238 # Aliases so we understand old gitweb.snapshot values in repository
240 our %known_snapshot_format_aliases = (
245 # backward compatibility: legacy gitweb config support
246 'x-gzip' => undef, 'gz' => undef,
247 'x-bzip2' => undef, 'bz2' => undef,
248 'x-zip' => undef, '' => undef,
251 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
252 # are changed, it may be appropriate to change these values too via
259 # Used to set the maximum load that we will still respond to gitweb queries.
260 # If server load exceed this value then return "503 server busy" error.
261 # If gitweb cannot determined server load, it is taken to be 0.
262 # Leave it undefined (or set to 'undef') to turn off load checking.
265 # configuration for 'highlight' (http://www.andre-simon.de/)
267 our %highlight_basename = (
270 'SConstruct' => 'py', # SCons equivalent of Makefile
271 'Makefile' => 'make',
274 our %highlight_ext = (
275 # main extensions, defining name of syntax;
276 # see files in /usr/share/highlight/langDefs/ directory
277 (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
278 # alternate extensions, see /etc/highlight/filetypes.conf
279 (map { $_ => 'c' } qw(c h)),
280 (map { $_ => 'sh' } qw(sh bash zsh ksh)),
281 (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
282 (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
283 (map { $_ => 'pl' } qw(pl perl pm)), # perhaps also 'cgi'
284 (map { $_ => 'make'} qw(make mak mk)),
285 (map { $_ => 'xml' } qw(xml xhtml html htm)),
288 # You define site-wide feature defaults here; override them with
289 # $GITWEB_CONFIG as necessary.
292 # 'sub' => feature-sub (subroutine),
293 # 'override' => allow-override (boolean),
294 # 'default' => [ default options...] (array reference)}
296 # if feature is overridable (it means that allow-override has true value),
297 # then feature-sub will be called with default options as parameters;
298 # return value of feature-sub indicates if to enable specified feature
300 # if there is no 'sub' key (no feature-sub), then feature cannot be
303 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
304 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
307 # Enable the 'blame' blob view, showing the last commit that modified
308 # each line in the file. This can be very CPU-intensive.
310 # To enable system wide have in $GITWEB_CONFIG
311 # $feature{'blame'}{'default'} = [1];
312 # To have project specific config enable override in $GITWEB_CONFIG
313 # $feature{'blame'}{'override'} = 1;
314 # and in project config gitweb.blame = 0|1;
316 'sub' => sub { feature_bool
('blame', @_) },
320 # Enable the 'snapshot' link, providing a compressed archive of any
321 # tree. This can potentially generate high traffic if you have large
324 # Value is a list of formats defined in %known_snapshot_formats that
326 # To disable system wide have in $GITWEB_CONFIG
327 # $feature{'snapshot'}{'default'} = [];
328 # To have project specific config enable override in $GITWEB_CONFIG
329 # $feature{'snapshot'}{'override'} = 1;
330 # and in project config, a comma-separated list of formats or "none"
331 # to disable. Example: gitweb.snapshot = tbz2,zip;
333 'sub' => \
&feature_snapshot
,
335 'default' => ['tgz']},
337 # Enable text search, which will list the commits which match author,
338 # committer or commit text to a given string. Enabled by default.
339 # Project specific override is not supported.
341 # Note that this controls all search features, which means that if
342 # it is disabled, then 'grep' and 'pickaxe' search would also be
348 # Enable grep search, which will list the files in currently selected
349 # tree containing the given string. Enabled by default. This can be
350 # potentially CPU-intensive, of course.
351 # Note that you need to have 'search' feature enabled too.
353 # To enable system wide have in $GITWEB_CONFIG
354 # $feature{'grep'}{'default'} = [1];
355 # To have project specific config enable override in $GITWEB_CONFIG
356 # $feature{'grep'}{'override'} = 1;
357 # and in project config gitweb.grep = 0|1;
359 'sub' => sub { feature_bool
('grep', @_) },
363 # Enable the pickaxe search, which will list the commits that modified
364 # a given string in a file. This can be practical and quite faster
365 # alternative to 'blame', but still potentially CPU-intensive.
366 # Note that you need to have 'search' feature enabled too.
368 # To enable system wide have in $GITWEB_CONFIG
369 # $feature{'pickaxe'}{'default'} = [1];
370 # To have project specific config enable override in $GITWEB_CONFIG
371 # $feature{'pickaxe'}{'override'} = 1;
372 # and in project config gitweb.pickaxe = 0|1;
374 'sub' => sub { feature_bool
('pickaxe', @_) },
378 # Enable showing size of blobs in a 'tree' view, in a separate
379 # column, similar to what 'ls -l' does. This cost a bit of IO.
381 # To disable system wide have in $GITWEB_CONFIG
382 # $feature{'show-sizes'}{'default'} = [0];
383 # To have project specific config enable override in $GITWEB_CONFIG
384 # $feature{'show-sizes'}{'override'} = 1;
385 # and in project config gitweb.showsizes = 0|1;
387 'sub' => sub { feature_bool
('showsizes', @_) },
391 # Make gitweb use an alternative format of the URLs which can be
392 # more readable and natural-looking: project name is embedded
393 # directly in the path and the query string contains other
394 # auxiliary information. All gitweb installations recognize
395 # URL in either format; this configures in which formats gitweb
398 # To enable system wide have in $GITWEB_CONFIG
399 # $feature{'pathinfo'}{'default'} = [1];
400 # Project specific override is not supported.
402 # Note that you will need to change the default location of CSS,
403 # favicon, logo and possibly other files to an absolute URL. Also,
404 # if gitweb.cgi serves as your indexfile, you will need to force
405 # $my_uri to contain the script name in your $GITWEB_CONFIG.
410 # Make gitweb consider projects in project root subdirectories
411 # to be forks of existing projects. Given project $projname.git,
412 # projects matching $projname/*.git will not be shown in the main
413 # projects list, instead a '+' mark will be added to $projname
414 # there and a 'forks' view will be enabled for the project, listing
415 # all the forks. If project list is taken from a file, forks have
416 # to be listed after the main project.
418 # To enable system wide have in $GITWEB_CONFIG
419 # $feature{'forks'}{'default'} = [1];
420 # Project specific override is not supported.
425 # Insert custom links to the action bar of all project pages.
426 # This enables you mainly to link to third-party scripts integrating
427 # into gitweb; e.g. git-browser for graphical history representation
428 # or custom web-based repository administration interface.
430 # The 'default' value consists of a list of triplets in the form
431 # (label, link, position) where position is the label after which
432 # to insert the link and link is a format string where %n expands
433 # to the project name, %f to the project path within the filesystem,
434 # %h to the current hash (h gitweb parameter) and %b to the current
435 # hash base (hb gitweb parameter); %% expands to %.
437 # To enable system wide have in $GITWEB_CONFIG e.g.
438 # $feature{'actions'}{'default'} = [('graphiclog',
439 # '/git-browser/by-commit.html?r=%n', 'summary')];
440 # Project specific override is not supported.
445 # Allow gitweb scan project content tags of project repository,
446 # and display the popular Web 2.0-ish "tag cloud" near the projects
447 # list. Note that this is something COMPLETELY different from the
450 # gitweb by itself can show existing tags, but it does not handle
451 # tagging itself; you need to do it externally, outside gitweb.
452 # The format is described in git_get_project_ctags() subroutine.
453 # You may want to install the HTML::TagCloud Perl module to get
454 # a pretty tag cloud instead of just a list of tags.
456 # To enable system wide have in $GITWEB_CONFIG
457 # $feature{'ctags'}{'default'} = [1];
458 # Project specific override is not supported.
460 # In the future whether ctags editing is enabled might depend
461 # on the value, but using 1 should always mean no editing of ctags.
466 # The maximum number of patches in a patchset generated in patch
467 # view. Set this to 0 or undef to disable patch view, or to a
468 # negative number to remove any limit.
470 # To disable system wide have in $GITWEB_CONFIG
471 # $feature{'patches'}{'default'} = [0];
472 # To have project specific config enable override in $GITWEB_CONFIG
473 # $feature{'patches'}{'override'} = 1;
474 # and in project config gitweb.patches = 0|n;
475 # where n is the maximum number of patches allowed in a patchset.
477 'sub' => \
&feature_patches
,
481 # Avatar support. When this feature is enabled, views such as
482 # shortlog or commit will display an avatar associated with
483 # the email of the committer(s) and/or author(s).
485 # Currently available providers are gravatar and picon.
486 # If an unknown provider is specified, the feature is disabled.
488 # Gravatar depends on Digest::MD5.
489 # Picon currently relies on the indiana.edu database.
491 # To enable system wide have in $GITWEB_CONFIG
492 # $feature{'avatar'}{'default'} = ['<provider>'];
493 # where <provider> is either gravatar or picon.
494 # To have project specific config enable override in $GITWEB_CONFIG
495 # $feature{'avatar'}{'override'} = 1;
496 # and in project config gitweb.avatar = <provider>;
498 'sub' => \
&feature_avatar
,
502 # Enable displaying how much time and how many git commands
503 # it took to generate and display page. Disabled by default.
504 # Project specific override is not supported.
509 # Enable turning some links into links to actions which require
510 # JavaScript to run (like 'blame_incremental'). Not enabled by
511 # default. Project specific override is currently not supported.
512 'javascript-actions' => {
516 # Enable and configure ability to change common timezone for dates
517 # in gitweb output via JavaScript. Enabled by default.
518 # Project specific override is not supported.
519 'javascript-timezone' => {
522 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
523 # or undef to turn off this feature
524 'gitweb_tz', # name of cookie where to store selected timezone
525 'datetime', # CSS class used to mark up dates for manipulation
528 # Syntax highlighting support. This is based on Daniel Svensson's
529 # and Sham Chukoury's work in gitweb-xmms2.git.
530 # It requires the 'highlight' program present in $PATH,
531 # and therefore is disabled by default.
533 # To enable system wide have in $GITWEB_CONFIG
534 # $feature{'highlight'}{'default'} = [1];
537 'sub' => sub { feature_bool
('highlight', @_) },
541 # Enable displaying of remote heads in the heads list
543 # To enable system wide have in $GITWEB_CONFIG
544 # $feature{'remote_heads'}{'default'} = [1];
545 # To have project specific config enable override in $GITWEB_CONFIG
546 # $feature{'remote_heads'}{'override'} = 1;
547 # and in project config gitweb.remoteheads = 0|1;
549 'sub' => sub { feature_bool
('remote_heads', @_) },
554 sub gitweb_get_feature
{
556 return unless exists $feature{$name};
557 my ($sub, $override, @defaults) = (
558 $feature{$name}{'sub'},
559 $feature{$name}{'override'},
560 @{$feature{$name}{'default'}});
561 # project specific override is possible only if we have project
562 our $git_dir; # global variable, declared later
563 if (!$override || !defined $git_dir) {
567 warn "feature $name is not overridable";
570 return $sub->(@defaults);
573 # A wrapper to check if a given feature is enabled.
574 # With this, you can say
576 # my $bool_feat = gitweb_check_feature('bool_feat');
577 # gitweb_check_feature('bool_feat') or somecode;
581 # my ($bool_feat) = gitweb_get_feature('bool_feat');
582 # (gitweb_get_feature('bool_feat'))[0] or somecode;
584 sub gitweb_check_feature
{
585 return (gitweb_get_feature
(@_))[0];
591 my ($val) = git_get_project_config
($key, '--bool');
595 } elsif ($val eq 'true') {
597 } elsif ($val eq 'false') {
602 sub feature_snapshot
{
605 my ($val) = git_get_project_config
('snapshot');
608 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
614 sub feature_patches
{
615 my @val = (git_get_project_config
('patches', '--int'));
625 my @val = (git_get_project_config
('avatar'));
627 return @val ? @val : @_;
630 # checking HEAD file with -e is fragile if the repository was
631 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
633 sub check_head_link
{
635 my $headfile = "$dir/HEAD";
636 return ((-e
$headfile) ||
637 (-l
$headfile && readlink($headfile) =~ /^refs\/heads\
//));
640 sub check_export_ok
{
642 return (check_head_link
($dir) &&
643 (!$export_ok || -e
"$dir/$export_ok") &&
644 (!$export_auth_hook || $export_auth_hook->($dir)));
647 # process alternate names for backward compatibility
648 # filter out unsupported (unknown) snapshot formats
649 sub filter_snapshot_fmts
{
653 exists $known_snapshot_format_aliases{$_} ?
654 $known_snapshot_format_aliases{$_} : $_} @fmts;
656 exists $known_snapshot_formats{$_} &&
657 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
660 # If it is set to code reference, it is code that it is to be run once per
661 # request, allowing updating configurations that change with each request,
662 # while running other code in config file only once.
664 # Otherwise, if it is false then gitweb would process config file only once;
665 # if it is true then gitweb config would be run for each request.
666 our $per_request_config = 1;
668 # read and parse gitweb config file given by its parameter.
669 # returns true on success, false on recoverable error, allowing
670 # to chain this subroutine, using first file that exists.
671 # dies on errors during parsing config file, as it is unrecoverable.
672 sub read_config_file
{
673 my $filename = shift;
674 return unless defined $filename;
675 # die if there are errors parsing config file
684 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
685 sub evaluate_gitweb_config
{
686 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
687 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
688 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
690 # Protect against duplications of file names, to not read config twice.
691 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
692 # there possibility of duplication of filename there doesn't matter.
693 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
694 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
696 # Common system-wide settings for convenience.
697 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
698 read_config_file
($GITWEB_CONFIG_COMMON);
700 # Use first config file that exists. This means use the per-instance
701 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
702 read_config_file
($GITWEB_CONFIG) and return;
703 read_config_file
($GITWEB_CONFIG_SYSTEM);
706 # Get loadavg of system, to compare against $maxload.
707 # Currently it requires '/proc/loadavg' present to get loadavg;
708 # if it is not present it returns 0, which means no load checking.
710 if( -e
'/proc/loadavg' ){
711 open my $fd, '<', '/proc/loadavg'
713 my @load = split(/\s+/, scalar <$fd>);
716 # The first three columns measure CPU and IO utilization of the last one,
717 # five, and 10 minute periods. The fourth column shows the number of
718 # currently running processes and the total number of processes in the m/n
719 # format. The last column displays the last process ID used.
720 return $load[0] || 0;
722 # additional checks for load average should go here for things that don't export
728 # version of the core git binary
730 sub evaluate_git_version
{
731 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
732 $number_of_git_cmds++;
736 if (defined $maxload && get_loadavg
() > $maxload) {
737 die_error
(503, "The load average on the server is too high");
741 # ======================================================================
742 # input validation and dispatch
744 # input parameters can be collected from a variety of sources (presently, CGI
745 # and PATH_INFO), so we define an %input_params hash that collects them all
746 # together during validation: this allows subsequent uses (e.g. href()) to be
747 # agnostic of the parameter origin
749 our %input_params = ();
751 # input parameters are stored with the long parameter name as key. This will
752 # also be used in the href subroutine to convert parameters to their CGI
753 # equivalent, and since the href() usage is the most frequent one, we store
754 # the name -> CGI key mapping here, instead of the reverse.
756 # XXX: Warning: If you touch this, check the search form for updating,
759 our @cgi_param_mapping = (
767 hash_parent_base
=> "hpb",
772 snapshot_format
=> "sf",
773 extra_options
=> "opt",
774 search_use_regexp
=> "sr",
777 project_filter
=> "pf",
778 # this must be last entry (for manipulation from JavaScript)
781 our %cgi_param_mapping = @cgi_param_mapping;
783 # we will also need to know the possible actions, for validation
785 "blame" => \
&git_blame
,
786 "blame_incremental" => \
&git_blame_incremental
,
787 "blame_data" => \
&git_blame_data
,
788 "blobdiff" => \
&git_blobdiff
,
789 "blobdiff_plain" => \
&git_blobdiff_plain
,
790 "blob" => \
&git_blob
,
791 "blob_plain" => \
&git_blob_plain
,
792 "commitdiff" => \
&git_commitdiff
,
793 "commitdiff_plain" => \
&git_commitdiff_plain
,
794 "commit" => \
&git_commit
,
795 "forks" => \
&git_forks
,
796 "heads" => \
&git_heads
,
797 "history" => \
&git_history
,
799 "patch" => \
&git_patch
,
800 "patches" => \
&git_patches
,
801 "remotes" => \
&git_remotes
,
803 "atom" => \
&git_atom
,
804 "search" => \
&git_search
,
805 "search_help" => \
&git_search_help
,
806 "shortlog" => \
&git_shortlog
,
807 "summary" => \
&git_summary
,
809 "tags" => \
&git_tags
,
810 "tree" => \
&git_tree
,
811 "snapshot" => \
&git_snapshot
,
812 "object" => \
&git_object
,
813 # those below don't need $project
814 "opml" => \
&git_opml
,
815 "project_list" => \
&git_project_list
,
816 "project_index" => \
&git_project_index
,
819 # finally, we have the hash of allowed extra_options for the commands that
821 our %allowed_options = (
822 "--no-merges" => [ qw(rss atom log shortlog history) ],
825 # fill %input_params with the CGI parameters. All values except for 'opt'
826 # should be single values, but opt can be an array. We should probably
827 # build an array of parameters that can be multi-valued, but since for the time
828 # being it's only this one, we just single it out
829 sub evaluate_query_params
{
832 while (my ($name, $symbol) = each %cgi_param_mapping) {
833 if ($symbol eq 'opt') {
834 $input_params{$name} = [ map { decode_utf8
($_) } $cgi->param($symbol) ];
836 $input_params{$name} = decode_utf8
($cgi->param($symbol));
841 # now read PATH_INFO and update the parameter list for missing parameters
842 sub evaluate_path_info
{
843 return if defined $input_params{'project'};
844 return if !$path_info;
845 $path_info =~ s
,^/+,,;
846 return if !$path_info;
848 # find which part of PATH_INFO is project
849 my $project = $path_info;
851 while ($project && !check_head_link
("$projectroot/$project")) {
852 $project =~ s
,/*[^/]*$,,;
854 return unless $project;
855 $input_params{'project'} = $project;
857 # do not change any parameters if an action is given using the query string
858 return if $input_params{'action'};
859 $path_info =~ s
,^\Q
$project\E
/*,,;
861 # next, check if we have an action
862 my $action = $path_info;
864 if (exists $actions{$action}) {
865 $path_info =~ s
,^$action/*,,;
866 $input_params{'action'} = $action;
869 # list of actions that want hash_base instead of hash, but can have no
870 # pathname (f) parameter
876 # we want to catch, among others
877 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
878 my ($parentrefname, $parentpathname, $refname, $pathname) =
879 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
881 # first, analyze the 'current' part
882 if (defined $pathname) {
883 # we got "branch:filename" or "branch:dir/"
884 # we could use git_get_type(branch:pathname), but:
885 # - it needs $git_dir
886 # - it does a git() call
887 # - the convention of terminating directories with a slash
888 # makes it superfluous
889 # - embedding the action in the PATH_INFO would make it even
891 $pathname =~ s
,^/+,,;
892 if (!$pathname || substr($pathname, -1) eq "/") {
893 $input_params{'action'} ||= "tree";
896 # the default action depends on whether we had parent info
898 if ($parentrefname) {
899 $input_params{'action'} ||= "blobdiff_plain";
901 $input_params{'action'} ||= "blob_plain";
904 $input_params{'hash_base'} ||= $refname;
905 $input_params{'file_name'} ||= $pathname;
906 } elsif (defined $refname) {
907 # we got "branch". In this case we have to choose if we have to
908 # set hash or hash_base.
910 # Most of the actions without a pathname only want hash to be
911 # set, except for the ones specified in @wants_base that want
912 # hash_base instead. It should also be noted that hand-crafted
913 # links having 'history' as an action and no pathname or hash
914 # set will fail, but that happens regardless of PATH_INFO.
915 if (defined $parentrefname) {
916 # if there is parent let the default be 'shortlog' action
917 # (for http://git.example.com/repo.git/A..B links); if there
918 # is no parent, dispatch will detect type of object and set
919 # action appropriately if required (if action is not set)
920 $input_params{'action'} ||= "shortlog";
922 if ($input_params{'action'} &&
923 grep { $_ eq $input_params{'action'} } @wants_base) {
924 $input_params{'hash_base'} ||= $refname;
926 $input_params{'hash'} ||= $refname;
930 # next, handle the 'parent' part, if present
931 if (defined $parentrefname) {
932 # a missing pathspec defaults to the 'current' filename, allowing e.g.
933 # someproject/blobdiff/oldrev..newrev:/filename
934 if ($parentpathname) {
935 $parentpathname =~ s
,^/+,,;
936 $parentpathname =~ s
,/$,,;
937 $input_params{'file_parent'} ||= $parentpathname;
939 $input_params{'file_parent'} ||= $input_params{'file_name'};
941 # we assume that hash_parent_base is wanted if a path was specified,
942 # or if the action wants hash_base instead of hash
943 if (defined $input_params{'file_parent'} ||
944 grep { $_ eq $input_params{'action'} } @wants_base) {
945 $input_params{'hash_parent_base'} ||= $parentrefname;
947 $input_params{'hash_parent'} ||= $parentrefname;
951 # for the snapshot action, we allow URLs in the form
952 # $project/snapshot/$hash.ext
953 # where .ext determines the snapshot and gets removed from the
954 # passed $refname to provide the $hash.
956 # To be able to tell that $refname includes the format extension, we
957 # require the following two conditions to be satisfied:
958 # - the hash input parameter MUST have been set from the $refname part
959 # of the URL (i.e. they must be equal)
960 # - the snapshot format MUST NOT have been defined already (e.g. from
962 # It's also useless to try any matching unless $refname has a dot,
963 # so we check for that too
964 if (defined $input_params{'action'} &&
965 $input_params{'action'} eq 'snapshot' &&
966 defined $refname && index($refname, '.') != -1 &&
967 $refname eq $input_params{'hash'} &&
968 !defined $input_params{'snapshot_format'}) {
969 # We loop over the known snapshot formats, checking for
970 # extensions. Allowed extensions are both the defined suffix
971 # (which includes the initial dot already) and the snapshot
972 # format key itself, with a prepended dot
973 while (my ($fmt, $opt) = each %known_snapshot_formats) {
975 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
979 # a valid suffix was found, so set the snapshot format
980 # and reset the hash parameter
981 $input_params{'snapshot_format'} = $fmt;
982 $input_params{'hash'} = $hash;
983 # we also set the format suffix to the one requested
984 # in the URL: this way a request for e.g. .tgz returns
985 # a .tgz instead of a .tar.gz
986 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
992 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
993 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
994 $searchtext, $search_regexp, $project_filter);
995 sub evaluate_and_validate_params
{
996 our $action = $input_params{'action'};
997 if (defined $action) {
998 if (!validate_action
($action)) {
999 die_error
(400, "Invalid action parameter");
1003 # parameters which are pathnames
1004 our $project = $input_params{'project'};
1005 if (defined $project) {
1006 if (!validate_project
($project)) {
1008 die_error
(404, "No such project");
1012 our $project_filter = $input_params{'project_filter'};
1013 if (defined $project_filter) {
1014 if (!validate_pathname
($project_filter)) {
1015 die_error
(404, "Invalid project_filter parameter");
1019 our $file_name = $input_params{'file_name'};
1020 if (defined $file_name) {
1021 if (!validate_pathname
($file_name)) {
1022 die_error
(400, "Invalid file parameter");
1026 our $file_parent = $input_params{'file_parent'};
1027 if (defined $file_parent) {
1028 if (!validate_pathname
($file_parent)) {
1029 die_error
(400, "Invalid file parent parameter");
1033 # parameters which are refnames
1034 our $hash = $input_params{'hash'};
1035 if (defined $hash) {
1036 if (!validate_refname
($hash)) {
1037 die_error
(400, "Invalid hash parameter");
1041 our $hash_parent = $input_params{'hash_parent'};
1042 if (defined $hash_parent) {
1043 if (!validate_refname
($hash_parent)) {
1044 die_error
(400, "Invalid hash parent parameter");
1048 our $hash_base = $input_params{'hash_base'};
1049 if (defined $hash_base) {
1050 if (!validate_refname
($hash_base)) {
1051 die_error
(400, "Invalid hash base parameter");
1055 our @extra_options = @{$input_params{'extra_options'}};
1056 # @extra_options is always defined, since it can only be (currently) set from
1057 # CGI, and $cgi->param() returns the empty array in array context if the param
1059 foreach my $opt (@extra_options) {
1060 if (not exists $allowed_options{$opt}) {
1061 die_error
(400, "Invalid option parameter");
1063 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1064 die_error
(400, "Invalid option parameter for this action");
1068 our $hash_parent_base = $input_params{'hash_parent_base'};
1069 if (defined $hash_parent_base) {
1070 if (!validate_refname
($hash_parent_base)) {
1071 die_error
(400, "Invalid hash parent base parameter");
1076 our $page = $input_params{'page'};
1077 if (defined $page) {
1078 if ($page =~ m/[^0-9]/) {
1079 die_error
(400, "Invalid page parameter");
1083 our $searchtype = $input_params{'searchtype'};
1084 if (defined $searchtype) {
1085 if ($searchtype =~ m/[^a-z]/) {
1086 die_error
(400, "Invalid searchtype parameter");
1090 our $search_use_regexp = $input_params{'search_use_regexp'};
1092 our $searchtext = $input_params{'searchtext'};
1093 our $search_regexp = undef;
1094 if (defined $searchtext) {
1095 if (length($searchtext) < 2) {
1096 die_error
(403, "At least two characters are required for search parameter");
1098 if ($search_use_regexp) {
1099 $search_regexp = $searchtext;
1100 if (!eval { qr/$search_regexp/; 1; }) {
1101 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1102 die_error
(400, "Invalid search regexp '$search_regexp'",
1106 $search_regexp = quotemeta $searchtext;
1111 # path to the current git repository
1113 sub evaluate_git_dir
{
1114 our $git_dir = "$projectroot/$project" if $project;
1117 our (@snapshot_fmts, $git_avatar);
1118 sub configure_gitweb_features
{
1119 # list of supported snapshot formats
1120 our @snapshot_fmts = gitweb_get_feature
('snapshot');
1121 @snapshot_fmts = filter_snapshot_fmts
(@snapshot_fmts);
1123 # check that the avatar feature is set to a known provider name,
1124 # and for each provider check if the dependencies are satisfied.
1125 # if the provider name is invalid or the dependencies are not met,
1126 # reset $git_avatar to the empty string.
1127 our ($git_avatar) = gitweb_get_feature
('avatar');
1128 if ($git_avatar eq 'gravatar') {
1129 $git_avatar = '' unless (eval { require Digest
::MD5
; 1; });
1130 } elsif ($git_avatar eq 'picon') {
1137 # custom error handler: 'die <message>' is Internal Server Error
1138 sub handle_errors_html
{
1139 my $msg = shift; # it is already HTML escaped
1141 # to avoid infinite loop where error occurs in die_error,
1142 # change handler to default handler, disabling handle_errors_html
1143 set_message
("Error occurred when inside die_error:\n$msg");
1145 # you cannot jump out of die_error when called as error handler;
1146 # the subroutine set via CGI::Carp::set_message is called _after_
1147 # HTTP headers are already written, so it cannot write them itself
1148 die_error
(undef, undef, $msg, -error_handler
=> 1, -no_http_header
=> 1);
1150 set_message
(\
&handle_errors_html
);
1154 if (!defined $action) {
1155 if (defined $hash) {
1156 $action = git_get_type
($hash);
1157 $action or die_error
(404, "Object does not exist");
1158 } elsif (defined $hash_base && defined $file_name) {
1159 $action = git_get_type
("$hash_base:$file_name");
1160 $action or die_error
(404, "File or directory does not exist");
1161 } elsif (defined $project) {
1162 $action = 'summary';
1164 $action = 'project_list';
1167 if (!defined($actions{$action})) {
1168 die_error
(400, "Unknown action");
1170 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1172 die_error
(400, "Project needed");
1174 $actions{$action}->();
1178 our $t0 = [ gettimeofday
() ]
1180 our $number_of_git_cmds = 0;
1183 our $first_request = 1;
1188 if ($first_request) {
1189 evaluate_gitweb_config
();
1190 evaluate_git_version
();
1192 if ($per_request_config) {
1193 if (ref($per_request_config) eq 'CODE') {
1194 $per_request_config->();
1195 } elsif (!$first_request) {
1196 evaluate_gitweb_config
();
1201 # $projectroot and $projects_list might be set in gitweb config file
1202 $projects_list ||= $projectroot;
1204 evaluate_query_params
();
1205 evaluate_path_info
();
1206 evaluate_and_validate_params
();
1209 configure_gitweb_features
();
1214 our $is_last_request = sub { 1 };
1215 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1218 sub configure_as_fcgi
{
1220 our $CGI = 'CGI::Fast';
1222 my $request_number = 0;
1223 # let each child service 100 requests
1224 our $is_last_request = sub { ++$request_number > 100 };
1227 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__
;
1229 if $script_name =~ /\.fcgi$/;
1231 return unless (@ARGV);
1233 require Getopt
::Long
;
1234 Getopt
::Long
::GetOptions
(
1235 'fastcgi|fcgi|f' => \
&configure_as_fcgi
,
1236 'nproc|n=i' => sub {
1237 my ($arg, $val) = @_;
1238 return unless eval { require FCGI
::ProcManager
; 1; };
1239 my $proc_manager = FCGI
::ProcManager-
>new({
1240 n_processes
=> $val,
1242 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1243 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1244 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1253 $pre_listen_hook->()
1254 if $pre_listen_hook;
1257 while ($cgi = $CGI->new()) {
1258 $pre_dispatch_hook->()
1259 if $pre_dispatch_hook;
1263 $post_dispatch_hook->()
1264 if $post_dispatch_hook;
1267 last REQUEST
if ($is_last_request->());
1276 if (defined caller) {
1277 # wrapped in a subroutine processing requests,
1278 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1281 # pure CGI script, serving single request
1285 ## ======================================================================
1288 # possible values of extra options
1289 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1290 # -replay => 1 - start from a current view (replay with modifications)
1291 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1292 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1295 # default is to use -absolute url() i.e. $my_uri
1296 my $href = $params{-full
} ? $my_url : $my_uri;
1298 # implicit -replay, must be first of implicit params
1299 $params{-replay
} = 1 if (keys %params == 1 && $params{-anchor
});
1301 $params{'project'} = $project unless exists $params{'project'};
1303 if ($params{-replay
}) {
1304 while (my ($name, $symbol) = each %cgi_param_mapping) {
1305 if (!exists $params{$name}) {
1306 $params{$name} = $input_params{$name};
1311 my $use_pathinfo = gitweb_check_feature
('pathinfo');
1312 if (defined $params{'project'} &&
1313 (exists $params{-path_info
} ? $params{-path_info
} : $use_pathinfo)) {
1314 # try to put as many parameters as possible in PATH_INFO:
1317 # - hash_parent or hash_parent_base:/file_parent
1318 # - hash or hash_base:/filename
1319 # - the snapshot_format as an appropriate suffix
1321 # When the script is the root DirectoryIndex for the domain,
1322 # $href here would be something like http://gitweb.example.com/
1323 # Thus, we strip any trailing / from $href, to spare us double
1324 # slashes in the final URL
1327 # Then add the project name, if present
1328 $href .= "/".esc_path_info
($params{'project'});
1329 delete $params{'project'};
1331 # since we destructively absorb parameters, we keep this
1332 # boolean that remembers if we're handling a snapshot
1333 my $is_snapshot = $params{'action'} eq 'snapshot';
1335 # Summary just uses the project path URL, any other action is
1337 if (defined $params{'action'}) {
1338 $href .= "/".esc_path_info
($params{'action'})
1339 unless $params{'action'} eq 'summary';
1340 delete $params{'action'};
1343 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1344 # stripping nonexistent or useless pieces
1345 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1346 || $params{'hash_parent'} || $params{'hash'});
1347 if (defined $params{'hash_base'}) {
1348 if (defined $params{'hash_parent_base'}) {
1349 $href .= esc_path_info
($params{'hash_parent_base'});
1350 # skip the file_parent if it's the same as the file_name
1351 if (defined $params{'file_parent'}) {
1352 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1353 delete $params{'file_parent'};
1354 } elsif ($params{'file_parent'} !~ /\.\./) {
1355 $href .= ":/".esc_path_info
($params{'file_parent'});
1356 delete $params{'file_parent'};
1360 delete $params{'hash_parent'};
1361 delete $params{'hash_parent_base'};
1362 } elsif (defined $params{'hash_parent'}) {
1363 $href .= esc_path_info
($params{'hash_parent'}). "..";
1364 delete $params{'hash_parent'};
1367 $href .= esc_path_info
($params{'hash_base'});
1368 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1369 $href .= ":/".esc_path_info
($params{'file_name'});
1370 delete $params{'file_name'};
1372 delete $params{'hash'};
1373 delete $params{'hash_base'};
1374 } elsif (defined $params{'hash'}) {
1375 $href .= esc_path_info
($params{'hash'});
1376 delete $params{'hash'};
1379 # If the action was a snapshot, we can absorb the
1380 # snapshot_format parameter too
1382 my $fmt = $params{'snapshot_format'};
1383 # snapshot_format should always be defined when href()
1384 # is called, but just in case some code forgets, we
1385 # fall back to the default
1386 $fmt ||= $snapshot_fmts[0];
1387 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1388 delete $params{'snapshot_format'};
1392 # now encode the parameters explicitly
1394 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1395 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1396 if (defined $params{$name}) {
1397 if (ref($params{$name}) eq "ARRAY") {
1398 foreach my $par (@{$params{$name}}) {
1399 push @result, $symbol . "=" . esc_param
($par);
1402 push @result, $symbol . "=" . esc_param
($params{$name});
1406 $href .= "?" . join(';', @result) if scalar @result;
1408 # final transformation: trailing spaces must be escaped (URI-encoded)
1409 $href =~ s/(\s+)$/CGI::escape($1)/e;
1411 if ($params{-anchor
}) {
1412 $href .= "#".esc_param
($params{-anchor
});
1419 ## ======================================================================
1420 ## validation, quoting/unquoting and escaping
1422 sub validate_action
{
1423 my $input = shift || return undef;
1424 return undef unless exists $actions{$input};
1428 sub validate_project
{
1429 my $input = shift || return undef;
1430 if (!validate_pathname
($input) ||
1431 !(-d
"$projectroot/$input") ||
1432 !check_export_ok
("$projectroot/$input") ||
1433 ($strict_export && !project_in_list
($input))) {
1440 sub validate_pathname
{
1441 my $input = shift || return undef;
1443 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1444 # at the beginning, at the end, and between slashes.
1445 # also this catches doubled slashes
1446 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1449 # no null characters
1450 if ($input =~ m!\0!) {
1456 sub is_valid_ref_format
{
1457 my $input = shift || return undef;
1459 # restrictions on ref name according to git-check-ref-format
1460 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1466 sub validate_refname
{
1467 my $input = shift || return undef;
1469 # textual hashes are O.K.
1470 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1473 # it must be correct pathname
1474 $input = validate_pathname
($input)
1476 # check git-check-ref-format restrictions
1477 is_valid_ref_format
($input)
1482 # decode sequences of octets in utf8 into Perl's internal form,
1483 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1484 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1487 return undef unless defined $str;
1489 if (utf8
::is_utf8
($str) || utf8
::decode
($str)) {
1492 return decode
($fallback_encoding, $str, Encode
::FB_DEFAULT
);
1496 # quote unsafe chars, but keep the slash, even when it's not
1497 # correct, but quoted slashes look too horrible in bookmarks
1500 return undef unless defined $str;
1501 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI
::escape
($1)/eg
;
1506 # the quoting rules for path_info fragment are slightly different
1509 return undef unless defined $str;
1511 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1512 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI
::escape
($1)/eg
;
1517 # quote unsafe chars in whole URL, so some characters cannot be quoted
1520 return undef unless defined $str;
1521 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI
::escape
($1)/eg
;
1526 # quote unsafe characters in HTML attributes
1529 # for XHTML conformance escaping '"' to '"' is not enough
1530 return esc_html
(@_);
1533 # replace invalid utf8 character with SUBSTITUTION sequence
1538 return undef unless defined $str;
1540 $str = to_utf8
($str);
1541 $str = $cgi->escapeHTML($str);
1542 if ($opts{'-nbsp'}) {
1543 $str =~ s/ / /g;
1545 $str =~ s
|([[:cntrl
:]])|(($1 ne "\t") ? quot_cec
($1) : $1)|eg
;
1549 # quote control characters and escape filename to HTML
1554 return undef unless defined $str;
1556 $str = to_utf8
($str);
1557 $str = $cgi->escapeHTML($str);
1558 if ($opts{'-nbsp'}) {
1559 $str =~ s/ / /g;
1561 $str =~ s
|([[:cntrl
:]])|quot_cec
($1)|eg
;
1565 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1569 return undef unless defined $str;
1571 $str = to_utf8
($str);
1572 $str =~ s
|([[:cntrl
:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec
($1))|eg
;
1576 # Make control characters "printable", using character escape codes (CEC)
1580 my %es = ( # character escape codes, aka escape sequences
1581 "\t" => '\t', # tab (HT)
1582 "\n" => '\n', # line feed (LF)
1583 "\r" => '\r', # carrige return (CR)
1584 "\f" => '\f', # form feed (FF)
1585 "\b" => '\b', # backspace (BS)
1586 "\a" => '\a', # alarm (bell) (BEL)
1587 "\e" => '\e', # escape (ESC)
1588 "\013" => '\v', # vertical tab (VT)
1589 "\000" => '\0', # nul character (NUL)
1591 my $chr = ( (exists $es{$cntrl})
1593 : sprintf('\%2x', ord($cntrl)) );
1594 if ($opts{-nohtml
}) {
1597 return "<span class=\"cntrl\">$chr</span>";
1601 # Alternatively use unicode control pictures codepoints,
1602 # Unicode "printable representation" (PR)
1607 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1608 if ($opts{-nohtml
}) {
1611 return "<span class=\"cntrl\">$chr</span>";
1615 # git may return quoted and escaped filenames
1621 my %es = ( # character escape codes, aka escape sequences
1622 't' => "\t", # tab (HT, TAB)
1623 'n' => "\n", # newline (NL)
1624 'r' => "\r", # return (CR)
1625 'f' => "\f", # form feed (FF)
1626 'b' => "\b", # backspace (BS)
1627 'a' => "\a", # alarm (bell) (BEL)
1628 'e' => "\e", # escape (ESC)
1629 'v' => "\013", # vertical tab (VT)
1632 if ($seq =~ m/^[0-7]{1,3}$/) {
1633 # octal char sequence
1634 return chr(oct($seq));
1635 } elsif (exists $es{$seq}) {
1636 # C escape sequence, aka character escape code
1639 # quoted ordinary character
1643 if ($str =~ m/^"(.*)"$/) {
1646 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1651 # escape tabs (convert tabs to spaces)
1655 while ((my $pos = index($line, "\t")) != -1) {
1656 if (my $count = (8 - ($pos % 8))) {
1657 my $spaces = ' ' x
$count;
1658 $line =~ s/\t/$spaces/;
1665 sub project_in_list
{
1666 my $project = shift;
1667 my @list = git_get_projects_list
();
1668 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1671 ## ----------------------------------------------------------------------
1672 ## HTML aware string manipulation
1674 # Try to chop given string on a word boundary between position
1675 # $len and $len+$add_len. If there is no word boundary there,
1676 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1677 # (marking chopped part) would be longer than given string.
1681 my $add_len = shift || 10;
1682 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1684 # Make sure perl knows it is utf8 encoded so we don't
1685 # cut in the middle of a utf8 multibyte char.
1686 $str = to_utf8
($str);
1688 # allow only $len chars, but don't cut a word if it would fit in $add_len
1689 # if it doesn't fit, cut it if it's still longer than the dots we would add
1690 # remove chopped character entities entirely
1692 # when chopping in the middle, distribute $len into left and right part
1693 # return early if chopping wouldn't make string shorter
1694 if ($where eq 'center') {
1695 return $str if ($len + 5 >= length($str)); # filler is length 5
1698 return $str if ($len + 4 >= length($str)); # filler is length 4
1701 # regexps: ending and beginning with word part up to $add_len
1702 my $endre = qr/.{$len}\w{0,$add_len}/;
1703 my $begre = qr/\w{0,$add_len}.{$len}/;
1705 if ($where eq 'left') {
1706 $str =~ m/^(.*?)($begre)$/;
1707 my ($lead, $body) = ($1, $2);
1708 if (length($lead) > 4) {
1711 return "$lead$body";
1713 } elsif ($where eq 'center') {
1714 $str =~ m/^($endre)(.*)$/;
1715 my ($left, $str) = ($1, $2);
1716 $str =~ m/^(.*?)($begre)$/;
1717 my ($mid, $right) = ($1, $2);
1718 if (length($mid) > 5) {
1721 return "$left$mid$right";
1724 $str =~ m/^($endre)(.*)$/;
1727 if (length($tail) > 4) {
1730 return "$body$tail";
1734 # takes the same arguments as chop_str, but also wraps a <span> around the
1735 # result with a title attribute if it does get chopped. Additionally, the
1736 # string is HTML-escaped.
1737 sub chop_and_escape_str
{
1740 my $chopped = chop_str
(@_);
1741 $str = to_utf8
($str);
1742 if ($chopped eq $str) {
1743 return esc_html
($chopped);
1745 $str =~ s/[[:cntrl:]]/?/g;
1746 return $cgi->span({-title
=>$str}, esc_html
($chopped));
1750 # Highlight selected fragments of string, using given CSS class,
1751 # and escape HTML. It is assumed that fragments do not overlap.
1752 # Regions are passed as list of pairs (array references).
1754 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1755 # '<span class="mark">foo</span>bar'
1756 sub esc_html_hl_regions
{
1757 my ($str, $css_class, @sel) = @_;
1758 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1759 @sel = grep { ref($_) eq 'ARRAY' } @sel;
1760 return esc_html
($str, %opts) unless @sel;
1766 my ($begin, $end) = @$s;
1768 # Don't create empty <span> elements.
1769 next if $end <= $begin;
1771 my $escaped = esc_html
(substr($str, $begin, $end - $begin),
1774 $out .= esc_html
(substr($str, $pos, $begin - $pos), %opts)
1775 if ($begin - $pos > 0);
1776 $out .= $cgi->span({-class => $css_class}, $escaped);
1780 $out .= esc_html
(substr($str, $pos), %opts)
1781 if ($pos < length($str));
1786 # return positions of beginning and end of each match
1788 my ($str, $regexp) = @_;
1789 return unless (defined $str && defined $regexp);
1792 while ($str =~ /$regexp/g) {
1793 push @matches, [$-[0], $+[0]];
1798 # highlight match (if any), and escape HTML
1799 sub esc_html_match_hl
{
1800 my ($str, $regexp) = @_;
1801 return esc_html
($str) unless defined $regexp;
1803 my @matches = matchpos_list
($str, $regexp);
1804 return esc_html
($str) unless @matches;
1806 return esc_html_hl_regions
($str, 'match', @matches);
1810 # highlight match (if any) of shortened string, and escape HTML
1811 sub esc_html_match_hl_chopped
{
1812 my ($str, $chopped, $regexp) = @_;
1813 return esc_html_match_hl
($str, $regexp) unless defined $chopped;
1815 my @matches = matchpos_list
($str, $regexp);
1816 return esc_html
($chopped) unless @matches;
1818 # filter matches so that we mark chopped string
1819 my $tail = "... "; # see chop_str
1820 unless ($chopped =~ s/\Q$tail\E$//) {
1823 my $chop_len = length($chopped);
1824 my $tail_len = length($tail);
1827 for my $m (@matches) {
1828 if ($m->[0] > $chop_len) {
1829 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1831 } elsif ($m->[1] > $chop_len) {
1832 push @filtered, [ $m->[0], $chop_len + $tail_len ];
1838 return esc_html_hl_regions
($chopped . $tail, 'match', @filtered);
1841 ## ----------------------------------------------------------------------
1842 ## functions returning short strings
1844 # CSS class for given age value (in seconds)
1848 if (!defined $age) {
1850 } elsif ($age < 60*60*2) {
1852 } elsif ($age < 60*60*24*2) {
1859 # convert age in seconds to "nn units ago" string
1864 if ($age > 60*60*24*365*2) {
1865 $age_str = (int $age/60/60/24/365);
1866 $age_str .= " years ago";
1867 } elsif ($age > 60*60*24*(365/12)*2) {
1868 $age_str = int $age/60/60/24/(365/12);
1869 $age_str .= " months ago";
1870 } elsif ($age > 60*60*24*7*2) {
1871 $age_str = int $age/60/60/24/7;
1872 $age_str .= " weeks ago";
1873 } elsif ($age > 60*60*24*2) {
1874 $age_str = int $age/60/60/24;
1875 $age_str .= " days ago";
1876 } elsif ($age > 60*60*2) {
1877 $age_str = int $age/60/60;
1878 $age_str .= " hours ago";
1879 } elsif ($age > 60*2) {
1880 $age_str = int $age/60;
1881 $age_str .= " min ago";
1882 } elsif ($age > 2) {
1883 $age_str = int $age;
1884 $age_str .= " sec ago";
1886 $age_str .= " right now";
1892 S_IFINVALID
=> 0030000,
1893 S_IFGITLINK
=> 0160000,
1896 # submodule/subproject, a commit object reference
1900 return (($mode & S_IFMT
) == S_IFGITLINK
)
1903 # convert file mode in octal to symbolic file mode string
1905 my $mode = oct shift;
1907 if (S_ISGITLINK
($mode)) {
1908 return 'm---------';
1909 } elsif (S_ISDIR
($mode & S_IFMT
)) {
1910 return 'drwxr-xr-x';
1911 } elsif (S_ISLNK
($mode)) {
1912 return 'lrwxrwxrwx';
1913 } elsif (S_ISREG
($mode)) {
1914 # git cares only about the executable bit
1915 if ($mode & S_IXUSR
) {
1916 return '-rwxr-xr-x';
1918 return '-rw-r--r--';
1921 return '----------';
1925 # convert file mode in octal to file type string
1929 if ($mode !~ m/^[0-7]+$/) {
1935 if (S_ISGITLINK
($mode)) {
1937 } elsif (S_ISDIR
($mode & S_IFMT
)) {
1939 } elsif (S_ISLNK
($mode)) {
1941 } elsif (S_ISREG
($mode)) {
1948 # convert file mode in octal to file type description string
1949 sub file_type_long
{
1952 if ($mode !~ m/^[0-7]+$/) {
1958 if (S_ISGITLINK
($mode)) {
1960 } elsif (S_ISDIR
($mode & S_IFMT
)) {
1962 } elsif (S_ISLNK
($mode)) {
1964 } elsif (S_ISREG
($mode)) {
1965 if ($mode & S_IXUSR
) {
1966 return "executable";
1976 ## ----------------------------------------------------------------------
1977 ## functions returning short HTML fragments, or transforming HTML fragments
1978 ## which don't belong to other sections
1980 # format line of commit message.
1981 sub format_log_line_html
{
1984 $line = esc_html
($line, -nbsp
=>1);
1985 $line =~ s
{\b([0-9a-fA-F
]{8,40})\b}{
1986 $cgi->a({-href
=> href
(action
=>"object", hash
=>$1),
1987 -class => "text"}, $1);
1993 # format marker of refs pointing to given object
1995 # the destination action is chosen based on object type and current context:
1996 # - for annotated tags, we choose the tag view unless it's the current view
1997 # already, in which case we go to shortlog view
1998 # - for other refs, we keep the current view if we're in history, shortlog or
1999 # log view, and select shortlog otherwise
2000 sub format_ref_marker
{
2001 my ($refs, $id) = @_;
2004 if (defined $refs->{$id}) {
2005 foreach my $ref (@{$refs->{$id}}) {
2006 # this code exploits the fact that non-lightweight tags are the
2007 # only indirect objects, and that they are the only objects for which
2008 # we want to use tag instead of shortlog as action
2009 my ($type, $name) = qw();
2010 my $indirect = ($ref =~ s/\^\{\}$//);
2011 # e.g. tags/v2.6.11 or heads/next
2012 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2021 $class .= " indirect" if $indirect;
2023 my $dest_action = "shortlog";
2026 $dest_action = "tag" unless $action eq "tag";
2027 } elsif ($action =~ /^(history|(short)?log)$/) {
2028 $dest_action = $action;
2032 $dest .= "refs/" unless $ref =~ m
!^refs
/!;
2035 my $link = $cgi->a({
2037 action
=>$dest_action,
2041 $markers .= " <span class=\"".esc_attr
($class)."\" title=\"".esc_attr
($ref)."\">" .
2047 return ' <span class="refs">'. $markers . '</span>';
2053 # format, perhaps shortened and with markers, title line
2054 sub format_subject_html
{
2055 my ($long, $short, $href, $extra) = @_;
2056 $extra = '' unless defined($extra);
2058 if (length($short) < length($long)) {
2059 $long =~ s/[[:cntrl:]]/?/g;
2060 return $cgi->a({-href
=> $href, -class => "list subject",
2061 -title
=> to_utf8
($long)},
2062 esc_html
($short)) . $extra;
2064 return $cgi->a({-href
=> $href, -class => "list subject"},
2065 esc_html
($long)) . $extra;
2069 # Rather than recomputing the url for an email multiple times, we cache it
2070 # after the first hit. This gives a visible benefit in views where the avatar
2071 # for the same email is used repeatedly (e.g. shortlog).
2072 # The cache is shared by all avatar engines (currently gravatar only), which
2073 # are free to use it as preferred. Since only one avatar engine is used for any
2074 # given page, there's no risk for cache conflicts.
2075 our %avatar_cache = ();
2077 # Compute the picon url for a given email, by using the picon search service over at
2078 # http://www.cs.indiana.edu/picons/search.html
2080 my $email = lc shift;
2081 if (!$avatar_cache{$email}) {
2082 my ($user, $domain) = split('@', $email);
2083 $avatar_cache{$email} =
2084 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2086 "users+domains+unknown/up/single";
2088 return $avatar_cache{$email};
2091 # Compute the gravatar url for a given email, if it's not in the cache already.
2092 # Gravatar stores only the part of the URL before the size, since that's the
2093 # one computationally more expensive. This also allows reuse of the cache for
2094 # different sizes (for this particular engine).
2096 my $email = lc shift;
2098 $avatar_cache{$email} ||=
2099 "//www.gravatar.com/avatar/" .
2100 Digest
::MD5
::md5_hex
($email) . "?s=";
2101 return $avatar_cache{$email} . $size;
2104 # Insert an avatar for the given $email at the given $size if the feature
2106 sub git_get_avatar
{
2107 my ($email, %opts) = @_;
2108 my $pre_white = ($opts{-pad_before
} ? " " : "");
2109 my $post_white = ($opts{-pad_after
} ? " " : "");
2110 $opts{-size
} ||= 'default';
2111 my $size = $avatar_size{$opts{-size
}} || $avatar_size{'default'};
2113 if ($git_avatar eq 'gravatar') {
2114 $url = gravatar_url
($email, $size);
2115 } elsif ($git_avatar eq 'picon') {
2116 $url = picon_url
($email);
2118 # Other providers can be added by extending the if chain, defining $url
2119 # as needed. If no variant puts something in $url, we assume avatars
2120 # are completely disabled/unavailable.
2123 "<img width=\"$size\" " .
2124 "class=\"avatar\" " .
2125 "src=\"".esc_url
($url)."\" " .
2133 sub format_search_author
{
2134 my ($author, $searchtype, $displaytext) = @_;
2135 my $have_search = gitweb_check_feature
('search');
2139 if ($searchtype eq 'author') {
2140 $performed = "authored";
2141 } elsif ($searchtype eq 'committer') {
2142 $performed = "committed";
2145 return $cgi->a({-href
=> href
(action
=>"search", hash
=>$hash,
2146 searchtext
=>$author,
2147 searchtype
=>$searchtype), class=>"list",
2148 title
=>"Search for commits $performed by $author"},
2152 return $displaytext;
2156 # format the author name of the given commit with the given tag
2157 # the author name is chopped and escaped according to the other
2158 # optional parameters (see chop_str).
2159 sub format_author_html
{
2162 my $author = chop_and_escape_str
($co->{'author_name'}, @_);
2163 return "<$tag class=\"author\">" .
2164 format_search_author
($co->{'author_name'}, "author",
2165 git_get_avatar
($co->{'author_email'}, -pad_after
=> 1) .
2170 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2171 sub format_git_diff_header_line
{
2173 my $diffinfo = shift;
2174 my ($from, $to) = @_;
2176 if ($diffinfo->{'nparents'}) {
2178 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2179 if ($to->{'href'}) {
2180 $line .= $cgi->a({-href
=> $to->{'href'}, -class => "path"},
2181 esc_path
($to->{'file'}));
2182 } else { # file was deleted (no href)
2183 $line .= esc_path
($to->{'file'});
2187 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2188 if ($from->{'href'}) {
2189 $line .= $cgi->a({-href
=> $from->{'href'}, -class => "path"},
2190 'a/' . esc_path
($from->{'file'}));
2191 } else { # file was added (no href)
2192 $line .= 'a/' . esc_path
($from->{'file'});
2195 if ($to->{'href'}) {
2196 $line .= $cgi->a({-href
=> $to->{'href'}, -class => "path"},
2197 'b/' . esc_path
($to->{'file'}));
2198 } else { # file was deleted
2199 $line .= 'b/' . esc_path
($to->{'file'});
2203 return "<div class=\"diff header\">$line</div>\n";
2206 # format extended diff header line, before patch itself
2207 sub format_extended_diff_header_line
{
2209 my $diffinfo = shift;
2210 my ($from, $to) = @_;
2213 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2214 $line .= $cgi->a({-href
=>$from->{'href'}, -class=>"path"},
2215 esc_path
($from->{'file'}));
2217 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2218 $line .= $cgi->a({-href
=>$to->{'href'}, -class=>"path"},
2219 esc_path
($to->{'file'}));
2221 # match single <mode>
2222 if ($line =~ m/\s(\d{6})$/) {
2223 $line .= '<span class="info"> (' .
2224 file_type_long
($1) .
2228 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2229 # can match only for combined diff
2231 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2232 if ($from->{'href'}[$i]) {
2233 $line .= $cgi->a({-href
=>$from->{'href'}[$i],
2235 substr($diffinfo->{'from_id'}[$i],0,7));
2240 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2243 if ($to->{'href'}) {
2244 $line .= $cgi->a({-href
=>$to->{'href'}, -class=>"hash"},
2245 substr($diffinfo->{'to_id'},0,7));
2250 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2251 # can match only for ordinary diff
2252 my ($from_link, $to_link);
2253 if ($from->{'href'}) {
2254 $from_link = $cgi->a({-href
=>$from->{'href'}, -class=>"hash"},
2255 substr($diffinfo->{'from_id'},0,7));
2257 $from_link = '0' x
7;
2259 if ($to->{'href'}) {
2260 $to_link = $cgi->a({-href
=>$to->{'href'}, -class=>"hash"},
2261 substr($diffinfo->{'to_id'},0,7));
2265 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2266 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2269 return $line . "<br/>\n";
2272 # format from-file/to-file diff header
2273 sub format_diff_from_to_header
{
2274 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2279 #assert($line =~ m/^---/) if DEBUG;
2280 # no extra formatting for "^--- /dev/null"
2281 if (! $diffinfo->{'nparents'}) {
2282 # ordinary (single parent) diff
2283 if ($line =~ m!^--- "?a/!) {
2284 if ($from->{'href'}) {
2286 $cgi->a({-href
=>$from->{'href'}, -class=>"path"},
2287 esc_path
($from->{'file'}));
2290 esc_path
($from->{'file'});
2293 $result .= qq
!<div
class="diff from_file">$line</div
>\n!;
2296 # combined diff (merge commit)
2297 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2298 if ($from->{'href'}[$i]) {
2300 $cgi->a({-href
=>href
(action
=>"blobdiff",
2301 hash_parent
=>$diffinfo->{'from_id'}[$i],
2302 hash_parent_base
=>$parents[$i],
2303 file_parent
=>$from->{'file'}[$i],
2304 hash
=>$diffinfo->{'to_id'},
2306 file_name
=>$to->{'file'}),
2308 -title
=>"diff" . ($i+1)},
2311 $cgi->a({-href
=>$from->{'href'}[$i], -class=>"path"},
2312 esc_path
($from->{'file'}[$i]));
2314 $line = '--- /dev/null';
2316 $result .= qq
!<div
class="diff from_file">$line</div
>\n!;
2321 #assert($line =~ m/^\+\+\+/) if DEBUG;
2322 # no extra formatting for "^+++ /dev/null"
2323 if ($line =~ m!^\+\+\+ "?b/!) {
2324 if ($to->{'href'}) {
2326 $cgi->a({-href
=>$to->{'href'}, -class=>"path"},
2327 esc_path
($to->{'file'}));
2330 esc_path
($to->{'file'});
2333 $result .= qq
!<div
class="diff to_file">$line</div
>\n!;
2338 # create note for patch simplified by combined diff
2339 sub format_diff_cc_simplified
{
2340 my ($diffinfo, @parents) = @_;
2343 $result .= "<div class=\"diff header\">" .
2345 if (!is_deleted
($diffinfo)) {
2346 $result .= $cgi->a({-href
=> href
(action
=>"blob",
2348 hash
=>$diffinfo->{'to_id'},
2349 file_name
=>$diffinfo->{'to_file'}),
2351 esc_path
($diffinfo->{'to_file'}));
2353 $result .= esc_path
($diffinfo->{'to_file'});
2355 $result .= "</div>\n" . # class="diff header"
2356 "<div class=\"diff nodifferences\">" .
2358 "</div>\n"; # class="diff nodifferences"
2363 sub diff_line_class
{
2364 my ($line, $from, $to) = @_;
2369 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2370 $num_sign = scalar @{$from->{'href'}};
2373 my @diff_line_classifier = (
2374 { regexp
=> qr/^\@\@{$num_sign} /, class => "chunk_header"},
2375 { regexp
=> qr/^\\/, class => "incomplete" },
2376 { regexp
=> qr/^ {$num_sign}/, class => "ctx" },
2377 # classifier for context must come before classifier add/rem,
2378 # or we would have to use more complicated regexp, for example
2379 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2380 { regexp
=> qr/^[+ ]{$num_sign}/, class => "add" },
2381 { regexp
=> qr/^[- ]{$num_sign}/, class => "rem" },
2383 for my $clsfy (@diff_line_classifier) {
2384 return $clsfy->{'class'}
2385 if ($line =~ $clsfy->{'regexp'});
2392 # assumes that $from and $to are defined and correctly filled,
2393 # and that $line holds a line of chunk header for unified diff
2394 sub format_unidiff_chunk_header
{
2395 my ($line, $from, $to) = @_;
2397 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2398 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2400 $from_lines = 0 unless defined $from_lines;
2401 $to_lines = 0 unless defined $to_lines;
2403 if ($from->{'href'}) {
2404 $from_text = $cgi->a({-href
=>"$from->{'href'}#l$from_start",
2405 -class=>"list"}, $from_text);
2407 if ($to->{'href'}) {
2408 $to_text = $cgi->a({-href
=>"$to->{'href'}#l$to_start",
2409 -class=>"list"}, $to_text);
2411 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2412 "<span class=\"section\">" . esc_html
($section, -nbsp
=>1) . "</span>";
2416 # assumes that $from and $to are defined and correctly filled,
2417 # and that $line holds a line of chunk header for combined diff
2418 sub format_cc_diff_chunk_header
{
2419 my ($line, $from, $to) = @_;
2421 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2422 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2424 @from_text = split(' ', $ranges);
2425 for (my $i = 0; $i < @from_text; ++$i) {
2426 ($from_start[$i], $from_nlines[$i]) =
2427 (split(',', substr($from_text[$i], 1)), 0);
2430 $to_text = pop @from_text;
2431 $to_start = pop @from_start;
2432 $to_nlines = pop @from_nlines;
2434 $line = "<span class=\"chunk_info\">$prefix ";
2435 for (my $i = 0; $i < @from_text; ++$i) {
2436 if ($from->{'href'}[$i]) {
2437 $line .= $cgi->a({-href
=>"$from->{'href'}[$i]#l$from_start[$i]",
2438 -class=>"list"}, $from_text[$i]);
2440 $line .= $from_text[$i];
2444 if ($to->{'href'}) {
2445 $line .= $cgi->a({-href
=>"$to->{'href'}#l$to_start",
2446 -class=>"list"}, $to_text);
2450 $line .= " $prefix</span>" .
2451 "<span class=\"section\">" . esc_html
($section, -nbsp
=>1) . "</span>";
2455 # process patch (diff) line (not to be used for diff headers),
2456 # returning HTML-formatted (but not wrapped) line.
2457 # If the line is passed as a reference, it is treated as HTML and not
2459 sub format_diff_line
{
2460 my ($line, $diff_class, $from, $to) = @_;
2466 $line = untabify
($line);
2468 if ($from && $to && $line =~ m/^\@{2} /) {
2469 $line = format_unidiff_chunk_header
($line, $from, $to);
2470 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2471 $line = format_cc_diff_chunk_header
($line, $from, $to);
2473 $line = esc_html
($line, -nbsp
=>1);
2477 my $diff_classes = "diff";
2478 $diff_classes .= " $diff_class" if ($diff_class);
2479 $line = "<div class=\"$diff_classes\">$line</div>\n";
2484 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2485 # linked. Pass the hash of the tree/commit to snapshot.
2486 sub format_snapshot_links
{
2488 my $num_fmts = @snapshot_fmts;
2489 if ($num_fmts > 1) {
2490 # A parenthesized list of links bearing format names.
2491 # e.g. "snapshot (_tar.gz_ _zip_)"
2492 return "snapshot (" . join(' ', map
2499 }, $known_snapshot_formats{$_}{'display'})
2500 , @snapshot_fmts) . ")";
2501 } elsif ($num_fmts == 1) {
2502 # A single "snapshot" link whose tooltip bears the format name.
2504 my ($fmt) = @snapshot_fmts;
2510 snapshot_format
=>$fmt
2512 -title
=> "in format: $known_snapshot_formats{$fmt}{'display'}"
2514 } else { # $num_fmts == 0
2519 ## ......................................................................
2520 ## functions returning values to be passed, perhaps after some
2521 ## transformation, to other functions; e.g. returning arguments to href()
2523 # returns hash to be passed to href to generate gitweb URL
2524 # in -title key it returns description of link
2526 my $format = shift || 'Atom';
2527 my %res = (action
=> lc($format));
2529 # feed links are possible only for project views
2530 return unless (defined $project);
2531 # some views should link to OPML, or to generic project feed,
2532 # or don't have specific feed yet (so they should use generic)
2533 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2536 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2537 # from tag links; this also makes possible to detect branch links
2538 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2539 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2542 # find log type for feed description (title)
2544 if (defined $file_name) {
2545 $type = "history of $file_name";
2546 $type .= "/" if ($action eq 'tree');
2547 $type .= " on '$branch'" if (defined $branch);
2549 $type = "log of $branch" if (defined $branch);
2552 $res{-title
} = $type;
2553 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2554 $res{'file_name'} = $file_name;
2559 ## ----------------------------------------------------------------------
2560 ## git utility subroutines, invoking git commands
2562 # returns path to the core git executable and the --git-dir parameter as list
2564 $number_of_git_cmds++;
2565 return $GIT, '--git-dir='.$git_dir;
2568 # quote the given arguments for passing them to the shell
2569 # quote_command("command", "arg 1", "arg with ' and ! characters")
2570 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2571 # Try to avoid using this function wherever possible.
2574 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2577 # get HEAD ref of given project as hash
2578 sub git_get_head_hash
{
2579 return git_get_full_hash
(shift, 'HEAD');
2582 sub git_get_full_hash
{
2583 return git_get_hash
(@_);
2586 sub git_get_short_hash
{
2587 return git_get_hash
(@_, '--short=7');
2591 my ($project, $hash, @options) = @_;
2592 my $o_git_dir = $git_dir;
2594 $git_dir = "$projectroot/$project";
2595 if (open my $fd, '-|', git_cmd
(), 'rev-parse',
2596 '--verify', '-q', @options, $hash) {
2598 chomp $retval if defined $retval;
2601 if (defined $o_git_dir) {
2602 $git_dir = $o_git_dir;
2607 # get type of given object
2611 open my $fd, "-|", git_cmd
(), "cat-file", '-t', $hash or return;
2613 close $fd or return;
2618 # repository configuration
2619 our $config_file = '';
2622 # store multiple values for single key as anonymous array reference
2623 # single values stored directly in the hash, not as [ <value> ]
2624 sub hash_set_multi
{
2625 my ($hash, $key, $value) = @_;
2627 if (!exists $hash->{$key}) {
2628 $hash->{$key} = $value;
2629 } elsif (!ref $hash->{$key}) {
2630 $hash->{$key} = [ $hash->{$key}, $value ];
2632 push @{$hash->{$key}}, $value;
2636 # return hash of git project configuration
2637 # optionally limited to some section, e.g. 'gitweb'
2638 sub git_parse_project_config
{
2639 my $section_regexp = shift;
2644 open my $fh, "-|", git_cmd
(), "config", '-z', '-l',
2647 while (my $keyval = <$fh>) {
2649 my ($key, $value) = split(/\n/, $keyval, 2);
2651 hash_set_multi
(\
%config, $key, $value)
2652 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2659 # convert config value to boolean: 'true' or 'false'
2660 # no value, number > 0, 'true' and 'yes' values are true
2661 # rest of values are treated as false (never as error)
2662 sub config_to_bool
{
2665 return 1 if !defined $val; # section.key
2667 # strip leading and trailing whitespace
2671 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2672 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2675 # convert config value to simple decimal number
2676 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2677 # to be multiplied by 1024, 1048576, or 1073741824
2681 # strip leading and trailing whitespace
2685 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2687 # unknown unit is treated as 1
2688 return $num * ($unit eq 'g' ? 1073741824 :
2689 $unit eq 'm' ? 1048576 :
2690 $unit eq 'k' ? 1024 : 1);
2695 # convert config value to array reference, if needed
2696 sub config_to_multi
{
2699 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2702 sub git_get_project_config
{
2703 my ($key, $type) = @_;
2705 return unless defined $git_dir;
2708 return unless ($key);
2709 # only subsection, if exists, is case sensitive,
2710 # and not lowercased by 'git config -z -l'
2711 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2713 $key = join(".", lc($hi), $mi, lc($lo));
2714 return if ($lo =~ /\W/ || $hi =~ /\W/);
2718 return if ($key =~ /\W/);
2720 $key =~ s/^gitweb\.//;
2723 if (defined $type) {
2726 unless ($type eq 'bool' || $type eq 'int');
2730 if (!defined $config_file ||
2731 $config_file ne "$git_dir/config") {
2732 %config = git_parse_project_config
('gitweb');
2733 $config_file = "$git_dir/config";
2736 # check if config variable (key) exists
2737 return unless exists $config{"gitweb.$key"};
2740 if (!defined $type) {
2741 return $config{"gitweb.$key"};
2742 } elsif ($type eq 'bool') {
2743 # backward compatibility: 'git config --bool' returns true/false
2744 return config_to_bool
($config{"gitweb.$key"}) ? 'true' : 'false';
2745 } elsif ($type eq 'int') {
2746 return config_to_int
($config{"gitweb.$key"});
2748 return $config{"gitweb.$key"};
2751 # get hash of given path at given ref
2752 sub git_get_hash_by_path
{
2754 my $path = shift || return undef;
2759 open my $fd, "-|", git_cmd
(), "ls-tree", $base, "--", $path
2760 or die_error
(500, "Open git-ls-tree failed");
2762 close $fd or return undef;
2764 if (!defined $line) {
2765 # there is no tree or hash given by $path at $base
2769 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2770 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2771 if (defined $type && $type ne $2) {
2772 # type doesn't match
2778 # get path of entry with given hash at given tree-ish (ref)
2779 # used to get 'from' filename for combined diff (merge commit) for renames
2780 sub git_get_path_by_hash
{
2781 my $base = shift || return;
2782 my $hash = shift || return;
2786 open my $fd, "-|", git_cmd
(), "ls-tree", '-r', '-t', '-z', $base
2788 while (my $line = <$fd>) {
2791 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2792 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2793 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2802 ## ......................................................................
2803 ## git utility functions, directly accessing git repository
2805 # get the value of config variable either from file named as the variable
2806 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2807 # configuration variable in the repository config file.
2808 sub git_get_file_or_project_config
{
2809 my ($path, $name) = @_;
2811 $git_dir = "$projectroot/$path";
2812 open my $fd, '<', "$git_dir/$name"
2813 or return git_get_project_config
($name);
2816 if (defined $conf) {
2822 sub git_get_project_description
{
2824 return git_get_file_or_project_config
($path, 'description');
2827 sub git_get_project_category
{
2829 return git_get_file_or_project_config
($path, 'category');
2833 # supported formats:
2834 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2835 # - if its contents is a number, use it as tag weight,
2836 # - otherwise add a tag with weight 1
2837 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2838 # the same value multiple times increases tag weight
2839 # * `gitweb.ctag' multi-valued repo config variable
2840 sub git_get_project_ctags
{
2841 my $project = shift;
2844 $git_dir = "$projectroot/$project";
2845 if (opendir my $dh, "$git_dir/ctags") {
2846 my @files = grep { -f
$_ } map { "$git_dir/ctags/$_" } readdir($dh);
2847 foreach my $tagfile (@files) {
2848 open my $ct, '<', $tagfile
2854 (my $ctag = $tagfile) =~ s
#.*/##;
2855 if ($val =~ /^\d+$/) {
2856 $ctags->{$ctag} = $val;
2858 $ctags->{$ctag} = 1;
2863 } elsif (open my $fh, '<', "$git_dir/ctags") {
2864 while (my $line = <$fh>) {
2866 $ctags->{$line}++ if $line;
2871 my $taglist = config_to_multi
(git_get_project_config
('ctag'));
2872 foreach my $tag (@$taglist) {
2880 # return hash, where keys are content tags ('ctags'),
2881 # and values are sum of weights of given tag in every project
2882 sub git_gather_all_ctags
{
2883 my $projects = shift;
2886 foreach my $p (@$projects) {
2887 foreach my $ct (keys %{$p->{'ctags'}}) {
2888 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2895 sub git_populate_project_tagcloud
{
2898 # First, merge different-cased tags; tags vote on casing
2900 foreach (keys %$ctags) {
2901 $ctags_lc{lc $_}->{count
} += $ctags->{$_};
2902 if (not $ctags_lc{lc $_}->{topcount
}
2903 or $ctags_lc{lc $_}->{topcount
} < $ctags->{$_}) {
2904 $ctags_lc{lc $_}->{topcount
} = $ctags->{$_};
2905 $ctags_lc{lc $_}->{topname
} = $_;
2910 my $matched = $input_params{'ctag'};
2911 if (eval { require HTML
::TagCloud
; 1; }) {
2912 $cloud = HTML
::TagCloud-
>new;
2913 foreach my $ctag (sort keys %ctags_lc) {
2914 # Pad the title with spaces so that the cloud looks
2916 my $title = esc_html
($ctags_lc{$ctag}->{topname
});
2917 $title =~ s/ / /g;
2918 $title =~ s/^/ /g;
2919 $title =~ s/$/ /g;
2920 if (defined $matched && $matched eq $ctag) {
2921 $title = qq(<span class="match">$title</span>);
2923 $cloud->add($title, href
(project
=>undef, ctag
=>$ctag),
2924 $ctags_lc{$ctag}->{count
});
2928 foreach my $ctag (keys %ctags_lc) {
2929 my $title = esc_html
($ctags_lc{$ctag}->{topname
}, -nbsp
=>1);
2930 if (defined $matched && $matched eq $ctag) {
2931 $title = qq(<span class="match">$title</span>);
2933 $cloud->{$ctag}{count
} = $ctags_lc{$ctag}->{count
};
2934 $cloud->{$ctag}{ctag
} =
2935 $cgi->a({-href
=>href
(project
=>undef, ctag
=>$ctag)}, $title);
2941 sub git_show_project_tagcloud
{
2942 my ($cloud, $count) = @_;
2943 if (ref $cloud eq 'HTML::TagCloud') {
2944 return $cloud->html_and_css($count);
2946 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
2948 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
2950 $cloud->{$_}->{'ctag'}
2951 } splice(@tags, 0, $count)) .
2956 sub git_get_project_url_list
{
2959 $git_dir = "$projectroot/$path";
2960 open my $fd, '<', "$git_dir/cloneurl"
2961 or return wantarray ?
2962 @{ config_to_multi
(git_get_project_config
('url')) } :
2963 config_to_multi
(git_get_project_config
('url'));
2964 my @git_project_url_list = map { chomp; $_ } <$fd>;
2967 return wantarray ? @git_project_url_list : \
@git_project_url_list;
2970 sub git_get_projects_list
{
2971 my $filter = shift || '';
2972 my $paranoid = shift;
2975 if (-d
$projects_list) {
2976 # search in directory
2977 my $dir = $projects_list;
2978 # remove the trailing "/"
2980 my $pfxlen = length("$dir");
2981 my $pfxdepth = ($dir =~ tr!/!!);
2982 # when filtering, search only given subdirectory
2983 if ($filter && !$paranoid) {
2989 follow_fast
=> 1, # follow symbolic links
2990 follow_skip
=> 2, # ignore duplicates
2991 dangling_symlinks
=> 0, # ignore dangling symlinks, silently
2994 our $project_maxdepth;
2996 # skip project-list toplevel, if we get it.
2997 return if (m!^[/.]$!);
2998 # only directories can be git repositories
2999 return unless (-d
$_);
3000 # don't traverse too deep (Find is super slow on os x)
3001 # $project_maxdepth excludes depth of $projectroot
3002 if (($File::Find
::name
=~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3003 $File::Find
::prune
= 1;
3007 my $path = substr($File::Find
::name
, $pfxlen + 1);
3008 # paranoidly only filter here
3009 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3012 # we check related file in $projectroot
3013 if (check_export_ok
("$projectroot/$path")) {
3014 push @list, { path
=> $path };
3015 $File::Find
::prune
= 1;
3020 } elsif (-f
$projects_list) {
3021 # read from file(url-encoded):
3022 # 'git%2Fgit.git Linus+Torvalds'
3023 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3024 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3025 open my $fd, '<', $projects_list or return;
3027 while (my $line = <$fd>) {
3029 my ($path, $owner) = split ' ', $line;
3030 $path = unescape
($path);
3031 $owner = unescape
($owner);
3032 if (!defined $path) {
3035 # if $filter is rpovided, check if $path begins with $filter
3036 if ($filter && $path !~ m!^\Q$filter\E/!) {
3039 if (check_export_ok
("$projectroot/$path")) {
3044 $pr->{'owner'} = to_utf8
($owner);
3054 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3055 # as side effects it sets 'forks' field to list of forks for forked projects
3056 sub filter_forks_from_projects_list
{
3057 my $projects = shift;
3059 my %trie; # prefix tree of directories (path components)
3060 # generate trie out of those directories that might contain forks
3061 foreach my $pr (@$projects) {
3062 my $path = $pr->{'path'};
3063 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3064 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3065 next unless ($path); # skip '.git' repository: tests, git-instaweb
3066 next unless (-d
"$projectroot/$path"); # containing directory exists
3067 $pr->{'forks'} = []; # there can be 0 or more forks of project
3070 my @dirs = split('/', $path);
3071 # walk the trie, until either runs out of components or out of trie
3073 while (scalar @dirs &&
3074 exists($ref->{$dirs[0]})) {
3075 $ref = $ref->{shift @dirs};
3077 # create rest of trie structure from rest of components
3078 foreach my $dir (@dirs) {
3079 $ref = $ref->{$dir} = {};
3081 # create end marker, store $pr as a data
3082 $ref->{''} = $pr if (!exists $ref->{''});
3085 # filter out forks, by finding shortest prefix match for paths
3088 foreach my $pr (@$projects) {
3092 foreach my $dir (split('/', $pr->{'path'})) {
3093 if (exists $ref->{''}) {
3094 # found [shortest] prefix, is a fork - skip it
3095 push @{$ref->{''}{'forks'}}, $pr;
3098 if (!exists $ref->{$dir}) {
3099 # not in trie, cannot have prefix, not a fork
3100 push @filtered, $pr;
3103 # If the dir is there, we just walk one step down the trie.
3104 $ref = $ref->{$dir};
3106 # we ran out of trie
3107 # (shouldn't happen: it's either no match, or end marker)
3108 push @filtered, $pr;
3114 # note: fill_project_list_info must be run first,
3115 # for 'descr_long' and 'ctags' to be filled
3116 sub search_projects_list
{
3117 my ($projlist, %opts) = @_;
3118 my $tagfilter = $opts{'tagfilter'};
3119 my $search_re = $opts{'search_regexp'};
3122 unless ($tagfilter || $search_re);
3124 # searching projects require filling to be run before it;
3125 fill_project_list_info
($projlist,
3126 $tagfilter ? 'ctags' : (),
3127 $search_re ? ('path', 'descr') : ());
3130 foreach my $pr (@$projlist) {
3133 next unless ref($pr->{'ctags'}) eq 'HASH';
3135 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3140 $pr->{'path'} =~ /$search_re/ ||
3141 $pr->{'descr_long'} =~ /$search_re/;
3144 push @projects, $pr;
3150 our $gitweb_project_owner = undef;
3151 sub git_get_project_list_from_file
{
3153 return if (defined $gitweb_project_owner);
3155 $gitweb_project_owner = {};
3156 # read from file (url-encoded):
3157 # 'git%2Fgit.git Linus+Torvalds'
3158 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3159 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3160 if (-f
$projects_list) {
3161 open(my $fd, '<', $projects_list);
3162 while (my $line = <$fd>) {
3164 my ($pr, $ow) = split ' ', $line;
3165 $pr = unescape
($pr);
3166 $ow = unescape
($ow);
3167 $gitweb_project_owner->{$pr} = to_utf8
($ow);
3173 sub git_get_project_owner
{
3174 my $project = shift;
3177 return undef unless $project;
3178 $git_dir = "$projectroot/$project";
3180 if (!defined $gitweb_project_owner) {
3181 git_get_project_list_from_file
();
3184 if (exists $gitweb_project_owner->{$project}) {
3185 $owner = $gitweb_project_owner->{$project};
3187 if (!defined $owner){
3188 $owner = git_get_project_config
('owner');
3190 if (!defined $owner) {
3191 $owner = get_file_owner
("$git_dir");
3197 sub git_get_last_activity
{
3201 $git_dir = "$projectroot/$path";
3202 open($fd, "-|", git_cmd
(), 'for-each-ref',
3203 '--format=%(committer)',
3204 '--sort=-committerdate',
3206 'refs/heads') or return;
3207 my $most_recent = <$fd>;
3208 close $fd or return;
3209 if (defined $most_recent &&
3210 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3212 my $age = time - $timestamp;
3213 return ($age, age_string
($age));
3215 return (undef, undef);
3218 # Implementation note: when a single remote is wanted, we cannot use 'git
3219 # remote show -n' because that command always work (assuming it's a remote URL
3220 # if it's not defined), and we cannot use 'git remote show' because that would
3221 # try to make a network roundtrip. So the only way to find if that particular
3222 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3223 # and when we find what we want.
3224 sub git_get_remotes_list
{
3228 open my $fd, '-|' , git_cmd
(), 'remote', '-v';
3230 while (my $remote = <$fd>) {
3232 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3233 next if $wanted and not $remote eq $wanted;
3234 my ($url, $key) = ($1, $2);
3236 $remotes{$remote} ||= { 'heads' => () };
3237 $remotes{$remote}{$key} = $url;
3239 close $fd or return;
3240 return wantarray ? %remotes : \
%remotes;
3243 # Takes a hash of remotes as first parameter and fills it by adding the
3244 # available remote heads for each of the indicated remotes.
3245 sub fill_remote_heads
{
3246 my $remotes = shift;
3247 my @heads = map { "remotes/$_" } keys %$remotes;
3248 my @remoteheads = git_get_heads_list
(undef, @heads);
3249 foreach my $remote (keys %$remotes) {
3250 $remotes->{$remote}{'heads'} = [ grep {
3251 $_->{'name'} =~ s!^$remote/!!
3256 sub git_get_references
{
3257 my $type = shift || "";
3259 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3260 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3261 open my $fd, "-|", git_cmd
(), "show-ref", "--dereference",
3262 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3265 while (my $line = <$fd>) {
3267 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3268 if (defined $refs{$1}) {
3269 push @{$refs{$1}}, $2;
3275 close $fd or return;
3279 sub git_get_rev_name_tags
{
3280 my $hash = shift || return undef;
3282 open my $fd, "-|", git_cmd
(), "name-rev", "--tags", $hash
3284 my $name_rev = <$fd>;
3287 if ($name_rev =~ m
|^$hash tags
/(.*)$|) {
3290 # catches also '$hash undefined' output
3295 ## ----------------------------------------------------------------------
3296 ## parse to hash functions
3300 my $tz = shift || "-0000";
3303 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3304 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3305 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3306 $date{'hour'} = $hour;
3307 $date{'minute'} = $min;
3308 $date{'mday'} = $mday;
3309 $date{'day'} = $days[$wday];
3310 $date{'month'} = $months[$mon];
3311 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3312 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3313 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3314 $mday, $months[$mon], $hour ,$min;
3315 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3316 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3318 my ($tz_sign, $tz_hour, $tz_min) =
3319 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3320 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3321 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3322 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3323 $date{'hour_local'} = $hour;
3324 $date{'minute_local'} = $min;
3325 $date{'tz_local'} = $tz;
3326 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3327 1900+$year, $mon+1, $mday,
3328 $hour, $min, $sec, $tz);
3337 open my $fd, "-|", git_cmd
(), "cat-file", "tag", $tag_id or return;
3338 $tag{'id'} = $tag_id;
3339 while (my $line = <$fd>) {
3341 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3342 $tag{'object'} = $1;
3343 } elsif ($line =~ m/^type (.+)$/) {
3345 } elsif ($line =~ m/^tag (.+)$/) {
3347 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3348 $tag{'author'} = $1;
3349 $tag{'author_epoch'} = $2;
3350 $tag{'author_tz'} = $3;
3351 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3352 $tag{'author_name'} = $1;
3353 $tag{'author_email'} = $2;
3355 $tag{'author_name'} = $tag{'author'};
3357 } elsif ($line =~ m/--BEGIN/) {
3358 push @comment, $line;
3360 } elsif ($line eq "") {
3364 push @comment, <$fd>;
3365 $tag{'comment'} = \
@comment;
3366 close $fd or return;
3367 if (!defined $tag{'name'}) {
3373 sub parse_commit_text
{
3374 my ($commit_text, $withparents) = @_;
3375 my @commit_lines = split '\n', $commit_text;
3378 pop @commit_lines; # Remove '\0'
3380 if (! @commit_lines) {
3384 my $header = shift @commit_lines;
3385 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3388 ($co{'id'}, my @parents) = split ' ', $header;
3389 while (my $line = shift @commit_lines) {
3390 last if $line eq "\n";
3391 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3393 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3395 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3396 $co{'author'} = to_utf8
($1);
3397 $co{'author_epoch'} = $2;
3398 $co{'author_tz'} = $3;
3399 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3400 $co{'author_name'} = $1;
3401 $co{'author_email'} = $2;
3403 $co{'author_name'} = $co{'author'};
3405 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3406 $co{'committer'} = to_utf8
($1);
3407 $co{'committer_epoch'} = $2;
3408 $co{'committer_tz'} = $3;
3409 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3410 $co{'committer_name'} = $1;
3411 $co{'committer_email'} = $2;
3413 $co{'committer_name'} = $co{'committer'};
3417 if (!defined $co{'tree'}) {
3420 $co{'parents'} = \
@parents;
3421 $co{'parent'} = $parents[0];
3423 foreach my $title (@commit_lines) {
3426 $co{'title'} = chop_str
($title, 80, 5);
3427 # remove leading stuff of merges to make the interesting part visible
3428 if (length($title) > 50) {
3429 $title =~ s/^Automatic //;
3430 $title =~ s/^merge (of|with) /Merge ... /i;
3431 if (length($title) > 50) {
3432 $title =~ s/(http|rsync):\/\///;
3434 if (length($title) > 50) {
3435 $title =~ s/(master|www|rsync)\.//;
3437 if (length($title) > 50) {
3438 $title =~ s/kernel.org:?//;
3440 if (length($title) > 50) {
3441 $title =~ s/\/pub\/scm//;
3444 $co{'title_short'} = chop_str
($title, 50, 5);
3448 if (! defined $co{'title'} || $co{'title'} eq "") {
3449 $co{'title'} = $co{'title_short'} = '(no commit message)';
3451 # remove added spaces
3452 foreach my $line (@commit_lines) {
3455 $co{'comment'} = \
@commit_lines;
3457 my $age = time - $co{'committer_epoch'};
3459 $co{'age_string'} = age_string
($age);
3460 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3461 if ($age > 60*60*24*7*2) {
3462 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3463 $co{'age_string_age'} = $co{'age_string'};
3465 $co{'age_string_date'} = $co{'age_string'};
3466 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3472 my ($commit_id) = @_;
3477 open my $fd, "-|", git_cmd
(), "rev-list",
3483 or die_error
(500, "Open git-rev-list failed");
3484 %co = parse_commit_text
(<$fd>, 1);
3491 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3499 open my $fd, "-|", git_cmd
(), "rev-list",
3502 ("--max-count=" . $maxcount),
3503 ("--skip=" . $skip),
3507 ($filename ? ($filename) : ())
3508 or die_error
(500, "Open git-rev-list failed");
3509 while (my $line = <$fd>) {
3510 my %co = parse_commit_text
($line);
3515 return wantarray ? @cos : \
@cos;
3518 # parse line of git-diff-tree "raw" output
3519 sub parse_difftree_raw_line
{
3523 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3524 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3525 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3526 $res{'from_mode'} = $1;
3527 $res{'to_mode'} = $2;
3528 $res{'from_id'} = $3;
3530 $res{'status'} = $5;
3531 $res{'similarity'} = $6;
3532 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3533 ($res{'from_file'}, $res{'to_file'}) = map { unquote
($_) } split("\t", $7);
3535 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote
($7);
3538 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3539 # combined diff (for merge commit)
3540 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3541 $res{'nparents'} = length($1);
3542 $res{'from_mode'} = [ split(' ', $2) ];
3543 $res{'to_mode'} = pop @{$res{'from_mode'}};
3544 $res{'from_id'} = [ split(' ', $3) ];
3545 $res{'to_id'} = pop @{$res{'from_id'}};
3546 $res{'status'} = [ split('', $4) ];
3547 $res{'to_file'} = unquote
($5);
3549 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3550 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3551 $res{'commit'} = $1;
3554 return wantarray ? %res : \
%res;
3557 # wrapper: return parsed line of git-diff-tree "raw" output
3558 # (the argument might be raw line, or parsed info)
3559 sub parsed_difftree_line
{
3560 my $line_or_ref = shift;
3562 if (ref($line_or_ref) eq "HASH") {
3563 # pre-parsed (or generated by hand)
3564 return $line_or_ref;
3566 return parse_difftree_raw_line
($line_or_ref);
3570 # parse line of git-ls-tree output
3571 sub parse_ls_tree_line
{
3577 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3578 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3587 $res{'name'} = unquote
($5);
3590 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3591 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3599 $res{'name'} = unquote
($4);
3603 return wantarray ? %res : \
%res;
3606 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3607 sub parse_from_to_diffinfo
{
3608 my ($diffinfo, $from, $to, @parents) = @_;
3610 if ($diffinfo->{'nparents'}) {
3612 $from->{'file'} = [];
3613 $from->{'href'} = [];
3614 fill_from_file_info
($diffinfo, @parents)
3615 unless exists $diffinfo->{'from_file'};
3616 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3617 $from->{'file'}[$i] =
3618 defined $diffinfo->{'from_file'}[$i] ?
3619 $diffinfo->{'from_file'}[$i] :
3620 $diffinfo->{'to_file'};
3621 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3622 $from->{'href'}[$i] = href
(action
=>"blob",
3623 hash_base
=>$parents[$i],
3624 hash
=>$diffinfo->{'from_id'}[$i],
3625 file_name
=>$from->{'file'}[$i]);
3627 $from->{'href'}[$i] = undef;
3631 # ordinary (not combined) diff
3632 $from->{'file'} = $diffinfo->{'from_file'};
3633 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3634 $from->{'href'} = href
(action
=>"blob", hash_base
=>$hash_parent,
3635 hash
=>$diffinfo->{'from_id'},
3636 file_name
=>$from->{'file'});
3638 delete $from->{'href'};
3642 $to->{'file'} = $diffinfo->{'to_file'};
3643 if (!is_deleted
($diffinfo)) { # file exists in result
3644 $to->{'href'} = href
(action
=>"blob", hash_base
=>$hash,
3645 hash
=>$diffinfo->{'to_id'},
3646 file_name
=>$to->{'file'});
3648 delete $to->{'href'};
3652 ## ......................................................................
3653 ## parse to array of hashes functions
3655 sub git_get_heads_list
{
3656 my ($limit, @classes) = @_;
3657 @classes = ('heads') unless @classes;
3658 my @patterns = map { "refs/$_" } @classes;
3661 open my $fd, '-|', git_cmd
(), 'for-each-ref',
3662 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3663 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3666 while (my $line = <$fd>) {
3670 my ($refinfo, $committerinfo) = split(/\0/, $line);
3671 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3672 my ($committer, $epoch, $tz) =
3673 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3674 $ref_item{'fullname'} = $name;
3675 $name =~ s!^refs/(?:head|remote)s/!!;
3677 $ref_item{'name'} = $name;
3678 $ref_item{'id'} = $hash;
3679 $ref_item{'title'} = $title || '(no commit message)';
3680 $ref_item{'epoch'} = $epoch;
3682 $ref_item{'age'} = age_string
(time - $ref_item{'epoch'});
3684 $ref_item{'age'} = "unknown";
3687 push @headslist, \
%ref_item;
3691 return wantarray ? @headslist : \
@headslist;
3694 sub git_get_tags_list
{
3698 open my $fd, '-|', git_cmd
(), 'for-each-ref',
3699 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3700 '--format=%(objectname) %(objecttype) %(refname) '.
3701 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3704 while (my $line = <$fd>) {
3708 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3709 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3710 my ($creator, $epoch, $tz) =
3711 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3712 $ref_item{'fullname'} = $name;
3713 $name =~ s!^refs/tags/!!;
3715 $ref_item{'type'} = $type;
3716 $ref_item{'id'} = $id;
3717 $ref_item{'name'} = $name;
3718 if ($type eq "tag") {
3719 $ref_item{'subject'} = $title;
3720 $ref_item{'reftype'} = $reftype;
3721 $ref_item{'refid'} = $refid;
3723 $ref_item{'reftype'} = $type;
3724 $ref_item{'refid'} = $id;
3727 if ($type eq "tag" || $type eq "commit") {
3728 $ref_item{'epoch'} = $epoch;
3730 $ref_item{'age'} = age_string
(time - $ref_item{'epoch'});
3732 $ref_item{'age'} = "unknown";
3736 push @tagslist, \
%ref_item;
3740 return wantarray ? @tagslist : \
@tagslist;
3743 ## ----------------------------------------------------------------------
3744 ## filesystem-related functions
3746 sub get_file_owner
{
3749 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3750 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3751 if (!defined $gcos) {
3755 $owner =~ s/[,;].*$//;
3756 return to_utf8
($owner);
3759 # assume that file exists
3761 my $filename = shift;
3763 open my $fd, '<', $filename;
3764 print map { to_utf8
($_) } <$fd>;
3768 ## ......................................................................
3769 ## mimetype related functions
3771 sub mimetype_guess_file
{
3772 my $filename = shift;
3773 my $mimemap = shift;
3774 -r
$mimemap or return undef;
3777 open(my $mh, '<', $mimemap) or return undef;
3779 next if m/^#/; # skip comments
3780 my ($mimetype, @exts) = split(/\s+/);
3781 foreach my $ext (@exts) {
3782 $mimemap{$ext} = $mimetype;
3787 $filename =~ /\.([^.]*)$/;
3788 return $mimemap{$1};
3791 sub mimetype_guess
{
3792 my $filename = shift;
3794 $filename =~ /\./ or return undef;
3796 if ($mimetypes_file) {
3797 my $file = $mimetypes_file;
3798 if ($file !~ m!^/!) { # if it is relative path
3799 # it is relative to project
3800 $file = "$projectroot/$project/$file";
3802 $mime = mimetype_guess_file
($filename, $file);
3804 $mime ||= mimetype_guess_file
($filename, '/etc/mime.types');
3810 my $filename = shift;
3813 my $mime = mimetype_guess
($filename);
3814 $mime and return $mime;
3818 return $default_blob_plain_mimetype unless $fd;
3821 return 'text/plain';
3822 } elsif (! $filename) {
3823 return 'application/octet-stream';
3824 } elsif ($filename =~ m/\.png$/i) {
3826 } elsif ($filename =~ m/\.gif$/i) {
3828 } elsif ($filename =~ m/\.jpe?g$/i) {
3829 return 'image/jpeg';
3831 return 'application/octet-stream';
3835 sub blob_contenttype
{
3836 my ($fd, $file_name, $type) = @_;
3838 $type ||= blob_mimetype
($fd, $file_name);
3839 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3840 $type .= "; charset=$default_text_plain_charset";
3846 # guess file syntax for syntax highlighting; return undef if no highlighting
3847 # the name of syntax can (in the future) depend on syntax highlighter used
3848 sub guess_file_syntax
{
3849 my ($highlight, $mimetype, $file_name) = @_;
3850 return undef unless ($highlight && defined $file_name);
3851 my $basename = basename
($file_name, '.in');
3852 return $highlight_basename{$basename}
3853 if exists $highlight_basename{$basename};
3855 $basename =~ /\.([^.]*)$/;
3856 my $ext = $1 or return undef;
3857 return $highlight_ext{$ext}
3858 if exists $highlight_ext{$ext};
3863 # run highlighter and return FD of its output,
3864 # or return original FD if no highlighting
3865 sub run_highlighter
{
3866 my ($fd, $highlight, $syntax) = @_;
3867 return $fd unless ($highlight && defined $syntax);
3870 open $fd, quote_command
(git_cmd
(), "cat-file", "blob", $hash)." | ".
3871 quote_command
($highlight_bin).
3872 " --replace-tabs=8 --fragment --syntax $syntax |"
3873 or die_error
(500, "Couldn't open file or run syntax highlighter");
3877 ## ======================================================================
3878 ## functions printing HTML: header, footer, error page
3880 sub get_page_title
{
3881 my $title = to_utf8
($site_name);
3883 unless (defined $project) {
3884 if (defined $project_filter) {
3885 $title .= " - projects in '" . esc_path
($project_filter) . "'";
3889 $title .= " - " . to_utf8
($project);
3891 return $title unless (defined $action);
3892 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3894 return $title unless (defined $file_name);
3895 $title .= " - " . esc_path
($file_name);
3896 if ($action eq "tree" && $file_name !~ m
|/$|) {
3903 sub get_content_type_html
{
3904 # require explicit support from the UA if we are to send the page as
3905 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3906 # we have to do this because MSIE sometimes globs '*/*', pretending to
3907 # support xhtml+xml but choking when it gets what it asked for.
3908 if (defined $cgi->http('HTTP_ACCEPT') &&
3909 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\
+xml
(,|;|\s
|$)/ &&
3910 $cgi->Accept('application/xhtml+xml') != 0) {
3911 return 'application/xhtml+xml';
3917 sub print_feed_meta
{
3918 if (defined $project) {
3919 my %href_params = get_feed_info
();
3920 if (!exists $href_params{'-title'}) {
3921 $href_params{'-title'} = 'log';
3924 foreach my $format (qw(RSS Atom)) {
3925 my $type = lc($format);
3927 '-rel' => 'alternate',
3928 '-title' => esc_attr
("$project - $href_params{'-title'} - $format feed"),
3929 '-type' => "application/$type+xml"
3932 $href_params{'extra_options'} = undef;
3933 $href_params{'action'} = $type;
3934 $link_attr{'-href'} = href
(%href_params);
3936 "rel=\"$link_attr{'-rel'}\" ".
3937 "title=\"$link_attr{'-title'}\" ".
3938 "href=\"$link_attr{'-href'}\" ".
3939 "type=\"$link_attr{'-type'}\" ".
3942 $href_params{'extra_options'} = '--no-merges';
3943 $link_attr{'-href'} = href
(%href_params);
3944 $link_attr{'-title'} .= ' (no merges)';
3946 "rel=\"$link_attr{'-rel'}\" ".
3947 "title=\"$link_attr{'-title'}\" ".
3948 "href=\"$link_attr{'-href'}\" ".
3949 "type=\"$link_attr{'-type'}\" ".
3954 printf('<link rel="alternate" title="%s projects list" '.
3955 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3956 esc_attr
($site_name), href
(project
=>undef, action
=>"project_index"));
3957 printf('<link rel="alternate" title="%s projects feeds" '.
3958 'href="%s" type="text/x-opml" />'."\n",
3959 esc_attr
($site_name), href
(project
=>undef, action
=>"opml"));
3963 sub print_header_links
{
3966 # print out each stylesheet that exist, providing backwards capability
3967 # for those people who defined $stylesheet in a config file
3968 if (defined $stylesheet) {
3969 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
3971 foreach my $stylesheet (@stylesheets) {
3972 next unless $stylesheet;
3973 print '<link rel="stylesheet" type="text/css" href="'.esc_url
($stylesheet).'"/>'."\n";
3977 if ($status eq '200 OK');
3978 if (defined $favicon) {
3979 print qq(<link rel="shortcut icon" href=").esc_url
($favicon).qq(" type="image/png" />\n);
3983 sub print_nav_breadcrumbs_path
{
3984 my $dirprefix = undef;
3985 while (my $part = shift) {
3986 $dirprefix .= "/" if defined $dirprefix;
3987 $dirprefix .= $part;
3988 print $cgi->a({-href
=> href
(project
=> undef,
3989 project_filter
=> $dirprefix,
3990 action
=> "project_list")},
3991 esc_html
($part)) . " / ";
3995 sub print_nav_breadcrumbs
{
3998 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
3999 print $cgi->a({-href
=> esc_url
($crumb->[1])}, $crumb->[0]) . " / ";
4001 if (defined $project) {
4002 my @dirname = split '/', $project;
4003 my $projectbasename = pop @dirname;
4004 print_nav_breadcrumbs_path
(@dirname);
4005 print $cgi->a({-href
=> href
(action
=>"summary")}, esc_html
($projectbasename));
4006 if (defined $action) {
4007 my $action_print = $action ;
4008 if (defined $opts{-action_extra
}) {
4009 $action_print = $cgi->a({-href
=> href
(action
=>$action)},
4012 print " / $action_print";
4014 if (defined $opts{-action_extra
}) {
4015 print " / $opts{-action_extra}";
4018 } elsif (defined $project_filter) {
4019 print_nav_breadcrumbs_path
(split '/', $project_filter);
4023 sub print_search_form
{
4024 if (!defined $searchtext) {
4028 if (defined $hash_base) {
4029 $search_hash = $hash_base;
4030 } elsif (defined $hash) {
4031 $search_hash = $hash;
4033 $search_hash = "HEAD";
4035 my $action = $my_uri;
4036 my $use_pathinfo = gitweb_check_feature
('pathinfo');
4037 if ($use_pathinfo) {
4038 $action .= "/".esc_url
($project);
4040 print $cgi->startform(-method => "get", -action
=> $action) .
4041 "<div class=\"search\">\n" .
4043 $cgi->input({-name
=>"p", -value
=>$project, -type
=>"hidden"}) . "\n") .
4044 $cgi->input({-name
=>"a", -value
=>"search", -type
=>"hidden"}) . "\n" .
4045 $cgi->input({-name
=>"h", -value
=>$search_hash, -type
=>"hidden"}) . "\n" .
4046 $cgi->popup_menu(-name
=> 'st', -default => 'commit',
4047 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4048 " " . $cgi->a({-href
=> href
(action
=>"search_help"),
4049 -title
=> "search help" }, "?") . " search:\n",
4050 $cgi->textfield(-name
=> "s", -value
=> $searchtext, -override
=> 1) . "\n" .
4051 "<span title=\"Extended regular expression\">" .
4052 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
4053 -checked
=> $search_use_regexp) .
4056 $cgi->end_form() . "\n";
4059 sub git_header_html
{
4060 my $status = shift || "200 OK";
4061 my $expires = shift;
4064 my $title = get_page_title
();
4065 my $content_type = get_content_type_html
();
4066 print $cgi->header(-type
=>$content_type, -charset
=> 'utf-8',
4067 -status
=> $status, -expires
=> $expires)
4068 unless ($opts{'-no_http_header'});
4069 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4071 <?xml version="1.0" encoding="utf-8"?>
4072 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4073 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4074 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4075 <!-- git core binaries version $git_version -->
4077 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4078 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4079 <meta name="robots" content="index, nofollow"/>
4080 <title>$title</title>
4082 # the stylesheet, favicon etc urls won't work correctly with path_info
4083 # unless we set the appropriate base URL
4084 if ($ENV{'PATH_INFO'}) {
4085 print "<base href=\"".esc_url
($base_url)."\" />\n";
4087 print_header_links
($status);
4089 if (defined $site_html_head_string) {
4090 print to_utf8
($site_html_head_string);
4096 if (defined $site_header && -f
$site_header) {
4097 insert_file
($site_header);
4100 print "<div class=\"page_header\">\n";
4101 if (defined $logo) {
4102 print $cgi->a({-href
=> esc_url
($logo_url),
4103 -title
=> $logo_label},
4104 $cgi->img({-src
=> esc_url
($logo),
4105 -width
=> 72, -height
=> 27,
4107 -class => "logo"}));
4109 print_nav_breadcrumbs
(%opts);
4112 my $have_search = gitweb_check_feature
('search');
4113 if (defined $project && $have_search) {
4114 print_search_form
();
4118 sub git_footer_html
{
4119 my $feed_class = 'rss_logo';
4121 print "<div class=\"page_footer\">\n";
4122 if (defined $project) {
4123 my $descr = git_get_project_description
($project);
4124 if (defined $descr) {
4125 print "<div class=\"page_footer_text\">" . esc_html
($descr) . "</div>\n";
4128 my %href_params = get_feed_info
();
4129 if (!%href_params) {
4130 $feed_class .= ' generic';
4132 $href_params{'-title'} ||= 'log';
4134 foreach my $format (qw(RSS Atom)) {
4135 $href_params{'action'} = lc($format);
4136 print $cgi->a({-href
=> href
(%href_params),
4137 -title
=> "$href_params{'-title'} $format feed",
4138 -class => $feed_class}, $format)."\n";
4142 print $cgi->a({-href
=> href
(project
=>undef, action
=>"opml",
4143 project_filter
=> $project_filter),
4144 -class => $feed_class}, "OPML") . " ";
4145 print $cgi->a({-href
=> href
(project
=>undef, action
=>"project_index",
4146 project_filter
=> $project_filter),
4147 -class => $feed_class}, "TXT") . "\n";
4149 print "</div>\n"; # class="page_footer"
4151 if (defined $t0 && gitweb_check_feature
('timed')) {
4152 print "<div id=\"generating_info\">\n";
4153 print 'This page took '.
4154 '<span id="generating_time" class="time_span">'.
4155 tv_interval
($t0, [ gettimeofday
() ]).
4158 '<span id="generating_cmd">'.
4159 $number_of_git_cmds.
4160 '</span> git commands '.
4162 print "</div>\n"; # class="page_footer"
4165 if (defined $site_footer && -f
$site_footer) {
4166 insert_file
($site_footer);
4169 print qq
!<script type
="text/javascript" src
="!.esc_url($javascript).qq!"></script
>\n!;
4170 if (defined $action &&
4171 $action eq 'blame_incremental') {
4172 print qq
!<script type
="text/javascript">\n!.
4173 qq
!startBlame
("!. href(action=>"blame_data
", -replay=>1) .qq!",\n!.
4174 qq
! "!. href() .qq!");\n!.
4177 my ($jstimezone, $tz_cookie, $datetime_class) =
4178 gitweb_get_feature
('javascript-timezone');
4180 print qq
!<script type
="text/javascript">\n!.
4181 qq
!window
.onload
= function
() {\n!;
4182 if (gitweb_check_feature
('javascript-actions')) {
4183 print qq
! fixLinks
();\n!;
4185 if ($jstimezone && $tz_cookie && $datetime_class) {
4186 print qq
! var tz_cookie
= { name
: '$tz_cookie', expires
: 14, path
: '/' };\n!. # in days
4187 qq
! onloadTZSetup
('$jstimezone', tz_cookie
, '$datetime_class');\n!;
4197 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4198 # Example: die_error(404, 'Hash not found')
4199 # By convention, use the following status codes (as defined in RFC 2616):
4200 # 400: Invalid or missing CGI parameters, or
4201 # requested object exists but has wrong type.
4202 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4203 # this server or project.
4204 # 404: Requested object/revision/project doesn't exist.
4205 # 500: The server isn't configured properly, or
4206 # an internal error occurred (e.g. failed assertions caused by bugs), or
4207 # an unknown error occurred (e.g. the git binary died unexpectedly).
4208 # 503: The server is currently unavailable (because it is overloaded,
4209 # or down for maintenance). Generally, this is a temporary state.
4211 my $status = shift || 500;
4212 my $error = esc_html
(shift) || "Internal Server Error";
4216 my %http_responses = (
4217 400 => '400 Bad Request',
4218 403 => '403 Forbidden',
4219 404 => '404 Not Found',
4220 500 => '500 Internal Server Error',
4221 503 => '503 Service Unavailable',
4223 git_header_html
($http_responses{$status}, undef, %opts);
4225 <div class="page_body">
4230 if (defined $extra) {
4238 unless ($opts{'-error_handler'});
4241 ## ----------------------------------------------------------------------
4242 ## functions printing or outputting HTML: navigation
4244 sub git_print_page_nav
{
4245 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4246 $extra = '' if !defined $extra; # pager or formats
4248 my @navs = qw(summary shortlog log commit commitdiff tree);
4250 @navs = grep { $_ ne $suppress } @navs;
4253 my %arg = map { $_ => {action
=>$_} } @navs;
4254 if (defined $head) {
4255 for (qw(commit commitdiff)) {
4256 $arg{$_}{'hash'} = $head;
4258 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4259 for (qw(shortlog log)) {
4260 $arg{$_}{'hash'} = $head;
4265 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4266 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4268 my @actions = gitweb_get_feature
('actions');
4271 'n' => $project, # project name
4272 'f' => $git_dir, # project path within filesystem
4273 'h' => $treehead || '', # current hash ('h' parameter)
4274 'b' => $treebase || '', # hash base ('hb' parameter)
4277 my ($label, $link, $pos) = splice(@actions,0,3);
4279 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4281 $link =~ s/%([%nfhb])/$repl{$1}/g;
4282 $arg{$label}{'_href'} = $link;
4285 print "<div class=\"page_nav\">\n" .
4287 map { $_ eq $current ?
4288 $_ : $cgi->a({-href
=> ($arg{$_}{_href
} ? $arg{$_}{_href
} : href
(%{$arg{$_}}))}, "$_")
4290 print "<br/>\n$extra<br/>\n" .
4294 # returns a submenu for the nagivation of the refs views (tags, heads,
4295 # remotes) with the current view disabled and the remotes view only
4296 # available if the feature is enabled
4297 sub format_ref_views
{
4299 my @ref_views = qw{tags heads};
4300 push @ref_views, 'remotes' if gitweb_check_feature
('remote_heads');
4301 return join " | ", map {
4302 $_ eq $current ? $_ :
4303 $cgi->a({-href
=> href
(action
=>$_)}, $_)
4307 sub format_paging_nav
{
4308 my ($action, $page, $has_next_link) = @_;
4314 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)}, "first") .
4316 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
4317 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
4319 $paging_nav .= "first ⋅ prev";
4322 if ($has_next_link) {
4323 $paging_nav .= " ⋅ " .
4324 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
4325 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
4327 $paging_nav .= " ⋅ next";
4333 ## ......................................................................
4334 ## functions printing or outputting HTML: div
4336 sub git_print_header_div
{
4337 my ($action, $title, $hash, $hash_base) = @_;
4340 $args{'action'} = $action;
4341 $args{'hash'} = $hash if $hash;
4342 $args{'hash_base'} = $hash_base if $hash_base;
4344 print "<div class=\"header\">\n" .
4345 $cgi->a({-href
=> href
(%args), -class => "title"},
4346 $title ? $title : $action) .
4350 sub format_repo_url
{
4351 my ($name, $url) = @_;
4352 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4355 # Group output by placing it in a DIV element and adding a header.
4356 # Options for start_div() can be provided by passing a hash reference as the
4357 # first parameter to the function.
4358 # Options to git_print_header_div() can be provided by passing an array
4359 # reference. This must follow the options to start_div if they are present.
4360 # The content can be a scalar, which is output as-is, a scalar reference, which
4361 # is output after html escaping, an IO handle passed either as *handle or
4362 # *handle{IO}, or a function reference. In the latter case all following
4363 # parameters will be taken as argument to the content function call.
4364 sub git_print_section
{
4365 my ($div_args, $header_args, $content);
4367 if (ref($arg) eq 'HASH') {
4371 if (ref($arg) eq 'ARRAY') {
4372 $header_args = $arg;
4377 print $cgi->start_div($div_args);
4378 git_print_header_div
(@$header_args);
4380 if (ref($content) eq 'CODE') {
4382 } elsif (ref($content) eq 'SCALAR') {
4383 print esc_html
($$content);
4384 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4386 } elsif (!ref($content) && defined($content)) {
4390 print $cgi->end_div;
4393 sub format_timestamp_html
{
4395 my $strtime = $date->{'rfc2822'};
4397 my (undef, undef, $datetime_class) =
4398 gitweb_get_feature
('javascript-timezone');
4399 if ($datetime_class) {
4400 $strtime = qq
!<span
class="$datetime_class">$strtime</span
>!;
4403 my $localtime_format = '(%02d:%02d %s)';
4404 if ($date->{'hour_local'} < 6) {
4405 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4408 sprintf($localtime_format,
4409 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4414 # Outputs the author name and date in long form
4415 sub git_print_authorship
{
4418 my $tag = $opts{-tag
} || 'div';
4419 my $author = $co->{'author_name'};
4421 my %ad = parse_date
($co->{'author_epoch'}, $co->{'author_tz'});
4422 print "<$tag class=\"author_date\">" .
4423 format_search_author
($author, "author", esc_html
($author)) .
4424 " [".format_timestamp_html
(\
%ad)."]".
4425 git_get_avatar
($co->{'author_email'}, -pad_before
=> 1) .
4429 # Outputs table rows containing the full author or committer information,
4430 # in the format expected for 'commit' view (& similar).
4431 # Parameters are a commit hash reference, followed by the list of people
4432 # to output information for. If the list is empty it defaults to both
4433 # author and committer.
4434 sub git_print_authorship_rows
{
4436 # too bad we can't use @people = @_ || ('author', 'committer')
4438 @people = ('author', 'committer') unless @people;
4439 foreach my $who (@people) {
4440 my %wd = parse_date
($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4441 print "<tr><td>$who</td><td>" .
4442 format_search_author
($co->{"${who}_name"}, $who,
4443 esc_html
($co->{"${who}_name"})) . " " .
4444 format_search_author
($co->{"${who}_email"}, $who,
4445 esc_html
("<" . $co->{"${who}_email"} . ">")) .
4446 "</td><td rowspan=\"2\">" .
4447 git_get_avatar
($co->{"${who}_email"}, -size
=> 'double') .
4451 format_timestamp_html
(\
%wd) .
4457 sub git_print_page_path
{
4463 print "<div class=\"page_path\">";
4464 print $cgi->a({-href
=> href
(action
=>"tree", hash_base
=>$hb),
4465 -title
=> 'tree root'}, to_utf8
("[$project]"));
4467 if (defined $name) {
4468 my @dirname = split '/', $name;
4469 my $basename = pop @dirname;
4472 foreach my $dir (@dirname) {
4473 $fullname .= ($fullname ? '/' : '') . $dir;
4474 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$fullname,
4476 -title
=> $fullname}, esc_path
($dir));
4479 if (defined $type && $type eq 'blob') {
4480 print $cgi->a({-href
=> href
(action
=>"blob_plain", file_name
=>$file_name,
4482 -title
=> $name}, esc_path
($basename));
4483 } elsif (defined $type && $type eq 'tree') {
4484 print $cgi->a({-href
=> href
(action
=>"tree", file_name
=>$file_name,
4486 -title
=> $name}, esc_path
($basename));
4489 print esc_path
($basename);
4492 print "<br/></div>\n";
4499 if ($opts{'-remove_title'}) {
4500 # remove title, i.e. first line of log
4503 # remove leading empty lines
4504 while (defined $log->[0] && $log->[0] eq "") {
4509 my $skip_blank_line = 0;
4510 foreach my $line (@$log) {
4511 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4512 if (! $opts{'-remove_signoff'}) {
4513 print "<span class=\"signoff\">" . esc_html
($line) . "</span><br/>\n";
4514 $skip_blank_line = 1;
4519 if ($line =~ m
,\s
*([a-z
]*link): (https
?://\S
+),i
) {
4520 if (! $opts{'-remove_signoff'}) {
4521 print "<span class=\"signoff\">" . esc_html
($1) . ": " .
4522 "<a href=\"" . esc_html
($2) . "\">" . esc_html
($2) . "</a>" .
4524 $skip_blank_line = 1;
4529 # print only one empty line
4530 # do not print empty line after signoff
4532 next if ($skip_blank_line);
4533 $skip_blank_line = 1;
4535 $skip_blank_line = 0;
4538 print format_log_line_html
($line) . "<br/>\n";
4541 if ($opts{'-final_empty_line'}) {
4542 # end with single empty line
4543 print "<br/>\n" unless $skip_blank_line;
4547 # return link target (what link points to)
4548 sub git_get_link_target
{
4553 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
4557 $link_target = <$fd>;
4562 return $link_target;
4565 # given link target, and the directory (basedir) the link is in,
4566 # return target of link relative to top directory (top tree);
4567 # return undef if it is not possible (including absolute links).
4568 sub normalize_link_target
{
4569 my ($link_target, $basedir) = @_;
4571 # absolute symlinks (beginning with '/') cannot be normalized
4572 return if (substr($link_target, 0, 1) eq '/');
4574 # normalize link target to path from top (root) tree (dir)
4577 $path = $basedir . '/' . $link_target;
4579 # we are in top (root) tree (dir)
4580 $path = $link_target;
4583 # remove //, /./, and /../
4585 foreach my $part (split('/', $path)) {
4586 # discard '.' and ''
4587 next if (!$part || $part eq '.');
4589 if ($part eq '..') {
4593 # link leads outside repository (outside top dir)
4597 push @path_parts, $part;
4600 $path = join('/', @path_parts);
4605 # print tree entry (row of git_tree), but without encompassing <tr> element
4606 sub git_print_tree_entry
{
4607 my ($t, $basedir, $hash_base, $have_blame) = @_;
4610 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4612 # The format of a table row is: mode list link. Where mode is
4613 # the mode of the entry, list is the name of the entry, an href,
4614 # and link is the action links of the entry.
4616 print "<td class=\"mode\">" . mode_str
($t->{'mode'}) . "</td>\n";
4617 if (exists $t->{'size'}) {
4618 print "<td class=\"size\">$t->{'size'}</td>\n";
4620 if ($t->{'type'} eq "blob") {
4621 print "<td class=\"list\">" .
4622 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4623 file_name
=>"$basedir$t->{'name'}", %base_key),
4624 -class => "list"}, esc_path
($t->{'name'}));
4625 if (S_ISLNK
(oct $t->{'mode'})) {
4626 my $link_target = git_get_link_target
($t->{'hash'});
4628 my $norm_target = normalize_link_target
($link_target, $basedir);
4629 if (defined $norm_target) {
4631 $cgi->a({-href
=> href
(action
=>"object", hash_base
=>$hash_base,
4632 file_name
=>$norm_target),
4633 -title
=> $norm_target}, esc_path
($link_target));
4635 print " -> " . esc_path
($link_target);
4640 print "<td class=\"link\">";
4641 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$t->{'hash'},
4642 file_name
=>"$basedir$t->{'name'}", %base_key)},
4646 $cgi->a({-href
=> href
(action
=>"blame", hash
=>$t->{'hash'},
4647 file_name
=>"$basedir$t->{'name'}", %base_key)},
4650 if (defined $hash_base) {
4652 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4653 hash
=>$t->{'hash'}, file_name
=>"$basedir$t->{'name'}")},
4657 $cgi->a({-href
=> href
(action
=>"blob_plain", hash_base
=>$hash_base,
4658 file_name
=>"$basedir$t->{'name'}")},
4662 } elsif ($t->{'type'} eq "tree") {
4663 print "<td class=\"list\">";
4664 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4665 file_name
=>"$basedir$t->{'name'}",
4667 esc_path
($t->{'name'}));
4669 print "<td class=\"link\">";
4670 print $cgi->a({-href
=> href
(action
=>"tree", hash
=>$t->{'hash'},
4671 file_name
=>"$basedir$t->{'name'}",
4674 if (defined $hash_base) {
4676 $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash_base,
4677 file_name
=>"$basedir$t->{'name'}")},
4682 # unknown object: we can only present history for it
4683 # (this includes 'commit' object, i.e. submodule support)
4684 print "<td class=\"list\">" .
4685 esc_path
($t->{'name'}) .
4687 print "<td class=\"link\">";
4688 if (defined $hash_base) {
4689 print $cgi->a({-href
=> href
(action
=>"history",
4690 hash_base
=>$hash_base,
4691 file_name
=>"$basedir$t->{'name'}")},
4698 ## ......................................................................
4699 ## functions printing large fragments of HTML
4701 # get pre-image filenames for merge (combined) diff
4702 sub fill_from_file_info
{
4703 my ($diff, @parents) = @_;
4705 $diff->{'from_file'} = [ ];
4706 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4707 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4708 if ($diff->{'status'}[$i] eq 'R' ||
4709 $diff->{'status'}[$i] eq 'C') {
4710 $diff->{'from_file'}[$i] =
4711 git_get_path_by_hash
($parents[$i], $diff->{'from_id'}[$i]);
4718 # is current raw difftree line of file deletion
4720 my $diffinfo = shift;
4722 return $diffinfo->{'to_id'} eq ('0' x
40);
4725 # does patch correspond to [previous] difftree raw line
4726 # $diffinfo - hashref of parsed raw diff format
4727 # $patchinfo - hashref of parsed patch diff format
4728 # (the same keys as in $diffinfo)
4729 sub is_patch_split
{
4730 my ($diffinfo, $patchinfo) = @_;
4732 return defined $diffinfo && defined $patchinfo
4733 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4737 sub git_difftree_body
{
4738 my ($difftree, $hash, @parents) = @_;
4739 my ($parent) = $parents[0];
4740 my $have_blame = gitweb_check_feature
('blame');
4741 print "<div class=\"list_head\">\n";
4742 if ($#{$difftree} > 10) {
4743 print(($#{$difftree} + 1) . " files changed:\n");
4747 print "<table class=\"" .
4748 (@parents > 1 ? "combined " : "") .
4751 # header only for combined diff in 'commitdiff' view
4752 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4755 print "<thead><tr>\n" .
4756 "<th></th><th></th>\n"; # filename, patchN link
4757 for (my $i = 0; $i < @parents; $i++) {
4758 my $par = $parents[$i];
4760 $cgi->a({-href
=> href
(action
=>"commitdiff",
4761 hash
=>$hash, hash_parent
=>$par),
4762 -title
=> 'commitdiff to parent number ' .
4763 ($i+1) . ': ' . substr($par,0,7)},
4767 print "</tr></thead>\n<tbody>\n";
4772 foreach my $line (@{$difftree}) {
4773 my $diff = parsed_difftree_line
($line);
4776 print "<tr class=\"dark\">\n";
4778 print "<tr class=\"light\">\n";
4782 if (exists $diff->{'nparents'}) { # combined diff
4784 fill_from_file_info
($diff, @parents)
4785 unless exists $diff->{'from_file'};
4787 if (!is_deleted
($diff)) {
4788 # file exists in the result (child) commit
4790 $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4791 file_name
=>$diff->{'to_file'},
4793 -class => "list"}, esc_path
($diff->{'to_file'})) .
4797 esc_path
($diff->{'to_file'}) .
4801 if ($action eq 'commitdiff') {
4804 print "<td class=\"link\">" .
4805 $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4811 my $has_history = 0;
4812 my $not_deleted = 0;
4813 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4814 my $hash_parent = $parents[$i];
4815 my $from_hash = $diff->{'from_id'}[$i];
4816 my $from_path = $diff->{'from_file'}[$i];
4817 my $status = $diff->{'status'}[$i];
4819 $has_history ||= ($status ne 'A');
4820 $not_deleted ||= ($status ne 'D');
4822 if ($status eq 'A') {
4823 print "<td class=\"link\" align=\"right\"> | </td>\n";
4824 } elsif ($status eq 'D') {
4825 print "<td class=\"link\">" .
4826 $cgi->a({-href
=> href
(action
=>"blob",
4829 file_name
=>$from_path)},
4833 if ($diff->{'to_id'} eq $from_hash) {
4834 print "<td class=\"link nochange\">";
4836 print "<td class=\"link\">";
4838 print $cgi->a({-href
=> href
(action
=>"blobdiff",
4839 hash
=>$diff->{'to_id'},
4840 hash_parent
=>$from_hash,
4842 hash_parent_base
=>$hash_parent,
4843 file_name
=>$diff->{'to_file'},
4844 file_parent
=>$from_path)},
4850 print "<td class=\"link\">";
4852 print $cgi->a({-href
=> href
(action
=>"blob",
4853 hash
=>$diff->{'to_id'},
4854 file_name
=>$diff->{'to_file'},
4857 print " | " if ($has_history);
4860 print $cgi->a({-href
=> href
(action
=>"history",
4861 file_name
=>$diff->{'to_file'},
4868 next; # instead of 'else' clause, to avoid extra indent
4870 # else ordinary diff
4872 my ($to_mode_oct, $to_mode_str, $to_file_type);
4873 my ($from_mode_oct, $from_mode_str, $from_file_type);
4874 if ($diff->{'to_mode'} ne ('0' x
6)) {
4875 $to_mode_oct = oct $diff->{'to_mode'};
4876 if (S_ISREG
($to_mode_oct)) { # only for regular file
4877 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4879 $to_file_type = file_type
($diff->{'to_mode'});
4881 if ($diff->{'from_mode'} ne ('0' x
6)) {
4882 $from_mode_oct = oct $diff->{'from_mode'};
4883 if (S_ISREG
($from_mode_oct)) { # only for regular file
4884 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4886 $from_file_type = file_type
($diff->{'from_mode'});
4889 if ($diff->{'status'} eq "A") { # created
4890 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4891 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4892 $mode_chng .= "]</span>";
4894 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4895 hash_base
=>$hash, file_name
=>$diff->{'file'}),
4896 -class => "list"}, esc_path
($diff->{'file'}));
4898 print "<td>$mode_chng</td>\n";
4899 print "<td class=\"link\">";
4900 if ($action eq 'commitdiff') {
4903 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4907 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4908 hash_base
=>$hash, file_name
=>$diff->{'file'})},
4912 } elsif ($diff->{'status'} eq "D") { # deleted
4913 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4915 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
4916 hash_base
=>$parent, file_name
=>$diff->{'file'}),
4917 -class => "list"}, esc_path
($diff->{'file'}));
4919 print "<td>$mode_chng</td>\n";
4920 print "<td class=\"link\">";
4921 if ($action eq 'commitdiff') {
4924 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4928 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'from_id'},
4929 hash_base
=>$parent, file_name
=>$diff->{'file'})},
4932 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$parent,
4933 file_name
=>$diff->{'file'})},
4936 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$parent,
4937 file_name
=>$diff->{'file'})},
4941 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4942 my $mode_chnge = "";
4943 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4944 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4945 if ($from_file_type ne $to_file_type) {
4946 $mode_chnge .= " from $from_file_type to $to_file_type";
4948 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4949 if ($from_mode_str && $to_mode_str) {
4950 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4951 } elsif ($to_mode_str) {
4952 $mode_chnge .= " mode: $to_mode_str";
4955 $mode_chnge .= "]</span>\n";
4958 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4959 hash_base
=>$hash, file_name
=>$diff->{'file'}),
4960 -class => "list"}, esc_path
($diff->{'file'}));
4962 print "<td>$mode_chnge</td>\n";
4963 print "<td class=\"link\">";
4964 if ($action eq 'commitdiff') {
4967 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
4970 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4971 # "commit" view and modified file (not onlu mode changed)
4972 print $cgi->a({-href
=> href
(action
=>"blobdiff",
4973 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
4974 hash_base
=>$hash, hash_parent_base
=>$parent,
4975 file_name
=>$diff->{'file'})},
4979 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
4980 hash_base
=>$hash, file_name
=>$diff->{'file'})},
4983 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
4984 file_name
=>$diff->{'file'})},
4987 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
4988 file_name
=>$diff->{'file'})},
4992 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4993 my %status_name = ('R' => 'moved', 'C' => 'copied');
4994 my $nstatus = $status_name{$diff->{'status'}};
4996 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4997 # mode also for directories, so we cannot use $to_mode_str
4998 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5001 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$hash,
5002 hash
=>$diff->{'to_id'}, file_name
=>$diff->{'to_file'}),
5003 -class => "list"}, esc_path
($diff->{'to_file'})) . "</td>\n" .
5004 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5005 $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$parent,
5006 hash
=>$diff->{'from_id'}, file_name
=>$diff->{'from_file'}),
5007 -class => "list"}, esc_path
($diff->{'from_file'})) .
5008 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5009 "<td class=\"link\">";
5010 if ($action eq 'commitdiff') {
5013 print $cgi->a({-href
=> href
(-anchor
=>"patch$patchno")},
5016 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5017 # "commit" view and modified file (not only pure rename or copy)
5018 print $cgi->a({-href
=> href
(action
=>"blobdiff",
5019 hash
=>$diff->{'to_id'}, hash_parent
=>$diff->{'from_id'},
5020 hash_base
=>$hash, hash_parent_base
=>$parent,
5021 file_name
=>$diff->{'to_file'}, file_parent
=>$diff->{'from_file'})},
5025 print $cgi->a({-href
=> href
(action
=>"blob", hash
=>$diff->{'to_id'},
5026 hash_base
=>$parent, file_name
=>$diff->{'to_file'})},
5029 print $cgi->a({-href
=> href
(action
=>"blame", hash_base
=>$hash,
5030 file_name
=>$diff->{'to_file'})},
5033 print $cgi->a({-href
=> href
(action
=>"history", hash_base
=>$hash,
5034 file_name
=>$diff->{'to_file'})},
5038 } # we should not encounter Unmerged (U) or Unknown (X) status
5041 print "</tbody>" if $has_header;
5045 # Print context lines and then rem/add lines in a side-by-side manner.
5046 sub print_sidebyside_diff_lines
{
5047 my ($ctx, $rem, $add) = @_;
5049 # print context block before add/rem block
5052 '<div class="chunk_block ctx">',
5053 '<div class="old">',
5056 '<div class="new">',
5065 '<div class="chunk_block rem">',
5066 '<div class="old">',
5073 '<div class="chunk_block add">',
5074 '<div class="new">',
5080 '<div class="chunk_block chg">',
5081 '<div class="old">',
5084 '<div class="new">',
5091 # Print context lines and then rem/add lines in inline manner.
5092 sub print_inline_diff_lines
{
5093 my ($ctx, $rem, $add) = @_;
5095 print @$ctx, @$rem, @$add;
5098 # Format removed and added line, mark changed part and HTML-format them.
5099 # Implementation is based on contrib/diff-highlight
5100 sub format_rem_add_lines_pair
{
5101 my ($rem, $add, $num_parents) = @_;
5103 # We need to untabify lines before split()'ing them;
5104 # otherwise offsets would be invalid.
5107 $rem = untabify
($rem);
5108 $add = untabify
($add);
5110 my @rem = split(//, $rem);
5111 my @add = split(//, $add);
5112 my ($esc_rem, $esc_add);
5113 # Ignore leading +/- characters for each parent.
5114 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5115 my ($prefix_has_nonspace, $suffix_has_nonspace);
5117 my $shorter = (@rem < @add) ? @rem : @add;
5118 while ($prefix_len < $shorter) {
5119 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5121 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5125 while ($prefix_len + $suffix_len < $shorter) {
5126 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5128 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5132 # Mark lines that are different from each other, but have some common
5133 # part that isn't whitespace. If lines are completely different, don't
5134 # mark them because that would make output unreadable, especially if
5135 # diff consists of multiple lines.
5136 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5137 $esc_rem = esc_html_hl_regions
($rem, 'marked',
5138 [$prefix_len, @rem - $suffix_len], -nbsp
=>1);
5139 $esc_add = esc_html_hl_regions
($add, 'marked',
5140 [$prefix_len, @add - $suffix_len], -nbsp
=>1);
5142 $esc_rem = esc_html
($rem, -nbsp
=>1);
5143 $esc_add = esc_html
($add, -nbsp
=>1);
5146 return format_diff_line
(\
$esc_rem, 'rem'),
5147 format_diff_line
(\
$esc_add, 'add');
5150 # HTML-format diff context, removed and added lines.
5151 sub format_ctx_rem_add_lines
{
5152 my ($ctx, $rem, $add, $num_parents) = @_;
5153 my (@new_ctx, @new_rem, @new_add);
5154 my $can_highlight = 0;
5155 my $is_combined = ($num_parents > 1);
5157 # Highlight if every removed line has a corresponding added line.
5158 if (@$add > 0 && @$add == @$rem) {
5161 # Highlight lines in combined diff only if the chunk contains
5162 # diff between the same version, e.g.
5169 # Otherwise the highlightling would be confusing.
5171 for (my $i = 0; $i < @$add; $i++) {
5172 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5173 my $prefix_add = substr($add->[$i], 0, $num_parents);
5175 $prefix_rem =~ s/-/+/g;
5177 if ($prefix_rem ne $prefix_add) {
5185 if ($can_highlight) {
5186 for (my $i = 0; $i < @$add; $i++) {
5187 my ($line_rem, $line_add) = format_rem_add_lines_pair
(
5188 $rem->[$i], $add->[$i], $num_parents);
5189 push @new_rem, $line_rem;
5190 push @new_add, $line_add;
5193 @new_rem = map { format_diff_line
($_, 'rem') } @$rem;
5194 @new_add = map { format_diff_line
($_, 'add') } @$add;
5197 @new_ctx = map { format_diff_line
($_, 'ctx') } @$ctx;
5199 return (\
@new_ctx, \
@new_rem, \
@new_add);
5202 # Print context lines and then rem/add lines.
5203 sub print_diff_lines
{
5204 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5205 my $is_combined = $num_parents > 1;
5207 ($ctx, $rem, $add) = format_ctx_rem_add_lines
($ctx, $rem, $add,
5210 if ($diff_style eq 'sidebyside' && !$is_combined) {
5211 print_sidebyside_diff_lines
($ctx, $rem, $add);
5213 # default 'inline' style and unknown styles
5214 print_inline_diff_lines
($ctx, $rem, $add);
5218 sub print_diff_chunk
{
5219 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5220 my (@ctx, @rem, @add);
5222 # The class of the previous line.
5223 my $prev_class = '';
5225 return unless @chunk;
5227 # incomplete last line might be among removed or added lines,
5228 # or both, or among context lines: find which
5229 for (my $i = 1; $i < @chunk; $i++) {
5230 if ($chunk[$i][0] eq 'incomplete') {
5231 $chunk[$i][0] = $chunk[$i-1][0];
5236 push @chunk, ["", ""];
5238 foreach my $line_info (@chunk) {
5239 my ($class, $line) = @$line_info;
5241 # print chunk headers
5242 if ($class && $class eq 'chunk_header') {
5243 print format_diff_line
($line, $class, $from, $to);
5247 ## print from accumulator when have some add/rem lines or end
5248 # of chunk (flush context lines), or when have add and rem
5249 # lines and new block is reached (otherwise add/rem lines could
5251 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5252 (@rem && @add && $class ne $prev_class)) {
5253 print_diff_lines
(\
@ctx, \
@rem, \
@add,
5254 $diff_style, $num_parents);
5255 @ctx = @rem = @add = ();
5258 ## adding lines to accumulator
5261 # rem, add or change
5262 if ($class eq 'rem') {
5264 } elsif ($class eq 'add') {
5268 if ($class eq 'ctx') {
5272 $prev_class = $class;
5276 sub git_patchset_body
{
5277 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5278 my ($hash_parent) = $hash_parents[0];
5280 my $is_combined = (@hash_parents > 1);
5282 my $patch_number = 0;
5287 my @chunk; # for side-by-side diff
5289 print "<div class=\"patchset\">\n";
5291 # skip to first patch
5292 while ($patch_line = <$fd>) {
5295 last if ($patch_line =~ m/^diff /);
5299 while ($patch_line) {
5301 # parse "git diff" header line
5302 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5303 # $1 is from_name, which we do not use
5304 $to_name = unquote
($2);
5305 $to_name =~ s!^b/!!;
5306 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5307 # $1 is 'cc' or 'combined', which we do not use
5308 $to_name = unquote
($2);
5313 # check if current patch belong to current raw line
5314 # and parse raw git-diff line if needed
5315 if (is_patch_split
($diffinfo, { 'to_file' => $to_name })) {
5316 # this is continuation of a split patch
5317 print "<div class=\"patch cont\">\n";
5319 # advance raw git-diff output if needed
5320 $patch_idx++ if defined $diffinfo;
5322 # read and prepare patch information
5323 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5325 # compact combined diff output can have some patches skipped
5326 # find which patch (using pathname of result) we are at now;
5328 while ($to_name ne $diffinfo->{'to_file'}) {
5329 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5330 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5331 "</div>\n"; # class="patch"
5336 last if $patch_idx > $#$difftree;
5337 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5341 # modifies %from, %to hashes
5342 parse_from_to_diffinfo
($diffinfo, \
%from, \
%to, @hash_parents);
5344 # this is first patch for raw difftree line with $patch_idx index
5345 # we index @$difftree array from 0, but number patches from 1
5346 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5350 #assert($patch_line =~ m/^diff /) if DEBUG;
5351 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5353 # print "git diff" header
5354 print format_git_diff_header_line
($patch_line, $diffinfo,
5357 # print extended diff header
5358 print "<div class=\"diff extended_header\">\n";
5360 while ($patch_line = <$fd>) {
5363 last EXTENDED_HEADER
if ($patch_line =~ m/^--- |^diff /);
5365 print format_extended_diff_header_line
($patch_line, $diffinfo,
5368 print "</div>\n"; # class="diff extended_header"
5370 # from-file/to-file diff header
5371 if (! $patch_line) {
5372 print "</div>\n"; # class="patch"
5375 next PATCH
if ($patch_line =~ m/^diff /);
5376 #assert($patch_line =~ m/^---/) if DEBUG;
5378 my $last_patch_line = $patch_line;
5379 $patch_line = <$fd>;
5381 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5383 print format_diff_from_to_header
($last_patch_line, $patch_line,
5384 $diffinfo, \
%from, \
%to,
5389 while ($patch_line = <$fd>) {
5392 next PATCH
if ($patch_line =~ m/^diff /);
5394 my $class = diff_line_class
($patch_line, \
%from, \
%to);
5396 if ($class eq 'chunk_header') {
5397 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5401 push @chunk, [ $class, $patch_line ];
5406 print_diff_chunk
($diff_style, scalar @hash_parents, \
%from, \
%to, @chunk);
5409 print "</div>\n"; # class="patch"
5412 # for compact combined (--cc) format, with chunk and patch simplification
5413 # the patchset might be empty, but there might be unprocessed raw lines
5414 for (++$patch_idx if $patch_number > 0;
5415 $patch_idx < @$difftree;
5417 # read and prepare patch information
5418 $diffinfo = parsed_difftree_line
($difftree->[$patch_idx]);
5420 # generate anchor for "patch" links in difftree / whatchanged part
5421 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5422 format_diff_cc_simplified
($diffinfo, @hash_parents) .
5423 "</div>\n"; # class="patch"
5428 if ($patch_number == 0) {
5429 if (@hash_parents > 1) {
5430 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5432 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5436 print "</div>\n"; # class="patchset"
5439 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5441 sub git_project_search_form
{
5442 my ($searchtext, $search_use_regexp) = @_;
5445 if ($project_filter) {
5446 $limit = " in '$project_filter/'";
5449 print "<div class=\"projsearch\">\n";
5450 print $cgi->startform(-method => 'get', -action
=> $my_uri) .
5451 $cgi->hidden(-name
=> 'a', -value
=> 'project_list') . "\n";
5452 print $cgi->hidden(-name
=> 'pf', -value
=> $project_filter). "\n"
5453 if (defined $project_filter);
5454 print $cgi->textfield(-name
=> 's', -value
=> $searchtext,
5455 -title
=> "Search project by name and description$limit",
5456 -size
=> 60) . "\n" .
5457 "<span title=\"Extended regular expression\">" .
5458 $cgi->checkbox(-name
=> 'sr', -value
=> 1, -label
=> 're',
5459 -checked
=> $search_use_regexp) .
5461 $cgi->submit(-name
=> 'btnS', -value
=> 'Search') .
5462 $cgi->end_form() . "\n" .
5463 $cgi->a({-href
=> href
(project
=> undef, searchtext
=> undef,
5464 project_filter
=> $project_filter)},
5465 esc_html
("List all projects$limit")) . "<br />\n";
5469 # entry for given @keys needs filling if at least one of keys in list
5470 # is not present in %$project_info
5471 sub project_info_needs_filling
{
5472 my ($project_info, @keys) = @_;
5474 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5475 foreach my $key (@keys) {
5476 if (!exists $project_info->{$key}) {
5483 # fills project list info (age, description, owner, category, forks, etc.)
5484 # for each project in the list, removing invalid projects from
5485 # returned list, or fill only specified info.
5487 # Invalid projects are removed from the returned list if and only if you
5488 # ask 'age' or 'age_string' to be filled, because they are the only fields
5489 # that run unconditionally git command that requires repository, and
5490 # therefore do always check if project repository is invalid.
5493 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5494 # ensures that 'descr_long' and 'ctags' fields are filled
5495 # * @project_list = fill_project_list_info(\@project_list)
5496 # ensures that all fields are filled (and invalid projects removed)
5498 # NOTE: modifies $projlist, but does not remove entries from it
5499 sub fill_project_list_info
{
5500 my ($projlist, @wanted_keys) = @_;
5502 my $filter_set = sub { return @_; };
5504 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5505 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5508 my $show_ctags = gitweb_check_feature
('ctags');
5510 foreach my $pr (@$projlist) {
5511 if (project_info_needs_filling
($pr, $filter_set->('age', 'age_string'))) {
5512 my (@activity) = git_get_last_activity
($pr->{'path'});
5513 unless (@activity) {
5516 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5518 if (project_info_needs_filling
($pr, $filter_set->('descr', 'descr_long'))) {
5519 my $descr = git_get_project_description
($pr->{'path'}) || "";
5520 $descr = to_utf8
($descr);
5521 $pr->{'descr_long'} = $descr;
5522 $pr->{'descr'} = chop_str
($descr, $projects_list_description_width, 5);
5524 if (project_info_needs_filling
($pr, $filter_set->('owner'))) {
5525 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}") || "";
5528 project_info_needs_filling
($pr, $filter_set->('ctags'))) {
5529 $pr->{'ctags'} = git_get_project_ctags
($pr->{'path'});
5531 if ($projects_list_group_categories &&
5532 project_info_needs_filling
($pr, $filter_set->('category'))) {
5533 my $cat = git_get_project_category
($pr->{'path'}) ||
5534 $project_list_default_category;
5535 $pr->{'category'} = to_utf8
($cat);
5538 push @projects, $pr;
5544 sub sort_projects_list
{
5545 my ($projlist, $order) = @_;
5549 return sub { $a->{$key} cmp $b->{$key} };
5552 sub order_num_then_undef
{
5555 defined $a->{$key} ?
5556 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5557 (defined $b->{$key} ? 1 : 0)
5562 project
=> order_str
('path'),
5563 descr
=> order_str
('descr_long'),
5564 owner
=> order_str
('owner'),
5565 age
=> order_num_then_undef
('age'),
5568 my $ordering = $orderings{$order};
5569 return defined $ordering ? sort $ordering @$projlist : @$projlist;
5572 # returns a hash of categories, containing the list of project
5573 # belonging to each category
5574 sub build_projlist_by_category
{
5575 my ($projlist, $from, $to) = @_;
5578 $from = 0 unless defined $from;
5579 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5581 for (my $i = $from; $i <= $to; $i++) {
5582 my $pr = $projlist->[$i];
5583 push @{$categories{ $pr->{'category'} }}, $pr;
5586 return wantarray ? %categories : \
%categories;
5589 # print 'sort by' <th> element, generating 'sort by $name' replay link
5590 # if that order is not selected
5592 print format_sort_th
(@_);
5595 sub format_sort_th
{
5596 my ($name, $order, $header) = @_;
5598 $header ||= ucfirst($name);
5600 if ($order eq $name) {
5601 $sort_th .= "<th>$header</th>\n";
5603 $sort_th .= "<th>" .
5604 $cgi->a({-href
=> href
(-replay
=>1, order
=>$name),
5605 -class => "header"}, $header) .
5612 sub git_project_list_rows
{
5613 my ($projlist, $from, $to, $check_forks) = @_;
5615 $from = 0 unless defined $from;
5616 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5619 for (my $i = $from; $i <= $to; $i++) {
5620 my $pr = $projlist->[$i];
5623 print "<tr class=\"dark\">\n";
5625 print "<tr class=\"light\">\n";
5631 if ($pr->{'forks'}) {
5632 my $nforks = scalar @{$pr->{'forks'}};
5634 print $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks"),
5635 -title
=> "$nforks forks"}, "+");
5637 print $cgi->span({-title
=> "$nforks forks"}, "+");
5642 print "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5644 esc_html_match_hl
($pr->{'path'}, $search_regexp)) .
5646 "<td>" . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary"),
5648 -title
=> $pr->{'descr_long'}},
5650 ? esc_html_match_hl_chopped
($pr->{'descr_long'},
5651 $pr->{'descr'}, $search_regexp)
5652 : esc_html
($pr->{'descr'})) .
5654 unless ($omit_owner) {
5655 print "<td><i>" . chop_and_escape_str
($pr->{'owner'}, 15) . "</i></td>\n";
5657 unless ($omit_age_column) {
5658 print "<td class=\"". age_class
($pr->{'age'}) . "\">" .
5659 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5661 print"<td class=\"link\">" .
5662 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"summary")}, "summary") . " | " .
5663 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"shortlog")}, "shortlog") . " | " .
5664 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"log")}, "log") . " | " .
5665 $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"tree")}, "tree") .
5666 ($pr->{'forks'} ? " | " . $cgi->a({-href
=> href
(project
=>$pr->{'path'}, action
=>"forks")}, "forks") : '') .
5672 sub git_project_list_body
{
5673 # actually uses global variable $project
5674 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5675 my @projects = @$projlist;
5677 my $check_forks = gitweb_check_feature
('forks');
5678 my $show_ctags = gitweb_check_feature
('ctags');
5679 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5680 $check_forks = undef
5681 if ($tagfilter || $search_regexp);
5683 # filtering out forks before filling info allows to do less work
5684 @projects = filter_forks_from_projects_list
(\
@projects)
5686 # search_projects_list pre-fills required info
5687 @projects = search_projects_list
(\
@projects,
5688 'search_regexp' => $search_regexp,
5689 'tagfilter' => $tagfilter)
5690 if ($tagfilter || $search_regexp);
5692 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5693 push @all_fields, ('age', 'age_string') unless($omit_age_column);
5694 push @all_fields, 'owner' unless($omit_owner);
5695 @projects = fill_project_list_info
(\
@projects, @all_fields);
5697 $order ||= $default_projects_order;
5698 $from = 0 unless defined $from;
5699 $to = $#projects if (!defined $to || $#projects < $to);
5704 "<b>No such projects found</b><br />\n".
5705 "Click ".$cgi->a({-href
=>href
(project
=>undef)},"here")." to view all projects<br />\n".
5706 "</center>\n<br />\n";
5710 @projects = sort_projects_list
(\
@projects, $order);
5713 my $ctags = git_gather_all_ctags
(\
@projects);
5714 my $cloud = git_populate_project_tagcloud
($ctags);
5715 print git_show_project_tagcloud
($cloud, 64);
5718 print "<table class=\"project_list\">\n";
5719 unless ($no_header) {
5722 print "<th></th>\n";
5724 print_sort_th
('project', $order, 'Project');
5725 print_sort_th
('descr', $order, 'Description');
5726 print_sort_th
('owner', $order, 'Owner') unless $omit_owner;
5727 print_sort_th
('age', $order, 'Last Change') unless $omit_age_column;
5728 print "<th></th>\n" . # for links
5732 if ($projects_list_group_categories) {
5733 # only display categories with projects in the $from-$to window
5734 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5735 my %categories = build_projlist_by_category
(\
@projects, $from, $to);
5736 foreach my $cat (sort keys %categories) {
5737 unless ($cat eq "") {
5740 print "<td></td>\n";
5742 print "<td class=\"category\" colspan=\"5\">".esc_html
($cat)."</td>\n";
5746 git_project_list_rows
($categories{$cat}, undef, undef, $check_forks);
5749 git_project_list_rows
(\
@projects, $from, $to, $check_forks);
5752 if (defined $extra) {
5755 print "<td></td>\n";
5757 print "<td colspan=\"5\">$extra</td>\n" .
5764 # uses global variable $project
5765 my ($commitlist, $from, $to, $refs, $extra) = @_;
5767 $from = 0 unless defined $from;
5768 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5770 for (my $i = 0; $i <= $to; $i++) {
5771 my %co = %{$commitlist->[$i]};
5773 my $commit = $co{'id'};
5774 my $ref = format_ref_marker
($refs, $commit);
5775 git_print_header_div
('commit',
5776 "<span class=\"age\">$co{'age_string'}</span>" .
5777 esc_html
($co{'title'}) . $ref,
5779 print "<div class=\"title_text\">\n" .
5780 "<div class=\"log_link\">\n" .
5781 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") .
5783 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") .
5785 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree") .
5788 git_print_authorship
(\
%co, -tag
=> 'span');
5789 print "<br/>\n</div>\n";
5791 print "<div class=\"log_body\">\n";
5792 git_print_log
($co{'comment'}, -final_empty_line
=> 1);
5796 print "<div class=\"page_nav\">\n";
5802 sub git_shortlog_body
{
5803 # uses global variable $project
5804 my ($commitlist, $from, $to, $refs, $extra) = @_;
5806 $from = 0 unless defined $from;
5807 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5809 print "<table class=\"shortlog\">\n";
5811 for (my $i = $from; $i <= $to; $i++) {
5812 my %co = %{$commitlist->[$i]};
5813 my $commit = $co{'id'};
5814 my $ref = format_ref_marker
($refs, $commit);
5816 print "<tr class=\"dark\">\n";
5818 print "<tr class=\"light\">\n";
5821 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5822 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5823 format_author_html
('td', \
%co, 10) . "<td>";
5824 print format_subject_html
($co{'title'}, $co{'title_short'},
5825 href
(action
=>"commit", hash
=>$commit), $ref);
5827 "<td class=\"link\">" .
5828 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$commit)}, "commit") . " | " .
5829 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff") . " | " .
5830 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$commit, hash_base
=>$commit)}, "tree");
5831 my $snapshot_links = format_snapshot_links
($commit);
5832 if (defined $snapshot_links) {
5833 print " | " . $snapshot_links;
5838 if (defined $extra) {
5840 "<td colspan=\"4\">$extra</td>\n" .
5846 sub git_history_body
{
5847 # Warning: assumes constant type (blob or tree) during history
5848 my ($commitlist, $from, $to, $refs, $extra,
5849 $file_name, $file_hash, $ftype) = @_;
5851 $from = 0 unless defined $from;
5852 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5854 print "<table class=\"history\">\n";
5856 for (my $i = $from; $i <= $to; $i++) {
5857 my %co = %{$commitlist->[$i]};
5861 my $commit = $co{'id'};
5863 my $ref = format_ref_marker
($refs, $commit);
5866 print "<tr class=\"dark\">\n";
5868 print "<tr class=\"light\">\n";
5871 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5872 # shortlog: format_author_html('td', \%co, 10)
5873 format_author_html
('td', \
%co, 15, 3) . "<td>";
5874 # originally git_history used chop_str($co{'title'}, 50)
5875 print format_subject_html
($co{'title'}, $co{'title_short'},
5876 href
(action
=>"commit", hash
=>$commit), $ref);
5878 "<td class=\"link\">" .
5879 $cgi->a({-href
=> href
(action
=>$ftype, hash_base
=>$commit, file_name
=>$file_name)}, $ftype) . " | " .
5880 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$commit)}, "commitdiff");
5882 if ($ftype eq 'blob') {
5883 my $blob_current = $file_hash;
5884 my $blob_parent = git_get_hash_by_path
($commit, $file_name);
5885 if (defined $blob_current && defined $blob_parent &&
5886 $blob_current ne $blob_parent) {
5888 $cgi->a({-href
=> href
(action
=>"blobdiff",
5889 hash
=>$blob_current, hash_parent
=>$blob_parent,
5890 hash_base
=>$hash_base, hash_parent_base
=>$commit,
5891 file_name
=>$file_name)},
5898 if (defined $extra) {
5900 "<td colspan=\"4\">$extra</td>\n" .
5907 # uses global variable $project
5908 my ($taglist, $from, $to, $extra) = @_;
5909 $from = 0 unless defined $from;
5910 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5912 print "<table class=\"tags\">\n";
5914 for (my $i = $from; $i <= $to; $i++) {
5915 my $entry = $taglist->[$i];
5917 my $comment = $tag{'subject'};
5919 if (defined $comment) {
5920 $comment_short = chop_str
($comment, 30, 5);
5923 print "<tr class=\"dark\">\n";
5925 print "<tr class=\"light\">\n";
5928 if (defined $tag{'age'}) {
5929 print "<td><i>$tag{'age'}</i></td>\n";
5931 print "<td></td>\n";
5934 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'}),
5935 -class => "list name"}, esc_html
($tag{'name'})) .
5938 if (defined $comment) {
5939 print format_subject_html
($comment, $comment_short,
5940 href
(action
=>"tag", hash
=>$tag{'id'}));
5943 "<td class=\"selflink\">";
5944 if ($tag{'type'} eq "tag") {
5945 print $cgi->a({-href
=> href
(action
=>"tag", hash
=>$tag{'id'})}, "tag");
5950 "<td class=\"link\">" . " | " .
5951 $cgi->a({-href
=> href
(action
=>$tag{'reftype'}, hash
=>$tag{'refid'})}, $tag{'reftype'});
5952 if ($tag{'reftype'} eq "commit") {
5953 print " | " . $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$tag{'fullname'})}, "shortlog") .
5954 " | " . $cgi->a({-href
=> href
(action
=>"log", hash
=>$tag{'fullname'})}, "log");
5955 } elsif ($tag{'reftype'} eq "blob") {
5956 print " | " . $cgi->a({-href
=> href
(action
=>"blob_plain", hash
=>$tag{'refid'})}, "raw");
5961 if (defined $extra) {
5963 "<td colspan=\"5\">$extra</td>\n" .
5969 sub git_heads_body
{
5970 # uses global variable $project
5971 my ($headlist, $head_at, $from, $to, $extra) = @_;
5972 $from = 0 unless defined $from;
5973 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5975 print "<table class=\"heads\">\n";
5977 for (my $i = $from; $i <= $to; $i++) {
5978 my $entry = $headlist->[$i];
5980 my $curr = defined $head_at && $ref{'id'} eq $head_at;
5982 print "<tr class=\"dark\">\n";
5984 print "<tr class=\"light\">\n";
5987 print "<td><i>$ref{'age'}</i></td>\n" .
5988 ($curr ? "<td class=\"current_head\">" : "<td>") .
5989 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'}),
5990 -class => "list name"},esc_html
($ref{'name'})) .
5992 "<td class=\"link\">" .
5993 $cgi->a({-href
=> href
(action
=>"shortlog", hash
=>$ref{'fullname'})}, "shortlog") . " | " .
5994 $cgi->a({-href
=> href
(action
=>"log", hash
=>$ref{'fullname'})}, "log") . " | " .
5995 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$ref{'fullname'}, hash_base
=>$ref{'fullname'})}, "tree") .
5999 if (defined $extra) {
6001 "<td colspan=\"3\">$extra</td>\n" .
6007 # Display a single remote block
6008 sub git_remote_block
{
6009 my ($remote, $rdata, $limit, $head) = @_;
6011 my $heads = $rdata->{'heads'};
6012 my $fetch = $rdata->{'fetch'};
6013 my $push = $rdata->{'push'};
6015 my $urls_table = "<table class=\"projects_list\">\n" ;
6017 if (defined $fetch) {
6018 if ($fetch eq $push) {
6019 $urls_table .= format_repo_url
("URL", $fetch);
6021 $urls_table .= format_repo_url
("Fetch URL", $fetch);
6022 $urls_table .= format_repo_url
("Push URL", $push) if defined $push;
6024 } elsif (defined $push) {
6025 $urls_table .= format_repo_url
("Push URL", $push);
6027 $urls_table .= format_repo_url
("", "No remote URL");
6030 $urls_table .= "</table>\n";
6033 if (defined $limit && $limit < @$heads) {
6034 $dots = $cgi->a({-href
=> href
(action
=>"remotes", hash
=>$remote)}, "...");
6038 git_heads_body
($heads, $head, 0, $limit, $dots);
6041 # Display a list of remote names with the respective fetch and push URLs
6042 sub git_remotes_list
{
6043 my ($remotedata, $limit) = @_;
6044 print "<table class=\"heads\">\n";
6046 my @remotes = sort keys %$remotedata;
6048 my $limited = $limit && $limit < @remotes;
6050 $#remotes = $limit - 1 if $limited;
6052 while (my $remote = shift @remotes) {
6053 my $rdata = $remotedata->{$remote};
6054 my $fetch = $rdata->{'fetch'};
6055 my $push = $rdata->{'push'};
6057 print "<tr class=\"dark\">\n";
6059 print "<tr class=\"light\">\n";
6063 $cgi->a({-href
=> href
(action
=>'remotes', hash
=>$remote),
6064 -class=> "list name"},esc_html
($remote)) .
6066 print "<td class=\"link\">" .
6067 (defined $fetch ? $cgi->a({-href
=> $fetch}, "fetch") : "fetch") .
6069 (defined $push ? $cgi->a({-href
=> $push}, "push") : "push") .
6077 "<td colspan=\"3\">" .
6078 $cgi->a({-href
=> href
(action
=>"remotes")}, "...") .
6079 "</td>\n" . "</tr>\n";
6085 # Display remote heads grouped by remote, unless there are too many
6086 # remotes, in which case we only display the remote names
6087 sub git_remotes_body
{
6088 my ($remotedata, $limit, $head) = @_;
6089 if ($limit and $limit < keys %$remotedata) {
6090 git_remotes_list
($remotedata, $limit);
6092 fill_remote_heads
($remotedata);
6093 while (my ($remote, $rdata) = each %$remotedata) {
6094 git_print_section
({-class=>"remote", -id
=>$remote},
6095 ["remotes", $remote, $remote], sub {
6096 git_remote_block
($remote, $rdata, $limit, $head);
6102 sub git_search_message
{
6106 if ($searchtype eq 'commit') {
6107 $greptype = "--grep=";
6108 } elsif ($searchtype eq 'author') {
6109 $greptype = "--author=";
6110 } elsif ($searchtype eq 'committer') {
6111 $greptype = "--committer=";
6113 $greptype .= $searchtext;
6114 my @commitlist = parse_commits
($hash, 101, (100 * $page), undef,
6115 $greptype, '--regexp-ignore-case',
6116 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6118 my $paging_nav = '';
6121 $cgi->a({-href
=> href
(-replay
=>1, page
=>undef)},
6124 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page-1),
6125 -accesskey
=> "p", -title
=> "Alt-p"}, "prev");
6127 $paging_nav .= "first ⋅ prev";
6130 if ($#commitlist >= 100) {
6132 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
6133 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
6134 $paging_nav .= " ⋅ $next_link";
6136 $paging_nav .= " ⋅ next";
6141 git_print_page_nav
('','', $hash,$co{'tree'},$hash, $paging_nav);
6142 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6143 if ($page == 0 && !@commitlist) {
6144 print "<p>No match.</p>\n";
6146 git_search_grep_body
(\
@commitlist, 0, 99, $next_link);
6152 sub git_search_changes
{
6156 open my $fd, '-|', git_cmd
(), '--no-pager', 'log', @diff_opts,
6157 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6158 ($search_use_regexp ? '--pickaxe-regex' : ())
6159 or die_error
(500, "Open git-log failed");
6163 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6164 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6166 print "<table class=\"pickaxe search\">\n";
6170 while (my $line = <$fd>) {
6174 my %set = parse_difftree_raw_line
($line);
6175 if (defined $set{'commit'}) {
6176 # finish previous commit
6179 "<td class=\"link\">" .
6180 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6183 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6184 hash_base
=>$co{'id'})},
6191 print "<tr class=\"dark\">\n";
6193 print "<tr class=\"light\">\n";
6196 %co = parse_commit
($set{'commit'});
6197 my $author = chop_and_escape_str
($co{'author_name'}, 15, 5);
6198 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6199 "<td><i>$author</i></td>\n" .
6201 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6202 -class => "list subject"},
6203 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6204 } elsif (defined $set{'to_id'}) {
6205 next if ($set{'to_id'} =~ m/^0{40}$/);
6207 print $cgi->a({-href
=> href
(action
=>"blob", hash_base
=>$co{'id'},
6208 hash
=>$set{'to_id'}, file_name
=>$set{'to_file'}),
6210 "<span class=\"match\">" . esc_path
($set{'file'}) . "</span>") .
6216 # finish last commit (warning: repetition!)
6219 "<td class=\"link\">" .
6220 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})},
6223 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'},
6224 hash_base
=>$co{'id'})},
6235 sub git_search_files
{
6239 open my $fd, "-|", git_cmd
(), 'grep', '-n', '-z',
6240 $search_use_regexp ? ('-E', '-i') : '-F',
6241 $searchtext, $co{'tree'}
6242 or die_error
(500, "Open git-grep failed");
6246 git_print_page_nav
('','', $hash,$co{'tree'},$hash);
6247 git_print_header_div
('commit', esc_html
($co{'title'}), $hash);
6249 print "<table class=\"grep_search\">\n";
6254 while (my $line = <$fd>) {
6256 my ($file, $lno, $ltext, $binary);
6257 last if ($matches++ > 1000);
6258 if ($line =~ /^Binary file (.+) matches$/) {
6262 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6263 $file =~ s/^$co{'tree'}://;
6265 if ($file ne $lastfile) {
6266 $lastfile and print "</td></tr>\n";
6268 print "<tr class=\"dark\">\n";
6270 print "<tr class=\"light\">\n";
6272 $file_href = href
(action
=>"blob", hash_base
=>$co{'id'},
6274 print "<td class=\"list\">".
6275 $cgi->a({-href
=> $file_href, -class => "list"}, esc_path
($file));
6276 print "</td><td>\n";
6280 print "<div class=\"binary\">Binary file</div>\n";
6282 $ltext = untabify
($ltext);
6283 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6284 $ltext = esc_html
($1, -nbsp
=>1);
6285 $ltext .= '<span class="match">';
6286 $ltext .= esc_html
($2, -nbsp
=>1);
6287 $ltext .= '</span>';
6288 $ltext .= esc_html
($3, -nbsp
=>1);
6290 $ltext = esc_html
($ltext, -nbsp
=>1);
6292 print "<div class=\"pre\">" .
6293 $cgi->a({-href
=> $file_href.'#l'.$lno,
6294 -class => "linenr"}, sprintf('%4i', $lno)) .
6295 ' ' . $ltext . "</div>\n";
6299 print "</td></tr>\n";
6300 if ($matches > 1000) {
6301 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6304 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6313 sub git_search_grep_body
{
6314 my ($commitlist, $from, $to, $extra) = @_;
6315 $from = 0 unless defined $from;
6316 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6318 print "<table class=\"commit_search\">\n";
6320 for (my $i = $from; $i <= $to; $i++) {
6321 my %co = %{$commitlist->[$i]};
6325 my $commit = $co{'id'};
6327 print "<tr class=\"dark\">\n";
6329 print "<tr class=\"light\">\n";
6332 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6333 format_author_html
('td', \
%co, 15, 5) .
6335 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'}),
6336 -class => "list subject"},
6337 chop_and_escape_str
($co{'title'}, 50) . "<br/>");
6338 my $comment = $co{'comment'};
6339 foreach my $line (@$comment) {
6340 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6341 my ($lead, $match, $trail) = ($1, $2, $3);
6342 $match = chop_str
($match, 70, 5, 'center');
6343 my $contextlen = int((80 - length($match))/2);
6344 $contextlen = 30 if ($contextlen > 30);
6345 $lead = chop_str
($lead, $contextlen, 10, 'left');
6346 $trail = chop_str
($trail, $contextlen, 10, 'right');
6348 $lead = esc_html
($lead);
6349 $match = esc_html
($match);
6350 $trail = esc_html
($trail);
6352 print "$lead<span class=\"match\">$match</span>$trail<br />";
6356 "<td class=\"link\">" .
6357 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$co{'id'})}, "commit") .
6359 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$co{'id'})}, "commitdiff") .
6361 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$co{'id'})}, "tree");
6365 if (defined $extra) {
6367 "<td colspan=\"3\">$extra</td>\n" .
6373 ## ======================================================================
6374 ## ======================================================================
6377 sub git_project_list
{
6378 my $order = $input_params{'order'};
6379 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6380 die_error
(400, "Unknown order parameter");
6383 my @list = git_get_projects_list
($project_filter, $strict_export);
6385 die_error
(404, "No projects found");
6389 if (defined $home_text && -f
$home_text) {
6390 print "<div class=\"index_include\">\n";
6391 insert_file
($home_text);
6395 git_project_search_form
($searchtext, $search_use_regexp);
6396 git_project_list_body
(\
@list, $order);
6401 my $order = $input_params{'order'};
6402 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6403 die_error
(400, "Unknown order parameter");
6406 my $filter = $project;
6407 $filter =~ s/\.git$//;
6408 my @list = git_get_projects_list
($filter);
6410 die_error
(404, "No forks found");
6414 git_print_page_nav
('','');
6415 git_print_header_div
('summary', "$project forks");
6416 git_project_list_body
(\
@list, $order);
6420 sub git_project_index
{
6421 my @projects = git_get_projects_list
($project_filter, $strict_export);
6423 die_error
(404, "No projects found");
6427 -type
=> 'text/plain',
6428 -charset
=> 'utf-8',
6429 -content_disposition
=> 'inline; filename="index.aux"');
6431 foreach my $pr (@projects) {
6432 if (!exists $pr->{'owner'}) {
6433 $pr->{'owner'} = git_get_project_owner
("$pr->{'path'}");
6436 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6437 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6438 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6439 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf
("%%%02X", ord($1))/eg
;
6443 print "$path $owner\n";
6448 my $descr = git_get_project_description
($project) || "none";
6449 my %co = parse_commit
("HEAD");
6450 my %cd = %co ? parse_date
($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6451 my $head = $co{'id'};
6452 my $remote_heads = gitweb_check_feature
('remote_heads');
6454 my $owner = git_get_project_owner
($project);
6456 my $refs = git_get_references
();
6457 # These get_*_list functions return one more to allow us to see if
6458 # there are more ...
6459 my @taglist = git_get_tags_list
(16);
6460 my @headlist = git_get_heads_list
(16);
6461 my %remotedata = $remote_heads ? git_get_remotes_list
() : ();
6463 my $check_forks = gitweb_check_feature
('forks');
6466 # find forks of a project
6467 my $filter = $project;
6468 $filter =~ s/\.git$//;
6469 @forklist = git_get_projects_list
($filter);
6470 # filter out forks of forks
6471 @forklist = filter_forks_from_projects_list
(\
@forklist)
6476 git_print_page_nav
('summary','', $head);
6478 print "<div class=\"title\"> </div>\n";
6479 print "<table class=\"projects_list\">\n" .
6480 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html
($descr) . "</td></tr>\n";
6481 if ($owner and not $omit_owner) {
6482 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html
($owner) . "</td></tr>\n";
6484 if (defined $cd{'rfc2822'}) {
6485 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6486 "<td>".format_timestamp_html
(\
%cd)."</td></tr>\n";
6489 # use per project git URL list in $projectroot/$project/cloneurl
6490 # or make project git URL from git base URL and project name
6491 my $url_tag = "URL";
6492 my @url_list = git_get_project_url_list
($project);
6493 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6494 foreach my $git_url (@url_list) {
6495 next unless $git_url;
6496 print format_repo_url
($url_tag, $git_url);
6501 my $show_ctags = gitweb_check_feature
('ctags');
6503 my $ctags = git_get_project_ctags
($project);
6505 # without ability to add tags, don't show if there are none
6506 my $cloud = git_populate_project_tagcloud
($ctags);
6507 print "<tr id=\"metadata_ctags\">" .
6508 "<td>content tags</td>" .
6509 "<td>".git_show_project_tagcloud
($cloud, 48)."</td>" .
6516 # If XSS prevention is on, we don't include README.html.
6517 # TODO: Allow a readme in some safe format.
6518 if (!$prevent_xss && -s
"$projectroot/$project/README.html") {
6519 print "<div class=\"title\">readme</div>\n" .
6520 "<div class=\"readme\">\n";
6521 insert_file
("$projectroot/$project/README.html");
6522 print "\n</div>\n"; # class="readme"
6525 # we need to request one more than 16 (0..15) to check if
6527 my @commitlist = $head ? parse_commits
($head, 17) : ();
6529 git_print_header_div
('shortlog');
6530 git_shortlog_body
(\
@commitlist, 0, 15, $refs,
6531 $#commitlist <= 15 ? undef :
6532 $cgi->a({-href
=> href
(action
=>"shortlog")}, "..."));
6536 git_print_header_div
('tags');
6537 git_tags_body
(\
@taglist, 0, 15,
6538 $#taglist <= 15 ? undef :
6539 $cgi->a({-href
=> href
(action
=>"tags")}, "..."));
6543 git_print_header_div
('heads');
6544 git_heads_body
(\
@headlist, $head, 0, 15,
6545 $#headlist <= 15 ? undef :
6546 $cgi->a({-href
=> href
(action
=>"heads")}, "..."));
6550 git_print_header_div
('remotes');
6551 git_remotes_body
(\
%remotedata, 15, $head);
6555 git_print_header_div
('forks');
6556 git_project_list_body
(\
@forklist, 'age', 0, 15,
6557 $#forklist <= 15 ? undef :
6558 $cgi->a({-href
=> href
(action
=>"forks")}, "..."),
6566 my %tag = parse_tag
($hash);
6569 die_error
(404, "Unknown tag object");
6572 my $head = git_get_head_hash
($project);
6574 git_print_page_nav
('','', $head,undef,$head);
6575 git_print_header_div
('commit', esc_html
($tag{'name'}), $hash);
6576 print "<div class=\"title_text\">\n" .
6577 "<table class=\"object_header\">\n" .
6579 "<td>object</td>\n" .
6580 "<td>" . $cgi->a({-class => "list", -href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6581 $tag{'object'}) . "</td>\n" .
6582 "<td class=\"link\">" . $cgi->a({-href
=> href
(action
=>$tag{'type'}, hash
=>$tag{'object'})},
6583 $tag{'type'}) . "</td>\n" .
6585 if (defined($tag{'author'})) {
6586 git_print_authorship_rows
(\
%tag, 'author');
6588 print "</table>\n\n" .
6590 print "<div class=\"page_body\">";
6591 my $comment = $tag{'comment'};
6592 foreach my $line (@$comment) {
6594 print esc_html
($line, -nbsp
=>1) . "<br/>\n";
6600 sub git_blame_common
{
6601 my $format = shift || 'porcelain';
6602 if ($format eq 'porcelain' && $input_params{'javascript'}) {
6603 $format = 'incremental';
6604 $action = 'blame_incremental'; # for page title etc
6608 gitweb_check_feature
('blame')
6609 or die_error
(403, "Blame view not allowed");
6612 die_error
(400, "No file name given") unless $file_name;
6613 $hash_base ||= git_get_head_hash
($project);
6614 die_error
(404, "Couldn't find base commit") unless $hash_base;
6615 my %co = parse_commit
($hash_base)
6616 or die_error
(404, "Commit not found");
6618 if (!defined $hash) {
6619 $hash = git_get_hash_by_path
($hash_base, $file_name, "blob")
6620 or die_error
(404, "Error looking up file");
6622 $ftype = git_get_type
($hash);
6623 if ($ftype !~ "blob") {
6624 die_error
(400, "Object is not a blob");
6629 if ($format eq 'incremental') {
6630 # get file contents (as base)
6631 open $fd, "-|", git_cmd
(), 'cat-file', 'blob', $hash
6632 or die_error
(500, "Open git-cat-file failed");
6633 } elsif ($format eq 'data') {
6634 # run git-blame --incremental
6635 open $fd, "-|", git_cmd
(), "blame", "--incremental",
6636 $hash_base, "--", $file_name
6637 or die_error
(500, "Open git-blame --incremental failed");
6639 # run git-blame --porcelain
6640 open $fd, "-|", git_cmd
(), "blame", '-p',
6641 $hash_base, '--', $file_name
6642 or die_error
(500, "Open git-blame --porcelain failed");
6644 binmode $fd, ':utf8';
6646 # incremental blame data returns early
6647 if ($format eq 'data') {
6649 -type
=>"text/plain", -charset
=> "utf-8",
6650 -status
=> "200 OK");
6651 local $| = 1; # output autoflush
6652 while (my $line = <$fd>) {
6653 print to_utf8
($line);
6656 or print "ERROR $!\n";
6659 if (defined $t0 && gitweb_check_feature
('timed')) {
6661 tv_interval
($t0, [ gettimeofday
() ]).
6662 ' '.$number_of_git_cmds;
6672 $cgi->a({-href
=> href
(action
=>"blob", -replay
=>1)},
6675 if ($format eq 'incremental') {
6677 $cgi->a({-href
=> href
(action
=>"blame", javascript
=>0, -replay
=>1)},
6678 "blame") . " (non-incremental)";
6681 $cgi->a({-href
=> href
(action
=>"blame_incremental", -replay
=>1)},
6682 "blame") . " (incremental)";
6686 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
6689 $cgi->a({-href
=> href
(action
=>$action, file_name
=>$file_name)},
6691 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6692 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
6693 git_print_page_path
($file_name, $ftype, $hash_base);
6696 if ($format eq 'incremental') {
6697 print "<noscript>\n<div class=\"error\"><center><b>\n".
6698 "This page requires JavaScript to run.\n Use ".
6699 $cgi->a({-href
=> href
(action
=>'blame',javascript
=>0,-replay
=>1)},
6702 "</b></center></div>\n</noscript>\n";
6704 print qq
!<div id
="progress_bar" style
="width: 100%; background-color: yellow"></div
>\n!;
6707 print qq
!<div
class="page_body">\n!;
6708 print qq
!<div id
="progress_info">... / ...</div
>\n!
6709 if ($format eq 'incremental');
6710 print qq
!<table id
="blame_table" class="blame" width
="100%">\n!.
6711 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6713 qq
!<tr
><th
>Commit
</th><th>Line</th
><th
>Data
</th></tr
>\n!.
6717 my @rev_color = qw(light dark);
6718 my $num_colors = scalar(@rev_color);
6719 my $current_color = 0;
6721 if ($format eq 'incremental') {
6722 my $color_class = $rev_color[$current_color];
6727 while (my $line = <$fd>) {
6731 print qq
!<tr id
="l$linenr" class="$color_class">!.
6732 qq
!<td
class="sha1"><a href
=""> </a></td
>!.
6733 qq
!<td
class="linenr">!.
6734 qq
!<a
class="linenr" href
="">$linenr</a></td
>!;
6735 print qq
!<td
class="pre">! . esc_html
($line) . "</td>\n";
6739 } else { # porcelain, i.e. ordinary blame
6740 my %metainfo = (); # saves information about commits
6744 while (my $line = <$fd>) {
6746 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6747 # no <lines in group> for subsequent lines in group of lines
6748 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6749 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6750 if (!exists $metainfo{$full_rev}) {
6751 $metainfo{$full_rev} = { 'nprevious' => 0 };
6753 my $meta = $metainfo{$full_rev};
6755 while ($data = <$fd>) {
6757 last if ($data =~ s/^\t//); # contents of line
6758 if ($data =~ /^(\S+)(?: (.*))?$/) {
6759 $meta->{$1} = $2 unless exists $meta->{$1};
6761 if ($data =~ /^previous /) {
6762 $meta->{'nprevious'}++;
6765 my $short_rev = substr($full_rev, 0, 8);
6766 my $author = $meta->{'author'};
6768 parse_date
($meta->{'author-time'}, $meta->{'author-tz'});
6769 my $date = $date{'iso-tz'};
6771 $current_color = ($current_color + 1) % $num_colors;
6773 my $tr_class = $rev_color[$current_color];
6774 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6775 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6776 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6777 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6779 print "<td class=\"sha1\"";
6780 print " title=\"". esc_html
($author) . ", $date\"";
6781 print " rowspan=\"$group_size\"" if ($group_size > 1);
6783 print $cgi->a({-href
=> href
(action
=>"commit",
6785 file_name
=>$file_name)},
6786 esc_html
($short_rev));
6787 if ($group_size >= 2) {
6788 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6789 if (@author_initials) {
6791 esc_html
(join('', @author_initials));
6797 # 'previous' <sha1 of parent commit> <filename at commit>
6798 if (exists $meta->{'previous'} &&
6799 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6800 $meta->{'parent'} = $1;
6801 $meta->{'file_parent'} = unquote
($2);
6804 exists($meta->{'parent'}) ?
6805 $meta->{'parent'} : $full_rev;
6806 my $linenr_filename =
6807 exists($meta->{'file_parent'}) ?
6808 $meta->{'file_parent'} : unquote
($meta->{'filename'});
6809 my $blamed = href
(action
=> 'blame',
6810 file_name
=> $linenr_filename,
6811 hash_base
=> $linenr_commit);
6812 print "<td class=\"linenr\">";
6813 print $cgi->a({ -href
=> "$blamed#l$orig_lineno",
6814 -class => "linenr" },
6817 print "<td class=\"pre\">" . esc_html
($data) . "</td>\n";
6825 "</table>\n"; # class="blame"
6826 print "</div>\n"; # class="blame_body"
6828 or print "Reading blob failed\n";
6837 sub git_blame_incremental
{
6838 git_blame_common
('incremental');
6841 sub git_blame_data
{
6842 git_blame_common
('data');
6846 my $head = git_get_head_hash
($project);
6848 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('tags'));
6849 git_print_header_div
('summary', $project);
6851 my @tagslist = git_get_tags_list
();
6853 git_tags_body
(\
@tagslist);
6859 my $head = git_get_head_hash
($project);
6861 git_print_page_nav
('','', $head,undef,$head,format_ref_views
('heads'));
6862 git_print_header_div
('summary', $project);
6864 my @headslist = git_get_heads_list
();
6866 git_heads_body
(\
@headslist, $head);
6871 # used both for single remote view and for list of all the remotes
6873 gitweb_check_feature
('remote_heads')
6874 or die_error
(403, "Remote heads view is disabled");
6876 my $head = git_get_head_hash
($project);
6877 my $remote = $input_params{'hash'};
6879 my $remotedata = git_get_remotes_list
($remote);
6880 die_error
(500, "Unable to get remote information") unless defined $remotedata;
6882 unless (%$remotedata) {
6883 die_error
(404, defined $remote ?
6884 "Remote $remote not found" :
6885 "No remotes found");
6888 git_header_html
(undef, undef, -action_extra
=> $remote);
6889 git_print_page_nav
('', '', $head, undef, $head,
6890 format_ref_views
($remote ? '' : 'remotes'));
6892 fill_remote_heads
($remotedata);
6893 if (defined $remote) {
6894 git_print_header_div
('remotes', "$remote remote for $project");
6895 git_remote_block
($remote, $remotedata->{$remote}, undef, $head);
6897 git_print_header_div
('summary', "$project remotes");
6898 git_remotes_body
($remotedata, undef, $head);
6904 sub git_blob_plain
{
6908 if (!defined $hash) {
6909 if (defined $file_name) {
6910 my $base = $hash_base || git_get_head_hash
($project);
6911 $hash = git_get_hash_by_path
($base, $file_name, "blob")
6912 or die_error
(404, "Cannot find file");
6914 die_error
(400, "No file name defined");
6916 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6917 # blobs defined by non-textual hash id's can be cached
6921 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
6922 or die_error
(500, "Open git-cat-file blob '$hash' failed");
6924 # content-type (can include charset)
6925 $type = blob_contenttype
($fd, $file_name, $type);
6927 # "save as" filename, even when no $file_name is given
6928 my $save_as = "$hash";
6929 if (defined $file_name) {
6930 $save_as = $file_name;
6931 } elsif ($type =~ m/^text\//) {
6935 # With XSS prevention on, blobs of all types except a few known safe
6936 # ones are served with "Content-Disposition: attachment" to make sure
6937 # they don't run in our security domain. For certain image types,
6938 # blob view writes an <img> tag referring to blob_plain view, and we
6939 # want to be sure not to break that by serving the image as an
6940 # attachment (though Firefox 3 doesn't seem to care).
6941 my $sandbox = $prevent_xss &&
6942 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
6944 # serve text/* as text/plain
6946 ($type =~ m!^text/[a-z]+\b(.*)$! ||
6947 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T
$fd))) {
6949 $rest = defined $rest ? $rest : '';
6950 $type = "text/plain$rest";
6955 -expires
=> $expires,
6956 -content_disposition
=>
6957 ($sandbox ? 'attachment' : 'inline')
6958 . '; filename="' . $save_as . '"');
6960 binmode STDOUT
, ':raw';
6962 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
6969 if (!defined $hash) {
6970 if (defined $file_name) {
6971 my $base = $hash_base || git_get_head_hash
($project);
6972 $hash = git_get_hash_by_path
($base, $file_name, "blob")
6973 or die_error
(404, "Cannot find file");
6975 die_error
(400, "No file name defined");
6977 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6978 # blobs defined by non-textual hash id's can be cached
6982 my $have_blame = gitweb_check_feature
('blame');
6983 open my $fd, "-|", git_cmd
(), "cat-file", "blob", $hash
6984 or die_error
(500, "Couldn't cat $file_name, $hash");
6985 my $mimetype = blob_mimetype
($fd, $file_name);
6986 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
6987 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B
$fd) {
6989 return git_blob_plain
($mimetype);
6991 # we can have blame only for text/* mimetype
6992 $have_blame &&= ($mimetype =~ m!^text/!);
6994 my $highlight = gitweb_check_feature
('highlight');
6995 my $syntax = guess_file_syntax
($highlight, $mimetype, $file_name);
6996 $fd = run_highlighter
($fd, $highlight, $syntax)
6999 git_header_html
(undef, $expires);
7000 my $formats_nav = '';
7001 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7002 if (defined $file_name) {
7005 $cgi->a({-href
=> href
(action
=>"blame", -replay
=>1)},
7010 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7013 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7016 $cgi->a({-href
=> href
(action
=>"blob",
7017 hash_base
=>"HEAD", file_name
=>$file_name)},
7021 $cgi->a({-href
=> href
(action
=>"blob_plain", -replay
=>1)},
7024 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7025 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7027 print "<div class=\"page_nav\">\n" .
7028 "<br/><br/></div>\n" .
7029 "<div class=\"title\">".esc_html
($hash)."</div>\n";
7031 git_print_page_path
($file_name, "blob", $hash_base);
7032 print "<div class=\"page_body\">\n";
7033 if ($mimetype =~ m!^image/!) {
7034 print qq
!<img type
="!.esc_attr($mimetype).qq!"!;
7036 print qq
! alt
="!.esc_attr($file_name).qq!" title
="!.esc_attr($file_name).qq!"!;
7039 href(action=>"blob_plain
", hash=>$hash,
7040 hash_base=>$hash_base, file_name=>$file_name) .
7044 while (my $line = <$fd>) {
7047 $line = untabify
($line);
7048 printf qq
!<div
class="pre"><a id
="l%i" href
="%s#l%i" class="linenr">%4i</a> %s</div
>\n!,
7049 $nr, esc_attr
(href
(-replay
=> 1)), $nr, $nr,
7050 $syntax ? sanitize
($line) : esc_html
($line, -nbsp
=>1);
7054 or print "Reading blob failed.\n";
7060 if (!defined $hash_base) {
7061 $hash_base = "HEAD";
7063 if (!defined $hash) {
7064 if (defined $file_name) {
7065 $hash = git_get_hash_by_path
($hash_base, $file_name, "tree");
7070 die_error
(404, "No such tree") unless defined($hash);
7072 my $show_sizes = gitweb_check_feature
('show-sizes');
7073 my $have_blame = gitweb_check_feature
('blame');
7078 open my $fd, "-|", git_cmd
(), "ls-tree", '-z',
7079 ($show_sizes ? '-l' : ()), @extra_options, $hash
7080 or die_error
(500, "Open git-ls-tree failed");
7081 @entries = map { chomp; $_ } <$fd>;
7083 or die_error
(404, "Reading tree failed");
7086 my $refs = git_get_references
();
7087 my $ref = format_ref_marker
($refs, $hash_base);
7090 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7092 if (defined $file_name) {
7094 $cgi->a({-href
=> href
(action
=>"history", -replay
=>1)},
7096 $cgi->a({-href
=> href
(action
=>"tree",
7097 hash_base
=>"HEAD", file_name
=>$file_name)},
7100 my $snapshot_links = format_snapshot_links
($hash);
7101 if (defined $snapshot_links) {
7102 # FIXME: Should be available when we have no hash base as well.
7103 push @views_nav, $snapshot_links;
7105 git_print_page_nav
('tree','', $hash_base, undef, undef,
7106 join(' | ', @views_nav));
7107 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash_base);
7110 print "<div class=\"page_nav\">\n";
7111 print "<br/><br/></div>\n";
7112 print "<div class=\"title\">".esc_html
($hash)."</div>\n";
7114 if (defined $file_name) {
7115 $basedir = $file_name;
7116 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7119 git_print_page_path
($file_name, 'tree', $hash_base);
7121 print "<div class=\"page_body\">\n";
7122 print "<table class=\"tree\">\n";
7124 # '..' (top directory) link if possible
7125 if (defined $hash_base &&
7126 defined $file_name && $file_name =~ m![^/]+$!) {
7128 print "<tr class=\"dark\">\n";
7130 print "<tr class=\"light\">\n";
7134 my $up = $file_name;
7135 $up =~ s!/?[^/]+$!!;
7136 undef $up unless $up;
7137 # based on git_print_tree_entry
7138 print '<td class="mode">' . mode_str
('040000') . "</td>\n";
7139 print '<td class="size"> </td>'."\n" if $show_sizes;
7140 print '<td class="list">';
7141 print $cgi->a({-href
=> href
(action
=>"tree",
7142 hash_base
=>$hash_base,
7146 print "<td class=\"link\"></td>\n";
7150 foreach my $line (@entries) {
7151 my %t = parse_ls_tree_line
($line, -z
=> 1, -l
=> $show_sizes);
7154 print "<tr class=\"dark\">\n";
7156 print "<tr class=\"light\">\n";
7160 git_print_tree_entry
(\
%t, $basedir, $hash_base, $have_blame);
7164 print "</table>\n" .
7170 my ($project, $hash) = @_;
7172 # path/to/project.git -> project
7173 # path/to/project/.git -> project
7174 my $name = to_utf8
($project);
7175 $name =~ s
,([^/])/*\
.git
$,$1,;
7176 $name = basename
($name);
7178 $name =~ s/[[:cntrl:]]/?/g;
7181 if ($hash =~ /^[0-9a-fA-F]+$/) {
7182 # shorten SHA-1 hash
7183 my $full_hash = git_get_full_hash
($project, $hash);
7184 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7185 $ver = git_get_short_hash
($project, $hash);
7187 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7188 # tags don't need shortened SHA-1 hash
7191 # branches and other need shortened SHA-1 hash
7192 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
7195 $ver .= '-' . git_get_short_hash
($project, $hash);
7197 # in case of hierarchical branch names
7200 # name = project-version_string
7201 $name = "$name-$ver";
7203 return wantarray ? ($name, $name) : $name;
7206 sub exit_if_unmodified_since
{
7207 my ($latest_epoch) = @_;
7210 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7211 if (defined $if_modified) {
7213 if (eval { require HTTP
::Date
; 1; }) {
7214 $since = HTTP
::Date
::str2time
($if_modified);
7215 } elsif (eval { require Time
::ParseDate
; 1; }) {
7216 $since = Time
::ParseDate
::parsedate
($if_modified, GMT
=> 1);
7218 if (defined $since && $latest_epoch <= $since) {
7219 my %latest_date = parse_date
($latest_epoch);
7221 -last_modified
=> $latest_date{'rfc2822'},
7222 -status
=> '304 Not Modified');
7229 my $format = $input_params{'snapshot_format'};
7230 if (!@snapshot_fmts) {
7231 die_error
(403, "Snapshots not allowed");
7233 # default to first supported snapshot format
7234 $format ||= $snapshot_fmts[0];
7235 if ($format !~ m/^[a-z0-9]+$/) {
7236 die_error
(400, "Invalid snapshot format parameter");
7237 } elsif (!exists($known_snapshot_formats{$format})) {
7238 die_error
(400, "Unknown snapshot format");
7239 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7240 die_error
(403, "Snapshot format not allowed");
7241 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7242 die_error
(403, "Unsupported snapshot format");
7245 my $type = git_get_type
("$hash^{}");
7247 die_error
(404, 'Object does not exist');
7248 } elsif ($type eq 'blob') {
7249 die_error
(400, 'Object is not a tree-ish');
7252 my ($name, $prefix) = snapshot_name
($project, $hash);
7253 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7255 my %co = parse_commit
($hash);
7256 exit_if_unmodified_since
($co{'committer_epoch'}) if %co;
7258 my $cmd = quote_command
(
7259 git_cmd
(), 'archive',
7260 "--format=$known_snapshot_formats{$format}{'format'}",
7261 "--prefix=$prefix/", $hash);
7262 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7263 $cmd .= ' | ' . quote_command
(@{$known_snapshot_formats{$format}{'compressor'}});
7266 $filename =~ s/(["\\])/\\$1/g;
7269 %latest_date = parse_date
($co{'committer_epoch'}, $co{'committer_tz'});
7273 -type
=> $known_snapshot_formats{$format}{'type'},
7274 -content_disposition
=> 'inline; filename="' . $filename . '"',
7275 %co ? (-last_modified
=> $latest_date{'rfc2822'}) : (),
7276 -status
=> '200 OK');
7278 open my $fd, "-|", $cmd
7279 or die_error
(500, "Execute git-archive failed");
7280 binmode STDOUT
, ':raw';
7282 binmode STDOUT
, ':utf8'; # as set at the beginning of gitweb.cgi
7286 sub git_log_generic
{
7287 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7289 my $head = git_get_head_hash
($project);
7290 if (!defined $base) {
7293 if (!defined $page) {
7296 my $refs = git_get_references
();
7298 my $commit_hash = $base;
7299 if (defined $parent) {
7300 $commit_hash = "$parent..$base";
7303 parse_commits
($commit_hash, 101, (100 * $page),
7304 defined $file_name ? ($file_name, "--full-history") : ());
7307 if (!defined $file_hash && defined $file_name) {
7308 # some commits could have deleted file in question,
7309 # and not have it in tree, but one of them has to have it
7310 for (my $i = 0; $i < @commitlist; $i++) {
7311 $file_hash = git_get_hash_by_path
($commitlist[$i]{'id'}, $file_name);
7312 last if defined $file_hash;
7315 if (defined $file_hash) {
7316 $ftype = git_get_type
($file_hash);
7318 if (defined $file_name && !defined $ftype) {
7319 die_error
(500, "Unknown type of object");
7322 if (defined $file_name) {
7323 %co = parse_commit
($base)
7324 or die_error
(404, "Unknown commit object");
7328 my $paging_nav = format_paging_nav
($fmt_name, $page, $#commitlist >= 100);
7330 if ($#commitlist >= 100) {
7332 $cgi->a({-href
=> href
(-replay
=>1, page
=>$page+1),
7333 -accesskey
=> "n", -title
=> "Alt-n"}, "next");
7335 my $patch_max = gitweb_get_feature
('patches');
7336 if ($patch_max && !defined $file_name) {
7337 if ($patch_max < 0 || @commitlist <= $patch_max) {
7338 $paging_nav .= " ⋅ " .
7339 $cgi->a({-href
=> href
(action
=>"patches", -replay
=>1)},
7345 git_print_page_nav
($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7346 if (defined $file_name) {
7347 git_print_header_div
('commit', esc_html
($co{'title'}), $base);
7349 git_print_header_div
('summary', $project)
7351 git_print_page_path
($file_name, $ftype, $hash_base)
7352 if (defined $file_name);
7354 $body_subr->(\
@commitlist, 0, 99, $refs, $next_link,
7355 $file_name, $file_hash, $ftype);
7361 git_log_generic
('log', \
&git_log_body
,
7362 $hash, $hash_parent);
7366 $hash ||= $hash_base || "HEAD";
7367 my %co = parse_commit
($hash)
7368 or die_error
(404, "Unknown commit object");
7370 my $parent = $co{'parent'};
7371 my $parents = $co{'parents'}; # listref
7373 # we need to prepare $formats_nav before any parameter munging
7375 if (!defined $parent) {
7377 $formats_nav .= '(initial)';
7378 } elsif (@$parents == 1) {
7379 # single parent commit
7382 $cgi->a({-href
=> href
(action
=>"commit",
7384 esc_html
(substr($parent, 0, 7))) .
7391 $cgi->a({-href
=> href
(action
=>"commit",
7393 esc_html
(substr($_, 0, 7)));
7397 if (gitweb_check_feature
('patches') && @$parents <= 1) {
7398 $formats_nav .= " | " .
7399 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7403 if (!defined $parent) {
7407 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', "--no-commit-id",
7409 (@$parents <= 1 ? $parent : '-c'),
7411 or die_error
(500, "Open git-diff-tree failed");
7412 @difftree = map { chomp; $_ } <$fd>;
7413 close $fd or die_error
(404, "Reading git-diff-tree failed");
7415 # non-textual hash id's can be cached
7417 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7420 my $refs = git_get_references
();
7421 my $ref = format_ref_marker
($refs, $co{'id'});
7423 git_header_html
(undef, $expires);
7424 git_print_page_nav
('commit', '',
7425 $hash, $co{'tree'}, $hash,
7428 if (defined $co{'parent'}) {
7429 git_print_header_div
('commitdiff', esc_html
($co{'title'}) . $ref, $hash);
7431 git_print_header_div
('tree', esc_html
($co{'title'}) . $ref, $co{'tree'}, $hash);
7433 print "<div class=\"title_text\">\n" .
7434 "<table class=\"object_header\">\n";
7435 git_print_authorship_rows
(\
%co);
7436 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7439 "<td class=\"sha1\">" .
7440 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash),
7441 class => "list"}, $co{'tree'}) .
7443 "<td class=\"link\">" .
7444 $cgi->a({-href
=> href
(action
=>"tree", hash
=>$co{'tree'}, hash_base
=>$hash)},
7446 my $snapshot_links = format_snapshot_links
($hash);
7447 if (defined $snapshot_links) {
7448 print " | " . $snapshot_links;
7453 foreach my $par (@$parents) {
7456 "<td class=\"sha1\">" .
7457 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par),
7458 class => "list"}, $par) .
7460 "<td class=\"link\">" .
7461 $cgi->a({-href
=> href
(action
=>"commit", hash
=>$par)}, "commit") .
7463 $cgi->a({-href
=> href
(action
=>"commitdiff", hash
=>$hash, hash_parent
=>$par)}, "diff") .
7470 print "<div class=\"page_body\">\n";
7471 git_print_log
($co{'comment'});
7474 git_difftree_body
(\
@difftree, $hash, @$parents);
7480 # object is defined by:
7481 # - hash or hash_base alone
7482 # - hash_base and file_name
7485 # - hash or hash_base alone
7486 if ($hash || ($hash_base && !defined $file_name)) {
7487 my $object_id = $hash || $hash_base;
7489 open my $fd, "-|", quote_command
(
7490 git_cmd
(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7491 or die_error
(404, "Object does not exist");
7495 or die_error
(404, "Object does not exist");
7497 # - hash_base and file_name
7498 } elsif ($hash_base && defined $file_name) {
7499 $file_name =~ s
,/+$,,;
7501 system(git_cmd
(), "cat-file", '-e', $hash_base) == 0
7502 or die_error
(404, "Base object does not exist");
7504 # here errors should not happen
7505 open my $fd, "-|", git_cmd
(), "ls-tree", $hash_base, "--", $file_name
7506 or die_error
(500, "Open git-ls-tree failed");
7510 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7511 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7512 die_error
(404, "File or directory for given base does not exist");
7517 die_error
(400, "Not enough information to find object");
7520 print $cgi->redirect(-uri
=> href
(action
=>$type, -full
=>1,
7521 hash
=>$hash, hash_base
=>$hash_base,
7522 file_name
=>$file_name),
7523 -status
=> '302 Found');
7527 my $format = shift || 'html';
7528 my $diff_style = $input_params{'diff_style'} || 'inline';
7535 # preparing $fd and %diffinfo for git_patchset_body
7537 if (defined $hash_base && defined $hash_parent_base) {
7538 if (defined $file_name) {
7540 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7541 $hash_parent_base, $hash_base,
7542 "--", (defined $file_parent ? $file_parent : ()), $file_name
7543 or die_error
(500, "Open git-diff-tree failed");
7544 @difftree = map { chomp; $_ } <$fd>;
7546 or die_error
(404, "Reading git-diff-tree failed");
7548 or die_error
(404, "Blob diff not found");
7550 } elsif (defined $hash &&
7551 $hash =~ /[0-9a-fA-F]{40}/) {
7552 # try to find filename from $hash
7554 # read filtered raw output
7555 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7556 $hash_parent_base, $hash_base, "--"
7557 or die_error
(500, "Open git-diff-tree failed");
7559 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7561 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7562 map { chomp; $_ } <$fd>;
7564 or die_error
(404, "Reading git-diff-tree failed");
7566 or die_error
(404, "Blob diff not found");
7569 die_error
(400, "Missing one of the blob diff parameters");
7572 if (@difftree > 1) {
7573 die_error
(400, "Ambiguous blob diff specification");
7576 %diffinfo = parse_difftree_raw_line
($difftree[0]);
7577 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7578 $file_name ||= $diffinfo{'to_file'};
7580 $hash_parent ||= $diffinfo{'from_id'};
7581 $hash ||= $diffinfo{'to_id'};
7583 # non-textual hash id's can be cached
7584 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7585 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7590 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7591 '-p', ($format eq 'html' ? "--full-index" : ()),
7592 $hash_parent_base, $hash_base,
7593 "--", (defined $file_parent ? $file_parent : ()), $file_name
7594 or die_error
(500, "Open git-diff-tree failed");
7597 # old/legacy style URI -- not generated anymore since 1.4.3.
7599 die_error
('404 Not Found', "Missing one of the blob diff parameters")
7603 if ($format eq 'html') {
7605 $cgi->a({-href
=> href
(action
=>"blobdiff_plain", -replay
=>1)},
7607 $formats_nav .= diff_style_nav
($diff_style);
7608 git_header_html
(undef, $expires);
7609 if (defined $hash_base && (my %co = parse_commit
($hash_base))) {
7610 git_print_page_nav
('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7611 git_print_header_div
('commit', esc_html
($co{'title'}), $hash_base);
7613 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7614 print "<div class=\"title\">".esc_html
("$hash vs $hash_parent")."</div>\n";
7616 if (defined $file_name) {
7617 git_print_page_path
($file_name, "blob", $hash_base);
7619 print "<div class=\"page_path\"></div>\n";
7622 } elsif ($format eq 'plain') {
7624 -type
=> 'text/plain',
7625 -charset
=> 'utf-8',
7626 -expires
=> $expires,
7627 -content_disposition
=> 'inline; filename="' . "$file_name" . '.patch"');
7629 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7632 die_error
(400, "Unknown blobdiff format");
7636 if ($format eq 'html') {
7637 print "<div class=\"page_body\">\n";
7639 git_patchset_body
($fd, $diff_style,
7640 [ \
%diffinfo ], $hash_base, $hash_parent_base);
7643 print "</div>\n"; # class="page_body"
7647 while (my $line = <$fd>) {
7648 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7649 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7653 last if $line =~ m!^\+\+\+!;
7661 sub git_blobdiff_plain
{
7662 git_blobdiff
('plain');
7665 # assumes that it is added as later part of already existing navigation,
7666 # so it returns "| foo | bar" rather than just "foo | bar"
7667 sub diff_style_nav
{
7668 my ($diff_style, $is_combined) = @_;
7669 $diff_style ||= 'inline';
7671 return "" if ($is_combined);
7673 my @styles = (inline
=> 'inline', 'sidebyside' => 'side by side');
7674 my %styles = @styles;
7676 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7681 $_ eq $diff_style ? $styles{$_} :
7682 $cgi->a({-href
=> href
(-replay
=>1, diff_style
=> $_)}, $styles{$_})
7686 sub git_commitdiff
{
7688 my $format = $params{-format
} || 'html';
7689 my $diff_style = $input_params{'diff_style'} || 'inline';
7691 my ($patch_max) = gitweb_get_feature
('patches');
7692 if ($format eq 'patch') {
7693 die_error
(403, "Patch view not allowed") unless $patch_max;
7696 $hash ||= $hash_base || "HEAD";
7697 my %co = parse_commit
($hash)
7698 or die_error
(404, "Unknown commit object");
7700 # choose format for commitdiff for merge
7701 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7702 $hash_parent = '--cc';
7704 # we need to prepare $formats_nav before almost any parameter munging
7706 if ($format eq 'html') {
7708 $cgi->a({-href
=> href
(action
=>"commitdiff_plain", -replay
=>1)},
7710 if ($patch_max && @{$co{'parents'}} <= 1) {
7711 $formats_nav .= " | " .
7712 $cgi->a({-href
=> href
(action
=>"patch", -replay
=>1)},
7715 $formats_nav .= diff_style_nav
($diff_style, @{$co{'parents'}} > 1);
7717 if (defined $hash_parent &&
7718 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7719 # commitdiff with two commits given
7720 my $hash_parent_short = $hash_parent;
7721 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7722 $hash_parent_short = substr($hash_parent, 0, 7);
7726 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7727 if ($co{'parents'}[$i] eq $hash_parent) {
7728 $formats_nav .= ' parent ' . ($i+1);
7732 $formats_nav .= ': ' .
7733 $cgi->a({-href
=> href
(-replay
=>1,
7734 hash
=>$hash_parent, hash_base
=>undef)},
7735 esc_html
($hash_parent_short)) .
7737 } elsif (!$co{'parent'}) {
7739 $formats_nav .= ' (initial)';
7740 } elsif (scalar @{$co{'parents'}} == 1) {
7741 # single parent commit
7744 $cgi->a({-href
=> href
(-replay
=>1,
7745 hash
=>$co{'parent'}, hash_base
=>undef)},
7746 esc_html
(substr($co{'parent'}, 0, 7))) .
7750 if ($hash_parent eq '--cc') {
7751 $formats_nav .= ' | ' .
7752 $cgi->a({-href
=> href
(-replay
=>1,
7753 hash
=>$hash, hash_parent
=>'-c')},
7755 } else { # $hash_parent eq '-c'
7756 $formats_nav .= ' | ' .
7757 $cgi->a({-href
=> href
(-replay
=>1,
7758 hash
=>$hash, hash_parent
=>'--cc')},
7764 $cgi->a({-href
=> href
(-replay
=>1,
7765 hash
=>$_, hash_base
=>undef)},
7766 esc_html
(substr($_, 0, 7)));
7767 } @{$co{'parents'}} ) .
7772 my $hash_parent_param = $hash_parent;
7773 if (!defined $hash_parent_param) {
7774 # --cc for multiple parents, --root for parentless
7775 $hash_parent_param =
7776 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7782 if ($format eq 'html') {
7783 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7784 "--no-commit-id", "--patch-with-raw", "--full-index",
7785 $hash_parent_param, $hash, "--"
7786 or die_error
(500, "Open git-diff-tree failed");
7788 while (my $line = <$fd>) {
7790 # empty line ends raw part of diff-tree output
7792 push @difftree, scalar parse_difftree_raw_line
($line);
7795 } elsif ($format eq 'plain') {
7796 open $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
7797 '-p', $hash_parent_param, $hash, "--"
7798 or die_error
(500, "Open git-diff-tree failed");
7799 } elsif ($format eq 'patch') {
7800 # For commit ranges, we limit the output to the number of
7801 # patches specified in the 'patches' feature.
7802 # For single commits, we limit the output to a single patch,
7803 # diverging from the git-format-patch default.
7804 my @commit_spec = ();
7806 if ($patch_max > 0) {
7807 push @commit_spec, "-$patch_max";
7809 push @commit_spec, '-n', "$hash_parent..$hash";
7811 if ($params{-single
}) {
7812 push @commit_spec, '-1';
7814 if ($patch_max > 0) {
7815 push @commit_spec, "-$patch_max";
7817 push @commit_spec, "-n";
7819 push @commit_spec, '--root', $hash;
7821 open $fd, "-|", git_cmd
(), "format-patch", @diff_opts,
7822 '--encoding=utf8', '--stdout', @commit_spec
7823 or die_error
(500, "Open git-format-patch failed");
7825 die_error
(400, "Unknown commitdiff format");
7828 # non-textual hash id's can be cached
7830 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7834 # write commit message
7835 if ($format eq 'html') {
7836 my $refs = git_get_references
();
7837 my $ref = format_ref_marker
($refs, $co{'id'});
7839 git_header_html
(undef, $expires);
7840 git_print_page_nav
('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7841 git_print_header_div
('commit', esc_html
($co{'title'}) . $ref, $hash);
7842 print "<div class=\"title_text\">\n" .
7843 "<table class=\"object_header\">\n";
7844 git_print_authorship_rows
(\
%co);
7847 print "<div class=\"page_body\">\n";
7848 if (@{$co{'comment'}} > 1) {
7849 print "<div class=\"log\">\n";
7850 git_print_log
($co{'comment'}, -final_empty_line
=> 1, -remove_title
=> 1);
7851 print "</div>\n"; # class="log"
7854 } elsif ($format eq 'plain') {
7855 my $refs = git_get_references
("tags");
7856 my $tagname = git_get_rev_name_tags
($hash);
7857 my $filename = basename
($project) . "-$hash.patch";
7860 -type
=> 'text/plain',
7861 -charset
=> 'utf-8',
7862 -expires
=> $expires,
7863 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
7864 my %ad = parse_date
($co{'author_epoch'}, $co{'author_tz'});
7865 print "From: " . to_utf8
($co{'author'}) . "\n";
7866 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7867 print "Subject: " . to_utf8
($co{'title'}) . "\n";
7869 print "X-Git-Tag: $tagname\n" if $tagname;
7870 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7872 foreach my $line (@{$co{'comment'}}) {
7873 print to_utf8
($line) . "\n";
7876 } elsif ($format eq 'patch') {
7877 my $filename = basename
($project) . "-$hash.patch";
7880 -type
=> 'text/plain',
7881 -charset
=> 'utf-8',
7882 -expires
=> $expires,
7883 -content_disposition
=> 'inline; filename="' . "$filename" . '"');
7887 if ($format eq 'html') {
7888 my $use_parents = !defined $hash_parent ||
7889 $hash_parent eq '-c' || $hash_parent eq '--cc';
7890 git_difftree_body
(\
@difftree, $hash,
7891 $use_parents ? @{$co{'parents'}} : $hash_parent);
7894 git_patchset_body
($fd, $diff_style,
7896 $use_parents ? @{$co{'parents'}} : $hash_parent);
7898 print "</div>\n"; # class="page_body"
7901 } elsif ($format eq 'plain') {
7905 or print "Reading git-diff-tree failed\n";
7906 } elsif ($format eq 'patch') {
7910 or print "Reading git-format-patch failed\n";
7914 sub git_commitdiff_plain
{
7915 git_commitdiff
(-format
=> 'plain');
7918 # format-patch-style patches
7920 git_commitdiff
(-format
=> 'patch', -single
=> 1);
7924 git_commitdiff
(-format
=> 'patch');
7928 git_log_generic
('history', \
&git_history_body
,
7929 $hash_base, $hash_parent_base,
7934 $searchtype ||= 'commit';
7936 # check if appropriate features are enabled
7937 gitweb_check_feature
('search')
7938 or die_error
(403, "Search is disabled");
7939 if ($searchtype eq 'pickaxe') {
7940 # pickaxe may take all resources of your box and run for several minutes
7941 # with every query - so decide by yourself how public you make this feature
7942 gitweb_check_feature
('pickaxe')
7943 or die_error
(403, "Pickaxe search is disabled");
7945 if ($searchtype eq 'grep') {
7946 # grep search might be potentially CPU-intensive, too
7947 gitweb_check_feature
('grep')
7948 or die_error
(403, "Grep search is disabled");
7951 if (!defined $searchtext) {
7952 die_error
(400, "Text field is empty");
7954 if (!defined $hash) {
7955 $hash = git_get_head_hash
($project);
7957 my %co = parse_commit
($hash);
7959 die_error
(404, "Unknown commit object");
7961 if (!defined $page) {
7965 if ($searchtype eq 'commit' ||
7966 $searchtype eq 'author' ||
7967 $searchtype eq 'committer') {
7968 git_search_message
(%co);
7969 } elsif ($searchtype eq 'pickaxe') {
7970 git_search_changes
(%co);
7971 } elsif ($searchtype eq 'grep') {
7972 git_search_files
(%co);
7974 die_error
(400, "Unknown search type");
7978 sub git_search_help
{
7980 git_print_page_nav
('','', $hash,$hash,$hash);
7982 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
7983 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
7984 the pattern entered is recognized as the POSIX extended
7985 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
7988 <dt><b>commit</b></dt>
7989 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7991 my $have_grep = gitweb_check_feature
('grep');
7994 <dt><b>grep</b></dt>
7995 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7996 a different one) are searched for the given pattern. On large trees, this search can take
7997 a while and put some strain on the server, so please use it with some consideration. Note that
7998 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7999 case-sensitive.</dd>
8003 <dt><b>author</b></dt>
8004 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8005 <dt><b>committer</b></dt>
8006 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8008 my $have_pickaxe = gitweb_check_feature
('pickaxe');
8009 if ($have_pickaxe) {
8011 <dt><b>pickaxe</b></dt>
8012 <dd>All commits that caused the string to appear or disappear from any file (changes that
8013 added, removed or "modified" the string) will be listed. This search can take a while and
8014 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8015 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8023 git_log_generic
('shortlog', \
&git_shortlog_body
,
8024 $hash, $hash_parent);
8027 ## ......................................................................
8028 ## feeds (RSS, Atom; OPML)
8031 my $format = shift || 'atom';
8032 my $have_blame = gitweb_check_feature
('blame');
8034 # Atom: http://www.atomenabled.org/developers/syndication/
8035 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8036 if ($format ne 'rss' && $format ne 'atom') {
8037 die_error
(400, "Unknown web feed format");
8040 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8041 my $head = $hash || 'HEAD';
8042 my @commitlist = parse_commits
($head, 150, 0, $file_name);
8046 my $content_type = "application/$format+xml";
8047 if (defined $cgi->http('HTTP_ACCEPT') &&
8048 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8049 # browser (feed reader) prefers text/xml
8050 $content_type = 'text/xml';
8052 if (defined($commitlist[0])) {
8053 %latest_commit = %{$commitlist[0]};
8054 my $latest_epoch = $latest_commit{'committer_epoch'};
8055 exit_if_unmodified_since
($latest_epoch);
8056 %latest_date = parse_date
($latest_epoch, $latest_commit{'committer_tz'});
8059 -type
=> $content_type,
8060 -charset
=> 'utf-8',
8061 %latest_date ? (-last_modified
=> $latest_date{'rfc2822'}) : (),
8062 -status
=> '200 OK');
8064 # Optimization: skip generating the body if client asks only
8065 # for Last-Modified date.
8066 return if ($cgi->request_method() eq 'HEAD');
8069 my $title = "$site_name - $project/$action";
8070 my $feed_type = 'log';
8071 if (defined $hash) {
8072 $title .= " - '$hash'";
8073 $feed_type = 'branch log';
8074 if (defined $file_name) {
8075 $title .= " :: $file_name";
8076 $feed_type = 'history';
8078 } elsif (defined $file_name) {
8079 $title .= " - $file_name";
8080 $feed_type = 'history';
8082 $title .= " $feed_type";
8083 $title = esc_html
($title);
8084 my $descr = git_get_project_description
($project);
8085 if (defined $descr) {
8086 $descr = esc_html
($descr);
8088 $descr = "$project " .
8089 ($format eq 'rss' ? 'RSS' : 'Atom') .
8092 my $owner = git_get_project_owner
($project);
8093 $owner = esc_html
($owner);
8097 if (defined $file_name) {
8098 $alt_url = href
(-full
=>1, action
=>"history", hash
=>$hash, file_name
=>$file_name);
8099 } elsif (defined $hash) {
8100 $alt_url = href
(-full
=>1, action
=>"log", hash
=>$hash);
8102 $alt_url = href
(-full
=>1, action
=>"summary");
8104 print qq
!<?xml version
="1.0" encoding
="utf-8"?>\n!;
8105 if ($format eq 'rss') {
8107 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8110 print "<title>$title</title>\n" .
8111 "<link>$alt_url</link>\n" .
8112 "<description>$descr</description>\n" .
8113 "<language>en</language>\n" .
8114 # project owner is responsible for 'editorial' content
8115 "<managingEditor>$owner</managingEditor>\n";
8116 if (defined $logo || defined $favicon) {
8117 # prefer the logo to the favicon, since RSS
8118 # doesn't allow both
8119 my $img = esc_url
($logo || $favicon);
8121 "<url>$img</url>\n" .
8122 "<title>$title</title>\n" .
8123 "<link>$alt_url</link>\n" .
8127 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8128 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8130 print "<generator>gitweb v.$version/$git_version</generator>\n";
8131 } elsif ($format eq 'atom') {
8133 <feed xmlns="http://www.w3.org/2005/Atom">
8135 print "<title>$title</title>\n" .
8136 "<subtitle>$descr</subtitle>\n" .
8137 '<link rel="alternate" type="text/html" href="' .
8138 $alt_url . '" />' . "\n" .
8139 '<link rel="self" type="' . $content_type . '" href="' .
8140 $cgi->self_url() . '" />' . "\n" .
8141 "<id>" . href
(-full
=>1) . "</id>\n" .
8142 # use project owner for feed author
8143 "<author><name>$owner</name></author>\n";
8144 if (defined $favicon) {
8145 print "<icon>" . esc_url
($favicon) . "</icon>\n";
8147 if (defined $logo) {
8148 # not twice as wide as tall: 72 x 27 pixels
8149 print "<logo>" . esc_url
($logo) . "</logo>\n";
8151 if (! %latest_date) {
8152 # dummy date to keep the feed valid until commits trickle in:
8153 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8155 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8157 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8161 for (my $i = 0; $i <= $#commitlist; $i++) {
8162 my %co = %{$commitlist[$i]};
8163 my $commit = $co{'id'};
8164 # we read 150, we always show 30 and the ones more recent than 48 hours
8165 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8168 my %cd = parse_date
($co{'author_epoch'}, $co{'author_tz'});
8170 # get list of changed files
8171 open my $fd, "-|", git_cmd
(), "diff-tree", '-r', @diff_opts,
8172 $co{'parent'} || "--root",
8173 $co{'id'}, "--", (defined $file_name ? $file_name : ())
8175 my @difftree = map { chomp; $_ } <$fd>;
8179 # print element (entry, item)
8180 my $co_url = href
(-full
=>1, action
=>"commitdiff", hash
=>$commit);
8181 if ($format eq 'rss') {
8183 "<title>" . esc_html
($co{'title'}) . "</title>\n" .
8184 "<author>" . esc_html
($co{'author'}) . "</author>\n" .
8185 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8186 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8187 "<link>$co_url</link>\n" .
8188 "<description>" . esc_html
($co{'title'}) . "</description>\n" .
8189 "<content:encoded>" .
8191 } elsif ($format eq 'atom') {
8193 "<title type=\"html\">" . esc_html
($co{'title'}) . "</title>\n" .
8194 "<updated>$cd{'iso-8601'}</updated>\n" .
8196 " <name>" . esc_html
($co{'author_name'}) . "</name>\n";
8197 if ($co{'author_email'}) {
8198 print " <email>" . esc_html
($co{'author_email'}) . "</email>\n";
8200 print "</author>\n" .
8201 # use committer for contributor
8203 " <name>" . esc_html
($co{'committer_name'}) . "</name>\n";
8204 if ($co{'committer_email'}) {
8205 print " <email>" . esc_html
($co{'committer_email'}) . "</email>\n";
8207 print "</contributor>\n" .
8208 "<published>$cd{'iso-8601'}</published>\n" .
8209 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8210 "<id>$co_url</id>\n" .
8211 "<content type=\"xhtml\" xml:base=\"" . esc_url
($my_url) . "\">\n" .
8212 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8214 my $comment = $co{'comment'};
8216 foreach my $line (@$comment) {
8217 $line = esc_html
($line);
8220 print "</pre><ul>\n";
8221 foreach my $difftree_line (@difftree) {
8222 my %difftree = parse_difftree_raw_line
($difftree_line);
8223 next if !$difftree{'from_id'};
8225 my $file = $difftree{'file'} || $difftree{'to_file'};
8229 $cgi->a({-href
=> href
(-full
=>1, action
=>"blobdiff",
8230 hash
=>$difftree{'to_id'}, hash_parent
=>$difftree{'from_id'},
8231 hash_base
=>$co{'id'}, hash_parent_base
=>$co{'parent'},
8232 file_name
=>$file, file_parent
=>$difftree{'from_file'}),
8233 -title
=> "diff"}, 'D');
8235 print $cgi->a({-href
=> href
(-full
=>1, action
=>"blame",
8236 file_name
=>$file, hash_base
=>$commit),
8237 -title
=> "blame"}, 'B');
8239 # if this is not a feed of a file history
8240 if (!defined $file_name || $file_name ne $file) {
8241 print $cgi->a({-href
=> href
(-full
=>1, action
=>"history",
8242 file_name
=>$file, hash
=>$commit),
8243 -title
=> "history"}, 'H');
8245 $file = esc_path
($file);
8249 if ($format eq 'rss') {
8250 print "</ul>]]>\n" .
8251 "</content:encoded>\n" .
8253 } elsif ($format eq 'atom') {
8254 print "</ul>\n</div>\n" .
8261 if ($format eq 'rss') {
8262 print "</channel>\n</rss>\n";
8263 } elsif ($format eq 'atom') {
8277 my @list = git_get_projects_list
($project_filter, $strict_export);
8279 die_error
(404, "No projects found");
8283 -type
=> 'text/xml',
8284 -charset
=> 'utf-8',
8285 -content_disposition
=> 'inline; filename="opml.xml"');
8287 my $title = esc_html
($site_name);
8288 my $filter = " within subdirectory ";
8289 if (defined $project_filter) {
8290 $filter .= esc_html
($project_filter);
8295 <?xml version="1.0" encoding="utf-8"?>
8296 <opml version="1.0">
8298 <title>$title OPML Export$filter</title>
8301 <outline text="git RSS feeds">
8304 foreach my $pr (@list) {
8306 my $head = git_get_head_hash
($proj{'path'});
8307 if (!defined $head) {
8310 $git_dir = "$projectroot/$proj{'path'}";
8311 my %co = parse_commit
($head);
8316 my $path = esc_html
(chop_str
($proj{'path'}, 25, 5));
8317 my $rss = href
('project' => $proj{'path'}, 'action' => 'rss', -full
=> 1);
8318 my $html = href
('project' => $proj{'path'}, 'action' => 'summary', -full
=> 1);
8319 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";