gitweb: Add a feature to show side-by-side diff
[git/jnareb-git.git] / gitweb / gitweb.perl
blobaf4f67b1142849654521e811dd822b07ea723d02
1 #!/usr/bin/perl
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
10 use 5.008;
11 use strict;
12 use warnings;
13 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
16 use Encode;
17 use Fcntl ':mode';
18 use File::Find qw();
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;
26 BEGIN {
27 CGI->compile() if $ENV{'MOD_PERL'};
30 our $version = "++GIT_VERSION++";
32 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
33 sub evaluate_uri {
34 our $cgi;
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
46 # later on.
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
52 # as base URL.
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 = $ENV{"PATH_INFO"};
56 if ($path_info) {
57 if ($my_url =~ s,\Q$path_info\E$,, &&
58 $my_uri =~ s,\Q$path_info\E$,, &&
59 defined $ENV{'SCRIPT_NAME'}) {
60 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
64 # target of the home link on top of all pages
65 our $home_link = $my_uri || "/";
68 # core git executable to use
69 # this can just be "git" if your webserver has a sensible PATH
70 our $GIT = "++GIT_BINDIR++/git";
72 # absolute fs-path which will be prepended to the project path
73 #our $projectroot = "/pub/scm";
74 our $projectroot = "++GITWEB_PROJECTROOT++";
76 # fs traversing limit for getting project list
77 # the number is relative to the projectroot
78 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
80 # string of the home link on top of all pages
81 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
83 # name of your site or organization to appear in page titles
84 # replace this with something more descriptive for clearer bookmarks
85 our $site_name = "++GITWEB_SITENAME++"
86 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
88 # filename of html text to include at top of each page
89 our $site_header = "++GITWEB_SITE_HEADER++";
90 # html text to include at home page
91 our $home_text = "++GITWEB_HOMETEXT++";
92 # filename of html text to include at bottom of each page
93 our $site_footer = "++GITWEB_SITE_FOOTER++";
95 # URI of stylesheets
96 our @stylesheets = ("++GITWEB_CSS++");
97 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
98 our $stylesheet = undef;
99 # URI of GIT logo (72x27 size)
100 our $logo = "++GITWEB_LOGO++";
101 # URI of GIT favicon, assumed to be image/png type
102 our $favicon = "++GITWEB_FAVICON++";
103 # URI of gitweb.js (JavaScript code for gitweb)
104 our $javascript = "++GITWEB_JS++";
106 # URI and label (title) of GIT logo link
107 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
108 #our $logo_label = "git documentation";
109 our $logo_url = "http://git-scm.com/";
110 our $logo_label = "git homepage";
112 # source of projects list
113 our $projects_list = "++GITWEB_LIST++";
115 # the width (in characters) of the projects list "Description" column
116 our $projects_list_description_width = 25;
118 # group projects by category on the projects list
119 # (enabled if this variable evaluates to true)
120 our $projects_list_group_categories = 0;
122 # default category if none specified
123 # (leave the empty string for no category)
124 our $project_list_default_category = "";
126 # default order of projects list
127 # valid values are none, project, descr, owner, and age
128 our $default_projects_order = "project";
130 # show repository only if this file exists
131 # (only effective if this variable evaluates to true)
132 our $export_ok = "++GITWEB_EXPORT_OK++";
134 # show repository only if this subroutine returns true
135 # when given the path to the project, for example:
136 # sub { return -e "$_[0]/git-daemon-export-ok"; }
137 our $export_auth_hook = undef;
139 # only allow viewing of repositories also shown on the overview page
140 our $strict_export = "++GITWEB_STRICT_EXPORT++";
142 # list of git base URLs used for URL to where fetch project from,
143 # i.e. full URL is "$git_base_url/$project"
144 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
146 # default blob_plain mimetype and default charset for text/plain blob
147 our $default_blob_plain_mimetype = 'text/plain';
148 our $default_text_plain_charset = undef;
150 # file to use for guessing MIME types before trying /etc/mime.types
151 # (relative to the current git repository)
152 our $mimetypes_file = undef;
154 # assume this charset if line contains non-UTF-8 characters;
155 # it should be valid encoding (see Encoding::Supported(3pm) for list),
156 # for which encoding all byte sequences are valid, for example
157 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
158 # could be even 'utf-8' for the old behavior)
159 our $fallback_encoding = 'latin1';
161 # rename detection options for git-diff and git-diff-tree
162 # - default is '-M', with the cost proportional to
163 # (number of removed files) * (number of new files).
164 # - more costly is '-C' (which implies '-M'), with the cost proportional to
165 # (number of changed files + number of removed files) * (number of new files)
166 # - even more costly is '-C', '--find-copies-harder' with cost
167 # (number of files in the original tree) * (number of new files)
168 # - one might want to include '-B' option, e.g. '-B', '-M'
169 our @diff_opts = ('-M'); # taken from git_commit
171 # Disables features that would allow repository owners to inject script into
172 # the gitweb domain.
173 our $prevent_xss = 0;
175 # Path to the highlight executable to use (must be the one from
176 # http://www.andre-simon.de due to assumptions about parameters and output).
177 # Useful if highlight is not installed on your webserver's PATH.
178 # [Default: highlight]
179 our $highlight_bin = "++HIGHLIGHT_BIN++";
181 # information about snapshot formats that gitweb is capable of serving
182 our %known_snapshot_formats = (
183 # name => {
184 # 'display' => display name,
185 # 'type' => mime type,
186 # 'suffix' => filename suffix,
187 # 'format' => --format for git-archive,
188 # 'compressor' => [compressor command and arguments]
189 # (array reference, optional)
190 # 'disabled' => boolean (optional)}
192 'tgz' => {
193 'display' => 'tar.gz',
194 'type' => 'application/x-gzip',
195 'suffix' => '.tar.gz',
196 'format' => 'tar',
197 'compressor' => ['gzip', '-n']},
199 'tbz2' => {
200 'display' => 'tar.bz2',
201 'type' => 'application/x-bzip2',
202 'suffix' => '.tar.bz2',
203 'format' => 'tar',
204 'compressor' => ['bzip2']},
206 'txz' => {
207 'display' => 'tar.xz',
208 'type' => 'application/x-xz',
209 'suffix' => '.tar.xz',
210 'format' => 'tar',
211 'compressor' => ['xz'],
212 'disabled' => 1},
214 'zip' => {
215 'display' => 'zip',
216 'type' => 'application/x-zip',
217 'suffix' => '.zip',
218 'format' => 'zip'},
221 # Aliases so we understand old gitweb.snapshot values in repository
222 # configuration.
223 our %known_snapshot_format_aliases = (
224 'gzip' => 'tgz',
225 'bzip2' => 'tbz2',
226 'xz' => 'txz',
228 # backward compatibility: legacy gitweb config support
229 'x-gzip' => undef, 'gz' => undef,
230 'x-bzip2' => undef, 'bz2' => undef,
231 'x-zip' => undef, '' => undef,
234 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
235 # are changed, it may be appropriate to change these values too via
236 # $GITWEB_CONFIG.
237 our %avatar_size = (
238 'default' => 16,
239 'double' => 32
242 # Used to set the maximum load that we will still respond to gitweb queries.
243 # If server load exceed this value then return "503 server busy" error.
244 # If gitweb cannot determined server load, it is taken to be 0.
245 # Leave it undefined (or set to 'undef') to turn off load checking.
246 our $maxload = 300;
248 # configuration for 'highlight' (http://www.andre-simon.de/)
249 # match by basename
250 our %highlight_basename = (
251 #'Program' => 'py',
252 #'Library' => 'py',
253 'SConstruct' => 'py', # SCons equivalent of Makefile
254 'Makefile' => 'make',
256 # match by extension
257 our %highlight_ext = (
258 # main extensions, defining name of syntax;
259 # see files in /usr/share/highlight/langDefs/ directory
260 map { $_ => $_ }
261 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make),
262 # alternate extensions, see /etc/highlight/filetypes.conf
263 'h' => 'c',
264 map { $_ => 'sh' } qw(bash zsh ksh),
265 map { $_ => 'cpp' } qw(cxx c++ cc),
266 map { $_ => 'php' } qw(php3 php4 php5 phps),
267 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
268 map { $_ => 'make'} qw(mak mk),
269 map { $_ => 'xml' } qw(xhtml html htm),
272 # You define site-wide feature defaults here; override them with
273 # $GITWEB_CONFIG as necessary.
274 our %feature = (
275 # feature => {
276 # 'sub' => feature-sub (subroutine),
277 # 'override' => allow-override (boolean),
278 # 'default' => [ default options...] (array reference)}
280 # if feature is overridable (it means that allow-override has true value),
281 # then feature-sub will be called with default options as parameters;
282 # return value of feature-sub indicates if to enable specified feature
284 # if there is no 'sub' key (no feature-sub), then feature cannot be
285 # overridden
287 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
288 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
289 # is enabled
291 # Enable the 'blame' blob view, showing the last commit that modified
292 # each line in the file. This can be very CPU-intensive.
294 # To enable system wide have in $GITWEB_CONFIG
295 # $feature{'blame'}{'default'} = [1];
296 # To have project specific config enable override in $GITWEB_CONFIG
297 # $feature{'blame'}{'override'} = 1;
298 # and in project config gitweb.blame = 0|1;
299 'blame' => {
300 'sub' => sub { feature_bool('blame', @_) },
301 'override' => 0,
302 'default' => [0]},
304 # Enable the 'snapshot' link, providing a compressed archive of any
305 # tree. This can potentially generate high traffic if you have large
306 # project.
308 # Value is a list of formats defined in %known_snapshot_formats that
309 # you wish to offer.
310 # To disable system wide have in $GITWEB_CONFIG
311 # $feature{'snapshot'}{'default'} = [];
312 # To have project specific config enable override in $GITWEB_CONFIG
313 # $feature{'snapshot'}{'override'} = 1;
314 # and in project config, a comma-separated list of formats or "none"
315 # to disable. Example: gitweb.snapshot = tbz2,zip;
316 'snapshot' => {
317 'sub' => \&feature_snapshot,
318 'override' => 0,
319 'default' => ['tgz']},
321 # Enable text search, which will list the commits which match author,
322 # committer or commit text to a given string. Enabled by default.
323 # Project specific override is not supported.
325 # Note that this controls all search features, which means that if
326 # it is disabled, then 'grep' and 'pickaxe' search would also be
327 # disabled.
328 'search' => {
329 'override' => 0,
330 'default' => [1]},
332 # Enable grep search, which will list the files in currently selected
333 # tree containing the given string. Enabled by default. This can be
334 # potentially CPU-intensive, of course.
335 # Note that you need to have 'search' feature enabled too.
337 # To enable system wide have in $GITWEB_CONFIG
338 # $feature{'grep'}{'default'} = [1];
339 # To have project specific config enable override in $GITWEB_CONFIG
340 # $feature{'grep'}{'override'} = 1;
341 # and in project config gitweb.grep = 0|1;
342 'grep' => {
343 'sub' => sub { feature_bool('grep', @_) },
344 'override' => 0,
345 'default' => [1]},
347 # Enable the pickaxe search, which will list the commits that modified
348 # a given string in a file. This can be practical and quite faster
349 # alternative to 'blame', but still potentially CPU-intensive.
350 # Note that you need to have 'search' feature enabled too.
352 # To enable system wide have in $GITWEB_CONFIG
353 # $feature{'pickaxe'}{'default'} = [1];
354 # To have project specific config enable override in $GITWEB_CONFIG
355 # $feature{'pickaxe'}{'override'} = 1;
356 # and in project config gitweb.pickaxe = 0|1;
357 'pickaxe' => {
358 'sub' => sub { feature_bool('pickaxe', @_) },
359 'override' => 0,
360 'default' => [1]},
362 # Enable showing size of blobs in a 'tree' view, in a separate
363 # column, similar to what 'ls -l' does. This cost a bit of IO.
365 # To disable system wide have in $GITWEB_CONFIG
366 # $feature{'show-sizes'}{'default'} = [0];
367 # To have project specific config enable override in $GITWEB_CONFIG
368 # $feature{'show-sizes'}{'override'} = 1;
369 # and in project config gitweb.showsizes = 0|1;
370 'show-sizes' => {
371 'sub' => sub { feature_bool('showsizes', @_) },
372 'override' => 0,
373 'default' => [1]},
375 # Make gitweb use an alternative format of the URLs which can be
376 # more readable and natural-looking: project name is embedded
377 # directly in the path and the query string contains other
378 # auxiliary information. All gitweb installations recognize
379 # URL in either format; this configures in which formats gitweb
380 # generates links.
382 # To enable system wide have in $GITWEB_CONFIG
383 # $feature{'pathinfo'}{'default'} = [1];
384 # Project specific override is not supported.
386 # Note that you will need to change the default location of CSS,
387 # favicon, logo and possibly other files to an absolute URL. Also,
388 # if gitweb.cgi serves as your indexfile, you will need to force
389 # $my_uri to contain the script name in your $GITWEB_CONFIG.
390 'pathinfo' => {
391 'override' => 0,
392 'default' => [0]},
394 # Make gitweb consider projects in project root subdirectories
395 # to be forks of existing projects. Given project $projname.git,
396 # projects matching $projname/*.git will not be shown in the main
397 # projects list, instead a '+' mark will be added to $projname
398 # there and a 'forks' view will be enabled for the project, listing
399 # all the forks. If project list is taken from a file, forks have
400 # to be listed after the main project.
402 # To enable system wide have in $GITWEB_CONFIG
403 # $feature{'forks'}{'default'} = [1];
404 # Project specific override is not supported.
405 'forks' => {
406 'override' => 0,
407 'default' => [0]},
409 # Insert custom links to the action bar of all project pages.
410 # This enables you mainly to link to third-party scripts integrating
411 # into gitweb; e.g. git-browser for graphical history representation
412 # or custom web-based repository administration interface.
414 # The 'default' value consists of a list of triplets in the form
415 # (label, link, position) where position is the label after which
416 # to insert the link and link is a format string where %n expands
417 # to the project name, %f to the project path within the filesystem,
418 # %h to the current hash (h gitweb parameter) and %b to the current
419 # hash base (hb gitweb parameter); %% expands to %.
421 # To enable system wide have in $GITWEB_CONFIG e.g.
422 # $feature{'actions'}{'default'} = [('graphiclog',
423 # '/git-browser/by-commit.html?r=%n', 'summary')];
424 # Project specific override is not supported.
425 'actions' => {
426 'override' => 0,
427 'default' => []},
429 # Allow gitweb scan project content tags of project repository,
430 # and display the popular Web 2.0-ish "tag cloud" near the projects
431 # list. Note that this is something COMPLETELY different from the
432 # normal Git tags.
434 # gitweb by itself can show existing tags, but it does not handle
435 # tagging itself; you need to do it externally, outside gitweb.
436 # The format is described in git_get_project_ctags() subroutine.
437 # You may want to install the HTML::TagCloud Perl module to get
438 # a pretty tag cloud instead of just a list of tags.
440 # To enable system wide have in $GITWEB_CONFIG
441 # $feature{'ctags'}{'default'} = [1];
442 # Project specific override is not supported.
444 # In the future whether ctags editing is enabled might depend
445 # on the value, but using 1 should always mean no editing of ctags.
446 'ctags' => {
447 'override' => 0,
448 'default' => [0]},
450 # The maximum number of patches in a patchset generated in patch
451 # view. Set this to 0 or undef to disable patch view, or to a
452 # negative number to remove any limit.
454 # To disable system wide have in $GITWEB_CONFIG
455 # $feature{'patches'}{'default'} = [0];
456 # To have project specific config enable override in $GITWEB_CONFIG
457 # $feature{'patches'}{'override'} = 1;
458 # and in project config gitweb.patches = 0|n;
459 # where n is the maximum number of patches allowed in a patchset.
460 'patches' => {
461 'sub' => \&feature_patches,
462 'override' => 0,
463 'default' => [16]},
465 # Avatar support. When this feature is enabled, views such as
466 # shortlog or commit will display an avatar associated with
467 # the email of the committer(s) and/or author(s).
469 # Currently available providers are gravatar and picon.
470 # If an unknown provider is specified, the feature is disabled.
472 # Gravatar depends on Digest::MD5.
473 # Picon currently relies on the indiana.edu database.
475 # To enable system wide have in $GITWEB_CONFIG
476 # $feature{'avatar'}{'default'} = ['<provider>'];
477 # where <provider> is either gravatar or picon.
478 # To have project specific config enable override in $GITWEB_CONFIG
479 # $feature{'avatar'}{'override'} = 1;
480 # and in project config gitweb.avatar = <provider>;
481 'avatar' => {
482 'sub' => \&feature_avatar,
483 'override' => 0,
484 'default' => ['']},
486 # Enable displaying how much time and how many git commands
487 # it took to generate and display page. Disabled by default.
488 # Project specific override is not supported.
489 'timed' => {
490 'override' => 0,
491 'default' => [0]},
493 # Enable turning some links into links to actions which require
494 # JavaScript to run (like 'blame_incremental'). Not enabled by
495 # default. Project specific override is currently not supported.
496 'javascript-actions' => {
497 'override' => 0,
498 'default' => [0]},
500 # Enable and configure ability to change common timezone for dates
501 # in gitweb output via JavaScript. Enabled by default.
502 # Project specific override is not supported.
503 'javascript-timezone' => {
504 'override' => 0,
505 'default' => [
506 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
507 # or undef to turn off this feature
508 'gitweb_tz', # name of cookie where to store selected timezone
509 'datetime', # CSS class used to mark up dates for manipulation
512 # Syntax highlighting support. This is based on Daniel Svensson's
513 # and Sham Chukoury's work in gitweb-xmms2.git.
514 # It requires the 'highlight' program present in $PATH,
515 # and therefore is disabled by default.
517 # To enable system wide have in $GITWEB_CONFIG
518 # $feature{'highlight'}{'default'} = [1];
520 'highlight' => {
521 'sub' => sub { feature_bool('highlight', @_) },
522 'override' => 0,
523 'default' => [0]},
525 # Enable displaying of remote heads in the heads list
527 # To enable system wide have in $GITWEB_CONFIG
528 # $feature{'remote_heads'}{'default'} = [1];
529 # To have project specific config enable override in $GITWEB_CONFIG
530 # $feature{'remote_heads'}{'override'} = 1;
531 # and in project config gitweb.remote_heads = 0|1;
532 'remote_heads' => {
533 'sub' => sub { feature_bool('remote_heads', @_) },
534 'override' => 0,
535 'default' => [0]},
538 sub gitweb_get_feature {
539 my ($name) = @_;
540 return unless exists $feature{$name};
541 my ($sub, $override, @defaults) = (
542 $feature{$name}{'sub'},
543 $feature{$name}{'override'},
544 @{$feature{$name}{'default'}});
545 # project specific override is possible only if we have project
546 our $git_dir; # global variable, declared later
547 if (!$override || !defined $git_dir) {
548 return @defaults;
550 if (!defined $sub) {
551 warn "feature $name is not overridable";
552 return @defaults;
554 return $sub->(@defaults);
557 # A wrapper to check if a given feature is enabled.
558 # With this, you can say
560 # my $bool_feat = gitweb_check_feature('bool_feat');
561 # gitweb_check_feature('bool_feat') or somecode;
563 # instead of
565 # my ($bool_feat) = gitweb_get_feature('bool_feat');
566 # (gitweb_get_feature('bool_feat'))[0] or somecode;
568 sub gitweb_check_feature {
569 return (gitweb_get_feature(@_))[0];
573 sub feature_bool {
574 my $key = shift;
575 my ($val) = git_get_project_config($key, '--bool');
577 if (!defined $val) {
578 return ($_[0]);
579 } elsif ($val eq 'true') {
580 return (1);
581 } elsif ($val eq 'false') {
582 return (0);
586 sub feature_snapshot {
587 my (@fmts) = @_;
589 my ($val) = git_get_project_config('snapshot');
591 if ($val) {
592 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
595 return @fmts;
598 sub feature_patches {
599 my @val = (git_get_project_config('patches', '--int'));
601 if (@val) {
602 return @val;
605 return ($_[0]);
608 sub feature_avatar {
609 my @val = (git_get_project_config('avatar'));
611 return @val ? @val : @_;
614 # checking HEAD file with -e is fragile if the repository was
615 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
616 # and then pruned.
617 sub check_head_link {
618 my ($dir) = @_;
619 my $headfile = "$dir/HEAD";
620 return ((-e $headfile) ||
621 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
624 sub check_export_ok {
625 my ($dir) = @_;
626 return (check_head_link($dir) &&
627 (!$export_ok || -e "$dir/$export_ok") &&
628 (!$export_auth_hook || $export_auth_hook->($dir)));
631 # process alternate names for backward compatibility
632 # filter out unsupported (unknown) snapshot formats
633 sub filter_snapshot_fmts {
634 my @fmts = @_;
636 @fmts = map {
637 exists $known_snapshot_format_aliases{$_} ?
638 $known_snapshot_format_aliases{$_} : $_} @fmts;
639 @fmts = grep {
640 exists $known_snapshot_formats{$_} &&
641 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
644 # If it is set to code reference, it is code that it is to be run once per
645 # request, allowing updating configurations that change with each request,
646 # while running other code in config file only once.
648 # Otherwise, if it is false then gitweb would process config file only once;
649 # if it is true then gitweb config would be run for each request.
650 our $per_request_config = 1;
652 # read and parse gitweb config file given by its parameter.
653 # returns true on success, false on recoverable error, allowing
654 # to chain this subroutine, using first file that exists.
655 # dies on errors during parsing config file, as it is unrecoverable.
656 sub read_config_file {
657 my $filename = shift;
658 return unless defined $filename;
659 # die if there are errors parsing config file
660 if (-e $filename) {
661 do $filename;
662 die $@ if $@;
663 return 1;
665 return;
668 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
669 sub evaluate_gitweb_config {
670 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
671 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
672 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
674 # Protect agains duplications of file names, to not read config twice.
675 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
676 # there possibility of duplication of filename there doesn't matter.
677 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
678 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
680 # Common system-wide settings for convenience.
681 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
682 read_config_file($GITWEB_CONFIG_COMMON);
684 # Use first config file that exists. This means use the per-instance
685 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
686 read_config_file($GITWEB_CONFIG) and return;
687 read_config_file($GITWEB_CONFIG_SYSTEM);
690 # Get loadavg of system, to compare against $maxload.
691 # Currently it requires '/proc/loadavg' present to get loadavg;
692 # if it is not present it returns 0, which means no load checking.
693 sub get_loadavg {
694 if( -e '/proc/loadavg' ){
695 open my $fd, '<', '/proc/loadavg'
696 or return 0;
697 my @load = split(/\s+/, scalar <$fd>);
698 close $fd;
700 # The first three columns measure CPU and IO utilization of the last one,
701 # five, and 10 minute periods. The fourth column shows the number of
702 # currently running processes and the total number of processes in the m/n
703 # format. The last column displays the last process ID used.
704 return $load[0] || 0;
706 # additional checks for load average should go here for things that don't export
707 # /proc/loadavg
709 return 0;
712 # version of the core git binary
713 our $git_version;
714 sub evaluate_git_version {
715 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
716 $number_of_git_cmds++;
719 sub check_loadavg {
720 if (defined $maxload && get_loadavg() > $maxload) {
721 die_error(503, "The load average on the server is too high");
725 # ======================================================================
726 # input validation and dispatch
728 # input parameters can be collected from a variety of sources (presently, CGI
729 # and PATH_INFO), so we define an %input_params hash that collects them all
730 # together during validation: this allows subsequent uses (e.g. href()) to be
731 # agnostic of the parameter origin
733 our %input_params = ();
735 # input parameters are stored with the long parameter name as key. This will
736 # also be used in the href subroutine to convert parameters to their CGI
737 # equivalent, and since the href() usage is the most frequent one, we store
738 # the name -> CGI key mapping here, instead of the reverse.
740 # XXX: Warning: If you touch this, check the search form for updating,
741 # too.
743 our @cgi_param_mapping = (
744 project => "p",
745 action => "a",
746 file_name => "f",
747 file_parent => "fp",
748 hash => "h",
749 hash_parent => "hp",
750 hash_base => "hb",
751 hash_parent_base => "hpb",
752 page => "pg",
753 order => "o",
754 searchtext => "s",
755 searchtype => "st",
756 snapshot_format => "sf",
757 extra_options => "opt",
758 search_use_regexp => "sr",
759 ctag => "by_tag",
760 diff_style => "ds",
761 # this must be last entry (for manipulation from JavaScript)
762 javascript => "js"
764 our %cgi_param_mapping = @cgi_param_mapping;
766 # we will also need to know the possible actions, for validation
767 our %actions = (
768 "blame" => \&git_blame,
769 "blame_incremental" => \&git_blame_incremental,
770 "blame_data" => \&git_blame_data,
771 "blobdiff" => \&git_blobdiff,
772 "blobdiff_plain" => \&git_blobdiff_plain,
773 "blob" => \&git_blob,
774 "blob_plain" => \&git_blob_plain,
775 "commitdiff" => \&git_commitdiff,
776 "commitdiff_plain" => \&git_commitdiff_plain,
777 "commit" => \&git_commit,
778 "forks" => \&git_forks,
779 "heads" => \&git_heads,
780 "history" => \&git_history,
781 "log" => \&git_log,
782 "patch" => \&git_patch,
783 "patches" => \&git_patches,
784 "remotes" => \&git_remotes,
785 "rss" => \&git_rss,
786 "atom" => \&git_atom,
787 "search" => \&git_search,
788 "search_help" => \&git_search_help,
789 "shortlog" => \&git_shortlog,
790 "summary" => \&git_summary,
791 "tag" => \&git_tag,
792 "tags" => \&git_tags,
793 "tree" => \&git_tree,
794 "snapshot" => \&git_snapshot,
795 "object" => \&git_object,
796 # those below don't need $project
797 "opml" => \&git_opml,
798 "project_list" => \&git_project_list,
799 "project_index" => \&git_project_index,
802 # finally, we have the hash of allowed extra_options for the commands that
803 # allow them
804 our %allowed_options = (
805 "--no-merges" => [ qw(rss atom log shortlog history) ],
808 # fill %input_params with the CGI parameters. All values except for 'opt'
809 # should be single values, but opt can be an array. We should probably
810 # build an array of parameters that can be multi-valued, but since for the time
811 # being it's only this one, we just single it out
812 sub evaluate_query_params {
813 our $cgi;
815 while (my ($name, $symbol) = each %cgi_param_mapping) {
816 if ($symbol eq 'opt') {
817 $input_params{$name} = [ $cgi->param($symbol) ];
818 } else {
819 $input_params{$name} = $cgi->param($symbol);
824 # now read PATH_INFO and update the parameter list for missing parameters
825 sub evaluate_path_info {
826 return if defined $input_params{'project'};
827 return if !$path_info;
828 $path_info =~ s,^/+,,;
829 return if !$path_info;
831 # find which part of PATH_INFO is project
832 my $project = $path_info;
833 $project =~ s,/+$,,;
834 while ($project && !check_head_link("$projectroot/$project")) {
835 $project =~ s,/*[^/]*$,,;
837 return unless $project;
838 $input_params{'project'} = $project;
840 # do not change any parameters if an action is given using the query string
841 return if $input_params{'action'};
842 $path_info =~ s,^\Q$project\E/*,,;
844 # next, check if we have an action
845 my $action = $path_info;
846 $action =~ s,/.*$,,;
847 if (exists $actions{$action}) {
848 $path_info =~ s,^$action/*,,;
849 $input_params{'action'} = $action;
852 # list of actions that want hash_base instead of hash, but can have no
853 # pathname (f) parameter
854 my @wants_base = (
855 'tree',
856 'history',
859 # we want to catch, among others
860 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
861 my ($parentrefname, $parentpathname, $refname, $pathname) =
862 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
864 # first, analyze the 'current' part
865 if (defined $pathname) {
866 # we got "branch:filename" or "branch:dir/"
867 # we could use git_get_type(branch:pathname), but:
868 # - it needs $git_dir
869 # - it does a git() call
870 # - the convention of terminating directories with a slash
871 # makes it superfluous
872 # - embedding the action in the PATH_INFO would make it even
873 # more superfluous
874 $pathname =~ s,^/+,,;
875 if (!$pathname || substr($pathname, -1) eq "/") {
876 $input_params{'action'} ||= "tree";
877 $pathname =~ s,/$,,;
878 } else {
879 # the default action depends on whether we had parent info
880 # or not
881 if ($parentrefname) {
882 $input_params{'action'} ||= "blobdiff_plain";
883 } else {
884 $input_params{'action'} ||= "blob_plain";
887 $input_params{'hash_base'} ||= $refname;
888 $input_params{'file_name'} ||= $pathname;
889 } elsif (defined $refname) {
890 # we got "branch". In this case we have to choose if we have to
891 # set hash or hash_base.
893 # Most of the actions without a pathname only want hash to be
894 # set, except for the ones specified in @wants_base that want
895 # hash_base instead. It should also be noted that hand-crafted
896 # links having 'history' as an action and no pathname or hash
897 # set will fail, but that happens regardless of PATH_INFO.
898 if (defined $parentrefname) {
899 # if there is parent let the default be 'shortlog' action
900 # (for http://git.example.com/repo.git/A..B links); if there
901 # is no parent, dispatch will detect type of object and set
902 # action appropriately if required (if action is not set)
903 $input_params{'action'} ||= "shortlog";
905 if ($input_params{'action'} &&
906 grep { $_ eq $input_params{'action'} } @wants_base) {
907 $input_params{'hash_base'} ||= $refname;
908 } else {
909 $input_params{'hash'} ||= $refname;
913 # next, handle the 'parent' part, if present
914 if (defined $parentrefname) {
915 # a missing pathspec defaults to the 'current' filename, allowing e.g.
916 # someproject/blobdiff/oldrev..newrev:/filename
917 if ($parentpathname) {
918 $parentpathname =~ s,^/+,,;
919 $parentpathname =~ s,/$,,;
920 $input_params{'file_parent'} ||= $parentpathname;
921 } else {
922 $input_params{'file_parent'} ||= $input_params{'file_name'};
924 # we assume that hash_parent_base is wanted if a path was specified,
925 # or if the action wants hash_base instead of hash
926 if (defined $input_params{'file_parent'} ||
927 grep { $_ eq $input_params{'action'} } @wants_base) {
928 $input_params{'hash_parent_base'} ||= $parentrefname;
929 } else {
930 $input_params{'hash_parent'} ||= $parentrefname;
934 # for the snapshot action, we allow URLs in the form
935 # $project/snapshot/$hash.ext
936 # where .ext determines the snapshot and gets removed from the
937 # passed $refname to provide the $hash.
939 # To be able to tell that $refname includes the format extension, we
940 # require the following two conditions to be satisfied:
941 # - the hash input parameter MUST have been set from the $refname part
942 # of the URL (i.e. they must be equal)
943 # - the snapshot format MUST NOT have been defined already (e.g. from
944 # CGI parameter sf)
945 # It's also useless to try any matching unless $refname has a dot,
946 # so we check for that too
947 if (defined $input_params{'action'} &&
948 $input_params{'action'} eq 'snapshot' &&
949 defined $refname && index($refname, '.') != -1 &&
950 $refname eq $input_params{'hash'} &&
951 !defined $input_params{'snapshot_format'}) {
952 # We loop over the known snapshot formats, checking for
953 # extensions. Allowed extensions are both the defined suffix
954 # (which includes the initial dot already) and the snapshot
955 # format key itself, with a prepended dot
956 while (my ($fmt, $opt) = each %known_snapshot_formats) {
957 my $hash = $refname;
958 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
959 next;
961 my $sfx = $1;
962 # a valid suffix was found, so set the snapshot format
963 # and reset the hash parameter
964 $input_params{'snapshot_format'} = $fmt;
965 $input_params{'hash'} = $hash;
966 # we also set the format suffix to the one requested
967 # in the URL: this way a request for e.g. .tgz returns
968 # a .tgz instead of a .tar.gz
969 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
970 last;
975 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
976 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
977 $searchtext, $search_regexp);
978 sub evaluate_and_validate_params {
979 our $action = $input_params{'action'};
980 if (defined $action) {
981 if (!validate_action($action)) {
982 die_error(400, "Invalid action parameter");
986 # parameters which are pathnames
987 our $project = $input_params{'project'};
988 if (defined $project) {
989 if (!validate_project($project)) {
990 undef $project;
991 die_error(404, "No such project");
995 our $file_name = $input_params{'file_name'};
996 if (defined $file_name) {
997 if (!validate_pathname($file_name)) {
998 die_error(400, "Invalid file parameter");
1002 our $file_parent = $input_params{'file_parent'};
1003 if (defined $file_parent) {
1004 if (!validate_pathname($file_parent)) {
1005 die_error(400, "Invalid file parent parameter");
1009 # parameters which are refnames
1010 our $hash = $input_params{'hash'};
1011 if (defined $hash) {
1012 if (!validate_refname($hash)) {
1013 die_error(400, "Invalid hash parameter");
1017 our $hash_parent = $input_params{'hash_parent'};
1018 if (defined $hash_parent) {
1019 if (!validate_refname($hash_parent)) {
1020 die_error(400, "Invalid hash parent parameter");
1024 our $hash_base = $input_params{'hash_base'};
1025 if (defined $hash_base) {
1026 if (!validate_refname($hash_base)) {
1027 die_error(400, "Invalid hash base parameter");
1031 our @extra_options = @{$input_params{'extra_options'}};
1032 # @extra_options is always defined, since it can only be (currently) set from
1033 # CGI, and $cgi->param() returns the empty array in array context if the param
1034 # is not set
1035 foreach my $opt (@extra_options) {
1036 if (not exists $allowed_options{$opt}) {
1037 die_error(400, "Invalid option parameter");
1039 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1040 die_error(400, "Invalid option parameter for this action");
1044 our $hash_parent_base = $input_params{'hash_parent_base'};
1045 if (defined $hash_parent_base) {
1046 if (!validate_refname($hash_parent_base)) {
1047 die_error(400, "Invalid hash parent base parameter");
1051 # other parameters
1052 our $page = $input_params{'page'};
1053 if (defined $page) {
1054 if ($page =~ m/[^0-9]/) {
1055 die_error(400, "Invalid page parameter");
1059 our $searchtype = $input_params{'searchtype'};
1060 if (defined $searchtype) {
1061 if ($searchtype =~ m/[^a-z]/) {
1062 die_error(400, "Invalid searchtype parameter");
1066 our $search_use_regexp = $input_params{'search_use_regexp'};
1068 our $searchtext = $input_params{'searchtext'};
1069 our $search_regexp;
1070 if (defined $searchtext) {
1071 if (length($searchtext) < 2) {
1072 die_error(403, "At least two characters are required for search parameter");
1074 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1078 # path to the current git repository
1079 our $git_dir;
1080 sub evaluate_git_dir {
1081 our $git_dir = "$projectroot/$project" if $project;
1084 our (@snapshot_fmts, $git_avatar);
1085 sub configure_gitweb_features {
1086 # list of supported snapshot formats
1087 our @snapshot_fmts = gitweb_get_feature('snapshot');
1088 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1090 # check that the avatar feature is set to a known provider name,
1091 # and for each provider check if the dependencies are satisfied.
1092 # if the provider name is invalid or the dependencies are not met,
1093 # reset $git_avatar to the empty string.
1094 our ($git_avatar) = gitweb_get_feature('avatar');
1095 if ($git_avatar eq 'gravatar') {
1096 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1097 } elsif ($git_avatar eq 'picon') {
1098 # no dependencies
1099 } else {
1100 $git_avatar = '';
1104 # custom error handler: 'die <message>' is Internal Server Error
1105 sub handle_errors_html {
1106 my $msg = shift; # it is already HTML escaped
1108 # to avoid infinite loop where error occurs in die_error,
1109 # change handler to default handler, disabling handle_errors_html
1110 set_message("Error occured when inside die_error:\n$msg");
1112 # you cannot jump out of die_error when called as error handler;
1113 # the subroutine set via CGI::Carp::set_message is called _after_
1114 # HTTP headers are already written, so it cannot write them itself
1115 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1117 set_message(\&handle_errors_html);
1119 # dispatch
1120 sub dispatch {
1121 if (!defined $action) {
1122 if (defined $hash) {
1123 $action = git_get_type($hash);
1124 } elsif (defined $hash_base && defined $file_name) {
1125 $action = git_get_type("$hash_base:$file_name");
1126 } elsif (defined $project) {
1127 $action = 'summary';
1128 } else {
1129 $action = 'project_list';
1132 if (!defined($actions{$action})) {
1133 die_error(400, "Unknown action");
1135 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1136 !$project) {
1137 die_error(400, "Project needed");
1139 $actions{$action}->();
1142 sub reset_timer {
1143 our $t0 = [ gettimeofday() ]
1144 if defined $t0;
1145 our $number_of_git_cmds = 0;
1148 our $first_request = 1;
1149 sub run_request {
1150 reset_timer();
1152 evaluate_uri();
1153 if ($first_request) {
1154 evaluate_gitweb_config();
1155 evaluate_git_version();
1157 if ($per_request_config) {
1158 if (ref($per_request_config) eq 'CODE') {
1159 $per_request_config->();
1160 } elsif (!$first_request) {
1161 evaluate_gitweb_config();
1164 check_loadavg();
1166 # $projectroot and $projects_list might be set in gitweb config file
1167 $projects_list ||= $projectroot;
1169 evaluate_query_params();
1170 evaluate_path_info();
1171 evaluate_and_validate_params();
1172 evaluate_git_dir();
1174 configure_gitweb_features();
1176 dispatch();
1179 our $is_last_request = sub { 1 };
1180 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1181 our $CGI = 'CGI';
1182 our $cgi;
1183 sub configure_as_fcgi {
1184 require CGI::Fast;
1185 our $CGI = 'CGI::Fast';
1187 my $request_number = 0;
1188 # let each child service 100 requests
1189 our $is_last_request = sub { ++$request_number > 100 };
1191 sub evaluate_argv {
1192 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1193 configure_as_fcgi()
1194 if $script_name =~ /\.fcgi$/;
1196 return unless (@ARGV);
1198 require Getopt::Long;
1199 Getopt::Long::GetOptions(
1200 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1201 'nproc|n=i' => sub {
1202 my ($arg, $val) = @_;
1203 return unless eval { require FCGI::ProcManager; 1; };
1204 my $proc_manager = FCGI::ProcManager->new({
1205 n_processes => $val,
1207 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1208 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1209 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1214 sub run {
1215 evaluate_argv();
1217 $first_request = 1;
1218 $pre_listen_hook->()
1219 if $pre_listen_hook;
1221 REQUEST:
1222 while ($cgi = $CGI->new()) {
1223 $pre_dispatch_hook->()
1224 if $pre_dispatch_hook;
1226 run_request();
1228 $post_dispatch_hook->()
1229 if $post_dispatch_hook;
1230 $first_request = 0;
1232 last REQUEST if ($is_last_request->());
1235 DONE_GITWEB:
1239 run();
1241 if (defined caller) {
1242 # wrapped in a subroutine processing requests,
1243 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1244 return;
1245 } else {
1246 # pure CGI script, serving single request
1247 exit;
1250 ## ======================================================================
1251 ## action links
1253 # possible values of extra options
1254 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1255 # -replay => 1 - start from a current view (replay with modifications)
1256 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1257 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1258 sub href {
1259 my %params = @_;
1260 # default is to use -absolute url() i.e. $my_uri
1261 my $href = $params{-full} ? $my_url : $my_uri;
1263 # implicit -replay, must be first of implicit params
1264 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1266 $params{'project'} = $project unless exists $params{'project'};
1268 if ($params{-replay}) {
1269 while (my ($name, $symbol) = each %cgi_param_mapping) {
1270 if (!exists $params{$name}) {
1271 $params{$name} = $input_params{$name};
1276 my $use_pathinfo = gitweb_check_feature('pathinfo');
1277 if (defined $params{'project'} &&
1278 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1279 # try to put as many parameters as possible in PATH_INFO:
1280 # - project name
1281 # - action
1282 # - hash_parent or hash_parent_base:/file_parent
1283 # - hash or hash_base:/filename
1284 # - the snapshot_format as an appropriate suffix
1286 # When the script is the root DirectoryIndex for the domain,
1287 # $href here would be something like http://gitweb.example.com/
1288 # Thus, we strip any trailing / from $href, to spare us double
1289 # slashes in the final URL
1290 $href =~ s,/$,,;
1292 # Then add the project name, if present
1293 $href .= "/".esc_path_info($params{'project'});
1294 delete $params{'project'};
1296 # since we destructively absorb parameters, we keep this
1297 # boolean that remembers if we're handling a snapshot
1298 my $is_snapshot = $params{'action'} eq 'snapshot';
1300 # Summary just uses the project path URL, any other action is
1301 # added to the URL
1302 if (defined $params{'action'}) {
1303 $href .= "/".esc_path_info($params{'action'})
1304 unless $params{'action'} eq 'summary';
1305 delete $params{'action'};
1308 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1309 # stripping nonexistent or useless pieces
1310 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1311 || $params{'hash_parent'} || $params{'hash'});
1312 if (defined $params{'hash_base'}) {
1313 if (defined $params{'hash_parent_base'}) {
1314 $href .= esc_path_info($params{'hash_parent_base'});
1315 # skip the file_parent if it's the same as the file_name
1316 if (defined $params{'file_parent'}) {
1317 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1318 delete $params{'file_parent'};
1319 } elsif ($params{'file_parent'} !~ /\.\./) {
1320 $href .= ":/".esc_path_info($params{'file_parent'});
1321 delete $params{'file_parent'};
1324 $href .= "..";
1325 delete $params{'hash_parent'};
1326 delete $params{'hash_parent_base'};
1327 } elsif (defined $params{'hash_parent'}) {
1328 $href .= esc_path_info($params{'hash_parent'}). "..";
1329 delete $params{'hash_parent'};
1332 $href .= esc_path_info($params{'hash_base'});
1333 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1334 $href .= ":/".esc_path_info($params{'file_name'});
1335 delete $params{'file_name'};
1337 delete $params{'hash'};
1338 delete $params{'hash_base'};
1339 } elsif (defined $params{'hash'}) {
1340 $href .= esc_path_info($params{'hash'});
1341 delete $params{'hash'};
1344 # If the action was a snapshot, we can absorb the
1345 # snapshot_format parameter too
1346 if ($is_snapshot) {
1347 my $fmt = $params{'snapshot_format'};
1348 # snapshot_format should always be defined when href()
1349 # is called, but just in case some code forgets, we
1350 # fall back to the default
1351 $fmt ||= $snapshot_fmts[0];
1352 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1353 delete $params{'snapshot_format'};
1357 # now encode the parameters explicitly
1358 my @result = ();
1359 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1360 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1361 if (defined $params{$name}) {
1362 if (ref($params{$name}) eq "ARRAY") {
1363 foreach my $par (@{$params{$name}}) {
1364 push @result, $symbol . "=" . esc_param($par);
1366 } else {
1367 push @result, $symbol . "=" . esc_param($params{$name});
1371 $href .= "?" . join(';', @result) if scalar @result;
1373 # final transformation: trailing spaces must be escaped (URI-encoded)
1374 $href =~ s/(\s+)$/CGI::escape($1)/e;
1376 if ($params{-anchor}) {
1377 $href .= "#".esc_param($params{-anchor});
1380 return $href;
1384 ## ======================================================================
1385 ## validation, quoting/unquoting and escaping
1387 sub validate_action {
1388 my $input = shift || return undef;
1389 return undef unless exists $actions{$input};
1390 return $input;
1393 sub validate_project {
1394 my $input = shift || return undef;
1395 if (!validate_pathname($input) ||
1396 !(-d "$projectroot/$input") ||
1397 !check_export_ok("$projectroot/$input") ||
1398 ($strict_export && !project_in_list($input))) {
1399 return undef;
1400 } else {
1401 return $input;
1405 sub validate_pathname {
1406 my $input = shift || return undef;
1408 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1409 # at the beginning, at the end, and between slashes.
1410 # also this catches doubled slashes
1411 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1412 return undef;
1414 # no null characters
1415 if ($input =~ m!\0!) {
1416 return undef;
1418 return $input;
1421 sub validate_refname {
1422 my $input = shift || return undef;
1424 # textual hashes are O.K.
1425 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1426 return $input;
1428 # it must be correct pathname
1429 $input = validate_pathname($input)
1430 or return undef;
1431 # restrictions on ref name according to git-check-ref-format
1432 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1433 return undef;
1435 return $input;
1438 # decode sequences of octets in utf8 into Perl's internal form,
1439 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1440 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1441 sub to_utf8 {
1442 my $str = shift;
1443 return undef unless defined $str;
1444 if (utf8::valid($str)) {
1445 utf8::decode($str);
1446 return $str;
1447 } else {
1448 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1452 # quote unsafe chars, but keep the slash, even when it's not
1453 # correct, but quoted slashes look too horrible in bookmarks
1454 sub esc_param {
1455 my $str = shift;
1456 return undef unless defined $str;
1457 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1458 $str =~ s/ /\+/g;
1459 return $str;
1462 # the quoting rules for path_info fragment are slightly different
1463 sub esc_path_info {
1464 my $str = shift;
1465 return undef unless defined $str;
1467 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1468 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1470 return $str;
1473 # quote unsafe chars in whole URL, so some characters cannot be quoted
1474 sub esc_url {
1475 my $str = shift;
1476 return undef unless defined $str;
1477 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1478 $str =~ s/ /\+/g;
1479 return $str;
1482 # quote unsafe characters in HTML attributes
1483 sub esc_attr {
1485 # for XHTML conformance escaping '"' to '&quot;' is not enough
1486 return esc_html(@_);
1489 # replace invalid utf8 character with SUBSTITUTION sequence
1490 sub esc_html {
1491 my $str = shift;
1492 my %opts = @_;
1494 return undef unless defined $str;
1496 $str = to_utf8($str);
1497 $str = $cgi->escapeHTML($str);
1498 if ($opts{'-nbsp'}) {
1499 $str =~ s/ /&nbsp;/g;
1501 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1502 return $str;
1505 # quote control characters and escape filename to HTML
1506 sub esc_path {
1507 my $str = shift;
1508 my %opts = @_;
1510 return undef unless defined $str;
1512 $str = to_utf8($str);
1513 $str = $cgi->escapeHTML($str);
1514 if ($opts{'-nbsp'}) {
1515 $str =~ s/ /&nbsp;/g;
1517 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1518 return $str;
1521 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1522 sub sanitize {
1523 my $str = shift;
1525 return undef unless defined $str;
1527 $str = to_utf8($str);
1528 $str =~ s|([[:cntrl:]])|($1 =~ /[\t\n\r]/ ? $1 : quot_cec($1))|eg;
1529 return $str;
1532 # Make control characters "printable", using character escape codes (CEC)
1533 sub quot_cec {
1534 my $cntrl = shift;
1535 my %opts = @_;
1536 my %es = ( # character escape codes, aka escape sequences
1537 "\t" => '\t', # tab (HT)
1538 "\n" => '\n', # line feed (LF)
1539 "\r" => '\r', # carrige return (CR)
1540 "\f" => '\f', # form feed (FF)
1541 "\b" => '\b', # backspace (BS)
1542 "\a" => '\a', # alarm (bell) (BEL)
1543 "\e" => '\e', # escape (ESC)
1544 "\013" => '\v', # vertical tab (VT)
1545 "\000" => '\0', # nul character (NUL)
1547 my $chr = ( (exists $es{$cntrl})
1548 ? $es{$cntrl}
1549 : sprintf('\%2x', ord($cntrl)) );
1550 if ($opts{-nohtml}) {
1551 return $chr;
1552 } else {
1553 return "<span class=\"cntrl\">$chr</span>";
1557 # Alternatively use unicode control pictures codepoints,
1558 # Unicode "printable representation" (PR)
1559 sub quot_upr {
1560 my $cntrl = shift;
1561 my %opts = @_;
1563 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1564 if ($opts{-nohtml}) {
1565 return $chr;
1566 } else {
1567 return "<span class=\"cntrl\">$chr</span>";
1571 # git may return quoted and escaped filenames
1572 sub unquote {
1573 my $str = shift;
1575 sub unq {
1576 my $seq = shift;
1577 my %es = ( # character escape codes, aka escape sequences
1578 't' => "\t", # tab (HT, TAB)
1579 'n' => "\n", # newline (NL)
1580 'r' => "\r", # return (CR)
1581 'f' => "\f", # form feed (FF)
1582 'b' => "\b", # backspace (BS)
1583 'a' => "\a", # alarm (bell) (BEL)
1584 'e' => "\e", # escape (ESC)
1585 'v' => "\013", # vertical tab (VT)
1588 if ($seq =~ m/^[0-7]{1,3}$/) {
1589 # octal char sequence
1590 return chr(oct($seq));
1591 } elsif (exists $es{$seq}) {
1592 # C escape sequence, aka character escape code
1593 return $es{$seq};
1595 # quoted ordinary character
1596 return $seq;
1599 if ($str =~ m/^"(.*)"$/) {
1600 # needs unquoting
1601 $str = $1;
1602 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1604 return $str;
1607 # escape tabs (convert tabs to spaces)
1608 sub untabify {
1609 my $line = shift;
1611 while ((my $pos = index($line, "\t")) != -1) {
1612 if (my $count = (8 - ($pos % 8))) {
1613 my $spaces = ' ' x $count;
1614 $line =~ s/\t/$spaces/;
1618 return $line;
1621 sub project_in_list {
1622 my $project = shift;
1623 my @list = git_get_projects_list();
1624 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1627 ## ----------------------------------------------------------------------
1628 ## HTML aware string manipulation
1630 # Try to chop given string on a word boundary between position
1631 # $len and $len+$add_len. If there is no word boundary there,
1632 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1633 # (marking chopped part) would be longer than given string.
1634 sub chop_str {
1635 my $str = shift;
1636 my $len = shift;
1637 my $add_len = shift || 10;
1638 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1640 # Make sure perl knows it is utf8 encoded so we don't
1641 # cut in the middle of a utf8 multibyte char.
1642 $str = to_utf8($str);
1644 # allow only $len chars, but don't cut a word if it would fit in $add_len
1645 # if it doesn't fit, cut it if it's still longer than the dots we would add
1646 # remove chopped character entities entirely
1648 # when chopping in the middle, distribute $len into left and right part
1649 # return early if chopping wouldn't make string shorter
1650 if ($where eq 'center') {
1651 return $str if ($len + 5 >= length($str)); # filler is length 5
1652 $len = int($len/2);
1653 } else {
1654 return $str if ($len + 4 >= length($str)); # filler is length 4
1657 # regexps: ending and beginning with word part up to $add_len
1658 my $endre = qr/.{$len}\w{0,$add_len}/;
1659 my $begre = qr/\w{0,$add_len}.{$len}/;
1661 if ($where eq 'left') {
1662 $str =~ m/^(.*?)($begre)$/;
1663 my ($lead, $body) = ($1, $2);
1664 if (length($lead) > 4) {
1665 $lead = " ...";
1667 return "$lead$body";
1669 } elsif ($where eq 'center') {
1670 $str =~ m/^($endre)(.*)$/;
1671 my ($left, $str) = ($1, $2);
1672 $str =~ m/^(.*?)($begre)$/;
1673 my ($mid, $right) = ($1, $2);
1674 if (length($mid) > 5) {
1675 $mid = " ... ";
1677 return "$left$mid$right";
1679 } else {
1680 $str =~ m/^($endre)(.*)$/;
1681 my $body = $1;
1682 my $tail = $2;
1683 if (length($tail) > 4) {
1684 $tail = "... ";
1686 return "$body$tail";
1690 # takes the same arguments as chop_str, but also wraps a <span> around the
1691 # result with a title attribute if it does get chopped. Additionally, the
1692 # string is HTML-escaped.
1693 sub chop_and_escape_str {
1694 my ($str) = @_;
1696 my $chopped = chop_str(@_);
1697 if ($chopped eq $str) {
1698 return esc_html($chopped);
1699 } else {
1700 $str =~ s/[[:cntrl:]]/?/g;
1701 return $cgi->span({-title=>$str}, esc_html($chopped));
1705 ## ----------------------------------------------------------------------
1706 ## functions returning short strings
1708 # CSS class for given age value (in seconds)
1709 sub age_class {
1710 my $age = shift;
1712 if (!defined $age) {
1713 return "noage";
1714 } elsif ($age < 60*60*2) {
1715 return "age0";
1716 } elsif ($age < 60*60*24*2) {
1717 return "age1";
1718 } else {
1719 return "age2";
1723 # convert age in seconds to "nn units ago" string
1724 sub age_string {
1725 my $age = shift;
1726 my $age_str;
1728 if ($age > 60*60*24*365*2) {
1729 $age_str = (int $age/60/60/24/365);
1730 $age_str .= " years ago";
1731 } elsif ($age > 60*60*24*(365/12)*2) {
1732 $age_str = int $age/60/60/24/(365/12);
1733 $age_str .= " months ago";
1734 } elsif ($age > 60*60*24*7*2) {
1735 $age_str = int $age/60/60/24/7;
1736 $age_str .= " weeks ago";
1737 } elsif ($age > 60*60*24*2) {
1738 $age_str = int $age/60/60/24;
1739 $age_str .= " days ago";
1740 } elsif ($age > 60*60*2) {
1741 $age_str = int $age/60/60;
1742 $age_str .= " hours ago";
1743 } elsif ($age > 60*2) {
1744 $age_str = int $age/60;
1745 $age_str .= " min ago";
1746 } elsif ($age > 2) {
1747 $age_str = int $age;
1748 $age_str .= " sec ago";
1749 } else {
1750 $age_str .= " right now";
1752 return $age_str;
1755 use constant {
1756 S_IFINVALID => 0030000,
1757 S_IFGITLINK => 0160000,
1760 # submodule/subproject, a commit object reference
1761 sub S_ISGITLINK {
1762 my $mode = shift;
1764 return (($mode & S_IFMT) == S_IFGITLINK)
1767 # convert file mode in octal to symbolic file mode string
1768 sub mode_str {
1769 my $mode = oct shift;
1771 if (S_ISGITLINK($mode)) {
1772 return 'm---------';
1773 } elsif (S_ISDIR($mode & S_IFMT)) {
1774 return 'drwxr-xr-x';
1775 } elsif (S_ISLNK($mode)) {
1776 return 'lrwxrwxrwx';
1777 } elsif (S_ISREG($mode)) {
1778 # git cares only about the executable bit
1779 if ($mode & S_IXUSR) {
1780 return '-rwxr-xr-x';
1781 } else {
1782 return '-rw-r--r--';
1784 } else {
1785 return '----------';
1789 # convert file mode in octal to file type string
1790 sub file_type {
1791 my $mode = shift;
1793 if ($mode !~ m/^[0-7]+$/) {
1794 return $mode;
1795 } else {
1796 $mode = oct $mode;
1799 if (S_ISGITLINK($mode)) {
1800 return "submodule";
1801 } elsif (S_ISDIR($mode & S_IFMT)) {
1802 return "directory";
1803 } elsif (S_ISLNK($mode)) {
1804 return "symlink";
1805 } elsif (S_ISREG($mode)) {
1806 return "file";
1807 } else {
1808 return "unknown";
1812 # convert file mode in octal to file type description string
1813 sub file_type_long {
1814 my $mode = shift;
1816 if ($mode !~ m/^[0-7]+$/) {
1817 return $mode;
1818 } else {
1819 $mode = oct $mode;
1822 if (S_ISGITLINK($mode)) {
1823 return "submodule";
1824 } elsif (S_ISDIR($mode & S_IFMT)) {
1825 return "directory";
1826 } elsif (S_ISLNK($mode)) {
1827 return "symlink";
1828 } elsif (S_ISREG($mode)) {
1829 if ($mode & S_IXUSR) {
1830 return "executable";
1831 } else {
1832 return "file";
1834 } else {
1835 return "unknown";
1840 ## ----------------------------------------------------------------------
1841 ## functions returning short HTML fragments, or transforming HTML fragments
1842 ## which don't belong to other sections
1844 # format line of commit message.
1845 sub format_log_line_html {
1846 my $line = shift;
1848 $line = esc_html($line, -nbsp=>1);
1849 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1850 $cgi->a({-href => href(action=>"object", hash=>$1),
1851 -class => "text"}, $1);
1852 }eg;
1854 return $line;
1857 # format marker of refs pointing to given object
1859 # the destination action is chosen based on object type and current context:
1860 # - for annotated tags, we choose the tag view unless it's the current view
1861 # already, in which case we go to shortlog view
1862 # - for other refs, we keep the current view if we're in history, shortlog or
1863 # log view, and select shortlog otherwise
1864 sub format_ref_marker {
1865 my ($refs, $id) = @_;
1866 my $markers = '';
1868 if (defined $refs->{$id}) {
1869 foreach my $ref (@{$refs->{$id}}) {
1870 # this code exploits the fact that non-lightweight tags are the
1871 # only indirect objects, and that they are the only objects for which
1872 # we want to use tag instead of shortlog as action
1873 my ($type, $name) = qw();
1874 my $indirect = ($ref =~ s/\^\{\}$//);
1875 # e.g. tags/v2.6.11 or heads/next
1876 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1877 $type = $1;
1878 $name = $2;
1879 } else {
1880 $type = "ref";
1881 $name = $ref;
1884 my $class = $type;
1885 $class .= " indirect" if $indirect;
1887 my $dest_action = "shortlog";
1889 if ($indirect) {
1890 $dest_action = "tag" unless $action eq "tag";
1891 } elsif ($action =~ /^(history|(short)?log)$/) {
1892 $dest_action = $action;
1895 my $dest = "";
1896 $dest .= "refs/" unless $ref =~ m!^refs/!;
1897 $dest .= $ref;
1899 my $link = $cgi->a({
1900 -href => href(
1901 action=>$dest_action,
1902 hash=>$dest
1903 )}, $name);
1905 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
1906 $link . "</span>";
1910 if ($markers) {
1911 return ' <span class="refs">'. $markers . '</span>';
1912 } else {
1913 return "";
1917 # format, perhaps shortened and with markers, title line
1918 sub format_subject_html {
1919 my ($long, $short, $href, $extra) = @_;
1920 $extra = '' unless defined($extra);
1922 if (length($short) < length($long)) {
1923 $long =~ s/[[:cntrl:]]/?/g;
1924 return $cgi->a({-href => $href, -class => "list subject",
1925 -title => to_utf8($long)},
1926 esc_html($short)) . $extra;
1927 } else {
1928 return $cgi->a({-href => $href, -class => "list subject"},
1929 esc_html($long)) . $extra;
1933 # Rather than recomputing the url for an email multiple times, we cache it
1934 # after the first hit. This gives a visible benefit in views where the avatar
1935 # for the same email is used repeatedly (e.g. shortlog).
1936 # The cache is shared by all avatar engines (currently gravatar only), which
1937 # are free to use it as preferred. Since only one avatar engine is used for any
1938 # given page, there's no risk for cache conflicts.
1939 our %avatar_cache = ();
1941 # Compute the picon url for a given email, by using the picon search service over at
1942 # http://www.cs.indiana.edu/picons/search.html
1943 sub picon_url {
1944 my $email = lc shift;
1945 if (!$avatar_cache{$email}) {
1946 my ($user, $domain) = split('@', $email);
1947 $avatar_cache{$email} =
1948 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1949 "$domain/$user/" .
1950 "users+domains+unknown/up/single";
1952 return $avatar_cache{$email};
1955 # Compute the gravatar url for a given email, if it's not in the cache already.
1956 # Gravatar stores only the part of the URL before the size, since that's the
1957 # one computationally more expensive. This also allows reuse of the cache for
1958 # different sizes (for this particular engine).
1959 sub gravatar_url {
1960 my $email = lc shift;
1961 my $size = shift;
1962 $avatar_cache{$email} ||=
1963 "http://www.gravatar.com/avatar/" .
1964 Digest::MD5::md5_hex($email) . "?s=";
1965 return $avatar_cache{$email} . $size;
1968 # Insert an avatar for the given $email at the given $size if the feature
1969 # is enabled.
1970 sub git_get_avatar {
1971 my ($email, %opts) = @_;
1972 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1973 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1974 $opts{-size} ||= 'default';
1975 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1976 my $url = "";
1977 if ($git_avatar eq 'gravatar') {
1978 $url = gravatar_url($email, $size);
1979 } elsif ($git_avatar eq 'picon') {
1980 $url = picon_url($email);
1982 # Other providers can be added by extending the if chain, defining $url
1983 # as needed. If no variant puts something in $url, we assume avatars
1984 # are completely disabled/unavailable.
1985 if ($url) {
1986 return $pre_white .
1987 "<img width=\"$size\" " .
1988 "class=\"avatar\" " .
1989 "src=\"".esc_url($url)."\" " .
1990 "alt=\"\" " .
1991 "/>" . $post_white;
1992 } else {
1993 return "";
1997 sub format_search_author {
1998 my ($author, $searchtype, $displaytext) = @_;
1999 my $have_search = gitweb_check_feature('search');
2001 if ($have_search) {
2002 my $performed = "";
2003 if ($searchtype eq 'author') {
2004 $performed = "authored";
2005 } elsif ($searchtype eq 'committer') {
2006 $performed = "committed";
2009 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2010 searchtext=>$author,
2011 searchtype=>$searchtype), class=>"list",
2012 title=>"Search for commits $performed by $author"},
2013 $displaytext);
2015 } else {
2016 return $displaytext;
2020 # format the author name of the given commit with the given tag
2021 # the author name is chopped and escaped according to the other
2022 # optional parameters (see chop_str).
2023 sub format_author_html {
2024 my $tag = shift;
2025 my $co = shift;
2026 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2027 return "<$tag class=\"author\">" .
2028 format_search_author($co->{'author_name'}, "author",
2029 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2030 $author) .
2031 "</$tag>";
2034 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2035 sub format_git_diff_header_line {
2036 my $line = shift;
2037 my $diffinfo = shift;
2038 my ($from, $to) = @_;
2040 if ($diffinfo->{'nparents'}) {
2041 # combined diff
2042 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2043 if ($to->{'href'}) {
2044 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2045 esc_path($to->{'file'}));
2046 } else { # file was deleted (no href)
2047 $line .= esc_path($to->{'file'});
2049 } else {
2050 # "ordinary" diff
2051 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2052 if ($from->{'href'}) {
2053 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2054 'a/' . esc_path($from->{'file'}));
2055 } else { # file was added (no href)
2056 $line .= 'a/' . esc_path($from->{'file'});
2058 $line .= ' ';
2059 if ($to->{'href'}) {
2060 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2061 'b/' . esc_path($to->{'file'}));
2062 } else { # file was deleted
2063 $line .= 'b/' . esc_path($to->{'file'});
2067 return "<div class=\"diff header\">$line</div>\n";
2070 # format extended diff header line, before patch itself
2071 sub format_extended_diff_header_line {
2072 my $line = shift;
2073 my $diffinfo = shift;
2074 my ($from, $to) = @_;
2076 # match <path>
2077 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2078 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2079 esc_path($from->{'file'}));
2081 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2082 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2083 esc_path($to->{'file'}));
2085 # match single <mode>
2086 if ($line =~ m/\s(\d{6})$/) {
2087 $line .= '<span class="info"> (' .
2088 file_type_long($1) .
2089 ')</span>';
2091 # match <hash>
2092 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2093 # can match only for combined diff
2094 $line = 'index ';
2095 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2096 if ($from->{'href'}[$i]) {
2097 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2098 -class=>"hash"},
2099 substr($diffinfo->{'from_id'}[$i],0,7));
2100 } else {
2101 $line .= '0' x 7;
2103 # separator
2104 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2106 $line .= '..';
2107 if ($to->{'href'}) {
2108 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2109 substr($diffinfo->{'to_id'},0,7));
2110 } else {
2111 $line .= '0' x 7;
2114 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2115 # can match only for ordinary diff
2116 my ($from_link, $to_link);
2117 if ($from->{'href'}) {
2118 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2119 substr($diffinfo->{'from_id'},0,7));
2120 } else {
2121 $from_link = '0' x 7;
2123 if ($to->{'href'}) {
2124 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2125 substr($diffinfo->{'to_id'},0,7));
2126 } else {
2127 $to_link = '0' x 7;
2129 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2130 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2133 return $line . "<br/>\n";
2136 # format from-file/to-file diff header
2137 sub format_diff_from_to_header {
2138 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2139 my $line;
2140 my $result = '';
2142 $line = $from_line;
2143 #assert($line =~ m/^---/) if DEBUG;
2144 # no extra formatting for "^--- /dev/null"
2145 if (! $diffinfo->{'nparents'}) {
2146 # ordinary (single parent) diff
2147 if ($line =~ m!^--- "?a/!) {
2148 if ($from->{'href'}) {
2149 $line = '--- a/' .
2150 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2151 esc_path($from->{'file'}));
2152 } else {
2153 $line = '--- a/' .
2154 esc_path($from->{'file'});
2157 $result .= qq!<div class="diff from_file">$line</div>\n!;
2159 } else {
2160 # combined diff (merge commit)
2161 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2162 if ($from->{'href'}[$i]) {
2163 $line = '--- ' .
2164 $cgi->a({-href=>href(action=>"blobdiff",
2165 hash_parent=>$diffinfo->{'from_id'}[$i],
2166 hash_parent_base=>$parents[$i],
2167 file_parent=>$from->{'file'}[$i],
2168 hash=>$diffinfo->{'to_id'},
2169 hash_base=>$hash,
2170 file_name=>$to->{'file'}),
2171 -class=>"path",
2172 -title=>"diff" . ($i+1)},
2173 $i+1) .
2174 '/' .
2175 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2176 esc_path($from->{'file'}[$i]));
2177 } else {
2178 $line = '--- /dev/null';
2180 $result .= qq!<div class="diff from_file">$line</div>\n!;
2184 $line = $to_line;
2185 #assert($line =~ m/^\+\+\+/) if DEBUG;
2186 # no extra formatting for "^+++ /dev/null"
2187 if ($line =~ m!^\+\+\+ "?b/!) {
2188 if ($to->{'href'}) {
2189 $line = '+++ b/' .
2190 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2191 esc_path($to->{'file'}));
2192 } else {
2193 $line = '+++ b/' .
2194 esc_path($to->{'file'});
2197 $result .= qq!<div class="diff to_file">$line</div>\n!;
2199 return $result;
2202 # create note for patch simplified by combined diff
2203 sub format_diff_cc_simplified {
2204 my ($diffinfo, @parents) = @_;
2205 my $result = '';
2207 $result .= "<div class=\"diff header\">" .
2208 "diff --cc ";
2209 if (!is_deleted($diffinfo)) {
2210 $result .= $cgi->a({-href => href(action=>"blob",
2211 hash_base=>$hash,
2212 hash=>$diffinfo->{'to_id'},
2213 file_name=>$diffinfo->{'to_file'}),
2214 -class => "path"},
2215 esc_path($diffinfo->{'to_file'}));
2216 } else {
2217 $result .= esc_path($diffinfo->{'to_file'});
2219 $result .= "</div>\n" . # class="diff header"
2220 "<div class=\"diff nodifferences\">" .
2221 "Simple merge" .
2222 "</div>\n"; # class="diff nodifferences"
2224 return $result;
2227 sub diff_line_class {
2228 my ($line, $from, $to) = @_;
2230 # ordinary diff
2231 my $num_sign = 1;
2232 # combined diff
2233 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2234 $num_sign = scalar @{$from->{'href'}};
2237 my @diff_line_classifier = (
2238 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2239 { regexp => qr/^\\/, class => "incomplete" },
2240 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2241 # classifier for context must come before classifier add/rem,
2242 # or we would have to use more complicated regexp, for example
2243 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2244 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2245 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2247 for my $clsfy (@diff_line_classifier) {
2248 return $clsfy->{'class'}
2249 if ($line =~ $clsfy->{'regexp'});
2252 # fallback
2253 return "";
2256 # assumes that $from and $to are defined and correctly filled,
2257 # and that $line holds a line of chunk header for unified diff
2258 sub format_unidiff_chunk_header {
2259 my ($line, $from, $to) = @_;
2261 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2262 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2264 $from_lines = 0 unless defined $from_lines;
2265 $to_lines = 0 unless defined $to_lines;
2267 if ($from->{'href'}) {
2268 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2269 -class=>"list"}, $from_text);
2271 if ($to->{'href'}) {
2272 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2273 -class=>"list"}, $to_text);
2275 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2276 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2277 return $line;
2280 # assumes that $from and $to are defined and correctly filled,
2281 # and that $line holds a line of chunk header for combined diff
2282 sub format_cc_diff_chunk_header {
2283 my ($line, $from, $to) = @_;
2285 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2286 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2288 @from_text = split(' ', $ranges);
2289 for (my $i = 0; $i < @from_text; ++$i) {
2290 ($from_start[$i], $from_nlines[$i]) =
2291 (split(',', substr($from_text[$i], 1)), 0);
2294 $to_text = pop @from_text;
2295 $to_start = pop @from_start;
2296 $to_nlines = pop @from_nlines;
2298 $line = "<span class=\"chunk_info\">$prefix ";
2299 for (my $i = 0; $i < @from_text; ++$i) {
2300 if ($from->{'href'}[$i]) {
2301 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2302 -class=>"list"}, $from_text[$i]);
2303 } else {
2304 $line .= $from_text[$i];
2306 $line .= " ";
2308 if ($to->{'href'}) {
2309 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2310 -class=>"list"}, $to_text);
2311 } else {
2312 $line .= $to_text;
2314 $line .= " $prefix</span>" .
2315 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2316 return $line;
2319 # process patch (diff) line (not to be used for diff headers),
2320 # returning class and HTML-formatted (but not wrapped) line
2321 sub process_diff_line {
2322 my $line = shift;
2323 my ($from, $to) = @_;
2325 my $diff_class = diff_line_class($line, $from, $to);
2327 chomp $line;
2328 $line = untabify($line);
2330 if ($from && $to && $line =~ m/^\@{2} /) {
2331 $line = format_unidiff_chunk_header($line, $from, $to);
2332 return $diff_class, $line;
2334 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2335 $line = format_cc_diff_chunk_header($line, $from, $to);
2336 return $diff_class, $line;
2339 return $diff_class, esc_html($line, -nbsp=>1);
2342 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2343 # linked. Pass the hash of the tree/commit to snapshot.
2344 sub format_snapshot_links {
2345 my ($hash) = @_;
2346 my $num_fmts = @snapshot_fmts;
2347 if ($num_fmts > 1) {
2348 # A parenthesized list of links bearing format names.
2349 # e.g. "snapshot (_tar.gz_ _zip_)"
2350 return "snapshot (" . join(' ', map
2351 $cgi->a({
2352 -href => href(
2353 action=>"snapshot",
2354 hash=>$hash,
2355 snapshot_format=>$_
2357 }, $known_snapshot_formats{$_}{'display'})
2358 , @snapshot_fmts) . ")";
2359 } elsif ($num_fmts == 1) {
2360 # A single "snapshot" link whose tooltip bears the format name.
2361 # i.e. "_snapshot_"
2362 my ($fmt) = @snapshot_fmts;
2363 return
2364 $cgi->a({
2365 -href => href(
2366 action=>"snapshot",
2367 hash=>$hash,
2368 snapshot_format=>$fmt
2370 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2371 }, "snapshot");
2372 } else { # $num_fmts == 0
2373 return undef;
2377 ## ......................................................................
2378 ## functions returning values to be passed, perhaps after some
2379 ## transformation, to other functions; e.g. returning arguments to href()
2381 # returns hash to be passed to href to generate gitweb URL
2382 # in -title key it returns description of link
2383 sub get_feed_info {
2384 my $format = shift || 'Atom';
2385 my %res = (action => lc($format));
2387 # feed links are possible only for project views
2388 return unless (defined $project);
2389 # some views should link to OPML, or to generic project feed,
2390 # or don't have specific feed yet (so they should use generic)
2391 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2393 my $branch;
2394 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2395 # from tag links; this also makes possible to detect branch links
2396 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2397 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2398 $branch = $1;
2400 # find log type for feed description (title)
2401 my $type = 'log';
2402 if (defined $file_name) {
2403 $type = "history of $file_name";
2404 $type .= "/" if ($action eq 'tree');
2405 $type .= " on '$branch'" if (defined $branch);
2406 } else {
2407 $type = "log of $branch" if (defined $branch);
2410 $res{-title} = $type;
2411 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2412 $res{'file_name'} = $file_name;
2414 return %res;
2417 ## ----------------------------------------------------------------------
2418 ## git utility subroutines, invoking git commands
2420 # returns path to the core git executable and the --git-dir parameter as list
2421 sub git_cmd {
2422 $number_of_git_cmds++;
2423 return $GIT, '--git-dir='.$git_dir;
2426 # quote the given arguments for passing them to the shell
2427 # quote_command("command", "arg 1", "arg with ' and ! characters")
2428 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2429 # Try to avoid using this function wherever possible.
2430 sub quote_command {
2431 return join(' ',
2432 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2435 # get HEAD ref of given project as hash
2436 sub git_get_head_hash {
2437 return git_get_full_hash(shift, 'HEAD');
2440 sub git_get_full_hash {
2441 return git_get_hash(@_);
2444 sub git_get_short_hash {
2445 return git_get_hash(@_, '--short=7');
2448 sub git_get_hash {
2449 my ($project, $hash, @options) = @_;
2450 my $o_git_dir = $git_dir;
2451 my $retval = undef;
2452 $git_dir = "$projectroot/$project";
2453 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2454 '--verify', '-q', @options, $hash) {
2455 $retval = <$fd>;
2456 chomp $retval if defined $retval;
2457 close $fd;
2459 if (defined $o_git_dir) {
2460 $git_dir = $o_git_dir;
2462 return $retval;
2465 # get type of given object
2466 sub git_get_type {
2467 my $hash = shift;
2469 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2470 my $type = <$fd>;
2471 close $fd or return;
2472 chomp $type;
2473 return $type;
2476 # repository configuration
2477 our $config_file = '';
2478 our %config;
2480 # store multiple values for single key as anonymous array reference
2481 # single values stored directly in the hash, not as [ <value> ]
2482 sub hash_set_multi {
2483 my ($hash, $key, $value) = @_;
2485 if (!exists $hash->{$key}) {
2486 $hash->{$key} = $value;
2487 } elsif (!ref $hash->{$key}) {
2488 $hash->{$key} = [ $hash->{$key}, $value ];
2489 } else {
2490 push @{$hash->{$key}}, $value;
2494 # return hash of git project configuration
2495 # optionally limited to some section, e.g. 'gitweb'
2496 sub git_parse_project_config {
2497 my $section_regexp = shift;
2498 my %config;
2500 local $/ = "\0";
2502 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2503 or return;
2505 while (my $keyval = <$fh>) {
2506 chomp $keyval;
2507 my ($key, $value) = split(/\n/, $keyval, 2);
2509 hash_set_multi(\%config, $key, $value)
2510 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2512 close $fh;
2514 return %config;
2517 # convert config value to boolean: 'true' or 'false'
2518 # no value, number > 0, 'true' and 'yes' values are true
2519 # rest of values are treated as false (never as error)
2520 sub config_to_bool {
2521 my $val = shift;
2523 return 1 if !defined $val; # section.key
2525 # strip leading and trailing whitespace
2526 $val =~ s/^\s+//;
2527 $val =~ s/\s+$//;
2529 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2530 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2533 # convert config value to simple decimal number
2534 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2535 # to be multiplied by 1024, 1048576, or 1073741824
2536 sub config_to_int {
2537 my $val = shift;
2539 # strip leading and trailing whitespace
2540 $val =~ s/^\s+//;
2541 $val =~ s/\s+$//;
2543 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2544 $unit = lc($unit);
2545 # unknown unit is treated as 1
2546 return $num * ($unit eq 'g' ? 1073741824 :
2547 $unit eq 'm' ? 1048576 :
2548 $unit eq 'k' ? 1024 : 1);
2550 return $val;
2553 # convert config value to array reference, if needed
2554 sub config_to_multi {
2555 my $val = shift;
2557 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2560 sub git_get_project_config {
2561 my ($key, $type) = @_;
2563 return unless defined $git_dir;
2565 # key sanity check
2566 return unless ($key);
2567 # only subsection, if exists, is case sensitive,
2568 # and not lowercased by 'git config -z -l'
2569 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2570 $key = join(".", lc($hi), $mi, lc($lo));
2571 } else {
2572 $key = lc($key);
2574 $key =~ s/^gitweb\.//;
2575 return if ($key =~ m/\W/);
2577 # type sanity check
2578 if (defined $type) {
2579 $type =~ s/^--//;
2580 $type = undef
2581 unless ($type eq 'bool' || $type eq 'int');
2584 # get config
2585 if (!defined $config_file ||
2586 $config_file ne "$git_dir/config") {
2587 %config = git_parse_project_config('gitweb');
2588 $config_file = "$git_dir/config";
2591 # check if config variable (key) exists
2592 return unless exists $config{"gitweb.$key"};
2594 # ensure given type
2595 if (!defined $type) {
2596 return $config{"gitweb.$key"};
2597 } elsif ($type eq 'bool') {
2598 # backward compatibility: 'git config --bool' returns true/false
2599 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2600 } elsif ($type eq 'int') {
2601 return config_to_int($config{"gitweb.$key"});
2603 return $config{"gitweb.$key"};
2606 # get hash of given path at given ref
2607 sub git_get_hash_by_path {
2608 my $base = shift;
2609 my $path = shift || return undef;
2610 my $type = shift;
2612 $path =~ s,/+$,,;
2614 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2615 or die_error(500, "Open git-ls-tree failed");
2616 my $line = <$fd>;
2617 close $fd or return undef;
2619 if (!defined $line) {
2620 # there is no tree or hash given by $path at $base
2621 return undef;
2624 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2625 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2626 if (defined $type && $type ne $2) {
2627 # type doesn't match
2628 return undef;
2630 return $3;
2633 # get path of entry with given hash at given tree-ish (ref)
2634 # used to get 'from' filename for combined diff (merge commit) for renames
2635 sub git_get_path_by_hash {
2636 my $base = shift || return;
2637 my $hash = shift || return;
2639 local $/ = "\0";
2641 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2642 or return undef;
2643 while (my $line = <$fd>) {
2644 chomp $line;
2646 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2647 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2648 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2649 close $fd;
2650 return $1;
2653 close $fd;
2654 return undef;
2657 ## ......................................................................
2658 ## git utility functions, directly accessing git repository
2660 # get the value of config variable either from file named as the variable
2661 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2662 # configuration variable in the repository config file.
2663 sub git_get_file_or_project_config {
2664 my ($path, $name) = @_;
2666 $git_dir = "$projectroot/$path";
2667 open my $fd, '<', "$git_dir/$name"
2668 or return git_get_project_config($name);
2669 my $conf = <$fd>;
2670 close $fd;
2671 if (defined $conf) {
2672 chomp $conf;
2674 return $conf;
2677 sub git_get_project_description {
2678 my $path = shift;
2679 return git_get_file_or_project_config($path, 'description');
2682 sub git_get_project_category {
2683 my $path = shift;
2684 return git_get_file_or_project_config($path, 'category');
2688 # supported formats:
2689 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2690 # - if its contents is a number, use it as tag weight,
2691 # - otherwise add a tag with weight 1
2692 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2693 # the same value multiple times increases tag weight
2694 # * `gitweb.ctag' multi-valued repo config variable
2695 sub git_get_project_ctags {
2696 my $project = shift;
2697 my $ctags = {};
2699 $git_dir = "$projectroot/$project";
2700 if (opendir my $dh, "$git_dir/ctags") {
2701 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2702 foreach my $tagfile (@files) {
2703 open my $ct, '<', $tagfile
2704 or next;
2705 my $val = <$ct>;
2706 chomp $val if $val;
2707 close $ct;
2709 (my $ctag = $tagfile) =~ s#.*/##;
2710 if ($val =~ /^\d+$/) {
2711 $ctags->{$ctag} = $val;
2712 } else {
2713 $ctags->{$ctag} = 1;
2716 closedir $dh;
2718 } elsif (open my $fh, '<', "$git_dir/ctags") {
2719 while (my $line = <$fh>) {
2720 chomp $line;
2721 $ctags->{$line}++ if $line;
2723 close $fh;
2725 } else {
2726 my $taglist = config_to_multi(git_get_project_config('ctag'));
2727 foreach my $tag (@$taglist) {
2728 $ctags->{$tag}++;
2732 return $ctags;
2735 # return hash, where keys are content tags ('ctags'),
2736 # and values are sum of weights of given tag in every project
2737 sub git_gather_all_ctags {
2738 my $projects = shift;
2739 my $ctags = {};
2741 foreach my $p (@$projects) {
2742 foreach my $ct (keys %{$p->{'ctags'}}) {
2743 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2747 return $ctags;
2750 sub git_populate_project_tagcloud {
2751 my $ctags = shift;
2753 # First, merge different-cased tags; tags vote on casing
2754 my %ctags_lc;
2755 foreach (keys %$ctags) {
2756 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2757 if (not $ctags_lc{lc $_}->{topcount}
2758 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2759 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2760 $ctags_lc{lc $_}->{topname} = $_;
2764 my $cloud;
2765 my $matched = $cgi->param('by_tag');
2766 if (eval { require HTML::TagCloud; 1; }) {
2767 $cloud = HTML::TagCloud->new;
2768 foreach my $ctag (sort keys %ctags_lc) {
2769 # Pad the title with spaces so that the cloud looks
2770 # less crammed.
2771 my $title = esc_html($ctags_lc{$ctag}->{topname});
2772 $title =~ s/ /&nbsp;/g;
2773 $title =~ s/^/&nbsp;/g;
2774 $title =~ s/$/&nbsp;/g;
2775 if (defined $matched && $matched eq $ctag) {
2776 $title = qq(<span class="match">$title</span>);
2778 $cloud->add($title, href(project=>undef, ctag=>$ctag),
2779 $ctags_lc{$ctag}->{count});
2781 } else {
2782 $cloud = {};
2783 foreach my $ctag (keys %ctags_lc) {
2784 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
2785 if (defined $matched && $matched eq $ctag) {
2786 $title = qq(<span class="match">$title</span>);
2788 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
2789 $cloud->{$ctag}{ctag} =
2790 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
2793 return $cloud;
2796 sub git_show_project_tagcloud {
2797 my ($cloud, $count) = @_;
2798 if (ref $cloud eq 'HTML::TagCloud') {
2799 return $cloud->html_and_css($count);
2800 } else {
2801 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
2802 return
2803 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
2804 join (', ', map {
2805 $cloud->{$_}->{'ctag'}
2806 } splice(@tags, 0, $count)) .
2807 '</div>';
2811 sub git_get_project_url_list {
2812 my $path = shift;
2814 $git_dir = "$projectroot/$path";
2815 open my $fd, '<', "$git_dir/cloneurl"
2816 or return wantarray ?
2817 @{ config_to_multi(git_get_project_config('url')) } :
2818 config_to_multi(git_get_project_config('url'));
2819 my @git_project_url_list = map { chomp; $_ } <$fd>;
2820 close $fd;
2822 return wantarray ? @git_project_url_list : \@git_project_url_list;
2825 sub git_get_projects_list {
2826 my $filter = shift || '';
2827 my @list;
2829 $filter =~ s/\.git$//;
2831 if (-d $projects_list) {
2832 # search in directory
2833 my $dir = $projects_list;
2834 # remove the trailing "/"
2835 $dir =~ s!/+$!!;
2836 my $pfxlen = length("$projects_list");
2837 my $pfxdepth = ($projects_list =~ tr!/!!);
2838 # when filtering, search only given subdirectory
2839 if ($filter) {
2840 $dir .= "/$filter";
2841 $dir =~ s!/+$!!;
2844 File::Find::find({
2845 follow_fast => 1, # follow symbolic links
2846 follow_skip => 2, # ignore duplicates
2847 dangling_symlinks => 0, # ignore dangling symlinks, silently
2848 wanted => sub {
2849 # global variables
2850 our $project_maxdepth;
2851 our $projectroot;
2852 # skip project-list toplevel, if we get it.
2853 return if (m!^[/.]$!);
2854 # only directories can be git repositories
2855 return unless (-d $_);
2856 # don't traverse too deep (Find is super slow on os x)
2857 # $project_maxdepth excludes depth of $projectroot
2858 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2859 $File::Find::prune = 1;
2860 return;
2863 my $path = substr($File::Find::name, $pfxlen + 1);
2864 # we check related file in $projectroot
2865 if (check_export_ok("$projectroot/$path")) {
2866 push @list, { path => $path };
2867 $File::Find::prune = 1;
2870 }, "$dir");
2872 } elsif (-f $projects_list) {
2873 # read from file(url-encoded):
2874 # 'git%2Fgit.git Linus+Torvalds'
2875 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2876 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2877 open my $fd, '<', $projects_list or return;
2878 PROJECT:
2879 while (my $line = <$fd>) {
2880 chomp $line;
2881 my ($path, $owner) = split ' ', $line;
2882 $path = unescape($path);
2883 $owner = unescape($owner);
2884 if (!defined $path) {
2885 next;
2887 # if $filter is rpovided, check if $path begins with $filter
2888 if ($filter && $path !~ m!^\Q$filter\E/!) {
2889 next;
2891 if (check_export_ok("$projectroot/$path")) {
2892 my $pr = {
2893 path => $path,
2894 owner => to_utf8($owner),
2896 push @list, $pr;
2899 close $fd;
2901 return @list;
2904 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
2905 # as side effects it sets 'forks' field to list of forks for forked projects
2906 sub filter_forks_from_projects_list {
2907 my $projects = shift;
2909 my %trie; # prefix tree of directories (path components)
2910 # generate trie out of those directories that might contain forks
2911 foreach my $pr (@$projects) {
2912 my $path = $pr->{'path'};
2913 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
2914 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
2915 next unless ($path); # skip '.git' repository: tests, git-instaweb
2916 next unless (-d $path); # containing directory exists
2917 $pr->{'forks'} = []; # there can be 0 or more forks of project
2919 # add to trie
2920 my @dirs = split('/', $path);
2921 # walk the trie, until either runs out of components or out of trie
2922 my $ref = \%trie;
2923 while (scalar @dirs &&
2924 exists($ref->{$dirs[0]})) {
2925 $ref = $ref->{shift @dirs};
2927 # create rest of trie structure from rest of components
2928 foreach my $dir (@dirs) {
2929 $ref = $ref->{$dir} = {};
2931 # create end marker, store $pr as a data
2932 $ref->{''} = $pr if (!exists $ref->{''});
2935 # filter out forks, by finding shortest prefix match for paths
2936 my @filtered;
2937 PROJECT:
2938 foreach my $pr (@$projects) {
2939 # trie lookup
2940 my $ref = \%trie;
2941 DIR:
2942 foreach my $dir (split('/', $pr->{'path'})) {
2943 if (exists $ref->{''}) {
2944 # found [shortest] prefix, is a fork - skip it
2945 push @{$ref->{''}{'forks'}}, $pr;
2946 next PROJECT;
2948 if (!exists $ref->{$dir}) {
2949 # not in trie, cannot have prefix, not a fork
2950 push @filtered, $pr;
2951 next PROJECT;
2953 # If the dir is there, we just walk one step down the trie.
2954 $ref = $ref->{$dir};
2956 # we ran out of trie
2957 # (shouldn't happen: it's either no match, or end marker)
2958 push @filtered, $pr;
2961 return @filtered;
2964 # note: fill_project_list_info must be run first,
2965 # for 'descr_long' and 'ctags' to be filled
2966 sub search_projects_list {
2967 my ($projlist, %opts) = @_;
2968 my $tagfilter = $opts{'tagfilter'};
2969 my $searchtext = $opts{'searchtext'};
2971 return @$projlist
2972 unless ($tagfilter || $searchtext);
2974 my @projects;
2975 PROJECT:
2976 foreach my $pr (@$projlist) {
2978 if ($tagfilter) {
2979 next unless ref($pr->{'ctags'}) eq 'HASH';
2980 next unless
2981 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
2984 if ($searchtext) {
2985 next unless
2986 $pr->{'path'} =~ /$searchtext/ ||
2987 $pr->{'descr_long'} =~ /$searchtext/;
2990 push @projects, $pr;
2993 return @projects;
2996 our $gitweb_project_owner = undef;
2997 sub git_get_project_list_from_file {
2999 return if (defined $gitweb_project_owner);
3001 $gitweb_project_owner = {};
3002 # read from file (url-encoded):
3003 # 'git%2Fgit.git Linus+Torvalds'
3004 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3005 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3006 if (-f $projects_list) {
3007 open(my $fd, '<', $projects_list);
3008 while (my $line = <$fd>) {
3009 chomp $line;
3010 my ($pr, $ow) = split ' ', $line;
3011 $pr = unescape($pr);
3012 $ow = unescape($ow);
3013 $gitweb_project_owner->{$pr} = to_utf8($ow);
3015 close $fd;
3019 sub git_get_project_owner {
3020 my $project = shift;
3021 my $owner;
3023 return undef unless $project;
3024 $git_dir = "$projectroot/$project";
3026 if (!defined $gitweb_project_owner) {
3027 git_get_project_list_from_file();
3030 if (exists $gitweb_project_owner->{$project}) {
3031 $owner = $gitweb_project_owner->{$project};
3033 if (!defined $owner){
3034 $owner = git_get_project_config('owner');
3036 if (!defined $owner) {
3037 $owner = get_file_owner("$git_dir");
3040 return $owner;
3043 sub git_get_last_activity {
3044 my ($path) = @_;
3045 my $fd;
3047 $git_dir = "$projectroot/$path";
3048 open($fd, "-|", git_cmd(), 'for-each-ref',
3049 '--format=%(committer)',
3050 '--sort=-committerdate',
3051 '--count=1',
3052 'refs/heads') or return;
3053 my $most_recent = <$fd>;
3054 close $fd or return;
3055 if (defined $most_recent &&
3056 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3057 my $timestamp = $1;
3058 my $age = time - $timestamp;
3059 return ($age, age_string($age));
3061 return (undef, undef);
3064 # Implementation note: when a single remote is wanted, we cannot use 'git
3065 # remote show -n' because that command always work (assuming it's a remote URL
3066 # if it's not defined), and we cannot use 'git remote show' because that would
3067 # try to make a network roundtrip. So the only way to find if that particular
3068 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3069 # and when we find what we want.
3070 sub git_get_remotes_list {
3071 my $wanted = shift;
3072 my %remotes = ();
3074 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3075 return unless $fd;
3076 while (my $remote = <$fd>) {
3077 chomp $remote;
3078 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3079 next if $wanted and not $remote eq $wanted;
3080 my ($url, $key) = ($1, $2);
3082 $remotes{$remote} ||= { 'heads' => () };
3083 $remotes{$remote}{$key} = $url;
3085 close $fd or return;
3086 return wantarray ? %remotes : \%remotes;
3089 # Takes a hash of remotes as first parameter and fills it by adding the
3090 # available remote heads for each of the indicated remotes.
3091 sub fill_remote_heads {
3092 my $remotes = shift;
3093 my @heads = map { "remotes/$_" } keys %$remotes;
3094 my @remoteheads = git_get_heads_list(undef, @heads);
3095 foreach my $remote (keys %$remotes) {
3096 $remotes->{$remote}{'heads'} = [ grep {
3097 $_->{'name'} =~ s!^$remote/!!
3098 } @remoteheads ];
3102 sub git_get_references {
3103 my $type = shift || "";
3104 my %refs;
3105 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3106 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3107 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3108 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3109 or return;
3111 while (my $line = <$fd>) {
3112 chomp $line;
3113 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3114 if (defined $refs{$1}) {
3115 push @{$refs{$1}}, $2;
3116 } else {
3117 $refs{$1} = [ $2 ];
3121 close $fd or return;
3122 return \%refs;
3125 sub git_get_rev_name_tags {
3126 my $hash = shift || return undef;
3128 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3129 or return;
3130 my $name_rev = <$fd>;
3131 close $fd;
3133 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3134 return $1;
3135 } else {
3136 # catches also '$hash undefined' output
3137 return undef;
3141 ## ----------------------------------------------------------------------
3142 ## parse to hash functions
3144 sub parse_date {
3145 my $epoch = shift;
3146 my $tz = shift || "-0000";
3148 my %date;
3149 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3150 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3151 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3152 $date{'hour'} = $hour;
3153 $date{'minute'} = $min;
3154 $date{'mday'} = $mday;
3155 $date{'day'} = $days[$wday];
3156 $date{'month'} = $months[$mon];
3157 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3158 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3159 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3160 $mday, $months[$mon], $hour ,$min;
3161 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3162 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3164 my ($tz_sign, $tz_hour, $tz_min) =
3165 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3166 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3167 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3168 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3169 $date{'hour_local'} = $hour;
3170 $date{'minute_local'} = $min;
3171 $date{'tz_local'} = $tz;
3172 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3173 1900+$year, $mon+1, $mday,
3174 $hour, $min, $sec, $tz);
3175 return %date;
3178 sub parse_tag {
3179 my $tag_id = shift;
3180 my %tag;
3181 my @comment;
3183 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3184 $tag{'id'} = $tag_id;
3185 while (my $line = <$fd>) {
3186 chomp $line;
3187 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3188 $tag{'object'} = $1;
3189 } elsif ($line =~ m/^type (.+)$/) {
3190 $tag{'type'} = $1;
3191 } elsif ($line =~ m/^tag (.+)$/) {
3192 $tag{'name'} = $1;
3193 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3194 $tag{'author'} = $1;
3195 $tag{'author_epoch'} = $2;
3196 $tag{'author_tz'} = $3;
3197 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3198 $tag{'author_name'} = $1;
3199 $tag{'author_email'} = $2;
3200 } else {
3201 $tag{'author_name'} = $tag{'author'};
3203 } elsif ($line =~ m/--BEGIN/) {
3204 push @comment, $line;
3205 last;
3206 } elsif ($line eq "") {
3207 last;
3210 push @comment, <$fd>;
3211 $tag{'comment'} = \@comment;
3212 close $fd or return;
3213 if (!defined $tag{'name'}) {
3214 return
3216 return %tag
3219 sub parse_commit_text {
3220 my ($commit_text, $withparents) = @_;
3221 my @commit_lines = split '\n', $commit_text;
3222 my %co;
3224 pop @commit_lines; # Remove '\0'
3226 if (! @commit_lines) {
3227 return;
3230 my $header = shift @commit_lines;
3231 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3232 return;
3234 ($co{'id'}, my @parents) = split ' ', $header;
3235 while (my $line = shift @commit_lines) {
3236 last if $line eq "\n";
3237 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3238 $co{'tree'} = $1;
3239 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3240 push @parents, $1;
3241 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3242 $co{'author'} = to_utf8($1);
3243 $co{'author_epoch'} = $2;
3244 $co{'author_tz'} = $3;
3245 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3246 $co{'author_name'} = $1;
3247 $co{'author_email'} = $2;
3248 } else {
3249 $co{'author_name'} = $co{'author'};
3251 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3252 $co{'committer'} = to_utf8($1);
3253 $co{'committer_epoch'} = $2;
3254 $co{'committer_tz'} = $3;
3255 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3256 $co{'committer_name'} = $1;
3257 $co{'committer_email'} = $2;
3258 } else {
3259 $co{'committer_name'} = $co{'committer'};
3263 if (!defined $co{'tree'}) {
3264 return;
3266 $co{'parents'} = \@parents;
3267 $co{'parent'} = $parents[0];
3269 foreach my $title (@commit_lines) {
3270 $title =~ s/^ //;
3271 if ($title ne "") {
3272 $co{'title'} = chop_str($title, 80, 5);
3273 # remove leading stuff of merges to make the interesting part visible
3274 if (length($title) > 50) {
3275 $title =~ s/^Automatic //;
3276 $title =~ s/^merge (of|with) /Merge ... /i;
3277 if (length($title) > 50) {
3278 $title =~ s/(http|rsync):\/\///;
3280 if (length($title) > 50) {
3281 $title =~ s/(master|www|rsync)\.//;
3283 if (length($title) > 50) {
3284 $title =~ s/kernel.org:?//;
3286 if (length($title) > 50) {
3287 $title =~ s/\/pub\/scm//;
3290 $co{'title_short'} = chop_str($title, 50, 5);
3291 last;
3294 if (! defined $co{'title'} || $co{'title'} eq "") {
3295 $co{'title'} = $co{'title_short'} = '(no commit message)';
3297 # remove added spaces
3298 foreach my $line (@commit_lines) {
3299 $line =~ s/^ //;
3301 $co{'comment'} = \@commit_lines;
3303 my $age = time - $co{'committer_epoch'};
3304 $co{'age'} = $age;
3305 $co{'age_string'} = age_string($age);
3306 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3307 if ($age > 60*60*24*7*2) {
3308 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3309 $co{'age_string_age'} = $co{'age_string'};
3310 } else {
3311 $co{'age_string_date'} = $co{'age_string'};
3312 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3314 return %co;
3317 sub parse_commit {
3318 my ($commit_id) = @_;
3319 my %co;
3321 local $/ = "\0";
3323 open my $fd, "-|", git_cmd(), "rev-list",
3324 "--parents",
3325 "--header",
3326 "--max-count=1",
3327 $commit_id,
3328 "--",
3329 or die_error(500, "Open git-rev-list failed");
3330 %co = parse_commit_text(<$fd>, 1);
3331 close $fd;
3333 return %co;
3336 sub parse_commits {
3337 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3338 my @cos;
3340 $maxcount ||= 1;
3341 $skip ||= 0;
3343 local $/ = "\0";
3345 open my $fd, "-|", git_cmd(), "rev-list",
3346 "--header",
3347 @args,
3348 ("--max-count=" . $maxcount),
3349 ("--skip=" . $skip),
3350 @extra_options,
3351 $commit_id,
3352 "--",
3353 ($filename ? ($filename) : ())
3354 or die_error(500, "Open git-rev-list failed");
3355 while (my $line = <$fd>) {
3356 my %co = parse_commit_text($line);
3357 push @cos, \%co;
3359 close $fd;
3361 return wantarray ? @cos : \@cos;
3364 # parse line of git-diff-tree "raw" output
3365 sub parse_difftree_raw_line {
3366 my $line = shift;
3367 my %res;
3369 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3370 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3371 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3372 $res{'from_mode'} = $1;
3373 $res{'to_mode'} = $2;
3374 $res{'from_id'} = $3;
3375 $res{'to_id'} = $4;
3376 $res{'status'} = $5;
3377 $res{'similarity'} = $6;
3378 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3379 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3380 } else {
3381 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3384 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3385 # combined diff (for merge commit)
3386 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3387 $res{'nparents'} = length($1);
3388 $res{'from_mode'} = [ split(' ', $2) ];
3389 $res{'to_mode'} = pop @{$res{'from_mode'}};
3390 $res{'from_id'} = [ split(' ', $3) ];
3391 $res{'to_id'} = pop @{$res{'from_id'}};
3392 $res{'status'} = [ split('', $4) ];
3393 $res{'to_file'} = unquote($5);
3395 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3396 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3397 $res{'commit'} = $1;
3400 return wantarray ? %res : \%res;
3403 # wrapper: return parsed line of git-diff-tree "raw" output
3404 # (the argument might be raw line, or parsed info)
3405 sub parsed_difftree_line {
3406 my $line_or_ref = shift;
3408 if (ref($line_or_ref) eq "HASH") {
3409 # pre-parsed (or generated by hand)
3410 return $line_or_ref;
3411 } else {
3412 return parse_difftree_raw_line($line_or_ref);
3416 # parse line of git-ls-tree output
3417 sub parse_ls_tree_line {
3418 my $line = shift;
3419 my %opts = @_;
3420 my %res;
3422 if ($opts{'-l'}) {
3423 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3424 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3426 $res{'mode'} = $1;
3427 $res{'type'} = $2;
3428 $res{'hash'} = $3;
3429 $res{'size'} = $4;
3430 if ($opts{'-z'}) {
3431 $res{'name'} = $5;
3432 } else {
3433 $res{'name'} = unquote($5);
3435 } else {
3436 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3437 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3439 $res{'mode'} = $1;
3440 $res{'type'} = $2;
3441 $res{'hash'} = $3;
3442 if ($opts{'-z'}) {
3443 $res{'name'} = $4;
3444 } else {
3445 $res{'name'} = unquote($4);
3449 return wantarray ? %res : \%res;
3452 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3453 sub parse_from_to_diffinfo {
3454 my ($diffinfo, $from, $to, @parents) = @_;
3456 if ($diffinfo->{'nparents'}) {
3457 # combined diff
3458 $from->{'file'} = [];
3459 $from->{'href'} = [];
3460 fill_from_file_info($diffinfo, @parents)
3461 unless exists $diffinfo->{'from_file'};
3462 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3463 $from->{'file'}[$i] =
3464 defined $diffinfo->{'from_file'}[$i] ?
3465 $diffinfo->{'from_file'}[$i] :
3466 $diffinfo->{'to_file'};
3467 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3468 $from->{'href'}[$i] = href(action=>"blob",
3469 hash_base=>$parents[$i],
3470 hash=>$diffinfo->{'from_id'}[$i],
3471 file_name=>$from->{'file'}[$i]);
3472 } else {
3473 $from->{'href'}[$i] = undef;
3476 } else {
3477 # ordinary (not combined) diff
3478 $from->{'file'} = $diffinfo->{'from_file'};
3479 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3480 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3481 hash=>$diffinfo->{'from_id'},
3482 file_name=>$from->{'file'});
3483 } else {
3484 delete $from->{'href'};
3488 $to->{'file'} = $diffinfo->{'to_file'};
3489 if (!is_deleted($diffinfo)) { # file exists in result
3490 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3491 hash=>$diffinfo->{'to_id'},
3492 file_name=>$to->{'file'});
3493 } else {
3494 delete $to->{'href'};
3498 ## ......................................................................
3499 ## parse to array of hashes functions
3501 sub git_get_heads_list {
3502 my ($limit, @classes) = @_;
3503 @classes = ('heads') unless @classes;
3504 my @patterns = map { "refs/$_" } @classes;
3505 my @headslist;
3507 open my $fd, '-|', git_cmd(), 'for-each-ref',
3508 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3509 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3510 @patterns
3511 or return;
3512 while (my $line = <$fd>) {
3513 my %ref_item;
3515 chomp $line;
3516 my ($refinfo, $committerinfo) = split(/\0/, $line);
3517 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3518 my ($committer, $epoch, $tz) =
3519 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3520 $ref_item{'fullname'} = $name;
3521 $name =~ s!^refs/(?:head|remote)s/!!;
3523 $ref_item{'name'} = $name;
3524 $ref_item{'id'} = $hash;
3525 $ref_item{'title'} = $title || '(no commit message)';
3526 $ref_item{'epoch'} = $epoch;
3527 if ($epoch) {
3528 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3529 } else {
3530 $ref_item{'age'} = "unknown";
3533 push @headslist, \%ref_item;
3535 close $fd;
3537 return wantarray ? @headslist : \@headslist;
3540 sub git_get_tags_list {
3541 my $limit = shift;
3542 my @tagslist;
3544 open my $fd, '-|', git_cmd(), 'for-each-ref',
3545 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3546 '--format=%(objectname) %(objecttype) %(refname) '.
3547 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3548 'refs/tags'
3549 or return;
3550 while (my $line = <$fd>) {
3551 my %ref_item;
3553 chomp $line;
3554 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3555 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3556 my ($creator, $epoch, $tz) =
3557 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3558 $ref_item{'fullname'} = $name;
3559 $name =~ s!^refs/tags/!!;
3561 $ref_item{'type'} = $type;
3562 $ref_item{'id'} = $id;
3563 $ref_item{'name'} = $name;
3564 if ($type eq "tag") {
3565 $ref_item{'subject'} = $title;
3566 $ref_item{'reftype'} = $reftype;
3567 $ref_item{'refid'} = $refid;
3568 } else {
3569 $ref_item{'reftype'} = $type;
3570 $ref_item{'refid'} = $id;
3573 if ($type eq "tag" || $type eq "commit") {
3574 $ref_item{'epoch'} = $epoch;
3575 if ($epoch) {
3576 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3577 } else {
3578 $ref_item{'age'} = "unknown";
3582 push @tagslist, \%ref_item;
3584 close $fd;
3586 return wantarray ? @tagslist : \@tagslist;
3589 ## ----------------------------------------------------------------------
3590 ## filesystem-related functions
3592 sub get_file_owner {
3593 my $path = shift;
3595 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3596 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3597 if (!defined $gcos) {
3598 return undef;
3600 my $owner = $gcos;
3601 $owner =~ s/[,;].*$//;
3602 return to_utf8($owner);
3605 # assume that file exists
3606 sub insert_file {
3607 my $filename = shift;
3609 open my $fd, '<', $filename;
3610 print map { to_utf8($_) } <$fd>;
3611 close $fd;
3614 ## ......................................................................
3615 ## mimetype related functions
3617 sub mimetype_guess_file {
3618 my $filename = shift;
3619 my $mimemap = shift;
3620 -r $mimemap or return undef;
3622 my %mimemap;
3623 open(my $mh, '<', $mimemap) or return undef;
3624 while (<$mh>) {
3625 next if m/^#/; # skip comments
3626 my ($mimetype, @exts) = split(/\s+/);
3627 foreach my $ext (@exts) {
3628 $mimemap{$ext} = $mimetype;
3631 close($mh);
3633 $filename =~ /\.([^.]*)$/;
3634 return $mimemap{$1};
3637 sub mimetype_guess {
3638 my $filename = shift;
3639 my $mime;
3640 $filename =~ /\./ or return undef;
3642 if ($mimetypes_file) {
3643 my $file = $mimetypes_file;
3644 if ($file !~ m!^/!) { # if it is relative path
3645 # it is relative to project
3646 $file = "$projectroot/$project/$file";
3648 $mime = mimetype_guess_file($filename, $file);
3650 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3651 return $mime;
3654 sub blob_mimetype {
3655 my $fd = shift;
3656 my $filename = shift;
3658 if ($filename) {
3659 my $mime = mimetype_guess($filename);
3660 $mime and return $mime;
3663 # just in case
3664 return $default_blob_plain_mimetype unless $fd;
3666 if (-T $fd) {
3667 return 'text/plain';
3668 } elsif (! $filename) {
3669 return 'application/octet-stream';
3670 } elsif ($filename =~ m/\.png$/i) {
3671 return 'image/png';
3672 } elsif ($filename =~ m/\.gif$/i) {
3673 return 'image/gif';
3674 } elsif ($filename =~ m/\.jpe?g$/i) {
3675 return 'image/jpeg';
3676 } else {
3677 return 'application/octet-stream';
3681 sub blob_contenttype {
3682 my ($fd, $file_name, $type) = @_;
3684 $type ||= blob_mimetype($fd, $file_name);
3685 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3686 $type .= "; charset=$default_text_plain_charset";
3689 return $type;
3692 # guess file syntax for syntax highlighting; return undef if no highlighting
3693 # the name of syntax can (in the future) depend on syntax highlighter used
3694 sub guess_file_syntax {
3695 my ($highlight, $mimetype, $file_name) = @_;
3696 return undef unless ($highlight && defined $file_name);
3697 my $basename = basename($file_name, '.in');
3698 return $highlight_basename{$basename}
3699 if exists $highlight_basename{$basename};
3701 $basename =~ /\.([^.]*)$/;
3702 my $ext = $1 or return undef;
3703 return $highlight_ext{$ext}
3704 if exists $highlight_ext{$ext};
3706 return undef;
3709 # run highlighter and return FD of its output,
3710 # or return original FD if no highlighting
3711 sub run_highlighter {
3712 my ($fd, $highlight, $syntax) = @_;
3713 return $fd unless ($highlight && defined $syntax);
3715 close $fd;
3716 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3717 quote_command($highlight_bin).
3718 " --replace-tabs=8 --fragment --syntax $syntax |"
3719 or die_error(500, "Couldn't open file or run syntax highlighter");
3720 return $fd;
3723 ## ======================================================================
3724 ## functions printing HTML: header, footer, error page
3726 sub get_page_title {
3727 my $title = to_utf8($site_name);
3729 return $title unless (defined $project);
3730 $title .= " - " . to_utf8($project);
3732 return $title unless (defined $action);
3733 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3735 return $title unless (defined $file_name);
3736 $title .= " - " . esc_path($file_name);
3737 if ($action eq "tree" && $file_name !~ m|/$|) {
3738 $title .= "/";
3741 return $title;
3744 sub get_content_type_html {
3745 # require explicit support from the UA if we are to send the page as
3746 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3747 # we have to do this because MSIE sometimes globs '*/*', pretending to
3748 # support xhtml+xml but choking when it gets what it asked for.
3749 if (defined $cgi->http('HTTP_ACCEPT') &&
3750 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3751 $cgi->Accept('application/xhtml+xml') != 0) {
3752 return 'application/xhtml+xml';
3753 } else {
3754 return 'text/html';
3758 sub print_feed_meta {
3759 if (defined $project) {
3760 my %href_params = get_feed_info();
3761 if (!exists $href_params{'-title'}) {
3762 $href_params{'-title'} = 'log';
3765 foreach my $format (qw(RSS Atom)) {
3766 my $type = lc($format);
3767 my %link_attr = (
3768 '-rel' => 'alternate',
3769 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
3770 '-type' => "application/$type+xml"
3773 $href_params{'action'} = $type;
3774 $link_attr{'-href'} = href(%href_params);
3775 print "<link ".
3776 "rel=\"$link_attr{'-rel'}\" ".
3777 "title=\"$link_attr{'-title'}\" ".
3778 "href=\"$link_attr{'-href'}\" ".
3779 "type=\"$link_attr{'-type'}\" ".
3780 "/>\n";
3782 $href_params{'extra_options'} = '--no-merges';
3783 $link_attr{'-href'} = href(%href_params);
3784 $link_attr{'-title'} .= ' (no merges)';
3785 print "<link ".
3786 "rel=\"$link_attr{'-rel'}\" ".
3787 "title=\"$link_attr{'-title'}\" ".
3788 "href=\"$link_attr{'-href'}\" ".
3789 "type=\"$link_attr{'-type'}\" ".
3790 "/>\n";
3793 } else {
3794 printf('<link rel="alternate" title="%s projects list" '.
3795 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3796 esc_attr($site_name), href(project=>undef, action=>"project_index"));
3797 printf('<link rel="alternate" title="%s projects feeds" '.
3798 'href="%s" type="text/x-opml" />'."\n",
3799 esc_attr($site_name), href(project=>undef, action=>"opml"));
3803 sub print_header_links {
3804 my $status = shift;
3806 # print out each stylesheet that exist, providing backwards capability
3807 # for those people who defined $stylesheet in a config file
3808 if (defined $stylesheet) {
3809 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3810 } else {
3811 foreach my $stylesheet (@stylesheets) {
3812 next unless $stylesheet;
3813 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3816 print_feed_meta()
3817 if ($status eq '200 OK');
3818 if (defined $favicon) {
3819 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
3823 sub print_nav_breadcrumbs {
3824 my %opts = @_;
3826 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3827 if (defined $project) {
3828 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3829 if (defined $action) {
3830 my $action_print = $action ;
3831 if (defined $opts{-action_extra}) {
3832 $action_print = $cgi->a({-href => href(action=>$action)},
3833 $action);
3835 print " / $action_print";
3837 if (defined $opts{-action_extra}) {
3838 print " / $opts{-action_extra}";
3840 print "\n";
3844 sub print_search_form {
3845 if (!defined $searchtext) {
3846 $searchtext = "";
3848 my $search_hash;
3849 if (defined $hash_base) {
3850 $search_hash = $hash_base;
3851 } elsif (defined $hash) {
3852 $search_hash = $hash;
3853 } else {
3854 $search_hash = "HEAD";
3856 my $action = $my_uri;
3857 my $use_pathinfo = gitweb_check_feature('pathinfo');
3858 if ($use_pathinfo) {
3859 $action .= "/".esc_url($project);
3861 print $cgi->startform(-method => "get", -action => $action) .
3862 "<div class=\"search\">\n" .
3863 (!$use_pathinfo &&
3864 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3865 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3866 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3867 $cgi->popup_menu(-name => 'st', -default => 'commit',
3868 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3869 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3870 " search:\n",
3871 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3872 "<span title=\"Extended regular expression\">" .
3873 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3874 -checked => $search_use_regexp) .
3875 "</span>" .
3876 "</div>" .
3877 $cgi->end_form() . "\n";
3880 sub git_header_html {
3881 my $status = shift || "200 OK";
3882 my $expires = shift;
3883 my %opts = @_;
3885 my $title = get_page_title();
3886 my $content_type = get_content_type_html();
3887 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3888 -status=> $status, -expires => $expires)
3889 unless ($opts{'-no_http_header'});
3890 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3891 print <<EOF;
3892 <?xml version="1.0" encoding="utf-8"?>
3893 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3894 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3895 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3896 <!-- git core binaries version $git_version -->
3897 <head>
3898 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3899 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3900 <meta name="robots" content="index, nofollow"/>
3901 <title>$title</title>
3903 # the stylesheet, favicon etc urls won't work correctly with path_info
3904 # unless we set the appropriate base URL
3905 if ($ENV{'PATH_INFO'}) {
3906 print "<base href=\"".esc_url($base_url)."\" />\n";
3908 print_header_links($status);
3909 print "</head>\n" .
3910 "<body>\n";
3912 if (defined $site_header && -f $site_header) {
3913 insert_file($site_header);
3916 print "<div class=\"page_header\">\n";
3917 if (defined $logo) {
3918 print $cgi->a({-href => esc_url($logo_url),
3919 -title => $logo_label},
3920 $cgi->img({-src => esc_url($logo),
3921 -width => 72, -height => 27,
3922 -alt => "git",
3923 -class => "logo"}));
3925 print_nav_breadcrumbs(%opts);
3926 print "</div>\n";
3928 my $have_search = gitweb_check_feature('search');
3929 if (defined $project && $have_search) {
3930 print_search_form();
3934 sub git_footer_html {
3935 my $feed_class = 'rss_logo';
3937 print "<div class=\"page_footer\">\n";
3938 if (defined $project) {
3939 my $descr = git_get_project_description($project);
3940 if (defined $descr) {
3941 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3944 my %href_params = get_feed_info();
3945 if (!%href_params) {
3946 $feed_class .= ' generic';
3948 $href_params{'-title'} ||= 'log';
3950 foreach my $format (qw(RSS Atom)) {
3951 $href_params{'action'} = lc($format);
3952 print $cgi->a({-href => href(%href_params),
3953 -title => "$href_params{'-title'} $format feed",
3954 -class => $feed_class}, $format)."\n";
3957 } else {
3958 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3959 -class => $feed_class}, "OPML") . " ";
3960 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3961 -class => $feed_class}, "TXT") . "\n";
3963 print "</div>\n"; # class="page_footer"
3965 if (defined $t0 && gitweb_check_feature('timed')) {
3966 print "<div id=\"generating_info\">\n";
3967 print 'This page took '.
3968 '<span id="generating_time" class="time_span">'.
3969 tv_interval($t0, [ gettimeofday() ]).
3970 ' seconds </span>'.
3971 ' and '.
3972 '<span id="generating_cmd">'.
3973 $number_of_git_cmds.
3974 '</span> git commands '.
3975 " to generate.\n";
3976 print "</div>\n"; # class="page_footer"
3979 if (defined $site_footer && -f $site_footer) {
3980 insert_file($site_footer);
3983 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
3984 if (defined $action &&
3985 $action eq 'blame_incremental') {
3986 print qq!<script type="text/javascript">\n!.
3987 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3988 qq! "!. href() .qq!");\n!.
3989 qq!</script>\n!;
3990 } else {
3991 my ($jstimezone, $tz_cookie, $datetime_class) =
3992 gitweb_get_feature('javascript-timezone');
3994 print qq!<script type="text/javascript">\n!.
3995 qq!window.onload = function () {\n!;
3996 if (gitweb_check_feature('javascript-actions')) {
3997 print qq! fixLinks();\n!;
3999 if ($jstimezone && $tz_cookie && $datetime_class) {
4000 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4001 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4003 print qq!};\n!.
4004 qq!</script>\n!;
4007 print "</body>\n" .
4008 "</html>";
4011 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4012 # Example: die_error(404, 'Hash not found')
4013 # By convention, use the following status codes (as defined in RFC 2616):
4014 # 400: Invalid or missing CGI parameters, or
4015 # requested object exists but has wrong type.
4016 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4017 # this server or project.
4018 # 404: Requested object/revision/project doesn't exist.
4019 # 500: The server isn't configured properly, or
4020 # an internal error occurred (e.g. failed assertions caused by bugs), or
4021 # an unknown error occurred (e.g. the git binary died unexpectedly).
4022 # 503: The server is currently unavailable (because it is overloaded,
4023 # or down for maintenance). Generally, this is a temporary state.
4024 sub die_error {
4025 my $status = shift || 500;
4026 my $error = esc_html(shift) || "Internal Server Error";
4027 my $extra = shift;
4028 my %opts = @_;
4030 my %http_responses = (
4031 400 => '400 Bad Request',
4032 403 => '403 Forbidden',
4033 404 => '404 Not Found',
4034 500 => '500 Internal Server Error',
4035 503 => '503 Service Unavailable',
4037 git_header_html($http_responses{$status}, undef, %opts);
4038 print <<EOF;
4039 <div class="page_body">
4040 <br /><br />
4041 $status - $error
4042 <br />
4044 if (defined $extra) {
4045 print "<hr />\n" .
4046 "$extra\n";
4048 print "</div>\n";
4050 git_footer_html();
4051 goto DONE_GITWEB
4052 unless ($opts{'-error_handler'});
4055 ## ----------------------------------------------------------------------
4056 ## functions printing or outputting HTML: navigation
4058 sub git_print_page_nav {
4059 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4060 $extra = '' if !defined $extra; # pager or formats
4062 my @navs = qw(summary shortlog log commit commitdiff tree);
4063 if ($suppress) {
4064 @navs = grep { $_ ne $suppress } @navs;
4067 my %arg = map { $_ => {action=>$_} } @navs;
4068 if (defined $head) {
4069 for (qw(commit commitdiff)) {
4070 $arg{$_}{'hash'} = $head;
4072 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4073 for (qw(shortlog log)) {
4074 $arg{$_}{'hash'} = $head;
4079 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4080 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4082 my @actions = gitweb_get_feature('actions');
4083 my %repl = (
4084 '%' => '%',
4085 'n' => $project, # project name
4086 'f' => $git_dir, # project path within filesystem
4087 'h' => $treehead || '', # current hash ('h' parameter)
4088 'b' => $treebase || '', # hash base ('hb' parameter)
4090 while (@actions) {
4091 my ($label, $link, $pos) = splice(@actions,0,3);
4092 # insert
4093 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4094 # munch munch
4095 $link =~ s/%([%nfhb])/$repl{$1}/g;
4096 $arg{$label}{'_href'} = $link;
4099 print "<div class=\"page_nav\">\n" .
4100 (join " | ",
4101 map { $_ eq $current ?
4102 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4103 } @navs);
4104 print "<br/>\n$extra<br/>\n" .
4105 "</div>\n";
4108 # returns a submenu for the nagivation of the refs views (tags, heads,
4109 # remotes) with the current view disabled and the remotes view only
4110 # available if the feature is enabled
4111 sub format_ref_views {
4112 my ($current) = @_;
4113 my @ref_views = qw{tags heads};
4114 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4115 return join " | ", map {
4116 $_ eq $current ? $_ :
4117 $cgi->a({-href => href(action=>$_)}, $_)
4118 } @ref_views
4121 sub format_paging_nav {
4122 my ($action, $page, $has_next_link) = @_;
4123 my $paging_nav;
4126 if ($page > 0) {
4127 $paging_nav .=
4128 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4129 " &sdot; " .
4130 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4131 -accesskey => "p", -title => "Alt-p"}, "prev");
4132 } else {
4133 $paging_nav .= "first &sdot; prev";
4136 if ($has_next_link) {
4137 $paging_nav .= " &sdot; " .
4138 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4139 -accesskey => "n", -title => "Alt-n"}, "next");
4140 } else {
4141 $paging_nav .= " &sdot; next";
4144 return $paging_nav;
4147 ## ......................................................................
4148 ## functions printing or outputting HTML: div
4150 sub git_print_header_div {
4151 my ($action, $title, $hash, $hash_base) = @_;
4152 my %args = ();
4154 $args{'action'} = $action;
4155 $args{'hash'} = $hash if $hash;
4156 $args{'hash_base'} = $hash_base if $hash_base;
4158 print "<div class=\"header\">\n" .
4159 $cgi->a({-href => href(%args), -class => "title"},
4160 $title ? $title : $action) .
4161 "\n</div>\n";
4164 sub format_repo_url {
4165 my ($name, $url) = @_;
4166 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4169 # Group output by placing it in a DIV element and adding a header.
4170 # Options for start_div() can be provided by passing a hash reference as the
4171 # first parameter to the function.
4172 # Options to git_print_header_div() can be provided by passing an array
4173 # reference. This must follow the options to start_div if they are present.
4174 # The content can be a scalar, which is output as-is, a scalar reference, which
4175 # is output after html escaping, an IO handle passed either as *handle or
4176 # *handle{IO}, or a function reference. In the latter case all following
4177 # parameters will be taken as argument to the content function call.
4178 sub git_print_section {
4179 my ($div_args, $header_args, $content);
4180 my $arg = shift;
4181 if (ref($arg) eq 'HASH') {
4182 $div_args = $arg;
4183 $arg = shift;
4185 if (ref($arg) eq 'ARRAY') {
4186 $header_args = $arg;
4187 $arg = shift;
4189 $content = $arg;
4191 print $cgi->start_div($div_args);
4192 git_print_header_div(@$header_args);
4194 if (ref($content) eq 'CODE') {
4195 $content->(@_);
4196 } elsif (ref($content) eq 'SCALAR') {
4197 print esc_html($$content);
4198 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4199 print <$content>;
4200 } elsif (!ref($content) && defined($content)) {
4201 print $content;
4204 print $cgi->end_div;
4207 sub format_timestamp_html {
4208 my $date = shift;
4209 my $strtime = $date->{'rfc2822'};
4211 my (undef, undef, $datetime_class) =
4212 gitweb_get_feature('javascript-timezone');
4213 if ($datetime_class) {
4214 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4217 my $localtime_format = '(%02d:%02d %s)';
4218 if ($date->{'hour_local'} < 6) {
4219 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4221 $strtime .= ' ' .
4222 sprintf($localtime_format,
4223 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4225 return $strtime;
4228 # Outputs the author name and date in long form
4229 sub git_print_authorship {
4230 my $co = shift;
4231 my %opts = @_;
4232 my $tag = $opts{-tag} || 'div';
4233 my $author = $co->{'author_name'};
4235 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4236 print "<$tag class=\"author_date\">" .
4237 format_search_author($author, "author", esc_html($author)) .
4238 " [".format_timestamp_html(\%ad)."]".
4239 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4240 "</$tag>\n";
4243 # Outputs table rows containing the full author or committer information,
4244 # in the format expected for 'commit' view (& similar).
4245 # Parameters are a commit hash reference, followed by the list of people
4246 # to output information for. If the list is empty it defaults to both
4247 # author and committer.
4248 sub git_print_authorship_rows {
4249 my $co = shift;
4250 # too bad we can't use @people = @_ || ('author', 'committer')
4251 my @people = @_;
4252 @people = ('author', 'committer') unless @people;
4253 foreach my $who (@people) {
4254 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4255 print "<tr><td>$who</td><td>" .
4256 format_search_author($co->{"${who}_name"}, $who,
4257 esc_html($co->{"${who}_name"})) . " " .
4258 format_search_author($co->{"${who}_email"}, $who,
4259 esc_html("<" . $co->{"${who}_email"} . ">")) .
4260 "</td><td rowspan=\"2\">" .
4261 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4262 "</td></tr>\n" .
4263 "<tr>" .
4264 "<td></td><td>" .
4265 format_timestamp_html(\%wd) .
4266 "</td>" .
4267 "</tr>\n";
4271 sub git_print_page_path {
4272 my $name = shift;
4273 my $type = shift;
4274 my $hb = shift;
4277 print "<div class=\"page_path\">";
4278 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4279 -title => 'tree root'}, to_utf8("[$project]"));
4280 print " / ";
4281 if (defined $name) {
4282 my @dirname = split '/', $name;
4283 my $basename = pop @dirname;
4284 my $fullname = '';
4286 foreach my $dir (@dirname) {
4287 $fullname .= ($fullname ? '/' : '') . $dir;
4288 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4289 hash_base=>$hb),
4290 -title => $fullname}, esc_path($dir));
4291 print " / ";
4293 if (defined $type && $type eq 'blob') {
4294 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4295 hash_base=>$hb),
4296 -title => $name}, esc_path($basename));
4297 } elsif (defined $type && $type eq 'tree') {
4298 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4299 hash_base=>$hb),
4300 -title => $name}, esc_path($basename));
4301 print " / ";
4302 } else {
4303 print esc_path($basename);
4306 print "<br/></div>\n";
4309 sub git_print_log {
4310 my $log = shift;
4311 my %opts = @_;
4313 if ($opts{'-remove_title'}) {
4314 # remove title, i.e. first line of log
4315 shift @$log;
4317 # remove leading empty lines
4318 while (defined $log->[0] && $log->[0] eq "") {
4319 shift @$log;
4322 # print log
4323 my $signoff = 0;
4324 my $empty = 0;
4325 foreach my $line (@$log) {
4326 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4327 $signoff = 1;
4328 $empty = 0;
4329 if (! $opts{'-remove_signoff'}) {
4330 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4331 next;
4332 } else {
4333 # remove signoff lines
4334 next;
4336 } else {
4337 $signoff = 0;
4340 # print only one empty line
4341 # do not print empty line after signoff
4342 if ($line eq "") {
4343 next if ($empty || $signoff);
4344 $empty = 1;
4345 } else {
4346 $empty = 0;
4349 print format_log_line_html($line) . "<br/>\n";
4352 if ($opts{'-final_empty_line'}) {
4353 # end with single empty line
4354 print "<br/>\n" unless $empty;
4358 # return link target (what link points to)
4359 sub git_get_link_target {
4360 my $hash = shift;
4361 my $link_target;
4363 # read link
4364 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4365 or return;
4367 local $/ = undef;
4368 $link_target = <$fd>;
4370 close $fd
4371 or return;
4373 return $link_target;
4376 # given link target, and the directory (basedir) the link is in,
4377 # return target of link relative to top directory (top tree);
4378 # return undef if it is not possible (including absolute links).
4379 sub normalize_link_target {
4380 my ($link_target, $basedir) = @_;
4382 # absolute symlinks (beginning with '/') cannot be normalized
4383 return if (substr($link_target, 0, 1) eq '/');
4385 # normalize link target to path from top (root) tree (dir)
4386 my $path;
4387 if ($basedir) {
4388 $path = $basedir . '/' . $link_target;
4389 } else {
4390 # we are in top (root) tree (dir)
4391 $path = $link_target;
4394 # remove //, /./, and /../
4395 my @path_parts;
4396 foreach my $part (split('/', $path)) {
4397 # discard '.' and ''
4398 next if (!$part || $part eq '.');
4399 # handle '..'
4400 if ($part eq '..') {
4401 if (@path_parts) {
4402 pop @path_parts;
4403 } else {
4404 # link leads outside repository (outside top dir)
4405 return;
4407 } else {
4408 push @path_parts, $part;
4411 $path = join('/', @path_parts);
4413 return $path;
4416 # print tree entry (row of git_tree), but without encompassing <tr> element
4417 sub git_print_tree_entry {
4418 my ($t, $basedir, $hash_base, $have_blame) = @_;
4420 my %base_key = ();
4421 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4423 # The format of a table row is: mode list link. Where mode is
4424 # the mode of the entry, list is the name of the entry, an href,
4425 # and link is the action links of the entry.
4427 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4428 if (exists $t->{'size'}) {
4429 print "<td class=\"size\">$t->{'size'}</td>\n";
4431 if ($t->{'type'} eq "blob") {
4432 print "<td class=\"list\">" .
4433 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4434 file_name=>"$basedir$t->{'name'}", %base_key),
4435 -class => "list"}, esc_path($t->{'name'}));
4436 if (S_ISLNK(oct $t->{'mode'})) {
4437 my $link_target = git_get_link_target($t->{'hash'});
4438 if ($link_target) {
4439 my $norm_target = normalize_link_target($link_target, $basedir);
4440 if (defined $norm_target) {
4441 print " -> " .
4442 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4443 file_name=>$norm_target),
4444 -title => $norm_target}, esc_path($link_target));
4445 } else {
4446 print " -> " . esc_path($link_target);
4450 print "</td>\n";
4451 print "<td class=\"link\">";
4452 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4453 file_name=>"$basedir$t->{'name'}", %base_key)},
4454 "blob");
4455 if ($have_blame) {
4456 print " | " .
4457 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4458 file_name=>"$basedir$t->{'name'}", %base_key)},
4459 "blame");
4461 if (defined $hash_base) {
4462 print " | " .
4463 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4464 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4465 "history");
4467 print " | " .
4468 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4469 file_name=>"$basedir$t->{'name'}")},
4470 "raw");
4471 print "</td>\n";
4473 } elsif ($t->{'type'} eq "tree") {
4474 print "<td class=\"list\">";
4475 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4476 file_name=>"$basedir$t->{'name'}",
4477 %base_key)},
4478 esc_path($t->{'name'}));
4479 print "</td>\n";
4480 print "<td class=\"link\">";
4481 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4482 file_name=>"$basedir$t->{'name'}",
4483 %base_key)},
4484 "tree");
4485 if (defined $hash_base) {
4486 print " | " .
4487 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4488 file_name=>"$basedir$t->{'name'}")},
4489 "history");
4491 print "</td>\n";
4492 } else {
4493 # unknown object: we can only present history for it
4494 # (this includes 'commit' object, i.e. submodule support)
4495 print "<td class=\"list\">" .
4496 esc_path($t->{'name'}) .
4497 "</td>\n";
4498 print "<td class=\"link\">";
4499 if (defined $hash_base) {
4500 print $cgi->a({-href => href(action=>"history",
4501 hash_base=>$hash_base,
4502 file_name=>"$basedir$t->{'name'}")},
4503 "history");
4505 print "</td>\n";
4509 ## ......................................................................
4510 ## functions printing large fragments of HTML
4512 # get pre-image filenames for merge (combined) diff
4513 sub fill_from_file_info {
4514 my ($diff, @parents) = @_;
4516 $diff->{'from_file'} = [ ];
4517 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4518 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4519 if ($diff->{'status'}[$i] eq 'R' ||
4520 $diff->{'status'}[$i] eq 'C') {
4521 $diff->{'from_file'}[$i] =
4522 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4526 return $diff;
4529 # is current raw difftree line of file deletion
4530 sub is_deleted {
4531 my $diffinfo = shift;
4533 return $diffinfo->{'to_id'} eq ('0' x 40);
4536 # does patch correspond to [previous] difftree raw line
4537 # $diffinfo - hashref of parsed raw diff format
4538 # $patchinfo - hashref of parsed patch diff format
4539 # (the same keys as in $diffinfo)
4540 sub is_patch_split {
4541 my ($diffinfo, $patchinfo) = @_;
4543 return defined $diffinfo && defined $patchinfo
4544 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4548 sub git_difftree_body {
4549 my ($difftree, $hash, @parents) = @_;
4550 my ($parent) = $parents[0];
4551 my $have_blame = gitweb_check_feature('blame');
4552 print "<div class=\"list_head\">\n";
4553 if ($#{$difftree} > 10) {
4554 print(($#{$difftree} + 1) . " files changed:\n");
4556 print "</div>\n";
4558 print "<table class=\"" .
4559 (@parents > 1 ? "combined " : "") .
4560 "diff_tree\">\n";
4562 # header only for combined diff in 'commitdiff' view
4563 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4564 if ($has_header) {
4565 # table header
4566 print "<thead><tr>\n" .
4567 "<th></th><th></th>\n"; # filename, patchN link
4568 for (my $i = 0; $i < @parents; $i++) {
4569 my $par = $parents[$i];
4570 print "<th>" .
4571 $cgi->a({-href => href(action=>"commitdiff",
4572 hash=>$hash, hash_parent=>$par),
4573 -title => 'commitdiff to parent number ' .
4574 ($i+1) . ': ' . substr($par,0,7)},
4575 $i+1) .
4576 "&nbsp;</th>\n";
4578 print "</tr></thead>\n<tbody>\n";
4581 my $alternate = 1;
4582 my $patchno = 0;
4583 foreach my $line (@{$difftree}) {
4584 my $diff = parsed_difftree_line($line);
4586 if ($alternate) {
4587 print "<tr class=\"dark\">\n";
4588 } else {
4589 print "<tr class=\"light\">\n";
4591 $alternate ^= 1;
4593 if (exists $diff->{'nparents'}) { # combined diff
4595 fill_from_file_info($diff, @parents)
4596 unless exists $diff->{'from_file'};
4598 if (!is_deleted($diff)) {
4599 # file exists in the result (child) commit
4600 print "<td>" .
4601 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4602 file_name=>$diff->{'to_file'},
4603 hash_base=>$hash),
4604 -class => "list"}, esc_path($diff->{'to_file'})) .
4605 "</td>\n";
4606 } else {
4607 print "<td>" .
4608 esc_path($diff->{'to_file'}) .
4609 "</td>\n";
4612 if ($action eq 'commitdiff') {
4613 # link to patch
4614 $patchno++;
4615 print "<td class=\"link\">" .
4616 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4617 "patch") .
4618 " | " .
4619 "</td>\n";
4622 my $has_history = 0;
4623 my $not_deleted = 0;
4624 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4625 my $hash_parent = $parents[$i];
4626 my $from_hash = $diff->{'from_id'}[$i];
4627 my $from_path = $diff->{'from_file'}[$i];
4628 my $status = $diff->{'status'}[$i];
4630 $has_history ||= ($status ne 'A');
4631 $not_deleted ||= ($status ne 'D');
4633 if ($status eq 'A') {
4634 print "<td class=\"link\" align=\"right\"> | </td>\n";
4635 } elsif ($status eq 'D') {
4636 print "<td class=\"link\">" .
4637 $cgi->a({-href => href(action=>"blob",
4638 hash_base=>$hash,
4639 hash=>$from_hash,
4640 file_name=>$from_path)},
4641 "blob" . ($i+1)) .
4642 " | </td>\n";
4643 } else {
4644 if ($diff->{'to_id'} eq $from_hash) {
4645 print "<td class=\"link nochange\">";
4646 } else {
4647 print "<td class=\"link\">";
4649 print $cgi->a({-href => href(action=>"blobdiff",
4650 hash=>$diff->{'to_id'},
4651 hash_parent=>$from_hash,
4652 hash_base=>$hash,
4653 hash_parent_base=>$hash_parent,
4654 file_name=>$diff->{'to_file'},
4655 file_parent=>$from_path)},
4656 "diff" . ($i+1)) .
4657 " | </td>\n";
4661 print "<td class=\"link\">";
4662 if ($not_deleted) {
4663 print $cgi->a({-href => href(action=>"blob",
4664 hash=>$diff->{'to_id'},
4665 file_name=>$diff->{'to_file'},
4666 hash_base=>$hash)},
4667 "blob");
4668 print " | " if ($has_history);
4670 if ($has_history) {
4671 print $cgi->a({-href => href(action=>"history",
4672 file_name=>$diff->{'to_file'},
4673 hash_base=>$hash)},
4674 "history");
4676 print "</td>\n";
4678 print "</tr>\n";
4679 next; # instead of 'else' clause, to avoid extra indent
4681 # else ordinary diff
4683 my ($to_mode_oct, $to_mode_str, $to_file_type);
4684 my ($from_mode_oct, $from_mode_str, $from_file_type);
4685 if ($diff->{'to_mode'} ne ('0' x 6)) {
4686 $to_mode_oct = oct $diff->{'to_mode'};
4687 if (S_ISREG($to_mode_oct)) { # only for regular file
4688 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4690 $to_file_type = file_type($diff->{'to_mode'});
4692 if ($diff->{'from_mode'} ne ('0' x 6)) {
4693 $from_mode_oct = oct $diff->{'from_mode'};
4694 if (S_ISREG($from_mode_oct)) { # only for regular file
4695 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4697 $from_file_type = file_type($diff->{'from_mode'});
4700 if ($diff->{'status'} eq "A") { # created
4701 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4702 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4703 $mode_chng .= "]</span>";
4704 print "<td>";
4705 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4706 hash_base=>$hash, file_name=>$diff->{'file'}),
4707 -class => "list"}, esc_path($diff->{'file'}));
4708 print "</td>\n";
4709 print "<td>$mode_chng</td>\n";
4710 print "<td class=\"link\">";
4711 if ($action eq 'commitdiff') {
4712 # link to patch
4713 $patchno++;
4714 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4715 "patch") .
4716 " | ";
4718 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4719 hash_base=>$hash, file_name=>$diff->{'file'})},
4720 "blob");
4721 print "</td>\n";
4723 } elsif ($diff->{'status'} eq "D") { # deleted
4724 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4725 print "<td>";
4726 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4727 hash_base=>$parent, file_name=>$diff->{'file'}),
4728 -class => "list"}, esc_path($diff->{'file'}));
4729 print "</td>\n";
4730 print "<td>$mode_chng</td>\n";
4731 print "<td class=\"link\">";
4732 if ($action eq 'commitdiff') {
4733 # link to patch
4734 $patchno++;
4735 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4736 "patch") .
4737 " | ";
4739 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4740 hash_base=>$parent, file_name=>$diff->{'file'})},
4741 "blob") . " | ";
4742 if ($have_blame) {
4743 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4744 file_name=>$diff->{'file'})},
4745 "blame") . " | ";
4747 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4748 file_name=>$diff->{'file'})},
4749 "history");
4750 print "</td>\n";
4752 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4753 my $mode_chnge = "";
4754 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4755 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4756 if ($from_file_type ne $to_file_type) {
4757 $mode_chnge .= " from $from_file_type to $to_file_type";
4759 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4760 if ($from_mode_str && $to_mode_str) {
4761 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4762 } elsif ($to_mode_str) {
4763 $mode_chnge .= " mode: $to_mode_str";
4766 $mode_chnge .= "]</span>\n";
4768 print "<td>";
4769 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4770 hash_base=>$hash, file_name=>$diff->{'file'}),
4771 -class => "list"}, esc_path($diff->{'file'}));
4772 print "</td>\n";
4773 print "<td>$mode_chnge</td>\n";
4774 print "<td class=\"link\">";
4775 if ($action eq 'commitdiff') {
4776 # link to patch
4777 $patchno++;
4778 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4779 "patch") .
4780 " | ";
4781 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4782 # "commit" view and modified file (not onlu mode changed)
4783 print $cgi->a({-href => href(action=>"blobdiff",
4784 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4785 hash_base=>$hash, hash_parent_base=>$parent,
4786 file_name=>$diff->{'file'})},
4787 "diff") .
4788 " | ";
4790 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4791 hash_base=>$hash, file_name=>$diff->{'file'})},
4792 "blob") . " | ";
4793 if ($have_blame) {
4794 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4795 file_name=>$diff->{'file'})},
4796 "blame") . " | ";
4798 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4799 file_name=>$diff->{'file'})},
4800 "history");
4801 print "</td>\n";
4803 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4804 my %status_name = ('R' => 'moved', 'C' => 'copied');
4805 my $nstatus = $status_name{$diff->{'status'}};
4806 my $mode_chng = "";
4807 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4808 # mode also for directories, so we cannot use $to_mode_str
4809 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4811 print "<td>" .
4812 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4813 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4814 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4815 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4816 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4817 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4818 -class => "list"}, esc_path($diff->{'from_file'})) .
4819 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4820 "<td class=\"link\">";
4821 if ($action eq 'commitdiff') {
4822 # link to patch
4823 $patchno++;
4824 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4825 "patch") .
4826 " | ";
4827 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4828 # "commit" view and modified file (not only pure rename or copy)
4829 print $cgi->a({-href => href(action=>"blobdiff",
4830 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4831 hash_base=>$hash, hash_parent_base=>$parent,
4832 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4833 "diff") .
4834 " | ";
4836 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4837 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4838 "blob") . " | ";
4839 if ($have_blame) {
4840 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4841 file_name=>$diff->{'to_file'})},
4842 "blame") . " | ";
4844 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4845 file_name=>$diff->{'to_file'})},
4846 "history");
4847 print "</td>\n";
4849 } # we should not encounter Unmerged (U) or Unknown (X) status
4850 print "</tr>\n";
4852 print "</tbody>" if $has_header;
4853 print "</table>\n";
4856 sub print_sidebyside_diff_chunk {
4857 my @chunk = @_;
4858 my (@ctx, @rem, @add);
4860 return unless @chunk;
4862 # incomplete last line might be among removed or added lines,
4863 # or among context lines
4864 if ($chunk[-1][0] eq 'incomplete' &&
4865 defined $chunk[-2]) {
4866 $chunk[-1] = [ $chunk[-2][0], $chunk[-1][1] ];
4869 # guardian
4870 push @chunk, ["", ""];
4872 foreach my $line_info (@chunk) {
4873 my ($class, $line) = @$line_info;
4875 # print chunk headers
4876 if ($class eq 'chunk_header') {
4877 print $line;
4878 next;
4881 # empty contents block on start rem/add block, or end
4882 if (@ctx && (!$class || $class eq 'rem' || $class eq 'add')) {
4883 print join '',
4884 '<div class="chunk_block ctx">',
4885 '<div class="old">',
4886 @ctx,
4887 '</div>',
4888 '<div class="new">',
4889 @ctx,
4890 '</div>',
4891 '</div>';
4892 @ctx = ();
4894 # rem, add or change
4895 if ($class eq 'rem') {
4896 push @rem, $line;
4897 } elsif ($class eq 'add') {
4898 push @add, $line;
4901 # empty add/rem block on start context block, or end
4902 if ((@rem || @add) && (!$class || $class eq 'ctx')) {
4903 if (!@add) {
4904 # pure removal
4905 print join '',
4906 '<div class="chunk_block rem">',
4907 '<div class="old">',
4908 @rem,
4909 '</div>',
4910 '</div>';
4911 } elsif (!@rem) {
4912 # pure addition
4913 print join '',
4914 '<div class="chunk_block add">',
4915 '<div class="new">',
4916 @add,
4917 '</div>',
4918 '</div>';
4919 } else {
4920 # assume that it is change
4921 print join '',
4922 '<div class="chunk_block chg">',
4923 '<div class="old">',
4924 @rem,
4925 '</div>',
4926 '<div class="new">',
4927 @add,
4928 '</div>',
4929 '</div>';
4931 @rem = @add = ();
4933 # context line
4934 if ($class eq 'ctx') {
4935 push @ctx, $line;
4940 sub git_patchset_body {
4941 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
4942 my ($hash_parent) = $hash_parents[0];
4944 my $is_combined = (@hash_parents > 1);
4945 my $patch_idx = 0;
4946 my $patch_number = 0;
4947 my $patch_line;
4948 my $diffinfo;
4949 my $to_name;
4950 my (%from, %to);
4952 print "<div class=\"patchset\">\n";
4954 # skip to first patch
4955 while ($patch_line = <$fd>) {
4956 chomp $patch_line;
4958 last if ($patch_line =~ m/^diff /);
4961 PATCH:
4962 while ($patch_line) {
4964 # parse "git diff" header line
4965 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4966 # $1 is from_name, which we do not use
4967 $to_name = unquote($2);
4968 $to_name =~ s!^b/!!;
4969 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4970 # $1 is 'cc' or 'combined', which we do not use
4971 $to_name = unquote($2);
4972 } else {
4973 $to_name = undef;
4976 # check if current patch belong to current raw line
4977 # and parse raw git-diff line if needed
4978 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4979 # this is continuation of a split patch
4980 print "<div class=\"patch cont\">\n";
4981 } else {
4982 # advance raw git-diff output if needed
4983 $patch_idx++ if defined $diffinfo;
4985 # read and prepare patch information
4986 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4988 # compact combined diff output can have some patches skipped
4989 # find which patch (using pathname of result) we are at now;
4990 if ($is_combined) {
4991 while ($to_name ne $diffinfo->{'to_file'}) {
4992 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4993 format_diff_cc_simplified($diffinfo, @hash_parents) .
4994 "</div>\n"; # class="patch"
4996 $patch_idx++;
4997 $patch_number++;
4999 last if $patch_idx > $#$difftree;
5000 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5004 # modifies %from, %to hashes
5005 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5007 # this is first patch for raw difftree line with $patch_idx index
5008 # we index @$difftree array from 0, but number patches from 1
5009 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5012 # git diff header
5013 #assert($patch_line =~ m/^diff /) if DEBUG;
5014 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5015 $patch_number++;
5016 # print "git diff" header
5017 print format_git_diff_header_line($patch_line, $diffinfo,
5018 \%from, \%to);
5020 # print extended diff header
5021 print "<div class=\"diff extended_header\">\n";
5022 EXTENDED_HEADER:
5023 while ($patch_line = <$fd>) {
5024 chomp $patch_line;
5026 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5028 print format_extended_diff_header_line($patch_line, $diffinfo,
5029 \%from, \%to);
5031 print "</div>\n"; # class="diff extended_header"
5033 # from-file/to-file diff header
5034 if (! $patch_line) {
5035 print "</div>\n"; # class="patch"
5036 last PATCH;
5038 next PATCH if ($patch_line =~ m/^diff /);
5039 #assert($patch_line =~ m/^---/) if DEBUG;
5041 my $last_patch_line = $patch_line;
5042 $patch_line = <$fd>;
5043 chomp $patch_line;
5044 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5046 print format_diff_from_to_header($last_patch_line, $patch_line,
5047 $diffinfo, \%from, \%to,
5048 @hash_parents);
5050 # the patch itself
5051 LINE:
5052 my @chunk;
5053 while ($patch_line = <$fd>) {
5054 chomp $patch_line;
5056 next PATCH if ($patch_line =~ m/^diff /);
5058 my ($class, $line) = process_diff_line($patch_line, \%from, \%to);
5059 my $diff_classes = "diff";
5060 $diff_classes .= " $class" if ($class);
5061 $line = "<div class=\"$diff_classes\">$line</div>\n";
5063 if ($diff_style eq 'sidebyside' && !$is_combined) {
5064 if ($class eq 'chunk_header') {
5065 print_sidebyside_diff_chunk(@chunk);
5066 @chunk = ( [ $class, $line ] );
5067 } else {
5068 push @chunk, [ $class, $line ];
5070 } else {
5071 # default 'inline' style and unknown styles
5072 print $line;
5075 print_sidebyside_diff_chunk(@chunk)
5076 if (@chunk);
5078 } continue {
5079 print "</div>\n"; # class="patch"
5082 # for compact combined (--cc) format, with chunk and patch simplification
5083 # the patchset might be empty, but there might be unprocessed raw lines
5084 for (++$patch_idx if $patch_number > 0;
5085 $patch_idx < @$difftree;
5086 ++$patch_idx) {
5087 # read and prepare patch information
5088 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5090 # generate anchor for "patch" links in difftree / whatchanged part
5091 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5092 format_diff_cc_simplified($diffinfo, @hash_parents) .
5093 "</div>\n"; # class="patch"
5095 $patch_number++;
5098 if ($patch_number == 0) {
5099 if (@hash_parents > 1) {
5100 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5101 } else {
5102 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5106 print "</div>\n"; # class="patchset"
5109 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5111 # fills project list info (age, description, owner, category, forks)
5112 # for each project in the list, removing invalid projects from
5113 # returned list
5114 # NOTE: modifies $projlist, but does not remove entries from it
5115 sub fill_project_list_info {
5116 my $projlist = shift;
5117 my @projects;
5119 my $show_ctags = gitweb_check_feature('ctags');
5120 PROJECT:
5121 foreach my $pr (@$projlist) {
5122 my (@activity) = git_get_last_activity($pr->{'path'});
5123 unless (@activity) {
5124 next PROJECT;
5126 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5127 if (!defined $pr->{'descr'}) {
5128 my $descr = git_get_project_description($pr->{'path'}) || "";
5129 $descr = to_utf8($descr);
5130 $pr->{'descr_long'} = $descr;
5131 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5133 if (!defined $pr->{'owner'}) {
5134 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5136 if ($show_ctags) {
5137 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5139 if ($projects_list_group_categories && !defined $pr->{'category'}) {
5140 my $cat = git_get_project_category($pr->{'path'}) ||
5141 $project_list_default_category;
5142 $pr->{'category'} = to_utf8($cat);
5145 push @projects, $pr;
5148 return @projects;
5151 sub sort_projects_list {
5152 my ($projlist, $order) = @_;
5153 my @projects;
5155 my %order_info = (
5156 project => { key => 'path', type => 'str' },
5157 descr => { key => 'descr_long', type => 'str' },
5158 owner => { key => 'owner', type => 'str' },
5159 age => { key => 'age', type => 'num' }
5161 my $oi = $order_info{$order};
5162 return @$projlist unless defined $oi;
5163 if ($oi->{'type'} eq 'str') {
5164 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @$projlist;
5165 } else {
5166 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @$projlist;
5169 return @projects;
5172 # returns a hash of categories, containing the list of project
5173 # belonging to each category
5174 sub build_projlist_by_category {
5175 my ($projlist, $from, $to) = @_;
5176 my %categories;
5178 $from = 0 unless defined $from;
5179 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5181 for (my $i = $from; $i <= $to; $i++) {
5182 my $pr = $projlist->[$i];
5183 push @{$categories{ $pr->{'category'} }}, $pr;
5186 return wantarray ? %categories : \%categories;
5189 # print 'sort by' <th> element, generating 'sort by $name' replay link
5190 # if that order is not selected
5191 sub print_sort_th {
5192 print format_sort_th(@_);
5195 sub format_sort_th {
5196 my ($name, $order, $header) = @_;
5197 my $sort_th = "";
5198 $header ||= ucfirst($name);
5200 if ($order eq $name) {
5201 $sort_th .= "<th>$header</th>\n";
5202 } else {
5203 $sort_th .= "<th>" .
5204 $cgi->a({-href => href(-replay=>1, order=>$name),
5205 -class => "header"}, $header) .
5206 "</th>\n";
5209 return $sort_th;
5212 sub git_project_list_rows {
5213 my ($projlist, $from, $to, $check_forks) = @_;
5215 $from = 0 unless defined $from;
5216 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5218 my $alternate = 1;
5219 for (my $i = $from; $i <= $to; $i++) {
5220 my $pr = $projlist->[$i];
5222 if ($alternate) {
5223 print "<tr class=\"dark\">\n";
5224 } else {
5225 print "<tr class=\"light\">\n";
5227 $alternate ^= 1;
5229 if ($check_forks) {
5230 print "<td>";
5231 if ($pr->{'forks'}) {
5232 my $nforks = scalar @{$pr->{'forks'}};
5233 if ($nforks > 0) {
5234 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5235 -title => "$nforks forks"}, "+");
5236 } else {
5237 print $cgi->span({-title => "$nforks forks"}, "+");
5240 print "</td>\n";
5242 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5243 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
5244 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5245 -class => "list", -title => $pr->{'descr_long'}},
5246 esc_html($pr->{'descr'})) . "</td>\n" .
5247 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5248 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5249 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
5250 "<td class=\"link\">" .
5251 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5252 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5253 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5254 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5255 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5256 "</td>\n" .
5257 "</tr>\n";
5261 sub git_project_list_body {
5262 # actually uses global variable $project
5263 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5264 my @projects = @$projlist;
5266 my $check_forks = gitweb_check_feature('forks');
5267 my $show_ctags = gitweb_check_feature('ctags');
5268 my $tagfilter = $show_ctags ? $cgi->param('by_tag') : undef;
5269 $check_forks = undef
5270 if ($tagfilter || $searchtext);
5272 # filtering out forks before filling info allows to do less work
5273 @projects = filter_forks_from_projects_list(\@projects)
5274 if ($check_forks);
5275 @projects = fill_project_list_info(\@projects);
5276 # searching projects require filling to be run before it
5277 @projects = search_projects_list(\@projects,
5278 'searchtext' => $searchtext,
5279 'tagfilter' => $tagfilter)
5280 if ($tagfilter || $searchtext);
5282 $order ||= $default_projects_order;
5283 $from = 0 unless defined $from;
5284 $to = $#projects if (!defined $to || $#projects < $to);
5286 # short circuit
5287 if ($from > $to) {
5288 print "<center>\n".
5289 "<b>No such projects found</b><br />\n".
5290 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5291 "</center>\n<br />\n";
5292 return;
5295 @projects = sort_projects_list(\@projects, $order);
5297 if ($show_ctags) {
5298 my $ctags = git_gather_all_ctags(\@projects);
5299 my $cloud = git_populate_project_tagcloud($ctags);
5300 print git_show_project_tagcloud($cloud, 64);
5303 print "<table class=\"project_list\">\n";
5304 unless ($no_header) {
5305 print "<tr>\n";
5306 if ($check_forks) {
5307 print "<th></th>\n";
5309 print_sort_th('project', $order, 'Project');
5310 print_sort_th('descr', $order, 'Description');
5311 print_sort_th('owner', $order, 'Owner');
5312 print_sort_th('age', $order, 'Last Change');
5313 print "<th></th>\n" . # for links
5314 "</tr>\n";
5317 if ($projects_list_group_categories) {
5318 # only display categories with projects in the $from-$to window
5319 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5320 my %categories = build_projlist_by_category(\@projects, $from, $to);
5321 foreach my $cat (sort keys %categories) {
5322 unless ($cat eq "") {
5323 print "<tr>\n";
5324 if ($check_forks) {
5325 print "<td></td>\n";
5327 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5328 print "</tr>\n";
5331 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5333 } else {
5334 git_project_list_rows(\@projects, $from, $to, $check_forks);
5337 if (defined $extra) {
5338 print "<tr>\n";
5339 if ($check_forks) {
5340 print "<td></td>\n";
5342 print "<td colspan=\"5\">$extra</td>\n" .
5343 "</tr>\n";
5345 print "</table>\n";
5348 sub git_log_body {
5349 # uses global variable $project
5350 my ($commitlist, $from, $to, $refs, $extra) = @_;
5352 $from = 0 unless defined $from;
5353 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5355 for (my $i = 0; $i <= $to; $i++) {
5356 my %co = %{$commitlist->[$i]};
5357 next if !%co;
5358 my $commit = $co{'id'};
5359 my $ref = format_ref_marker($refs, $commit);
5360 git_print_header_div('commit',
5361 "<span class=\"age\">$co{'age_string'}</span>" .
5362 esc_html($co{'title'}) . $ref,
5363 $commit);
5364 print "<div class=\"title_text\">\n" .
5365 "<div class=\"log_link\">\n" .
5366 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5367 " | " .
5368 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5369 " | " .
5370 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5371 "<br/>\n" .
5372 "</div>\n";
5373 git_print_authorship(\%co, -tag => 'span');
5374 print "<br/>\n</div>\n";
5376 print "<div class=\"log_body\">\n";
5377 git_print_log($co{'comment'}, -final_empty_line=> 1);
5378 print "</div>\n";
5380 if ($extra) {
5381 print "<div class=\"page_nav\">\n";
5382 print "$extra\n";
5383 print "</div>\n";
5387 sub git_shortlog_body {
5388 # uses global variable $project
5389 my ($commitlist, $from, $to, $refs, $extra) = @_;
5391 $from = 0 unless defined $from;
5392 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5394 print "<table class=\"shortlog\">\n";
5395 my $alternate = 1;
5396 for (my $i = $from; $i <= $to; $i++) {
5397 my %co = %{$commitlist->[$i]};
5398 my $commit = $co{'id'};
5399 my $ref = format_ref_marker($refs, $commit);
5400 if ($alternate) {
5401 print "<tr class=\"dark\">\n";
5402 } else {
5403 print "<tr class=\"light\">\n";
5405 $alternate ^= 1;
5406 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5407 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5408 format_author_html('td', \%co, 10) . "<td>";
5409 print format_subject_html($co{'title'}, $co{'title_short'},
5410 href(action=>"commit", hash=>$commit), $ref);
5411 print "</td>\n" .
5412 "<td class=\"link\">" .
5413 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5414 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5415 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5416 my $snapshot_links = format_snapshot_links($commit);
5417 if (defined $snapshot_links) {
5418 print " | " . $snapshot_links;
5420 print "</td>\n" .
5421 "</tr>\n";
5423 if (defined $extra) {
5424 print "<tr>\n" .
5425 "<td colspan=\"4\">$extra</td>\n" .
5426 "</tr>\n";
5428 print "</table>\n";
5431 sub git_history_body {
5432 # Warning: assumes constant type (blob or tree) during history
5433 my ($commitlist, $from, $to, $refs, $extra,
5434 $file_name, $file_hash, $ftype) = @_;
5436 $from = 0 unless defined $from;
5437 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5439 print "<table class=\"history\">\n";
5440 my $alternate = 1;
5441 for (my $i = $from; $i <= $to; $i++) {
5442 my %co = %{$commitlist->[$i]};
5443 if (!%co) {
5444 next;
5446 my $commit = $co{'id'};
5448 my $ref = format_ref_marker($refs, $commit);
5450 if ($alternate) {
5451 print "<tr class=\"dark\">\n";
5452 } else {
5453 print "<tr class=\"light\">\n";
5455 $alternate ^= 1;
5456 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5457 # shortlog: format_author_html('td', \%co, 10)
5458 format_author_html('td', \%co, 15, 3) . "<td>";
5459 # originally git_history used chop_str($co{'title'}, 50)
5460 print format_subject_html($co{'title'}, $co{'title_short'},
5461 href(action=>"commit", hash=>$commit), $ref);
5462 print "</td>\n" .
5463 "<td class=\"link\">" .
5464 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5465 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5467 if ($ftype eq 'blob') {
5468 my $blob_current = $file_hash;
5469 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5470 if (defined $blob_current && defined $blob_parent &&
5471 $blob_current ne $blob_parent) {
5472 print " | " .
5473 $cgi->a({-href => href(action=>"blobdiff",
5474 hash=>$blob_current, hash_parent=>$blob_parent,
5475 hash_base=>$hash_base, hash_parent_base=>$commit,
5476 file_name=>$file_name)},
5477 "diff to current");
5480 print "</td>\n" .
5481 "</tr>\n";
5483 if (defined $extra) {
5484 print "<tr>\n" .
5485 "<td colspan=\"4\">$extra</td>\n" .
5486 "</tr>\n";
5488 print "</table>\n";
5491 sub git_tags_body {
5492 # uses global variable $project
5493 my ($taglist, $from, $to, $extra) = @_;
5494 $from = 0 unless defined $from;
5495 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5497 print "<table class=\"tags\">\n";
5498 my $alternate = 1;
5499 for (my $i = $from; $i <= $to; $i++) {
5500 my $entry = $taglist->[$i];
5501 my %tag = %$entry;
5502 my $comment = $tag{'subject'};
5503 my $comment_short;
5504 if (defined $comment) {
5505 $comment_short = chop_str($comment, 30, 5);
5507 if ($alternate) {
5508 print "<tr class=\"dark\">\n";
5509 } else {
5510 print "<tr class=\"light\">\n";
5512 $alternate ^= 1;
5513 if (defined $tag{'age'}) {
5514 print "<td><i>$tag{'age'}</i></td>\n";
5515 } else {
5516 print "<td></td>\n";
5518 print "<td>" .
5519 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5520 -class => "list name"}, esc_html($tag{'name'})) .
5521 "</td>\n" .
5522 "<td>";
5523 if (defined $comment) {
5524 print format_subject_html($comment, $comment_short,
5525 href(action=>"tag", hash=>$tag{'id'}));
5527 print "</td>\n" .
5528 "<td class=\"selflink\">";
5529 if ($tag{'type'} eq "tag") {
5530 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5531 } else {
5532 print "&nbsp;";
5534 print "</td>\n" .
5535 "<td class=\"link\">" . " | " .
5536 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5537 if ($tag{'reftype'} eq "commit") {
5538 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5539 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5540 } elsif ($tag{'reftype'} eq "blob") {
5541 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5543 print "</td>\n" .
5544 "</tr>";
5546 if (defined $extra) {
5547 print "<tr>\n" .
5548 "<td colspan=\"5\">$extra</td>\n" .
5549 "</tr>\n";
5551 print "</table>\n";
5554 sub git_heads_body {
5555 # uses global variable $project
5556 my ($headlist, $head, $from, $to, $extra) = @_;
5557 $from = 0 unless defined $from;
5558 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5560 print "<table class=\"heads\">\n";
5561 my $alternate = 1;
5562 for (my $i = $from; $i <= $to; $i++) {
5563 my $entry = $headlist->[$i];
5564 my %ref = %$entry;
5565 my $curr = $ref{'id'} eq $head;
5566 if ($alternate) {
5567 print "<tr class=\"dark\">\n";
5568 } else {
5569 print "<tr class=\"light\">\n";
5571 $alternate ^= 1;
5572 print "<td><i>$ref{'age'}</i></td>\n" .
5573 ($curr ? "<td class=\"current_head\">" : "<td>") .
5574 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5575 -class => "list name"},esc_html($ref{'name'})) .
5576 "</td>\n" .
5577 "<td class=\"link\">" .
5578 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5579 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5580 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
5581 "</td>\n" .
5582 "</tr>";
5584 if (defined $extra) {
5585 print "<tr>\n" .
5586 "<td colspan=\"3\">$extra</td>\n" .
5587 "</tr>\n";
5589 print "</table>\n";
5592 # Display a single remote block
5593 sub git_remote_block {
5594 my ($remote, $rdata, $limit, $head) = @_;
5596 my $heads = $rdata->{'heads'};
5597 my $fetch = $rdata->{'fetch'};
5598 my $push = $rdata->{'push'};
5600 my $urls_table = "<table class=\"projects_list\">\n" ;
5602 if (defined $fetch) {
5603 if ($fetch eq $push) {
5604 $urls_table .= format_repo_url("URL", $fetch);
5605 } else {
5606 $urls_table .= format_repo_url("Fetch URL", $fetch);
5607 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
5609 } elsif (defined $push) {
5610 $urls_table .= format_repo_url("Push URL", $push);
5611 } else {
5612 $urls_table .= format_repo_url("", "No remote URL");
5615 $urls_table .= "</table>\n";
5617 my $dots;
5618 if (defined $limit && $limit < @$heads) {
5619 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
5622 print $urls_table;
5623 git_heads_body($heads, $head, 0, $limit, $dots);
5626 # Display a list of remote names with the respective fetch and push URLs
5627 sub git_remotes_list {
5628 my ($remotedata, $limit) = @_;
5629 print "<table class=\"heads\">\n";
5630 my $alternate = 1;
5631 my @remotes = sort keys %$remotedata;
5633 my $limited = $limit && $limit < @remotes;
5635 $#remotes = $limit - 1 if $limited;
5637 while (my $remote = shift @remotes) {
5638 my $rdata = $remotedata->{$remote};
5639 my $fetch = $rdata->{'fetch'};
5640 my $push = $rdata->{'push'};
5641 if ($alternate) {
5642 print "<tr class=\"dark\">\n";
5643 } else {
5644 print "<tr class=\"light\">\n";
5646 $alternate ^= 1;
5647 print "<td>" .
5648 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
5649 -class=> "list name"},esc_html($remote)) .
5650 "</td>";
5651 print "<td class=\"link\">" .
5652 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
5653 " | " .
5654 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
5655 "</td>";
5657 print "</tr>\n";
5660 if ($limited) {
5661 print "<tr>\n" .
5662 "<td colspan=\"3\">" .
5663 $cgi->a({-href => href(action=>"remotes")}, "...") .
5664 "</td>\n" . "</tr>\n";
5667 print "</table>";
5670 # Display remote heads grouped by remote, unless there are too many
5671 # remotes, in which case we only display the remote names
5672 sub git_remotes_body {
5673 my ($remotedata, $limit, $head) = @_;
5674 if ($limit and $limit < keys %$remotedata) {
5675 git_remotes_list($remotedata, $limit);
5676 } else {
5677 fill_remote_heads($remotedata);
5678 while (my ($remote, $rdata) = each %$remotedata) {
5679 git_print_section({-class=>"remote", -id=>$remote},
5680 ["remotes", $remote, $remote], sub {
5681 git_remote_block($remote, $rdata, $limit, $head);
5687 sub git_search_message {
5688 my %co = @_;
5690 my $greptype;
5691 if ($searchtype eq 'commit') {
5692 $greptype = "--grep=";
5693 } elsif ($searchtype eq 'author') {
5694 $greptype = "--author=";
5695 } elsif ($searchtype eq 'committer') {
5696 $greptype = "--committer=";
5698 $greptype .= $searchtext;
5699 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5700 $greptype, '--regexp-ignore-case',
5701 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5703 my $paging_nav = '';
5704 if ($page > 0) {
5705 $paging_nav .=
5706 $cgi->a({-href => href(-replay=>1, page=>undef)},
5707 "first") .
5708 " &sdot; " .
5709 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5710 -accesskey => "p", -title => "Alt-p"}, "prev");
5711 } else {
5712 $paging_nav .= "first &sdot; prev";
5714 my $next_link = '';
5715 if ($#commitlist >= 100) {
5716 $next_link =
5717 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5718 -accesskey => "n", -title => "Alt-n"}, "next");
5719 $paging_nav .= " &sdot; $next_link";
5720 } else {
5721 $paging_nav .= " &sdot; next";
5724 git_header_html();
5726 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5727 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5728 if ($page == 0 && !@commitlist) {
5729 print "<p>No match.</p>\n";
5730 } else {
5731 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5734 git_footer_html();
5737 sub git_search_changes {
5738 my %co = @_;
5740 local $/ = "\n";
5741 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5742 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5743 ($search_use_regexp ? '--pickaxe-regex' : ())
5744 or die_error(500, "Open git-log failed");
5746 git_header_html();
5748 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5749 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5751 print "<table class=\"pickaxe search\">\n";
5752 my $alternate = 1;
5753 undef %co;
5754 my @files;
5755 while (my $line = <$fd>) {
5756 chomp $line;
5757 next unless $line;
5759 my %set = parse_difftree_raw_line($line);
5760 if (defined $set{'commit'}) {
5761 # finish previous commit
5762 if (%co) {
5763 print "</td>\n" .
5764 "<td class=\"link\">" .
5765 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
5766 "commit") .
5767 " | " .
5768 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
5769 hash_base=>$co{'id'})},
5770 "tree") .
5771 "</td>\n" .
5772 "</tr>\n";
5775 if ($alternate) {
5776 print "<tr class=\"dark\">\n";
5777 } else {
5778 print "<tr class=\"light\">\n";
5780 $alternate ^= 1;
5781 %co = parse_commit($set{'commit'});
5782 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5783 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5784 "<td><i>$author</i></td>\n" .
5785 "<td>" .
5786 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5787 -class => "list subject"},
5788 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5789 } elsif (defined $set{'to_id'}) {
5790 next if ($set{'to_id'} =~ m/^0{40}$/);
5792 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5793 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
5794 -class => "list"},
5795 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5796 "<br/>\n";
5799 close $fd;
5801 # finish last commit (warning: repetition!)
5802 if (%co) {
5803 print "</td>\n" .
5804 "<td class=\"link\">" .
5805 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
5806 "commit") .
5807 " | " .
5808 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
5809 hash_base=>$co{'id'})},
5810 "tree") .
5811 "</td>\n" .
5812 "</tr>\n";
5815 print "</table>\n";
5817 git_footer_html();
5820 sub git_search_files {
5821 my %co = @_;
5823 local $/ = "\n";
5824 open my $fd, "-|", git_cmd(), 'grep', '-n',
5825 $search_use_regexp ? ('-E', '-i') : '-F',
5826 $searchtext, $co{'tree'}
5827 or die_error(500, "Open git-grep failed");
5829 git_header_html();
5831 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5832 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5834 print "<table class=\"grep_search\">\n";
5835 my $alternate = 1;
5836 my $matches = 0;
5837 my $lastfile = '';
5838 while (my $line = <$fd>) {
5839 chomp $line;
5840 my ($file, $lno, $ltext, $binary);
5841 last if ($matches++ > 1000);
5842 if ($line =~ /^Binary file (.+) matches$/) {
5843 $file = $1;
5844 $binary = 1;
5845 } else {
5846 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5848 if ($file ne $lastfile) {
5849 $lastfile and print "</td></tr>\n";
5850 if ($alternate++) {
5851 print "<tr class=\"dark\">\n";
5852 } else {
5853 print "<tr class=\"light\">\n";
5855 print "<td class=\"list\">".
5856 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5857 file_name=>"$file"),
5858 -class => "list"}, esc_path($file));
5859 print "</td><td>\n";
5860 $lastfile = $file;
5862 if ($binary) {
5863 print "<div class=\"binary\">Binary file</div>\n";
5864 } else {
5865 $ltext = untabify($ltext);
5866 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
5867 $ltext = esc_html($1, -nbsp=>1);
5868 $ltext .= '<span class="match">';
5869 $ltext .= esc_html($2, -nbsp=>1);
5870 $ltext .= '</span>';
5871 $ltext .= esc_html($3, -nbsp=>1);
5872 } else {
5873 $ltext = esc_html($ltext, -nbsp=>1);
5875 print "<div class=\"pre\">" .
5876 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5877 file_name=>"$file").'#l'.$lno,
5878 -class => "linenr"}, sprintf('%4i', $lno))
5879 . ' ' . $ltext . "</div>\n";
5882 if ($lastfile) {
5883 print "</td></tr>\n";
5884 if ($matches > 1000) {
5885 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5887 } else {
5888 print "<div class=\"diff nodifferences\">No matches found</div>\n";
5890 close $fd;
5892 print "</table>\n";
5894 git_footer_html();
5897 sub git_search_grep_body {
5898 my ($commitlist, $from, $to, $extra) = @_;
5899 $from = 0 unless defined $from;
5900 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5902 print "<table class=\"commit_search\">\n";
5903 my $alternate = 1;
5904 for (my $i = $from; $i <= $to; $i++) {
5905 my %co = %{$commitlist->[$i]};
5906 if (!%co) {
5907 next;
5909 my $commit = $co{'id'};
5910 if ($alternate) {
5911 print "<tr class=\"dark\">\n";
5912 } else {
5913 print "<tr class=\"light\">\n";
5915 $alternate ^= 1;
5916 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5917 format_author_html('td', \%co, 15, 5) .
5918 "<td>" .
5919 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5920 -class => "list subject"},
5921 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5922 my $comment = $co{'comment'};
5923 foreach my $line (@$comment) {
5924 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5925 my ($lead, $match, $trail) = ($1, $2, $3);
5926 $match = chop_str($match, 70, 5, 'center');
5927 my $contextlen = int((80 - length($match))/2);
5928 $contextlen = 30 if ($contextlen > 30);
5929 $lead = chop_str($lead, $contextlen, 10, 'left');
5930 $trail = chop_str($trail, $contextlen, 10, 'right');
5932 $lead = esc_html($lead);
5933 $match = esc_html($match);
5934 $trail = esc_html($trail);
5936 print "$lead<span class=\"match\">$match</span>$trail<br />";
5939 print "</td>\n" .
5940 "<td class=\"link\">" .
5941 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5942 " | " .
5943 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5944 " | " .
5945 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5946 print "</td>\n" .
5947 "</tr>\n";
5949 if (defined $extra) {
5950 print "<tr>\n" .
5951 "<td colspan=\"3\">$extra</td>\n" .
5952 "</tr>\n";
5954 print "</table>\n";
5957 ## ======================================================================
5958 ## ======================================================================
5959 ## actions
5961 sub git_project_list {
5962 my $order = $input_params{'order'};
5963 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5964 die_error(400, "Unknown order parameter");
5967 my @list = git_get_projects_list();
5968 if (!@list) {
5969 die_error(404, "No projects found");
5972 git_header_html();
5973 if (defined $home_text && -f $home_text) {
5974 print "<div class=\"index_include\">\n";
5975 insert_file($home_text);
5976 print "</div>\n";
5978 print $cgi->startform(-method => "get") .
5979 "<p class=\"projsearch\">Search:\n" .
5980 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5981 "</p>" .
5982 $cgi->end_form() . "\n";
5983 git_project_list_body(\@list, $order);
5984 git_footer_html();
5987 sub git_forks {
5988 my $order = $input_params{'order'};
5989 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5990 die_error(400, "Unknown order parameter");
5993 my @list = git_get_projects_list($project);
5994 if (!@list) {
5995 die_error(404, "No forks found");
5998 git_header_html();
5999 git_print_page_nav('','');
6000 git_print_header_div('summary', "$project forks");
6001 git_project_list_body(\@list, $order);
6002 git_footer_html();
6005 sub git_project_index {
6006 my @projects = git_get_projects_list();
6007 if (!@projects) {
6008 die_error(404, "No projects found");
6011 print $cgi->header(
6012 -type => 'text/plain',
6013 -charset => 'utf-8',
6014 -content_disposition => 'inline; filename="index.aux"');
6016 foreach my $pr (@projects) {
6017 if (!exists $pr->{'owner'}) {
6018 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6021 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6022 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6023 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6024 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6025 $path =~ s/ /\+/g;
6026 $owner =~ s/ /\+/g;
6028 print "$path $owner\n";
6032 sub git_summary {
6033 my $descr = git_get_project_description($project) || "none";
6034 my %co = parse_commit("HEAD");
6035 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6036 my $head = $co{'id'};
6037 my $remote_heads = gitweb_check_feature('remote_heads');
6039 my $owner = git_get_project_owner($project);
6041 my $refs = git_get_references();
6042 # These get_*_list functions return one more to allow us to see if
6043 # there are more ...
6044 my @taglist = git_get_tags_list(16);
6045 my @headlist = git_get_heads_list(16);
6046 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6047 my @forklist;
6048 my $check_forks = gitweb_check_feature('forks');
6050 if ($check_forks) {
6051 # find forks of a project
6052 @forklist = git_get_projects_list($project);
6053 # filter out forks of forks
6054 @forklist = filter_forks_from_projects_list(\@forklist)
6055 if (@forklist);
6058 git_header_html();
6059 git_print_page_nav('summary','', $head);
6061 print "<div class=\"title\">&nbsp;</div>\n";
6062 print "<table class=\"projects_list\">\n" .
6063 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
6064 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6065 if (defined $cd{'rfc2822'}) {
6066 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6067 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6070 # use per project git URL list in $projectroot/$project/cloneurl
6071 # or make project git URL from git base URL and project name
6072 my $url_tag = "URL";
6073 my @url_list = git_get_project_url_list($project);
6074 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6075 foreach my $git_url (@url_list) {
6076 next unless $git_url;
6077 print format_repo_url($url_tag, $git_url);
6078 $url_tag = "";
6081 # Tag cloud
6082 my $show_ctags = gitweb_check_feature('ctags');
6083 if ($show_ctags) {
6084 my $ctags = git_get_project_ctags($project);
6085 if (%$ctags) {
6086 # without ability to add tags, don't show if there are none
6087 my $cloud = git_populate_project_tagcloud($ctags);
6088 print "<tr id=\"metadata_ctags\">" .
6089 "<td>content tags</td>" .
6090 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6091 "</tr>\n";
6095 print "</table>\n";
6097 # If XSS prevention is on, we don't include README.html.
6098 # TODO: Allow a readme in some safe format.
6099 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6100 print "<div class=\"title\">readme</div>\n" .
6101 "<div class=\"readme\">\n";
6102 insert_file("$projectroot/$project/README.html");
6103 print "\n</div>\n"; # class="readme"
6106 # we need to request one more than 16 (0..15) to check if
6107 # those 16 are all
6108 my @commitlist = $head ? parse_commits($head, 17) : ();
6109 if (@commitlist) {
6110 git_print_header_div('shortlog');
6111 git_shortlog_body(\@commitlist, 0, 15, $refs,
6112 $#commitlist <= 15 ? undef :
6113 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6116 if (@taglist) {
6117 git_print_header_div('tags');
6118 git_tags_body(\@taglist, 0, 15,
6119 $#taglist <= 15 ? undef :
6120 $cgi->a({-href => href(action=>"tags")}, "..."));
6123 if (@headlist) {
6124 git_print_header_div('heads');
6125 git_heads_body(\@headlist, $head, 0, 15,
6126 $#headlist <= 15 ? undef :
6127 $cgi->a({-href => href(action=>"heads")}, "..."));
6130 if (%remotedata) {
6131 git_print_header_div('remotes');
6132 git_remotes_body(\%remotedata, 15, $head);
6135 if (@forklist) {
6136 git_print_header_div('forks');
6137 git_project_list_body(\@forklist, 'age', 0, 15,
6138 $#forklist <= 15 ? undef :
6139 $cgi->a({-href => href(action=>"forks")}, "..."),
6140 'no_header');
6143 git_footer_html();
6146 sub git_tag {
6147 my %tag = parse_tag($hash);
6149 if (! %tag) {
6150 die_error(404, "Unknown tag object");
6153 my $head = git_get_head_hash($project);
6154 git_header_html();
6155 git_print_page_nav('','', $head,undef,$head);
6156 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6157 print "<div class=\"title_text\">\n" .
6158 "<table class=\"object_header\">\n" .
6159 "<tr>\n" .
6160 "<td>object</td>\n" .
6161 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6162 $tag{'object'}) . "</td>\n" .
6163 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6164 $tag{'type'}) . "</td>\n" .
6165 "</tr>\n";
6166 if (defined($tag{'author'})) {
6167 git_print_authorship_rows(\%tag, 'author');
6169 print "</table>\n\n" .
6170 "</div>\n";
6171 print "<div class=\"page_body\">";
6172 my $comment = $tag{'comment'};
6173 foreach my $line (@$comment) {
6174 chomp $line;
6175 print esc_html($line, -nbsp=>1) . "<br/>\n";
6177 print "</div>\n";
6178 git_footer_html();
6181 sub git_blame_common {
6182 my $format = shift || 'porcelain';
6183 if ($format eq 'porcelain' && $cgi->param('js')) {
6184 $format = 'incremental';
6185 $action = 'blame_incremental'; # for page title etc
6188 # permissions
6189 gitweb_check_feature('blame')
6190 or die_error(403, "Blame view not allowed");
6192 # error checking
6193 die_error(400, "No file name given") unless $file_name;
6194 $hash_base ||= git_get_head_hash($project);
6195 die_error(404, "Couldn't find base commit") unless $hash_base;
6196 my %co = parse_commit($hash_base)
6197 or die_error(404, "Commit not found");
6198 my $ftype = "blob";
6199 if (!defined $hash) {
6200 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6201 or die_error(404, "Error looking up file");
6202 } else {
6203 $ftype = git_get_type($hash);
6204 if ($ftype !~ "blob") {
6205 die_error(400, "Object is not a blob");
6209 my $fd;
6210 if ($format eq 'incremental') {
6211 # get file contents (as base)
6212 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6213 or die_error(500, "Open git-cat-file failed");
6214 } elsif ($format eq 'data') {
6215 # run git-blame --incremental
6216 open $fd, "-|", git_cmd(), "blame", "--incremental",
6217 $hash_base, "--", $file_name
6218 or die_error(500, "Open git-blame --incremental failed");
6219 } else {
6220 # run git-blame --porcelain
6221 open $fd, "-|", git_cmd(), "blame", '-p',
6222 $hash_base, '--', $file_name
6223 or die_error(500, "Open git-blame --porcelain failed");
6226 # incremental blame data returns early
6227 if ($format eq 'data') {
6228 print $cgi->header(
6229 -type=>"text/plain", -charset => "utf-8",
6230 -status=> "200 OK");
6231 local $| = 1; # output autoflush
6232 print while <$fd>;
6233 close $fd
6234 or print "ERROR $!\n";
6236 print 'END';
6237 if (defined $t0 && gitweb_check_feature('timed')) {
6238 print ' '.
6239 tv_interval($t0, [ gettimeofday() ]).
6240 ' '.$number_of_git_cmds;
6242 print "\n";
6244 return;
6247 # page header
6248 git_header_html();
6249 my $formats_nav =
6250 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6251 "blob") .
6252 " | ";
6253 if ($format eq 'incremental') {
6254 $formats_nav .=
6255 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6256 "blame") . " (non-incremental)";
6257 } else {
6258 $formats_nav .=
6259 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6260 "blame") . " (incremental)";
6262 $formats_nav .=
6263 " | " .
6264 $cgi->a({-href => href(action=>"history", -replay=>1)},
6265 "history") .
6266 " | " .
6267 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6268 "HEAD");
6269 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6270 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6271 git_print_page_path($file_name, $ftype, $hash_base);
6273 # page body
6274 if ($format eq 'incremental') {
6275 print "<noscript>\n<div class=\"error\"><center><b>\n".
6276 "This page requires JavaScript to run.\n Use ".
6277 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6278 'this page').
6279 " instead.\n".
6280 "</b></center></div>\n</noscript>\n";
6282 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6285 print qq!<div class="page_body">\n!;
6286 print qq!<div id="progress_info">... / ...</div>\n!
6287 if ($format eq 'incremental');
6288 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6289 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6290 qq!<thead>\n!.
6291 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6292 qq!</thead>\n!.
6293 qq!<tbody>\n!;
6295 my @rev_color = qw(light dark);
6296 my $num_colors = scalar(@rev_color);
6297 my $current_color = 0;
6299 if ($format eq 'incremental') {
6300 my $color_class = $rev_color[$current_color];
6302 #contents of a file
6303 my $linenr = 0;
6304 LINE:
6305 while (my $line = <$fd>) {
6306 chomp $line;
6307 $linenr++;
6309 print qq!<tr id="l$linenr" class="$color_class">!.
6310 qq!<td class="sha1"><a href=""> </a></td>!.
6311 qq!<td class="linenr">!.
6312 qq!<a class="linenr" href="">$linenr</a></td>!;
6313 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6314 print qq!</tr>\n!;
6317 } else { # porcelain, i.e. ordinary blame
6318 my %metainfo = (); # saves information about commits
6320 # blame data
6321 LINE:
6322 while (my $line = <$fd>) {
6323 chomp $line;
6324 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6325 # no <lines in group> for subsequent lines in group of lines
6326 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6327 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6328 if (!exists $metainfo{$full_rev}) {
6329 $metainfo{$full_rev} = { 'nprevious' => 0 };
6331 my $meta = $metainfo{$full_rev};
6332 my $data;
6333 while ($data = <$fd>) {
6334 chomp $data;
6335 last if ($data =~ s/^\t//); # contents of line
6336 if ($data =~ /^(\S+)(?: (.*))?$/) {
6337 $meta->{$1} = $2 unless exists $meta->{$1};
6339 if ($data =~ /^previous /) {
6340 $meta->{'nprevious'}++;
6343 my $short_rev = substr($full_rev, 0, 8);
6344 my $author = $meta->{'author'};
6345 my %date =
6346 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6347 my $date = $date{'iso-tz'};
6348 if ($group_size) {
6349 $current_color = ($current_color + 1) % $num_colors;
6351 my $tr_class = $rev_color[$current_color];
6352 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6353 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6354 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6355 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6356 if ($group_size) {
6357 print "<td class=\"sha1\"";
6358 print " title=\"". esc_html($author) . ", $date\"";
6359 print " rowspan=\"$group_size\"" if ($group_size > 1);
6360 print ">";
6361 print $cgi->a({-href => href(action=>"commit",
6362 hash=>$full_rev,
6363 file_name=>$file_name)},
6364 esc_html($short_rev));
6365 if ($group_size >= 2) {
6366 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6367 if (@author_initials) {
6368 print "<br />" .
6369 esc_html(join('', @author_initials));
6370 # or join('.', ...)
6373 print "</td>\n";
6375 # 'previous' <sha1 of parent commit> <filename at commit>
6376 if (exists $meta->{'previous'} &&
6377 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6378 $meta->{'parent'} = $1;
6379 $meta->{'file_parent'} = unquote($2);
6381 my $linenr_commit =
6382 exists($meta->{'parent'}) ?
6383 $meta->{'parent'} : $full_rev;
6384 my $linenr_filename =
6385 exists($meta->{'file_parent'}) ?
6386 $meta->{'file_parent'} : unquote($meta->{'filename'});
6387 my $blamed = href(action => 'blame',
6388 file_name => $linenr_filename,
6389 hash_base => $linenr_commit);
6390 print "<td class=\"linenr\">";
6391 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6392 -class => "linenr" },
6393 esc_html($lineno));
6394 print "</td>";
6395 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6396 print "</tr>\n";
6397 } # end while
6401 # footer
6402 print "</tbody>\n".
6403 "</table>\n"; # class="blame"
6404 print "</div>\n"; # class="blame_body"
6405 close $fd
6406 or print "Reading blob failed\n";
6408 git_footer_html();
6411 sub git_blame {
6412 git_blame_common();
6415 sub git_blame_incremental {
6416 git_blame_common('incremental');
6419 sub git_blame_data {
6420 git_blame_common('data');
6423 sub git_tags {
6424 my $head = git_get_head_hash($project);
6425 git_header_html();
6426 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6427 git_print_header_div('summary', $project);
6429 my @tagslist = git_get_tags_list();
6430 if (@tagslist) {
6431 git_tags_body(\@tagslist);
6433 git_footer_html();
6436 sub git_heads {
6437 my $head = git_get_head_hash($project);
6438 git_header_html();
6439 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6440 git_print_header_div('summary', $project);
6442 my @headslist = git_get_heads_list();
6443 if (@headslist) {
6444 git_heads_body(\@headslist, $head);
6446 git_footer_html();
6449 # used both for single remote view and for list of all the remotes
6450 sub git_remotes {
6451 gitweb_check_feature('remote_heads')
6452 or die_error(403, "Remote heads view is disabled");
6454 my $head = git_get_head_hash($project);
6455 my $remote = $input_params{'hash'};
6457 my $remotedata = git_get_remotes_list($remote);
6458 die_error(500, "Unable to get remote information") unless defined $remotedata;
6460 unless (%$remotedata) {
6461 die_error(404, defined $remote ?
6462 "Remote $remote not found" :
6463 "No remotes found");
6466 git_header_html(undef, undef, -action_extra => $remote);
6467 git_print_page_nav('', '', $head, undef, $head,
6468 format_ref_views($remote ? '' : 'remotes'));
6470 fill_remote_heads($remotedata);
6471 if (defined $remote) {
6472 git_print_header_div('remotes', "$remote remote for $project");
6473 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6474 } else {
6475 git_print_header_div('summary', "$project remotes");
6476 git_remotes_body($remotedata, undef, $head);
6479 git_footer_html();
6482 sub git_blob_plain {
6483 my $type = shift;
6484 my $expires;
6486 if (!defined $hash) {
6487 if (defined $file_name) {
6488 my $base = $hash_base || git_get_head_hash($project);
6489 $hash = git_get_hash_by_path($base, $file_name, "blob")
6490 or die_error(404, "Cannot find file");
6491 } else {
6492 die_error(400, "No file name defined");
6494 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6495 # blobs defined by non-textual hash id's can be cached
6496 $expires = "+1d";
6499 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6500 or die_error(500, "Open git-cat-file blob '$hash' failed");
6502 # content-type (can include charset)
6503 $type = blob_contenttype($fd, $file_name, $type);
6505 # "save as" filename, even when no $file_name is given
6506 my $save_as = "$hash";
6507 if (defined $file_name) {
6508 $save_as = $file_name;
6509 } elsif ($type =~ m/^text\//) {
6510 $save_as .= '.txt';
6513 # With XSS prevention on, blobs of all types except a few known safe
6514 # ones are served with "Content-Disposition: attachment" to make sure
6515 # they don't run in our security domain. For certain image types,
6516 # blob view writes an <img> tag referring to blob_plain view, and we
6517 # want to be sure not to break that by serving the image as an
6518 # attachment (though Firefox 3 doesn't seem to care).
6519 my $sandbox = $prevent_xss &&
6520 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
6522 # serve text/* as text/plain
6523 if ($prevent_xss &&
6524 ($type =~ m!^text/[a-z]+\b(.*)$! ||
6525 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
6526 my $rest = $1;
6527 $rest = defined $rest ? $rest : '';
6528 $type = "text/plain$rest";
6531 print $cgi->header(
6532 -type => $type,
6533 -expires => $expires,
6534 -content_disposition =>
6535 ($sandbox ? 'attachment' : 'inline')
6536 . '; filename="' . $save_as . '"');
6537 local $/ = undef;
6538 binmode STDOUT, ':raw';
6539 print <$fd>;
6540 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6541 close $fd;
6544 sub git_blob {
6545 my $expires;
6547 if (!defined $hash) {
6548 if (defined $file_name) {
6549 my $base = $hash_base || git_get_head_hash($project);
6550 $hash = git_get_hash_by_path($base, $file_name, "blob")
6551 or die_error(404, "Cannot find file");
6552 } else {
6553 die_error(400, "No file name defined");
6555 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6556 # blobs defined by non-textual hash id's can be cached
6557 $expires = "+1d";
6560 my $have_blame = gitweb_check_feature('blame');
6561 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6562 or die_error(500, "Couldn't cat $file_name, $hash");
6563 my $mimetype = blob_mimetype($fd, $file_name);
6564 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
6565 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
6566 close $fd;
6567 return git_blob_plain($mimetype);
6569 # we can have blame only for text/* mimetype
6570 $have_blame &&= ($mimetype =~ m!^text/!);
6572 my $highlight = gitweb_check_feature('highlight');
6573 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
6574 $fd = run_highlighter($fd, $highlight, $syntax)
6575 if $syntax;
6577 git_header_html(undef, $expires);
6578 my $formats_nav = '';
6579 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6580 if (defined $file_name) {
6581 if ($have_blame) {
6582 $formats_nav .=
6583 $cgi->a({-href => href(action=>"blame", -replay=>1)},
6584 "blame") .
6585 " | ";
6587 $formats_nav .=
6588 $cgi->a({-href => href(action=>"history", -replay=>1)},
6589 "history") .
6590 " | " .
6591 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6592 "raw") .
6593 " | " .
6594 $cgi->a({-href => href(action=>"blob",
6595 hash_base=>"HEAD", file_name=>$file_name)},
6596 "HEAD");
6597 } else {
6598 $formats_nav .=
6599 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6600 "raw");
6602 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6603 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6604 } else {
6605 print "<div class=\"page_nav\">\n" .
6606 "<br/><br/></div>\n" .
6607 "<div class=\"title\">".esc_html($hash)."</div>\n";
6609 git_print_page_path($file_name, "blob", $hash_base);
6610 print "<div class=\"page_body\">\n";
6611 if ($mimetype =~ m!^image/!) {
6612 print qq!<img type="!.esc_attr($mimetype).qq!"!;
6613 if ($file_name) {
6614 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
6616 print qq! src="! .
6617 href(action=>"blob_plain", hash=>$hash,
6618 hash_base=>$hash_base, file_name=>$file_name) .
6619 qq!" />\n!;
6620 } else {
6621 my $nr;
6622 while (my $line = <$fd>) {
6623 chomp $line;
6624 $nr++;
6625 $line = untabify($line);
6626 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
6627 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
6628 $syntax ? sanitize($line) : esc_html($line, -nbsp=>1);
6631 close $fd
6632 or print "Reading blob failed.\n";
6633 print "</div>";
6634 git_footer_html();
6637 sub git_tree {
6638 if (!defined $hash_base) {
6639 $hash_base = "HEAD";
6641 if (!defined $hash) {
6642 if (defined $file_name) {
6643 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
6644 } else {
6645 $hash = $hash_base;
6648 die_error(404, "No such tree") unless defined($hash);
6650 my $show_sizes = gitweb_check_feature('show-sizes');
6651 my $have_blame = gitweb_check_feature('blame');
6653 my @entries = ();
6655 local $/ = "\0";
6656 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
6657 ($show_sizes ? '-l' : ()), @extra_options, $hash
6658 or die_error(500, "Open git-ls-tree failed");
6659 @entries = map { chomp; $_ } <$fd>;
6660 close $fd
6661 or die_error(404, "Reading tree failed");
6664 my $refs = git_get_references();
6665 my $ref = format_ref_marker($refs, $hash_base);
6666 git_header_html();
6667 my $basedir = '';
6668 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6669 my @views_nav = ();
6670 if (defined $file_name) {
6671 push @views_nav,
6672 $cgi->a({-href => href(action=>"history", -replay=>1)},
6673 "history"),
6674 $cgi->a({-href => href(action=>"tree",
6675 hash_base=>"HEAD", file_name=>$file_name)},
6676 "HEAD"),
6678 my $snapshot_links = format_snapshot_links($hash);
6679 if (defined $snapshot_links) {
6680 # FIXME: Should be available when we have no hash base as well.
6681 push @views_nav, $snapshot_links;
6683 git_print_page_nav('tree','', $hash_base, undef, undef,
6684 join(' | ', @views_nav));
6685 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
6686 } else {
6687 undef $hash_base;
6688 print "<div class=\"page_nav\">\n";
6689 print "<br/><br/></div>\n";
6690 print "<div class=\"title\">".esc_html($hash)."</div>\n";
6692 if (defined $file_name) {
6693 $basedir = $file_name;
6694 if ($basedir ne '' && substr($basedir, -1) ne '/') {
6695 $basedir .= '/';
6697 git_print_page_path($file_name, 'tree', $hash_base);
6699 print "<div class=\"page_body\">\n";
6700 print "<table class=\"tree\">\n";
6701 my $alternate = 1;
6702 # '..' (top directory) link if possible
6703 if (defined $hash_base &&
6704 defined $file_name && $file_name =~ m![^/]+$!) {
6705 if ($alternate) {
6706 print "<tr class=\"dark\">\n";
6707 } else {
6708 print "<tr class=\"light\">\n";
6710 $alternate ^= 1;
6712 my $up = $file_name;
6713 $up =~ s!/?[^/]+$!!;
6714 undef $up unless $up;
6715 # based on git_print_tree_entry
6716 print '<td class="mode">' . mode_str('040000') . "</td>\n";
6717 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
6718 print '<td class="list">';
6719 print $cgi->a({-href => href(action=>"tree",
6720 hash_base=>$hash_base,
6721 file_name=>$up)},
6722 "..");
6723 print "</td>\n";
6724 print "<td class=\"link\"></td>\n";
6726 print "</tr>\n";
6728 foreach my $line (@entries) {
6729 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
6731 if ($alternate) {
6732 print "<tr class=\"dark\">\n";
6733 } else {
6734 print "<tr class=\"light\">\n";
6736 $alternate ^= 1;
6738 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
6740 print "</tr>\n";
6742 print "</table>\n" .
6743 "</div>";
6744 git_footer_html();
6747 sub snapshot_name {
6748 my ($project, $hash) = @_;
6750 # path/to/project.git -> project
6751 # path/to/project/.git -> project
6752 my $name = to_utf8($project);
6753 $name =~ s,([^/])/*\.git$,$1,;
6754 $name = basename($name);
6755 # sanitize name
6756 $name =~ s/[[:cntrl:]]/?/g;
6758 my $ver = $hash;
6759 if ($hash =~ /^[0-9a-fA-F]+$/) {
6760 # shorten SHA-1 hash
6761 my $full_hash = git_get_full_hash($project, $hash);
6762 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
6763 $ver = git_get_short_hash($project, $hash);
6765 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
6766 # tags don't need shortened SHA-1 hash
6767 $ver = $1;
6768 } else {
6769 # branches and other need shortened SHA-1 hash
6770 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
6771 $ver = $1;
6773 $ver .= '-' . git_get_short_hash($project, $hash);
6775 # in case of hierarchical branch names
6776 $ver =~ s!/!.!g;
6778 # name = project-version_string
6779 $name = "$name-$ver";
6781 return wantarray ? ($name, $name) : $name;
6784 sub git_snapshot {
6785 my $format = $input_params{'snapshot_format'};
6786 if (!@snapshot_fmts) {
6787 die_error(403, "Snapshots not allowed");
6789 # default to first supported snapshot format
6790 $format ||= $snapshot_fmts[0];
6791 if ($format !~ m/^[a-z0-9]+$/) {
6792 die_error(400, "Invalid snapshot format parameter");
6793 } elsif (!exists($known_snapshot_formats{$format})) {
6794 die_error(400, "Unknown snapshot format");
6795 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
6796 die_error(403, "Snapshot format not allowed");
6797 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
6798 die_error(403, "Unsupported snapshot format");
6801 my $type = git_get_type("$hash^{}");
6802 if (!$type) {
6803 die_error(404, 'Object does not exist');
6804 } elsif ($type eq 'blob') {
6805 die_error(400, 'Object is not a tree-ish');
6808 my ($name, $prefix) = snapshot_name($project, $hash);
6809 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6810 my $cmd = quote_command(
6811 git_cmd(), 'archive',
6812 "--format=$known_snapshot_formats{$format}{'format'}",
6813 "--prefix=$prefix/", $hash);
6814 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6815 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6818 $filename =~ s/(["\\])/\\$1/g;
6819 print $cgi->header(
6820 -type => $known_snapshot_formats{$format}{'type'},
6821 -content_disposition => 'inline; filename="' . $filename . '"',
6822 -status => '200 OK');
6824 open my $fd, "-|", $cmd
6825 or die_error(500, "Execute git-archive failed");
6826 binmode STDOUT, ':raw';
6827 print <$fd>;
6828 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6829 close $fd;
6832 sub git_log_generic {
6833 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6835 my $head = git_get_head_hash($project);
6836 if (!defined $base) {
6837 $base = $head;
6839 if (!defined $page) {
6840 $page = 0;
6842 my $refs = git_get_references();
6844 my $commit_hash = $base;
6845 if (defined $parent) {
6846 $commit_hash = "$parent..$base";
6848 my @commitlist =
6849 parse_commits($commit_hash, 101, (100 * $page),
6850 defined $file_name ? ($file_name, "--full-history") : ());
6852 my $ftype;
6853 if (!defined $file_hash && defined $file_name) {
6854 # some commits could have deleted file in question,
6855 # and not have it in tree, but one of them has to have it
6856 for (my $i = 0; $i < @commitlist; $i++) {
6857 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6858 last if defined $file_hash;
6861 if (defined $file_hash) {
6862 $ftype = git_get_type($file_hash);
6864 if (defined $file_name && !defined $ftype) {
6865 die_error(500, "Unknown type of object");
6867 my %co;
6868 if (defined $file_name) {
6869 %co = parse_commit($base)
6870 or die_error(404, "Unknown commit object");
6874 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6875 my $next_link = '';
6876 if ($#commitlist >= 100) {
6877 $next_link =
6878 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6879 -accesskey => "n", -title => "Alt-n"}, "next");
6881 my $patch_max = gitweb_get_feature('patches');
6882 if ($patch_max && !defined $file_name) {
6883 if ($patch_max < 0 || @commitlist <= $patch_max) {
6884 $paging_nav .= " &sdot; " .
6885 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6886 "patches");
6890 git_header_html();
6891 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6892 if (defined $file_name) {
6893 git_print_header_div('commit', esc_html($co{'title'}), $base);
6894 } else {
6895 git_print_header_div('summary', $project)
6897 git_print_page_path($file_name, $ftype, $hash_base)
6898 if (defined $file_name);
6900 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6901 $file_name, $file_hash, $ftype);
6903 git_footer_html();
6906 sub git_log {
6907 git_log_generic('log', \&git_log_body,
6908 $hash, $hash_parent);
6911 sub git_commit {
6912 $hash ||= $hash_base || "HEAD";
6913 my %co = parse_commit($hash)
6914 or die_error(404, "Unknown commit object");
6916 my $parent = $co{'parent'};
6917 my $parents = $co{'parents'}; # listref
6919 # we need to prepare $formats_nav before any parameter munging
6920 my $formats_nav;
6921 if (!defined $parent) {
6922 # --root commitdiff
6923 $formats_nav .= '(initial)';
6924 } elsif (@$parents == 1) {
6925 # single parent commit
6926 $formats_nav .=
6927 '(parent: ' .
6928 $cgi->a({-href => href(action=>"commit",
6929 hash=>$parent)},
6930 esc_html(substr($parent, 0, 7))) .
6931 ')';
6932 } else {
6933 # merge commit
6934 $formats_nav .=
6935 '(merge: ' .
6936 join(' ', map {
6937 $cgi->a({-href => href(action=>"commit",
6938 hash=>$_)},
6939 esc_html(substr($_, 0, 7)));
6940 } @$parents ) .
6941 ')';
6943 if (gitweb_check_feature('patches') && @$parents <= 1) {
6944 $formats_nav .= " | " .
6945 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6946 "patch");
6949 if (!defined $parent) {
6950 $parent = "--root";
6952 my @difftree;
6953 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6954 @diff_opts,
6955 (@$parents <= 1 ? $parent : '-c'),
6956 $hash, "--"
6957 or die_error(500, "Open git-diff-tree failed");
6958 @difftree = map { chomp; $_ } <$fd>;
6959 close $fd or die_error(404, "Reading git-diff-tree failed");
6961 # non-textual hash id's can be cached
6962 my $expires;
6963 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6964 $expires = "+1d";
6966 my $refs = git_get_references();
6967 my $ref = format_ref_marker($refs, $co{'id'});
6969 git_header_html(undef, $expires);
6970 git_print_page_nav('commit', '',
6971 $hash, $co{'tree'}, $hash,
6972 $formats_nav);
6974 if (defined $co{'parent'}) {
6975 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6976 } else {
6977 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6979 print "<div class=\"title_text\">\n" .
6980 "<table class=\"object_header\">\n";
6981 git_print_authorship_rows(\%co);
6982 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6983 print "<tr>" .
6984 "<td>tree</td>" .
6985 "<td class=\"sha1\">" .
6986 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6987 class => "list"}, $co{'tree'}) .
6988 "</td>" .
6989 "<td class=\"link\">" .
6990 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6991 "tree");
6992 my $snapshot_links = format_snapshot_links($hash);
6993 if (defined $snapshot_links) {
6994 print " | " . $snapshot_links;
6996 print "</td>" .
6997 "</tr>\n";
6999 foreach my $par (@$parents) {
7000 print "<tr>" .
7001 "<td>parent</td>" .
7002 "<td class=\"sha1\">" .
7003 $cgi->a({-href => href(action=>"commit", hash=>$par),
7004 class => "list"}, $par) .
7005 "</td>" .
7006 "<td class=\"link\">" .
7007 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7008 " | " .
7009 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7010 "</td>" .
7011 "</tr>\n";
7013 print "</table>".
7014 "</div>\n";
7016 print "<div class=\"page_body\">\n";
7017 git_print_log($co{'comment'});
7018 print "</div>\n";
7020 git_difftree_body(\@difftree, $hash, @$parents);
7022 git_footer_html();
7025 sub git_object {
7026 # object is defined by:
7027 # - hash or hash_base alone
7028 # - hash_base and file_name
7029 my $type;
7031 # - hash or hash_base alone
7032 if ($hash || ($hash_base && !defined $file_name)) {
7033 my $object_id = $hash || $hash_base;
7035 open my $fd, "-|", quote_command(
7036 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7037 or die_error(404, "Object does not exist");
7038 $type = <$fd>;
7039 chomp $type;
7040 close $fd
7041 or die_error(404, "Object does not exist");
7043 # - hash_base and file_name
7044 } elsif ($hash_base && defined $file_name) {
7045 $file_name =~ s,/+$,,;
7047 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7048 or die_error(404, "Base object does not exist");
7050 # here errors should not hapen
7051 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7052 or die_error(500, "Open git-ls-tree failed");
7053 my $line = <$fd>;
7054 close $fd;
7056 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7057 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7058 die_error(404, "File or directory for given base does not exist");
7060 $type = $2;
7061 $hash = $3;
7062 } else {
7063 die_error(400, "Not enough information to find object");
7066 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7067 hash=>$hash, hash_base=>$hash_base,
7068 file_name=>$file_name),
7069 -status => '302 Found');
7072 sub git_blobdiff {
7073 my $format = shift || 'html';
7074 my $diff_style = $input_params{'diff_style'} || 'inline';
7076 my $fd;
7077 my @difftree;
7078 my %diffinfo;
7079 my $expires;
7081 # preparing $fd and %diffinfo for git_patchset_body
7082 # new style URI
7083 if (defined $hash_base && defined $hash_parent_base) {
7084 if (defined $file_name) {
7085 # read raw output
7086 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7087 $hash_parent_base, $hash_base,
7088 "--", (defined $file_parent ? $file_parent : ()), $file_name
7089 or die_error(500, "Open git-diff-tree failed");
7090 @difftree = map { chomp; $_ } <$fd>;
7091 close $fd
7092 or die_error(404, "Reading git-diff-tree failed");
7093 @difftree
7094 or die_error(404, "Blob diff not found");
7096 } elsif (defined $hash &&
7097 $hash =~ /[0-9a-fA-F]{40}/) {
7098 # try to find filename from $hash
7100 # read filtered raw output
7101 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7102 $hash_parent_base, $hash_base, "--"
7103 or die_error(500, "Open git-diff-tree failed");
7104 @difftree =
7105 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
7106 # $hash == to_id
7107 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
7108 map { chomp; $_ } <$fd>;
7109 close $fd
7110 or die_error(404, "Reading git-diff-tree failed");
7111 @difftree
7112 or die_error(404, "Blob diff not found");
7114 } else {
7115 die_error(400, "Missing one of the blob diff parameters");
7118 if (@difftree > 1) {
7119 die_error(400, "Ambiguous blob diff specification");
7122 %diffinfo = parse_difftree_raw_line($difftree[0]);
7123 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7124 $file_name ||= $diffinfo{'to_file'};
7126 $hash_parent ||= $diffinfo{'from_id'};
7127 $hash ||= $diffinfo{'to_id'};
7129 # non-textual hash id's can be cached
7130 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
7131 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
7132 $expires = '+1d';
7135 # open patch output
7136 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7137 '-p', ($format eq 'html' ? "--full-index" : ()),
7138 $hash_parent_base, $hash_base,
7139 "--", (defined $file_parent ? $file_parent : ()), $file_name
7140 or die_error(500, "Open git-diff-tree failed");
7143 # old/legacy style URI -- not generated anymore since 1.4.3.
7144 if (!%diffinfo) {
7145 die_error('404 Not Found', "Missing one of the blob diff parameters")
7148 # header
7149 if ($format eq 'html') {
7150 my $formats_nav =
7151 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7152 "raw");
7153 git_header_html(undef, $expires);
7154 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7155 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7156 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7157 } else {
7158 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7159 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7161 if (defined $file_name) {
7162 git_print_page_path($file_name, "blob", $hash_base);
7163 } else {
7164 print "<div class=\"page_path\"></div>\n";
7167 } elsif ($format eq 'plain') {
7168 print $cgi->header(
7169 -type => 'text/plain',
7170 -charset => 'utf-8',
7171 -expires => $expires,
7172 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7174 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7176 } else {
7177 die_error(400, "Unknown blobdiff format");
7180 # patch
7181 if ($format eq 'html') {
7182 print "<div class=\"page_body\">\n";
7184 git_patchset_body($fd, $diff_style,
7185 [ \%diffinfo ], $hash_base, $hash_parent_base);
7186 close $fd;
7188 print "</div>\n"; # class="page_body"
7189 git_footer_html();
7191 } else {
7192 while (my $line = <$fd>) {
7193 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7194 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7196 print $line;
7198 last if $line =~ m!^\+\+\+!;
7200 local $/ = undef;
7201 print <$fd>;
7202 close $fd;
7206 sub git_blobdiff_plain {
7207 git_blobdiff('plain');
7210 sub git_commitdiff {
7211 my %params = @_;
7212 my $format = $params{-format} || 'html';
7213 my $diff_style = $input_params{'diff_style'} || 'inline';
7215 my ($patch_max) = gitweb_get_feature('patches');
7216 if ($format eq 'patch') {
7217 die_error(403, "Patch view not allowed") unless $patch_max;
7220 $hash ||= $hash_base || "HEAD";
7221 my %co = parse_commit($hash)
7222 or die_error(404, "Unknown commit object");
7224 # choose format for commitdiff for merge
7225 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7226 $hash_parent = '--cc';
7228 # we need to prepare $formats_nav before almost any parameter munging
7229 my $formats_nav;
7230 if ($format eq 'html') {
7231 $formats_nav =
7232 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7233 "raw");
7234 if ($patch_max && @{$co{'parents'}} <= 1) {
7235 $formats_nav .= " | " .
7236 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7237 "patch");
7240 if (defined $hash_parent &&
7241 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7242 # commitdiff with two commits given
7243 my $hash_parent_short = $hash_parent;
7244 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7245 $hash_parent_short = substr($hash_parent, 0, 7);
7247 $formats_nav .=
7248 ' (from';
7249 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7250 if ($co{'parents'}[$i] eq $hash_parent) {
7251 $formats_nav .= ' parent ' . ($i+1);
7252 last;
7255 $formats_nav .= ': ' .
7256 $cgi->a({-href => href(action=>"commitdiff",
7257 hash=>$hash_parent)},
7258 esc_html($hash_parent_short)) .
7259 ')';
7260 } elsif (!$co{'parent'}) {
7261 # --root commitdiff
7262 $formats_nav .= ' (initial)';
7263 } elsif (scalar @{$co{'parents'}} == 1) {
7264 # single parent commit
7265 $formats_nav .=
7266 ' (parent: ' .
7267 $cgi->a({-href => href(action=>"commitdiff",
7268 hash=>$co{'parent'})},
7269 esc_html(substr($co{'parent'}, 0, 7))) .
7270 ')';
7271 } else {
7272 # merge commit
7273 if ($hash_parent eq '--cc') {
7274 $formats_nav .= ' | ' .
7275 $cgi->a({-href => href(action=>"commitdiff",
7276 hash=>$hash, hash_parent=>'-c')},
7277 'combined');
7278 } else { # $hash_parent eq '-c'
7279 $formats_nav .= ' | ' .
7280 $cgi->a({-href => href(action=>"commitdiff",
7281 hash=>$hash, hash_parent=>'--cc')},
7282 'compact');
7284 $formats_nav .=
7285 ' (merge: ' .
7286 join(' ', map {
7287 $cgi->a({-href => href(action=>"commitdiff",
7288 hash=>$_)},
7289 esc_html(substr($_, 0, 7)));
7290 } @{$co{'parents'}} ) .
7291 ')';
7295 my $hash_parent_param = $hash_parent;
7296 if (!defined $hash_parent_param) {
7297 # --cc for multiple parents, --root for parentless
7298 $hash_parent_param =
7299 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7302 # read commitdiff
7303 my $fd;
7304 my @difftree;
7305 if ($format eq 'html') {
7306 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7307 "--no-commit-id", "--patch-with-raw", "--full-index",
7308 $hash_parent_param, $hash, "--"
7309 or die_error(500, "Open git-diff-tree failed");
7311 while (my $line = <$fd>) {
7312 chomp $line;
7313 # empty line ends raw part of diff-tree output
7314 last unless $line;
7315 push @difftree, scalar parse_difftree_raw_line($line);
7318 } elsif ($format eq 'plain') {
7319 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7320 '-p', $hash_parent_param, $hash, "--"
7321 or die_error(500, "Open git-diff-tree failed");
7322 } elsif ($format eq 'patch') {
7323 # For commit ranges, we limit the output to the number of
7324 # patches specified in the 'patches' feature.
7325 # For single commits, we limit the output to a single patch,
7326 # diverging from the git-format-patch default.
7327 my @commit_spec = ();
7328 if ($hash_parent) {
7329 if ($patch_max > 0) {
7330 push @commit_spec, "-$patch_max";
7332 push @commit_spec, '-n', "$hash_parent..$hash";
7333 } else {
7334 if ($params{-single}) {
7335 push @commit_spec, '-1';
7336 } else {
7337 if ($patch_max > 0) {
7338 push @commit_spec, "-$patch_max";
7340 push @commit_spec, "-n";
7342 push @commit_spec, '--root', $hash;
7344 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7345 '--encoding=utf8', '--stdout', @commit_spec
7346 or die_error(500, "Open git-format-patch failed");
7347 } else {
7348 die_error(400, "Unknown commitdiff format");
7351 # non-textual hash id's can be cached
7352 my $expires;
7353 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7354 $expires = "+1d";
7357 # write commit message
7358 if ($format eq 'html') {
7359 my $refs = git_get_references();
7360 my $ref = format_ref_marker($refs, $co{'id'});
7362 git_header_html(undef, $expires);
7363 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7364 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7365 print "<div class=\"title_text\">\n" .
7366 "<table class=\"object_header\">\n";
7367 git_print_authorship_rows(\%co);
7368 print "</table>".
7369 "</div>\n";
7370 print "<div class=\"page_body\">\n";
7371 if (@{$co{'comment'}} > 1) {
7372 print "<div class=\"log\">\n";
7373 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7374 print "</div>\n"; # class="log"
7377 } elsif ($format eq 'plain') {
7378 my $refs = git_get_references("tags");
7379 my $tagname = git_get_rev_name_tags($hash);
7380 my $filename = basename($project) . "-$hash.patch";
7382 print $cgi->header(
7383 -type => 'text/plain',
7384 -charset => 'utf-8',
7385 -expires => $expires,
7386 -content_disposition => 'inline; filename="' . "$filename" . '"');
7387 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7388 print "From: " . to_utf8($co{'author'}) . "\n";
7389 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7390 print "Subject: " . to_utf8($co{'title'}) . "\n";
7392 print "X-Git-Tag: $tagname\n" if $tagname;
7393 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7395 foreach my $line (@{$co{'comment'}}) {
7396 print to_utf8($line) . "\n";
7398 print "---\n\n";
7399 } elsif ($format eq 'patch') {
7400 my $filename = basename($project) . "-$hash.patch";
7402 print $cgi->header(
7403 -type => 'text/plain',
7404 -charset => 'utf-8',
7405 -expires => $expires,
7406 -content_disposition => 'inline; filename="' . "$filename" . '"');
7409 # write patch
7410 if ($format eq 'html') {
7411 my $use_parents = !defined $hash_parent ||
7412 $hash_parent eq '-c' || $hash_parent eq '--cc';
7413 git_difftree_body(\@difftree, $hash,
7414 $use_parents ? @{$co{'parents'}} : $hash_parent);
7415 print "<br/>\n";
7417 git_patchset_body($fd, $diff_style,
7418 \@difftree, $hash,
7419 $use_parents ? @{$co{'parents'}} : $hash_parent);
7420 close $fd;
7421 print "</div>\n"; # class="page_body"
7422 git_footer_html();
7424 } elsif ($format eq 'plain') {
7425 local $/ = undef;
7426 print <$fd>;
7427 close $fd
7428 or print "Reading git-diff-tree failed\n";
7429 } elsif ($format eq 'patch') {
7430 local $/ = undef;
7431 print <$fd>;
7432 close $fd
7433 or print "Reading git-format-patch failed\n";
7437 sub git_commitdiff_plain {
7438 git_commitdiff(-format => 'plain');
7441 # format-patch-style patches
7442 sub git_patch {
7443 git_commitdiff(-format => 'patch', -single => 1);
7446 sub git_patches {
7447 git_commitdiff(-format => 'patch');
7450 sub git_history {
7451 git_log_generic('history', \&git_history_body,
7452 $hash_base, $hash_parent_base,
7453 $file_name, $hash);
7456 sub git_search {
7457 $searchtype ||= 'commit';
7459 # check if appropriate features are enabled
7460 gitweb_check_feature('search')
7461 or die_error(403, "Search is disabled");
7462 if ($searchtype eq 'pickaxe') {
7463 # pickaxe may take all resources of your box and run for several minutes
7464 # with every query - so decide by yourself how public you make this feature
7465 gitweb_check_feature('pickaxe')
7466 or die_error(403, "Pickaxe search is disabled");
7468 if ($searchtype eq 'grep') {
7469 # grep search might be potentially CPU-intensive, too
7470 gitweb_check_feature('grep')
7471 or die_error(403, "Grep search is disabled");
7474 if (!defined $searchtext) {
7475 die_error(400, "Text field is empty");
7477 if (!defined $hash) {
7478 $hash = git_get_head_hash($project);
7480 my %co = parse_commit($hash);
7481 if (!%co) {
7482 die_error(404, "Unknown commit object");
7484 if (!defined $page) {
7485 $page = 0;
7488 if ($searchtype eq 'commit' ||
7489 $searchtype eq 'author' ||
7490 $searchtype eq 'committer') {
7491 git_search_message(%co);
7492 } elsif ($searchtype eq 'pickaxe') {
7493 git_search_changes(%co);
7494 } elsif ($searchtype eq 'grep') {
7495 git_search_files(%co);
7496 } else {
7497 die_error(400, "Unknown search type");
7501 sub git_search_help {
7502 git_header_html();
7503 git_print_page_nav('','', $hash,$hash,$hash);
7504 print <<EOT;
7505 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
7506 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
7507 the pattern entered is recognized as the POSIX extended
7508 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
7509 insensitive).</p>
7510 <dl>
7511 <dt><b>commit</b></dt>
7512 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7514 my $have_grep = gitweb_check_feature('grep');
7515 if ($have_grep) {
7516 print <<EOT;
7517 <dt><b>grep</b></dt>
7518 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7519 a different one) are searched for the given pattern. On large trees, this search can take
7520 a while and put some strain on the server, so please use it with some consideration. Note that
7521 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7522 case-sensitive.</dd>
7525 print <<EOT;
7526 <dt><b>author</b></dt>
7527 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7528 <dt><b>committer</b></dt>
7529 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7531 my $have_pickaxe = gitweb_check_feature('pickaxe');
7532 if ($have_pickaxe) {
7533 print <<EOT;
7534 <dt><b>pickaxe</b></dt>
7535 <dd>All commits that caused the string to appear or disappear from any file (changes that
7536 added, removed or "modified" the string) will be listed. This search can take a while and
7537 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7538 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7541 print "</dl>\n";
7542 git_footer_html();
7545 sub git_shortlog {
7546 git_log_generic('shortlog', \&git_shortlog_body,
7547 $hash, $hash_parent);
7550 ## ......................................................................
7551 ## feeds (RSS, Atom; OPML)
7553 sub git_feed {
7554 my $format = shift || 'atom';
7555 my $have_blame = gitweb_check_feature('blame');
7557 # Atom: http://www.atomenabled.org/developers/syndication/
7558 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
7559 if ($format ne 'rss' && $format ne 'atom') {
7560 die_error(400, "Unknown web feed format");
7563 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
7564 my $head = $hash || 'HEAD';
7565 my @commitlist = parse_commits($head, 150, 0, $file_name);
7567 my %latest_commit;
7568 my %latest_date;
7569 my $content_type = "application/$format+xml";
7570 if (defined $cgi->http('HTTP_ACCEPT') &&
7571 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
7572 # browser (feed reader) prefers text/xml
7573 $content_type = 'text/xml';
7575 if (defined($commitlist[0])) {
7576 %latest_commit = %{$commitlist[0]};
7577 my $latest_epoch = $latest_commit{'committer_epoch'};
7578 %latest_date = parse_date($latest_epoch, $latest_commit{'comitter_tz'});
7579 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7580 if (defined $if_modified) {
7581 my $since;
7582 if (eval { require HTTP::Date; 1; }) {
7583 $since = HTTP::Date::str2time($if_modified);
7584 } elsif (eval { require Time::ParseDate; 1; }) {
7585 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7587 if (defined $since && $latest_epoch <= $since) {
7588 print $cgi->header(
7589 -type => $content_type,
7590 -charset => 'utf-8',
7591 -last_modified => $latest_date{'rfc2822'},
7592 -status => '304 Not Modified');
7593 return;
7596 print $cgi->header(
7597 -type => $content_type,
7598 -charset => 'utf-8',
7599 -last_modified => $latest_date{'rfc2822'});
7600 } else {
7601 print $cgi->header(
7602 -type => $content_type,
7603 -charset => 'utf-8');
7606 # Optimization: skip generating the body if client asks only
7607 # for Last-Modified date.
7608 return if ($cgi->request_method() eq 'HEAD');
7610 # header variables
7611 my $title = "$site_name - $project/$action";
7612 my $feed_type = 'log';
7613 if (defined $hash) {
7614 $title .= " - '$hash'";
7615 $feed_type = 'branch log';
7616 if (defined $file_name) {
7617 $title .= " :: $file_name";
7618 $feed_type = 'history';
7620 } elsif (defined $file_name) {
7621 $title .= " - $file_name";
7622 $feed_type = 'history';
7624 $title .= " $feed_type";
7625 my $descr = git_get_project_description($project);
7626 if (defined $descr) {
7627 $descr = esc_html($descr);
7628 } else {
7629 $descr = "$project " .
7630 ($format eq 'rss' ? 'RSS' : 'Atom') .
7631 " feed";
7633 my $owner = git_get_project_owner($project);
7634 $owner = esc_html($owner);
7636 #header
7637 my $alt_url;
7638 if (defined $file_name) {
7639 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7640 } elsif (defined $hash) {
7641 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7642 } else {
7643 $alt_url = href(-full=>1, action=>"summary");
7645 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7646 if ($format eq 'rss') {
7647 print <<XML;
7648 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7649 <channel>
7651 print "<title>$title</title>\n" .
7652 "<link>$alt_url</link>\n" .
7653 "<description>$descr</description>\n" .
7654 "<language>en</language>\n" .
7655 # project owner is responsible for 'editorial' content
7656 "<managingEditor>$owner</managingEditor>\n";
7657 if (defined $logo || defined $favicon) {
7658 # prefer the logo to the favicon, since RSS
7659 # doesn't allow both
7660 my $img = esc_url($logo || $favicon);
7661 print "<image>\n" .
7662 "<url>$img</url>\n" .
7663 "<title>$title</title>\n" .
7664 "<link>$alt_url</link>\n" .
7665 "</image>\n";
7667 if (%latest_date) {
7668 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7669 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7671 print "<generator>gitweb v.$version/$git_version</generator>\n";
7672 } elsif ($format eq 'atom') {
7673 print <<XML;
7674 <feed xmlns="http://www.w3.org/2005/Atom">
7676 print "<title>$title</title>\n" .
7677 "<subtitle>$descr</subtitle>\n" .
7678 '<link rel="alternate" type="text/html" href="' .
7679 $alt_url . '" />' . "\n" .
7680 '<link rel="self" type="' . $content_type . '" href="' .
7681 $cgi->self_url() . '" />' . "\n" .
7682 "<id>" . href(-full=>1) . "</id>\n" .
7683 # use project owner for feed author
7684 "<author><name>$owner</name></author>\n";
7685 if (defined $favicon) {
7686 print "<icon>" . esc_url($favicon) . "</icon>\n";
7688 if (defined $logo) {
7689 # not twice as wide as tall: 72 x 27 pixels
7690 print "<logo>" . esc_url($logo) . "</logo>\n";
7692 if (! %latest_date) {
7693 # dummy date to keep the feed valid until commits trickle in:
7694 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7695 } else {
7696 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7698 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7701 # contents
7702 for (my $i = 0; $i <= $#commitlist; $i++) {
7703 my %co = %{$commitlist[$i]};
7704 my $commit = $co{'id'};
7705 # we read 150, we always show 30 and the ones more recent than 48 hours
7706 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7707 last;
7709 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
7711 # get list of changed files
7712 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7713 $co{'parent'} || "--root",
7714 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7715 or next;
7716 my @difftree = map { chomp; $_ } <$fd>;
7717 close $fd
7718 or next;
7720 # print element (entry, item)
7721 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7722 if ($format eq 'rss') {
7723 print "<item>\n" .
7724 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7725 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7726 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7727 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7728 "<link>$co_url</link>\n" .
7729 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7730 "<content:encoded>" .
7731 "<![CDATA[\n";
7732 } elsif ($format eq 'atom') {
7733 print "<entry>\n" .
7734 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7735 "<updated>$cd{'iso-8601'}</updated>\n" .
7736 "<author>\n" .
7737 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7738 if ($co{'author_email'}) {
7739 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7741 print "</author>\n" .
7742 # use committer for contributor
7743 "<contributor>\n" .
7744 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7745 if ($co{'committer_email'}) {
7746 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7748 print "</contributor>\n" .
7749 "<published>$cd{'iso-8601'}</published>\n" .
7750 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7751 "<id>$co_url</id>\n" .
7752 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7753 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7755 my $comment = $co{'comment'};
7756 print "<pre>\n";
7757 foreach my $line (@$comment) {
7758 $line = esc_html($line);
7759 print "$line\n";
7761 print "</pre><ul>\n";
7762 foreach my $difftree_line (@difftree) {
7763 my %difftree = parse_difftree_raw_line($difftree_line);
7764 next if !$difftree{'from_id'};
7766 my $file = $difftree{'file'} || $difftree{'to_file'};
7768 print "<li>" .
7769 "[" .
7770 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7771 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7772 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7773 file_name=>$file, file_parent=>$difftree{'from_file'}),
7774 -title => "diff"}, 'D');
7775 if ($have_blame) {
7776 print $cgi->a({-href => href(-full=>1, action=>"blame",
7777 file_name=>$file, hash_base=>$commit),
7778 -title => "blame"}, 'B');
7780 # if this is not a feed of a file history
7781 if (!defined $file_name || $file_name ne $file) {
7782 print $cgi->a({-href => href(-full=>1, action=>"history",
7783 file_name=>$file, hash=>$commit),
7784 -title => "history"}, 'H');
7786 $file = esc_path($file);
7787 print "] ".
7788 "$file</li>\n";
7790 if ($format eq 'rss') {
7791 print "</ul>]]>\n" .
7792 "</content:encoded>\n" .
7793 "</item>\n";
7794 } elsif ($format eq 'atom') {
7795 print "</ul>\n</div>\n" .
7796 "</content>\n" .
7797 "</entry>\n";
7801 # end of feed
7802 if ($format eq 'rss') {
7803 print "</channel>\n</rss>\n";
7804 } elsif ($format eq 'atom') {
7805 print "</feed>\n";
7809 sub git_rss {
7810 git_feed('rss');
7813 sub git_atom {
7814 git_feed('atom');
7817 sub git_opml {
7818 my @list = git_get_projects_list();
7819 if (!@list) {
7820 die_error(404, "No projects found");
7823 print $cgi->header(
7824 -type => 'text/xml',
7825 -charset => 'utf-8',
7826 -content_disposition => 'inline; filename="opml.xml"');
7828 print <<XML;
7829 <?xml version="1.0" encoding="utf-8"?>
7830 <opml version="1.0">
7831 <head>
7832 <title>$site_name OPML Export</title>
7833 </head>
7834 <body>
7835 <outline text="git RSS feeds">
7838 foreach my $pr (@list) {
7839 my %proj = %$pr;
7840 my $head = git_get_head_hash($proj{'path'});
7841 if (!defined $head) {
7842 next;
7844 $git_dir = "$projectroot/$proj{'path'}";
7845 my %co = parse_commit($head);
7846 if (!%co) {
7847 next;
7850 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7851 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7852 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7853 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7855 print <<XML;
7856 </outline>
7857 </body>
7858 </opml>