cfa511c3d335ab2160fbd0fb827d15511a491509
[git/jnareb-git.git] / gitweb / gitweb.perl
blobcfa511c3d335ab2160fbd0fb827d15511a491509
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;
14 use File::Spec;
15 # __DIR__ is taken from Dir::Self __DIR__ fragment
16 sub __DIR__ () {
17 File::Spec->rel2abs(join '', (File::Spec->splitpath(__FILE__))[0, 1]);
19 use lib __DIR__ . '/lib';
21 use CGI qw(:standard :escapeHTML -nosticky);
22 use CGI::Util qw(unescape);
23 use CGI::Carp qw(fatalsToBrowser set_message);
24 use Encode;
25 use Fcntl ':mode';
26 use File::Find qw();
27 use File::Basename qw(basename);
28 binmode STDOUT, ':utf8';
30 our $t0;
31 if (eval { require Time::HiRes; 1; }) {
32 $t0 = [Time::HiRes::gettimeofday()];
34 our $number_of_git_cmds = 0;
36 BEGIN {
37 CGI->compile() if $ENV{'MOD_PERL'};
40 our $version = "++GIT_VERSION++";
42 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
43 sub evaluate_uri {
44 our $cgi;
46 our $my_url = $cgi->url();
47 our $my_uri = $cgi->url(-absolute => 1);
49 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
50 # needed and used only for URLs with nonempty PATH_INFO
51 our $base_url = $my_url;
53 # When the script is used as DirectoryIndex, the URL does not contain the name
54 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
55 # have to do it ourselves. We make $path_info global because it's also used
56 # later on.
58 # Another issue with the script being the DirectoryIndex is that the resulting
59 # $my_url data is not the full script URL: this is good, because we want
60 # generated links to keep implying the script name if it wasn't explicitly
61 # indicated in the URL we're handling, but it means that $my_url cannot be used
62 # as base URL.
63 # Therefore, if we needed to strip PATH_INFO, then we know that we have
64 # to build the base URL ourselves:
65 our $path_info = $ENV{"PATH_INFO"};
66 if ($path_info) {
67 if ($my_url =~ s,\Q$path_info\E$,, &&
68 $my_uri =~ s,\Q$path_info\E$,, &&
69 defined $ENV{'SCRIPT_NAME'}) {
70 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
74 # target of the home link on top of all pages
75 our $home_link = $my_uri || "/";
78 # core git executable to use
79 # this can just be "git" if your webserver has a sensible PATH
80 our $GIT = "++GIT_BINDIR++/git";
82 # absolute fs-path which will be prepended to the project path
83 #our $projectroot = "/pub/scm";
84 our $projectroot = "++GITWEB_PROJECTROOT++";
86 # fs traversing limit for getting project list
87 # the number is relative to the projectroot
88 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
90 # string of the home link on top of all pages
91 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
93 # name of your site or organization to appear in page titles
94 # replace this with something more descriptive for clearer bookmarks
95 our $site_name = "++GITWEB_SITENAME++"
96 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
98 # filename of html text to include at top of each page
99 our $site_header = "++GITWEB_SITE_HEADER++";
100 # html text to include at home page
101 our $home_text = "++GITWEB_HOMETEXT++";
102 # filename of html text to include at bottom of each page
103 our $site_footer = "++GITWEB_SITE_FOOTER++";
105 # URI of stylesheets
106 our @stylesheets = ("++GITWEB_CSS++");
107 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
108 our $stylesheet = undef;
109 # URI of GIT logo (72x27 size)
110 our $logo = "++GITWEB_LOGO++";
111 # URI of GIT favicon, assumed to be image/png type
112 our $favicon = "++GITWEB_FAVICON++";
113 # URI of gitweb.js (JavaScript code for gitweb)
114 our $javascript = "++GITWEB_JS++";
116 # URI and label (title) of GIT logo link
117 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
118 #our $logo_label = "git documentation";
119 our $logo_url = "http://git-scm.com/";
120 our $logo_label = "git homepage";
122 # source of projects list
123 our $projects_list = "++GITWEB_LIST++";
125 # the width (in characters) of the projects list "Description" column
126 our $projects_list_description_width = 25;
128 # default order of projects list
129 # valid values are none, project, descr, owner, and age
130 our $default_projects_order = "project";
132 # show repository only if this file exists
133 # (only effective if this variable evaluates to true)
134 our $export_ok = "++GITWEB_EXPORT_OK++";
136 # show repository only if this subroutine returns true
137 # when given the path to the project, for example:
138 # sub { return -e "$_[0]/git-daemon-export-ok"; }
139 our $export_auth_hook = undef;
141 # only allow viewing of repositories also shown on the overview page
142 our $strict_export = "++GITWEB_STRICT_EXPORT++";
144 # list of git base URLs used for URL to where fetch project from,
145 # i.e. full URL is "$git_base_url/$project"
146 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
148 # default blob_plain mimetype and default charset for text/plain blob
149 our $default_blob_plain_mimetype = 'text/plain';
150 our $default_text_plain_charset = undef;
152 # file to use for guessing MIME types before trying /etc/mime.types
153 # (relative to the current git repository)
154 our $mimetypes_file = undef;
156 # assume this charset if line contains non-UTF-8 characters;
157 # it should be valid encoding (see Encoding::Supported(3pm) for list),
158 # for which encoding all byte sequences are valid, for example
159 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
160 # could be even 'utf-8' for the old behavior)
161 our $fallback_encoding = 'latin1';
163 # rename detection options for git-diff and git-diff-tree
164 # - default is '-M', with the cost proportional to
165 # (number of removed files) * (number of new files).
166 # - more costly is '-C' (which implies '-M'), with the cost proportional to
167 # (number of changed files + number of removed files) * (number of new files)
168 # - even more costly is '-C', '--find-copies-harder' with cost
169 # (number of files in the original tree) * (number of new files)
170 # - one might want to include '-B' option, e.g. '-B', '-M'
171 our @diff_opts = ('-M'); # taken from git_commit
173 # Disables features that would allow repository owners to inject script into
174 # the gitweb domain.
175 our $prevent_xss = 0;
177 # Path to the highlight executable to use (must be the one from
178 # http://www.andre-simon.de due to assumptions about parameters and output).
179 # Useful if highlight is not installed on your webserver's PATH.
180 # [Default: highlight]
181 our $highlight_bin = "++HIGHLIGHT_BIN++";
183 # information about snapshot formats that gitweb is capable of serving
184 our %known_snapshot_formats = (
185 # name => {
186 # 'display' => display name,
187 # 'type' => mime type,
188 # 'suffix' => filename suffix,
189 # 'format' => --format for git-archive,
190 # 'compressor' => [compressor command and arguments]
191 # (array reference, optional)
192 # 'disabled' => boolean (optional)}
194 'tgz' => {
195 'display' => 'tar.gz',
196 'type' => 'application/x-gzip',
197 'suffix' => '.tar.gz',
198 'format' => 'tar',
199 'compressor' => ['gzip']},
201 'tbz2' => {
202 'display' => 'tar.bz2',
203 'type' => 'application/x-bzip2',
204 'suffix' => '.tar.bz2',
205 'format' => 'tar',
206 'compressor' => ['bzip2']},
208 'txz' => {
209 'display' => 'tar.xz',
210 'type' => 'application/x-xz',
211 'suffix' => '.tar.xz',
212 'format' => 'tar',
213 'compressor' => ['xz'],
214 'disabled' => 1},
216 'zip' => {
217 'display' => 'zip',
218 'type' => 'application/x-zip',
219 'suffix' => '.zip',
220 'format' => 'zip'},
223 # Aliases so we understand old gitweb.snapshot values in repository
224 # configuration.
225 our %known_snapshot_format_aliases = (
226 'gzip' => 'tgz',
227 'bzip2' => 'tbz2',
228 'xz' => 'txz',
230 # backward compatibility: legacy gitweb config support
231 'x-gzip' => undef, 'gz' => undef,
232 'x-bzip2' => undef, 'bz2' => undef,
233 'x-zip' => undef, '' => undef,
236 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
237 # are changed, it may be appropriate to change these values too via
238 # $GITWEB_CONFIG.
239 our %avatar_size = (
240 'default' => 16,
241 'double' => 32
244 # Used to set the maximum load that we will still respond to gitweb queries.
245 # If server load exceed this value then return "503 server busy" error.
246 # If gitweb cannot determined server load, it is taken to be 0.
247 # Leave it undefined (or set to 'undef') to turn off load checking.
248 our $maxload = 300;
250 # configuration for 'highlight' (http://www.andre-simon.de/)
251 # match by basename
252 our %highlight_basename = (
253 #'Program' => 'py',
254 #'Library' => 'py',
255 'SConstruct' => 'py', # SCons equivalent of Makefile
256 'Makefile' => 'make',
258 # match by extension
259 our %highlight_ext = (
260 # main extensions, defining name of syntax;
261 # see files in /usr/share/highlight/langDefs/ directory
262 map { $_ => $_ }
263 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl),
264 # alternate extensions, see /etc/highlight/filetypes.conf
265 'h' => 'c',
266 map { $_ => 'cpp' } qw(cxx c++ cc),
267 map { $_ => 'php' } qw(php3 php4),
268 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
269 'mak' => 'make',
270 map { $_ => 'xml' } qw(xhtml html htm),
273 # You define site-wide feature defaults here; override them with
274 # $GITWEB_CONFIG as necessary.
275 our %feature = (
276 # feature => {
277 # 'sub' => feature-sub (subroutine),
278 # 'override' => allow-override (boolean),
279 # 'default' => [ default options...] (array reference)}
281 # if feature is overridable (it means that allow-override has true value),
282 # then feature-sub will be called with default options as parameters;
283 # return value of feature-sub indicates if to enable specified feature
285 # if there is no 'sub' key (no feature-sub), then feature cannot be
286 # overridden
288 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
289 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
290 # is enabled
292 # Enable the 'blame' blob view, showing the last commit that modified
293 # each line in the file. This can be very CPU-intensive.
295 # To enable system wide have in $GITWEB_CONFIG
296 # $feature{'blame'}{'default'} = [1];
297 # To have project specific config enable override in $GITWEB_CONFIG
298 # $feature{'blame'}{'override'} = 1;
299 # and in project config gitweb.blame = 0|1;
300 'blame' => {
301 'sub' => sub { feature_bool('blame', @_) },
302 'override' => 0,
303 'default' => [0]},
305 # Enable the 'snapshot' link, providing a compressed archive of any
306 # tree. This can potentially generate high traffic if you have large
307 # project.
309 # Value is a list of formats defined in %known_snapshot_formats that
310 # you wish to offer.
311 # To disable system wide have in $GITWEB_CONFIG
312 # $feature{'snapshot'}{'default'} = [];
313 # To have project specific config enable override in $GITWEB_CONFIG
314 # $feature{'snapshot'}{'override'} = 1;
315 # and in project config, a comma-separated list of formats or "none"
316 # to disable. Example: gitweb.snapshot = tbz2,zip;
317 'snapshot' => {
318 'sub' => \&feature_snapshot,
319 'override' => 0,
320 'default' => ['tgz']},
322 # Enable text search, which will list the commits which match author,
323 # committer or commit text to a given string. Enabled by default.
324 # Project specific override is not supported.
325 'search' => {
326 'override' => 0,
327 'default' => [1]},
329 # Enable grep search, which will list the files in currently selected
330 # tree containing the given string. Enabled by default. This can be
331 # potentially CPU-intensive, of course.
333 # To enable system wide have in $GITWEB_CONFIG
334 # $feature{'grep'}{'default'} = [1];
335 # To have project specific config enable override in $GITWEB_CONFIG
336 # $feature{'grep'}{'override'} = 1;
337 # and in project config gitweb.grep = 0|1;
338 'grep' => {
339 'sub' => sub { feature_bool('grep', @_) },
340 'override' => 0,
341 'default' => [1]},
343 # Enable the pickaxe search, which will list the commits that modified
344 # a given string in a file. This can be practical and quite faster
345 # alternative to 'blame', but still potentially CPU-intensive.
347 # To enable system wide have in $GITWEB_CONFIG
348 # $feature{'pickaxe'}{'default'} = [1];
349 # To have project specific config enable override in $GITWEB_CONFIG
350 # $feature{'pickaxe'}{'override'} = 1;
351 # and in project config gitweb.pickaxe = 0|1;
352 'pickaxe' => {
353 'sub' => sub { feature_bool('pickaxe', @_) },
354 'override' => 0,
355 'default' => [1]},
357 # Enable showing size of blobs in a 'tree' view, in a separate
358 # column, similar to what 'ls -l' does. This cost a bit of IO.
360 # To disable system wide have in $GITWEB_CONFIG
361 # $feature{'show-sizes'}{'default'} = [0];
362 # To have project specific config enable override in $GITWEB_CONFIG
363 # $feature{'show-sizes'}{'override'} = 1;
364 # and in project config gitweb.showsizes = 0|1;
365 'show-sizes' => {
366 'sub' => sub { feature_bool('showsizes', @_) },
367 'override' => 0,
368 'default' => [1]},
370 # Make gitweb use an alternative format of the URLs which can be
371 # more readable and natural-looking: project name is embedded
372 # directly in the path and the query string contains other
373 # auxiliary information. All gitweb installations recognize
374 # URL in either format; this configures in which formats gitweb
375 # generates links.
377 # To enable system wide have in $GITWEB_CONFIG
378 # $feature{'pathinfo'}{'default'} = [1];
379 # Project specific override is not supported.
381 # Note that you will need to change the default location of CSS,
382 # favicon, logo and possibly other files to an absolute URL. Also,
383 # if gitweb.cgi serves as your indexfile, you will need to force
384 # $my_uri to contain the script name in your $GITWEB_CONFIG.
385 'pathinfo' => {
386 'override' => 0,
387 'default' => [0]},
389 # Make gitweb consider projects in project root subdirectories
390 # to be forks of existing projects. Given project $projname.git,
391 # projects matching $projname/*.git will not be shown in the main
392 # projects list, instead a '+' mark will be added to $projname
393 # there and a 'forks' view will be enabled for the project, listing
394 # all the forks. If project list is taken from a file, forks have
395 # to be listed after the main project.
397 # To enable system wide have in $GITWEB_CONFIG
398 # $feature{'forks'}{'default'} = [1];
399 # Project specific override is not supported.
400 'forks' => {
401 'override' => 0,
402 'default' => [0]},
404 # Insert custom links to the action bar of all project pages.
405 # This enables you mainly to link to third-party scripts integrating
406 # into gitweb; e.g. git-browser for graphical history representation
407 # or custom web-based repository administration interface.
409 # The 'default' value consists of a list of triplets in the form
410 # (label, link, position) where position is the label after which
411 # to insert the link and link is a format string where %n expands
412 # to the project name, %f to the project path within the filesystem,
413 # %h to the current hash (h gitweb parameter) and %b to the current
414 # hash base (hb gitweb parameter); %% expands to %.
416 # To enable system wide have in $GITWEB_CONFIG e.g.
417 # $feature{'actions'}{'default'} = [('graphiclog',
418 # '/git-browser/by-commit.html?r=%n', 'summary')];
419 # Project specific override is not supported.
420 'actions' => {
421 'override' => 0,
422 'default' => []},
424 # Allow gitweb scan project content tags described in ctags/
425 # of project repository, and display the popular Web 2.0-ish
426 # "tag cloud" near the project list. Note that this is something
427 # COMPLETELY different from the normal Git tags.
429 # gitweb by itself can show existing tags, but it does not handle
430 # tagging itself; you need an external application for that.
431 # For an example script, check Girocco's cgi/tagproj.cgi.
432 # You may want to install the HTML::TagCloud Perl module to get
433 # a pretty tag cloud instead of just a list of tags.
435 # To enable system wide have in $GITWEB_CONFIG
436 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
437 # Project specific override is not supported.
438 'ctags' => {
439 'override' => 0,
440 'default' => [0]},
442 # The maximum number of patches in a patchset generated in patch
443 # view. Set this to 0 or undef to disable patch view, or to a
444 # negative number to remove any limit.
446 # To disable system wide have in $GITWEB_CONFIG
447 # $feature{'patches'}{'default'} = [0];
448 # To have project specific config enable override in $GITWEB_CONFIG
449 # $feature{'patches'}{'override'} = 1;
450 # and in project config gitweb.patches = 0|n;
451 # where n is the maximum number of patches allowed in a patchset.
452 'patches' => {
453 'sub' => \&feature_patches,
454 'override' => 0,
455 'default' => [16]},
457 # Avatar support. When this feature is enabled, views such as
458 # shortlog or commit will display an avatar associated with
459 # the email of the committer(s) and/or author(s).
461 # Currently available providers are gravatar and picon.
462 # If an unknown provider is specified, the feature is disabled.
464 # Gravatar depends on Digest::MD5.
465 # Picon currently relies on the indiana.edu database.
467 # To enable system wide have in $GITWEB_CONFIG
468 # $feature{'avatar'}{'default'} = ['<provider>'];
469 # where <provider> is either gravatar or picon.
470 # To have project specific config enable override in $GITWEB_CONFIG
471 # $feature{'avatar'}{'override'} = 1;
472 # and in project config gitweb.avatar = <provider>;
473 'avatar' => {
474 'sub' => \&feature_avatar,
475 'override' => 0,
476 'default' => ['']},
478 # Enable displaying how much time and how many git commands
479 # it took to generate and display page. Disabled by default.
480 # Project specific override is not supported.
481 'timed' => {
482 'override' => 0,
483 'default' => [0]},
485 # Enable turning some links into links to actions which require
486 # JavaScript to run (like 'blame_incremental'). Not enabled by
487 # default. Project specific override is currently not supported.
488 'javascript-actions' => {
489 'override' => 0,
490 'default' => [0]},
492 # Syntax highlighting support. This is based on Daniel Svensson's
493 # and Sham Chukoury's work in gitweb-xmms2.git.
494 # It requires the 'highlight' program present in $PATH,
495 # and therefore is disabled by default.
497 # To enable system wide have in $GITWEB_CONFIG
498 # $feature{'highlight'}{'default'} = [1];
500 'highlight' => {
501 'sub' => sub { feature_bool('highlight', @_) },
502 'override' => 0,
503 'default' => [0]},
506 sub gitweb_get_feature {
507 my ($name) = @_;
508 return unless exists $feature{$name};
509 my ($sub, $override, @defaults) = (
510 $feature{$name}{'sub'},
511 $feature{$name}{'override'},
512 @{$feature{$name}{'default'}});
513 # project specific override is possible only if we have project
514 our $git_dir; # global variable, declared later
515 if (!$override || !defined $git_dir) {
516 return @defaults;
518 if (!defined $sub) {
519 warn "feature $name is not overridable";
520 return @defaults;
522 return $sub->(@defaults);
525 # A wrapper to check if a given feature is enabled.
526 # With this, you can say
528 # my $bool_feat = gitweb_check_feature('bool_feat');
529 # gitweb_check_feature('bool_feat') or somecode;
531 # instead of
533 # my ($bool_feat) = gitweb_get_feature('bool_feat');
534 # (gitweb_get_feature('bool_feat'))[0] or somecode;
536 sub gitweb_check_feature {
537 return (gitweb_get_feature(@_))[0];
541 sub feature_bool {
542 my $key = shift;
543 my ($val) = git_get_project_config($key, '--bool');
545 if (!defined $val) {
546 return ($_[0]);
547 } elsif ($val eq 'true') {
548 return (1);
549 } elsif ($val eq 'false') {
550 return (0);
554 sub feature_snapshot {
555 my (@fmts) = @_;
557 my ($val) = git_get_project_config('snapshot');
559 if ($val) {
560 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
563 return @fmts;
566 sub feature_patches {
567 my @val = (git_get_project_config('patches', '--int'));
569 if (@val) {
570 return @val;
573 return ($_[0]);
576 sub feature_avatar {
577 my @val = (git_get_project_config('avatar'));
579 return @val ? @val : @_;
582 # checking HEAD file with -e is fragile if the repository was
583 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
584 # and then pruned.
585 sub check_head_link {
586 my ($dir) = @_;
587 my $headfile = "$dir/HEAD";
588 return ((-e $headfile) ||
589 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
592 sub check_export_ok {
593 my ($dir) = @_;
594 return (check_head_link($dir) &&
595 (!$export_ok || -e "$dir/$export_ok") &&
596 (!$export_auth_hook || $export_auth_hook->($dir)));
599 # process alternate names for backward compatibility
600 # filter out unsupported (unknown) snapshot formats
601 sub filter_snapshot_fmts {
602 my @fmts = @_;
604 @fmts = map {
605 exists $known_snapshot_format_aliases{$_} ?
606 $known_snapshot_format_aliases{$_} : $_} @fmts;
607 @fmts = grep {
608 exists $known_snapshot_formats{$_} &&
609 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
612 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
613 sub evaluate_gitweb_config {
614 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
615 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
616 # die if there are errors parsing config file
617 if (-e $GITWEB_CONFIG) {
618 do $GITWEB_CONFIG;
619 die $@ if $@;
620 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
621 do $GITWEB_CONFIG_SYSTEM;
622 die $@ if $@;
626 # Get loadavg of system, to compare against $maxload.
627 # Currently it requires '/proc/loadavg' present to get loadavg;
628 # if it is not present it returns 0, which means no load checking.
629 sub get_loadavg {
630 if( -e '/proc/loadavg' ){
631 open my $fd, '<', '/proc/loadavg'
632 or return 0;
633 my @load = split(/\s+/, scalar <$fd>);
634 close $fd;
636 # The first three columns measure CPU and IO utilization of the last one,
637 # five, and 10 minute periods. The fourth column shows the number of
638 # currently running processes and the total number of processes in the m/n
639 # format. The last column displays the last process ID used.
640 return $load[0] || 0;
642 # additional checks for load average should go here for things that don't export
643 # /proc/loadavg
645 return 0;
648 # version of the core git binary
649 our $git_version;
650 sub evaluate_git_version {
651 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
652 $number_of_git_cmds++;
655 sub check_loadavg {
656 if (defined $maxload && get_loadavg() > $maxload) {
657 die_error(503, "The load average on the server is too high");
661 # ======================================================================
662 # input validation and dispatch
664 # input parameters can be collected from a variety of sources (presently, CGI
665 # and PATH_INFO), so we define an %input_params hash that collects them all
666 # together during validation: this allows subsequent uses (e.g. href()) to be
667 # agnostic of the parameter origin
669 our %input_params = ();
671 # input parameters are stored with the long parameter name as key. This will
672 # also be used in the href subroutine to convert parameters to their CGI
673 # equivalent, and since the href() usage is the most frequent one, we store
674 # the name -> CGI key mapping here, instead of the reverse.
676 # XXX: Warning: If you touch this, check the search form for updating,
677 # too.
679 our @cgi_param_mapping = (
680 project => "p",
681 action => "a",
682 file_name => "f",
683 file_parent => "fp",
684 hash => "h",
685 hash_parent => "hp",
686 hash_base => "hb",
687 hash_parent_base => "hpb",
688 page => "pg",
689 order => "o",
690 searchtext => "s",
691 searchtype => "st",
692 snapshot_format => "sf",
693 extra_options => "opt",
694 search_use_regexp => "sr",
695 # this must be last entry (for manipulation from JavaScript)
696 javascript => "js"
698 our %cgi_param_mapping = @cgi_param_mapping;
700 # we will also need to know the possible actions, for validation
701 our %actions = (
702 "blame" => \&git_blame,
703 "blame_incremental" => \&git_blame_incremental,
704 "blame_data" => \&git_blame_data,
705 "blobdiff" => \&git_blobdiff,
706 "blobdiff_plain" => \&git_blobdiff_plain,
707 "blob" => \&git_blob,
708 "blob_plain" => \&git_blob_plain,
709 "commitdiff" => \&git_commitdiff,
710 "commitdiff_plain" => \&git_commitdiff_plain,
711 "commit" => \&git_commit,
712 "forks" => \&git_forks,
713 "heads" => \&git_heads,
714 "history" => \&git_history,
715 "log" => \&git_log,
716 "patch" => \&git_patch,
717 "patches" => \&git_patches,
718 "rss" => \&git_rss,
719 "atom" => \&git_atom,
720 "search" => \&git_search,
721 "search_help" => \&git_search_help,
722 "shortlog" => \&git_shortlog,
723 "summary" => \&git_summary,
724 "tag" => \&git_tag,
725 "tags" => \&git_tags,
726 "tree" => \&git_tree,
727 "snapshot" => \&git_snapshot,
728 "object" => \&git_object,
729 # those below don't need $project
730 "opml" => \&git_opml,
731 "project_list" => \&git_project_list,
732 "project_index" => \&git_project_index,
735 # finally, we have the hash of allowed extra_options for the commands that
736 # allow them
737 our %allowed_options = (
738 "--no-merges" => [ qw(rss atom log shortlog history) ],
741 # fill %input_params with the CGI parameters. All values except for 'opt'
742 # should be single values, but opt can be an array. We should probably
743 # build an array of parameters that can be multi-valued, but since for the time
744 # being it's only this one, we just single it out
745 sub evaluate_query_params {
746 our $cgi;
748 while (my ($name, $symbol) = each %cgi_param_mapping) {
749 if ($symbol eq 'opt') {
750 $input_params{$name} = [ $cgi->param($symbol) ];
751 } else {
752 $input_params{$name} = $cgi->param($symbol);
757 # now read PATH_INFO and update the parameter list for missing parameters
758 sub evaluate_path_info {
759 return if defined $input_params{'project'};
760 return if !$path_info;
761 $path_info =~ s,^/+,,;
762 return if !$path_info;
764 # find which part of PATH_INFO is project
765 my $project = $path_info;
766 $project =~ s,/+$,,;
767 while ($project && !check_head_link("$projectroot/$project")) {
768 $project =~ s,/*[^/]*$,,;
770 return unless $project;
771 $input_params{'project'} = $project;
773 # do not change any parameters if an action is given using the query string
774 return if $input_params{'action'};
775 $path_info =~ s,^\Q$project\E/*,,;
777 # next, check if we have an action
778 my $action = $path_info;
779 $action =~ s,/.*$,,;
780 if (exists $actions{$action}) {
781 $path_info =~ s,^$action/*,,;
782 $input_params{'action'} = $action;
785 # list of actions that want hash_base instead of hash, but can have no
786 # pathname (f) parameter
787 my @wants_base = (
788 'tree',
789 'history',
792 # we want to catch, among others
793 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
794 my ($parentrefname, $parentpathname, $refname, $pathname) =
795 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
797 # first, analyze the 'current' part
798 if (defined $pathname) {
799 # we got "branch:filename" or "branch:dir/"
800 # we could use git_get_type(branch:pathname), but:
801 # - it needs $git_dir
802 # - it does a git() call
803 # - the convention of terminating directories with a slash
804 # makes it superfluous
805 # - embedding the action in the PATH_INFO would make it even
806 # more superfluous
807 $pathname =~ s,^/+,,;
808 if (!$pathname || substr($pathname, -1) eq "/") {
809 $input_params{'action'} ||= "tree";
810 $pathname =~ s,/$,,;
811 } else {
812 # the default action depends on whether we had parent info
813 # or not
814 if ($parentrefname) {
815 $input_params{'action'} ||= "blobdiff_plain";
816 } else {
817 $input_params{'action'} ||= "blob_plain";
820 $input_params{'hash_base'} ||= $refname;
821 $input_params{'file_name'} ||= $pathname;
822 } elsif (defined $refname) {
823 # we got "branch". In this case we have to choose if we have to
824 # set hash or hash_base.
826 # Most of the actions without a pathname only want hash to be
827 # set, except for the ones specified in @wants_base that want
828 # hash_base instead. It should also be noted that hand-crafted
829 # links having 'history' as an action and no pathname or hash
830 # set will fail, but that happens regardless of PATH_INFO.
831 if (defined $parentrefname) {
832 # if there is parent let the default be 'shortlog' action
833 # (for http://git.example.com/repo.git/A..B links); if there
834 # is no parent, dispatch will detect type of object and set
835 # action appropriately if required (if action is not set)
836 $input_params{'action'} ||= "shortlog";
838 if ($input_params{'action'} &&
839 grep { $_ eq $input_params{'action'} } @wants_base) {
840 $input_params{'hash_base'} ||= $refname;
841 } else {
842 $input_params{'hash'} ||= $refname;
846 # next, handle the 'parent' part, if present
847 if (defined $parentrefname) {
848 # a missing pathspec defaults to the 'current' filename, allowing e.g.
849 # someproject/blobdiff/oldrev..newrev:/filename
850 if ($parentpathname) {
851 $parentpathname =~ s,^/+,,;
852 $parentpathname =~ s,/$,,;
853 $input_params{'file_parent'} ||= $parentpathname;
854 } else {
855 $input_params{'file_parent'} ||= $input_params{'file_name'};
857 # we assume that hash_parent_base is wanted if a path was specified,
858 # or if the action wants hash_base instead of hash
859 if (defined $input_params{'file_parent'} ||
860 grep { $_ eq $input_params{'action'} } @wants_base) {
861 $input_params{'hash_parent_base'} ||= $parentrefname;
862 } else {
863 $input_params{'hash_parent'} ||= $parentrefname;
867 # for the snapshot action, we allow URLs in the form
868 # $project/snapshot/$hash.ext
869 # where .ext determines the snapshot and gets removed from the
870 # passed $refname to provide the $hash.
872 # To be able to tell that $refname includes the format extension, we
873 # require the following two conditions to be satisfied:
874 # - the hash input parameter MUST have been set from the $refname part
875 # of the URL (i.e. they must be equal)
876 # - the snapshot format MUST NOT have been defined already (e.g. from
877 # CGI parameter sf)
878 # It's also useless to try any matching unless $refname has a dot,
879 # so we check for that too
880 if (defined $input_params{'action'} &&
881 $input_params{'action'} eq 'snapshot' &&
882 defined $refname && index($refname, '.') != -1 &&
883 $refname eq $input_params{'hash'} &&
884 !defined $input_params{'snapshot_format'}) {
885 # We loop over the known snapshot formats, checking for
886 # extensions. Allowed extensions are both the defined suffix
887 # (which includes the initial dot already) and the snapshot
888 # format key itself, with a prepended dot
889 while (my ($fmt, $opt) = each %known_snapshot_formats) {
890 my $hash = $refname;
891 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
892 next;
894 my $sfx = $1;
895 # a valid suffix was found, so set the snapshot format
896 # and reset the hash parameter
897 $input_params{'snapshot_format'} = $fmt;
898 $input_params{'hash'} = $hash;
899 # we also set the format suffix to the one requested
900 # in the URL: this way a request for e.g. .tgz returns
901 # a .tgz instead of a .tar.gz
902 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
903 last;
908 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
909 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
910 $searchtext, $search_regexp);
911 sub evaluate_and_validate_params {
912 our $action = $input_params{'action'};
913 if (defined $action) {
914 if (!validate_action($action)) {
915 die_error(400, "Invalid action parameter");
919 # parameters which are pathnames
920 our $project = $input_params{'project'};
921 if (defined $project) {
922 if (!validate_project($project)) {
923 undef $project;
924 die_error(404, "No such project");
928 our $file_name = $input_params{'file_name'};
929 if (defined $file_name) {
930 if (!validate_pathname($file_name)) {
931 die_error(400, "Invalid file parameter");
935 our $file_parent = $input_params{'file_parent'};
936 if (defined $file_parent) {
937 if (!validate_pathname($file_parent)) {
938 die_error(400, "Invalid file parent parameter");
942 # parameters which are refnames
943 our $hash = $input_params{'hash'};
944 if (defined $hash) {
945 if (!validate_refname($hash)) {
946 die_error(400, "Invalid hash parameter");
950 our $hash_parent = $input_params{'hash_parent'};
951 if (defined $hash_parent) {
952 if (!validate_refname($hash_parent)) {
953 die_error(400, "Invalid hash parent parameter");
957 our $hash_base = $input_params{'hash_base'};
958 if (defined $hash_base) {
959 if (!validate_refname($hash_base)) {
960 die_error(400, "Invalid hash base parameter");
964 our @extra_options = @{$input_params{'extra_options'}};
965 # @extra_options is always defined, since it can only be (currently) set from
966 # CGI, and $cgi->param() returns the empty array in array context if the param
967 # is not set
968 foreach my $opt (@extra_options) {
969 if (not exists $allowed_options{$opt}) {
970 die_error(400, "Invalid option parameter");
972 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
973 die_error(400, "Invalid option parameter for this action");
977 our $hash_parent_base = $input_params{'hash_parent_base'};
978 if (defined $hash_parent_base) {
979 if (!validate_refname($hash_parent_base)) {
980 die_error(400, "Invalid hash parent base parameter");
984 # other parameters
985 our $page = $input_params{'page'};
986 if (defined $page) {
987 if ($page =~ m/[^0-9]/) {
988 die_error(400, "Invalid page parameter");
992 our $searchtype = $input_params{'searchtype'};
993 if (defined $searchtype) {
994 if ($searchtype =~ m/[^a-z]/) {
995 die_error(400, "Invalid searchtype parameter");
999 our $search_use_regexp = $input_params{'search_use_regexp'};
1001 our $searchtext = $input_params{'searchtext'};
1002 our $search_regexp;
1003 if (defined $searchtext) {
1004 if (length($searchtext) < 2) {
1005 die_error(403, "At least two characters are required for search parameter");
1007 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1011 # path to the current git repository
1012 our $git_dir;
1013 sub evaluate_git_dir {
1014 our $git_dir = "$projectroot/$project" if $project;
1017 our (@snapshot_fmts, $git_avatar);
1018 sub configure_gitweb_features {
1019 # list of supported snapshot formats
1020 our @snapshot_fmts = gitweb_get_feature('snapshot');
1021 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1023 # check that the avatar feature is set to a known provider name,
1024 # and for each provider check if the dependencies are satisfied.
1025 # if the provider name is invalid or the dependencies are not met,
1026 # reset $git_avatar to the empty string.
1027 our ($git_avatar) = gitweb_get_feature('avatar');
1028 if ($git_avatar eq 'gravatar') {
1029 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1030 } elsif ($git_avatar eq 'picon') {
1031 # no dependencies
1032 } else {
1033 $git_avatar = '';
1037 # custom error handler: 'die <message>' is Internal Server Error
1038 sub handle_errors_html {
1039 my $msg = shift; # it is already HTML escaped
1041 # to avoid infinite loop where error occurs in die_error,
1042 # change handler to default handler, disabling handle_errors_html
1043 set_message("Error occured when inside die_error:\n$msg");
1045 # you cannot jump out of die_error when called as error handler;
1046 # the subroutine set via CGI::Carp::set_message is called _after_
1047 # HTTP headers are already written, so it cannot write them itself
1048 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1050 set_message(\&handle_errors_html);
1052 # dispatch
1053 sub dispatch {
1054 if (!defined $action) {
1055 if (defined $hash) {
1056 $action = git_get_type($hash);
1057 } elsif (defined $hash_base && defined $file_name) {
1058 $action = git_get_type("$hash_base:$file_name");
1059 } elsif (defined $project) {
1060 $action = 'summary';
1061 } else {
1062 $action = 'project_list';
1065 if (!defined($actions{$action})) {
1066 die_error(400, "Unknown action");
1068 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1069 !$project) {
1070 die_error(400, "Project needed");
1072 $actions{$action}->();
1075 sub reset_timer {
1076 our $t0 = [Time::HiRes::gettimeofday()]
1077 if defined $t0;
1078 our $number_of_git_cmds = 0;
1081 sub run_request {
1082 reset_timer();
1084 evaluate_uri();
1085 evaluate_gitweb_config();
1086 evaluate_git_version();
1087 check_loadavg();
1089 # $projectroot and $projects_list might be set in gitweb config file
1090 $projects_list ||= $projectroot;
1092 evaluate_query_params();
1093 evaluate_path_info();
1094 evaluate_and_validate_params();
1095 evaluate_git_dir();
1097 configure_gitweb_features();
1099 dispatch();
1102 our $is_last_request = sub { 1 };
1103 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1104 our $CGI = 'CGI';
1105 our $cgi;
1106 sub configure_as_fcgi {
1107 require CGI::Fast;
1108 our $CGI = 'CGI::Fast';
1110 my $request_number = 0;
1111 # let each child service 100 requests
1112 our $is_last_request = sub { ++$request_number > 100 };
1114 sub evaluate_argv {
1115 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1116 configure_as_fcgi()
1117 if $script_name =~ /\.fcgi$/;
1119 return unless (@ARGV);
1121 require Getopt::Long;
1122 Getopt::Long::GetOptions(
1123 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1124 'nproc|n=i' => sub {
1125 my ($arg, $val) = @_;
1126 return unless eval { require FCGI::ProcManager; 1; };
1127 my $proc_manager = FCGI::ProcManager->new({
1128 n_processes => $val,
1130 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1131 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1132 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1137 sub run {
1138 evaluate_argv();
1140 $pre_listen_hook->()
1141 if $pre_listen_hook;
1143 REQUEST:
1144 while ($cgi = $CGI->new()) {
1145 $pre_dispatch_hook->()
1146 if $pre_dispatch_hook;
1148 run_request();
1150 $post_dispatch_hook->()
1151 if $post_dispatch_hook;
1153 last REQUEST if ($is_last_request->());
1156 DONE_GITWEB:
1160 run();
1162 if (defined caller) {
1163 # wrapped in a subroutine processing requests,
1164 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1165 return;
1166 } else {
1167 # pure CGI script, serving single request
1168 exit;
1171 ## ======================================================================
1172 ## action links
1174 # possible values of extra options
1175 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1176 # -replay => 1 - start from a current view (replay with modifications)
1177 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1178 sub href {
1179 my %params = @_;
1180 # default is to use -absolute url() i.e. $my_uri
1181 my $href = $params{-full} ? $my_url : $my_uri;
1183 $params{'project'} = $project unless exists $params{'project'};
1185 if ($params{-replay}) {
1186 while (my ($name, $symbol) = each %cgi_param_mapping) {
1187 if (!exists $params{$name}) {
1188 $params{$name} = $input_params{$name};
1193 my $use_pathinfo = gitweb_check_feature('pathinfo');
1194 if (defined $params{'project'} &&
1195 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1196 # try to put as many parameters as possible in PATH_INFO:
1197 # - project name
1198 # - action
1199 # - hash_parent or hash_parent_base:/file_parent
1200 # - hash or hash_base:/filename
1201 # - the snapshot_format as an appropriate suffix
1203 # When the script is the root DirectoryIndex for the domain,
1204 # $href here would be something like http://gitweb.example.com/
1205 # Thus, we strip any trailing / from $href, to spare us double
1206 # slashes in the final URL
1207 $href =~ s,/$,,;
1209 # Then add the project name, if present
1210 $href .= "/".esc_url($params{'project'});
1211 delete $params{'project'};
1213 # since we destructively absorb parameters, we keep this
1214 # boolean that remembers if we're handling a snapshot
1215 my $is_snapshot = $params{'action'} eq 'snapshot';
1217 # Summary just uses the project path URL, any other action is
1218 # added to the URL
1219 if (defined $params{'action'}) {
1220 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1221 delete $params{'action'};
1224 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1225 # stripping nonexistent or useless pieces
1226 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1227 || $params{'hash_parent'} || $params{'hash'});
1228 if (defined $params{'hash_base'}) {
1229 if (defined $params{'hash_parent_base'}) {
1230 $href .= esc_url($params{'hash_parent_base'});
1231 # skip the file_parent if it's the same as the file_name
1232 if (defined $params{'file_parent'}) {
1233 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1234 delete $params{'file_parent'};
1235 } elsif ($params{'file_parent'} !~ /\.\./) {
1236 $href .= ":/".esc_url($params{'file_parent'});
1237 delete $params{'file_parent'};
1240 $href .= "..";
1241 delete $params{'hash_parent'};
1242 delete $params{'hash_parent_base'};
1243 } elsif (defined $params{'hash_parent'}) {
1244 $href .= esc_url($params{'hash_parent'}). "..";
1245 delete $params{'hash_parent'};
1248 $href .= esc_url($params{'hash_base'});
1249 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1250 $href .= ":/".esc_url($params{'file_name'});
1251 delete $params{'file_name'};
1253 delete $params{'hash'};
1254 delete $params{'hash_base'};
1255 } elsif (defined $params{'hash'}) {
1256 $href .= esc_url($params{'hash'});
1257 delete $params{'hash'};
1260 # If the action was a snapshot, we can absorb the
1261 # snapshot_format parameter too
1262 if ($is_snapshot) {
1263 my $fmt = $params{'snapshot_format'};
1264 # snapshot_format should always be defined when href()
1265 # is called, but just in case some code forgets, we
1266 # fall back to the default
1267 $fmt ||= $snapshot_fmts[0];
1268 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1269 delete $params{'snapshot_format'};
1273 # now encode the parameters explicitly
1274 my @result = ();
1275 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1276 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1277 if (defined $params{$name}) {
1278 if (ref($params{$name}) eq "ARRAY") {
1279 foreach my $par (@{$params{$name}}) {
1280 push @result, $symbol . "=" . esc_param($par);
1282 } else {
1283 push @result, $symbol . "=" . esc_param($params{$name});
1287 $href .= "?" . join(';', @result) if scalar @result;
1289 return $href;
1293 ## ======================================================================
1294 ## validation, quoting/unquoting and escaping
1296 sub validate_action {
1297 my $input = shift || return undef;
1298 return undef unless exists $actions{$input};
1299 return $input;
1302 sub validate_project {
1303 my $input = shift || return undef;
1304 if (!validate_pathname($input) ||
1305 !(-d "$projectroot/$input") ||
1306 !check_export_ok("$projectroot/$input") ||
1307 ($strict_export && !project_in_list($input))) {
1308 return undef;
1309 } else {
1310 return $input;
1314 sub validate_pathname {
1315 my $input = shift || return undef;
1317 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1318 # at the beginning, at the end, and between slashes.
1319 # also this catches doubled slashes
1320 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1321 return undef;
1323 # no null characters
1324 if ($input =~ m!\0!) {
1325 return undef;
1327 return $input;
1330 sub validate_refname {
1331 my $input = shift || return undef;
1333 # textual hashes are O.K.
1334 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1335 return $input;
1337 # it must be correct pathname
1338 $input = validate_pathname($input)
1339 or return undef;
1340 # restrictions on ref name according to git-check-ref-format
1341 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1342 return undef;
1344 return $input;
1347 # decode sequences of octets in utf8 into Perl's internal form,
1348 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1349 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1350 sub to_utf8 {
1351 my $str = shift;
1352 return undef unless defined $str;
1353 if (utf8::valid($str)) {
1354 utf8::decode($str);
1355 return $str;
1356 } else {
1357 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1361 # quote unsafe chars, but keep the slash, even when it's not
1362 # correct, but quoted slashes look too horrible in bookmarks
1363 sub esc_param {
1364 my $str = shift;
1365 return undef unless defined $str;
1366 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1367 $str =~ s/ /\+/g;
1368 return $str;
1371 # quote unsafe chars in whole URL, so some characters cannot be quoted
1372 sub esc_url {
1373 my $str = shift;
1374 return undef unless defined $str;
1375 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1376 $str =~ s/ /\+/g;
1377 return $str;
1380 # replace invalid utf8 character with SUBSTITUTION sequence
1381 sub esc_html {
1382 my $str = shift;
1383 my %opts = @_;
1385 return undef unless defined $str;
1387 $str = to_utf8($str);
1388 $str = $cgi->escapeHTML($str);
1389 if ($opts{'-nbsp'}) {
1390 $str =~ s/ /&nbsp;/g;
1392 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1393 return $str;
1396 # quote control characters and escape filename to HTML
1397 sub esc_path {
1398 my $str = shift;
1399 my %opts = @_;
1401 return undef unless defined $str;
1403 $str = to_utf8($str);
1404 $str = $cgi->escapeHTML($str);
1405 if ($opts{'-nbsp'}) {
1406 $str =~ s/ /&nbsp;/g;
1408 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1409 return $str;
1412 # Make control characters "printable", using character escape codes (CEC)
1413 sub quot_cec {
1414 my $cntrl = shift;
1415 my %opts = @_;
1416 my %es = ( # character escape codes, aka escape sequences
1417 "\t" => '\t', # tab (HT)
1418 "\n" => '\n', # line feed (LF)
1419 "\r" => '\r', # carrige return (CR)
1420 "\f" => '\f', # form feed (FF)
1421 "\b" => '\b', # backspace (BS)
1422 "\a" => '\a', # alarm (bell) (BEL)
1423 "\e" => '\e', # escape (ESC)
1424 "\013" => '\v', # vertical tab (VT)
1425 "\000" => '\0', # nul character (NUL)
1427 my $chr = ( (exists $es{$cntrl})
1428 ? $es{$cntrl}
1429 : sprintf('\%2x', ord($cntrl)) );
1430 if ($opts{-nohtml}) {
1431 return $chr;
1432 } else {
1433 return "<span class=\"cntrl\">$chr</span>";
1437 # Alternatively use unicode control pictures codepoints,
1438 # Unicode "printable representation" (PR)
1439 sub quot_upr {
1440 my $cntrl = shift;
1441 my %opts = @_;
1443 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1444 if ($opts{-nohtml}) {
1445 return $chr;
1446 } else {
1447 return "<span class=\"cntrl\">$chr</span>";
1451 # git may return quoted and escaped filenames
1452 sub unquote {
1453 my $str = shift;
1455 sub unq {
1456 my $seq = shift;
1457 my %es = ( # character escape codes, aka escape sequences
1458 't' => "\t", # tab (HT, TAB)
1459 'n' => "\n", # newline (NL)
1460 'r' => "\r", # return (CR)
1461 'f' => "\f", # form feed (FF)
1462 'b' => "\b", # backspace (BS)
1463 'a' => "\a", # alarm (bell) (BEL)
1464 'e' => "\e", # escape (ESC)
1465 'v' => "\013", # vertical tab (VT)
1468 if ($seq =~ m/^[0-7]{1,3}$/) {
1469 # octal char sequence
1470 return chr(oct($seq));
1471 } elsif (exists $es{$seq}) {
1472 # C escape sequence, aka character escape code
1473 return $es{$seq};
1475 # quoted ordinary character
1476 return $seq;
1479 if ($str =~ m/^"(.*)"$/) {
1480 # needs unquoting
1481 $str = $1;
1482 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1484 return $str;
1487 # escape tabs (convert tabs to spaces)
1488 sub untabify {
1489 my $line = shift;
1491 while ((my $pos = index($line, "\t")) != -1) {
1492 if (my $count = (8 - ($pos % 8))) {
1493 my $spaces = ' ' x $count;
1494 $line =~ s/\t/$spaces/;
1498 return $line;
1501 sub project_in_list {
1502 my $project = shift;
1503 my @list = git_get_projects_list();
1504 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1507 ## ----------------------------------------------------------------------
1508 ## HTML aware string manipulation
1510 # Try to chop given string on a word boundary between position
1511 # $len and $len+$add_len. If there is no word boundary there,
1512 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1513 # (marking chopped part) would be longer than given string.
1514 sub chop_str {
1515 my $str = shift;
1516 my $len = shift;
1517 my $add_len = shift || 10;
1518 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1520 # Make sure perl knows it is utf8 encoded so we don't
1521 # cut in the middle of a utf8 multibyte char.
1522 $str = to_utf8($str);
1524 # allow only $len chars, but don't cut a word if it would fit in $add_len
1525 # if it doesn't fit, cut it if it's still longer than the dots we would add
1526 # remove chopped character entities entirely
1528 # when chopping in the middle, distribute $len into left and right part
1529 # return early if chopping wouldn't make string shorter
1530 if ($where eq 'center') {
1531 return $str if ($len + 5 >= length($str)); # filler is length 5
1532 $len = int($len/2);
1533 } else {
1534 return $str if ($len + 4 >= length($str)); # filler is length 4
1537 # regexps: ending and beginning with word part up to $add_len
1538 my $endre = qr/.{$len}\w{0,$add_len}/;
1539 my $begre = qr/\w{0,$add_len}.{$len}/;
1541 if ($where eq 'left') {
1542 $str =~ m/^(.*?)($begre)$/;
1543 my ($lead, $body) = ($1, $2);
1544 if (length($lead) > 4) {
1545 $lead = " ...";
1547 return "$lead$body";
1549 } elsif ($where eq 'center') {
1550 $str =~ m/^($endre)(.*)$/;
1551 my ($left, $str) = ($1, $2);
1552 $str =~ m/^(.*?)($begre)$/;
1553 my ($mid, $right) = ($1, $2);
1554 if (length($mid) > 5) {
1555 $mid = " ... ";
1557 return "$left$mid$right";
1559 } else {
1560 $str =~ m/^($endre)(.*)$/;
1561 my $body = $1;
1562 my $tail = $2;
1563 if (length($tail) > 4) {
1564 $tail = "... ";
1566 return "$body$tail";
1570 # takes the same arguments as chop_str, but also wraps a <span> around the
1571 # result with a title attribute if it does get chopped. Additionally, the
1572 # string is HTML-escaped.
1573 sub chop_and_escape_str {
1574 my ($str) = @_;
1576 my $chopped = chop_str(@_);
1577 if ($chopped eq $str) {
1578 return esc_html($chopped);
1579 } else {
1580 $str =~ s/[[:cntrl:]]/?/g;
1581 return $cgi->span({-title=>$str}, esc_html($chopped));
1585 ## ----------------------------------------------------------------------
1586 ## functions returning short strings
1588 # CSS class for given age value (in seconds)
1589 sub age_class {
1590 my $age = shift;
1592 if (!defined $age) {
1593 return "noage";
1594 } elsif ($age < 60*60*2) {
1595 return "age0";
1596 } elsif ($age < 60*60*24*2) {
1597 return "age1";
1598 } else {
1599 return "age2";
1603 # convert age in seconds to "nn units ago" string
1604 sub age_string {
1605 my $age = shift;
1606 my $age_str;
1608 if ($age > 60*60*24*365*2) {
1609 $age_str = (int $age/60/60/24/365);
1610 $age_str .= " years ago";
1611 } elsif ($age > 60*60*24*(365/12)*2) {
1612 $age_str = int $age/60/60/24/(365/12);
1613 $age_str .= " months ago";
1614 } elsif ($age > 60*60*24*7*2) {
1615 $age_str = int $age/60/60/24/7;
1616 $age_str .= " weeks ago";
1617 } elsif ($age > 60*60*24*2) {
1618 $age_str = int $age/60/60/24;
1619 $age_str .= " days ago";
1620 } elsif ($age > 60*60*2) {
1621 $age_str = int $age/60/60;
1622 $age_str .= " hours ago";
1623 } elsif ($age > 60*2) {
1624 $age_str = int $age/60;
1625 $age_str .= " min ago";
1626 } elsif ($age > 2) {
1627 $age_str = int $age;
1628 $age_str .= " sec ago";
1629 } else {
1630 $age_str .= " right now";
1632 return $age_str;
1635 use constant {
1636 S_IFINVALID => 0030000,
1637 S_IFGITLINK => 0160000,
1640 # submodule/subproject, a commit object reference
1641 sub S_ISGITLINK {
1642 my $mode = shift;
1644 return (($mode & S_IFMT) == S_IFGITLINK)
1647 # convert file mode in octal to symbolic file mode string
1648 sub mode_str {
1649 my $mode = oct shift;
1651 if (S_ISGITLINK($mode)) {
1652 return 'm---------';
1653 } elsif (S_ISDIR($mode & S_IFMT)) {
1654 return 'drwxr-xr-x';
1655 } elsif (S_ISLNK($mode)) {
1656 return 'lrwxrwxrwx';
1657 } elsif (S_ISREG($mode)) {
1658 # git cares only about the executable bit
1659 if ($mode & S_IXUSR) {
1660 return '-rwxr-xr-x';
1661 } else {
1662 return '-rw-r--r--';
1664 } else {
1665 return '----------';
1669 # convert file mode in octal to file type string
1670 sub file_type {
1671 my $mode = shift;
1673 if ($mode !~ m/^[0-7]+$/) {
1674 return $mode;
1675 } else {
1676 $mode = oct $mode;
1679 if (S_ISGITLINK($mode)) {
1680 return "submodule";
1681 } elsif (S_ISDIR($mode & S_IFMT)) {
1682 return "directory";
1683 } elsif (S_ISLNK($mode)) {
1684 return "symlink";
1685 } elsif (S_ISREG($mode)) {
1686 return "file";
1687 } else {
1688 return "unknown";
1692 # convert file mode in octal to file type description string
1693 sub file_type_long {
1694 my $mode = shift;
1696 if ($mode !~ m/^[0-7]+$/) {
1697 return $mode;
1698 } else {
1699 $mode = oct $mode;
1702 if (S_ISGITLINK($mode)) {
1703 return "submodule";
1704 } elsif (S_ISDIR($mode & S_IFMT)) {
1705 return "directory";
1706 } elsif (S_ISLNK($mode)) {
1707 return "symlink";
1708 } elsif (S_ISREG($mode)) {
1709 if ($mode & S_IXUSR) {
1710 return "executable";
1711 } else {
1712 return "file";
1714 } else {
1715 return "unknown";
1720 ## ----------------------------------------------------------------------
1721 ## functions returning short HTML fragments, or transforming HTML fragments
1722 ## which don't belong to other sections
1724 # format line of commit message.
1725 sub format_log_line_html {
1726 my $line = shift;
1728 $line = esc_html($line, -nbsp=>1);
1729 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1730 $cgi->a({-href => href(action=>"object", hash=>$1),
1731 -class => "text"}, $1);
1732 }eg;
1734 return $line;
1737 # format marker of refs pointing to given object
1739 # the destination action is chosen based on object type and current context:
1740 # - for annotated tags, we choose the tag view unless it's the current view
1741 # already, in which case we go to shortlog view
1742 # - for other refs, we keep the current view if we're in history, shortlog or
1743 # log view, and select shortlog otherwise
1744 sub format_ref_marker {
1745 my ($refs, $id) = @_;
1746 my $markers = '';
1748 if (defined $refs->{$id}) {
1749 foreach my $ref (@{$refs->{$id}}) {
1750 # this code exploits the fact that non-lightweight tags are the
1751 # only indirect objects, and that they are the only objects for which
1752 # we want to use tag instead of shortlog as action
1753 my ($type, $name) = qw();
1754 my $indirect = ($ref =~ s/\^\{\}$//);
1755 # e.g. tags/v2.6.11 or heads/next
1756 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1757 $type = $1;
1758 $name = $2;
1759 } else {
1760 $type = "ref";
1761 $name = $ref;
1764 my $class = $type;
1765 $class .= " indirect" if $indirect;
1767 my $dest_action = "shortlog";
1769 if ($indirect) {
1770 $dest_action = "tag" unless $action eq "tag";
1771 } elsif ($action =~ /^(history|(short)?log)$/) {
1772 $dest_action = $action;
1775 my $dest = "";
1776 $dest .= "refs/" unless $ref =~ m!^refs/!;
1777 $dest .= $ref;
1779 my $link = $cgi->a({
1780 -href => href(
1781 action=>$dest_action,
1782 hash=>$dest
1783 )}, $name);
1785 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1786 $link . "</span>";
1790 if ($markers) {
1791 return ' <span class="refs">'. $markers . '</span>';
1792 } else {
1793 return "";
1797 # format, perhaps shortened and with markers, title line
1798 sub format_subject_html {
1799 my ($long, $short, $href, $extra) = @_;
1800 $extra = '' unless defined($extra);
1802 if (length($short) < length($long)) {
1803 $long =~ s/[[:cntrl:]]/?/g;
1804 return $cgi->a({-href => $href, -class => "list subject",
1805 -title => to_utf8($long)},
1806 esc_html($short)) . $extra;
1807 } else {
1808 return $cgi->a({-href => $href, -class => "list subject"},
1809 esc_html($long)) . $extra;
1813 # Rather than recomputing the url for an email multiple times, we cache it
1814 # after the first hit. This gives a visible benefit in views where the avatar
1815 # for the same email is used repeatedly (e.g. shortlog).
1816 # The cache is shared by all avatar engines (currently gravatar only), which
1817 # are free to use it as preferred. Since only one avatar engine is used for any
1818 # given page, there's no risk for cache conflicts.
1819 our %avatar_cache = ();
1821 # Compute the picon url for a given email, by using the picon search service over at
1822 # http://www.cs.indiana.edu/picons/search.html
1823 sub picon_url {
1824 my $email = lc shift;
1825 if (!$avatar_cache{$email}) {
1826 my ($user, $domain) = split('@', $email);
1827 $avatar_cache{$email} =
1828 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1829 "$domain/$user/" .
1830 "users+domains+unknown/up/single";
1832 return $avatar_cache{$email};
1835 # Compute the gravatar url for a given email, if it's not in the cache already.
1836 # Gravatar stores only the part of the URL before the size, since that's the
1837 # one computationally more expensive. This also allows reuse of the cache for
1838 # different sizes (for this particular engine).
1839 sub gravatar_url {
1840 my $email = lc shift;
1841 my $size = shift;
1842 $avatar_cache{$email} ||=
1843 "http://www.gravatar.com/avatar/" .
1844 Digest::MD5::md5_hex($email) . "?s=";
1845 return $avatar_cache{$email} . $size;
1848 # Insert an avatar for the given $email at the given $size if the feature
1849 # is enabled.
1850 sub git_get_avatar {
1851 my ($email, %opts) = @_;
1852 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1853 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1854 $opts{-size} ||= 'default';
1855 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1856 my $url = "";
1857 if ($git_avatar eq 'gravatar') {
1858 $url = gravatar_url($email, $size);
1859 } elsif ($git_avatar eq 'picon') {
1860 $url = picon_url($email);
1862 # Other providers can be added by extending the if chain, defining $url
1863 # as needed. If no variant puts something in $url, we assume avatars
1864 # are completely disabled/unavailable.
1865 if ($url) {
1866 return $pre_white .
1867 "<img width=\"$size\" " .
1868 "class=\"avatar\" " .
1869 "src=\"$url\" " .
1870 "alt=\"\" " .
1871 "/>" . $post_white;
1872 } else {
1873 return "";
1877 sub format_search_author {
1878 my ($author, $searchtype, $displaytext) = @_;
1879 my $have_search = gitweb_check_feature('search');
1881 if ($have_search) {
1882 my $performed = "";
1883 if ($searchtype eq 'author') {
1884 $performed = "authored";
1885 } elsif ($searchtype eq 'committer') {
1886 $performed = "committed";
1889 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1890 searchtext=>$author,
1891 searchtype=>$searchtype), class=>"list",
1892 title=>"Search for commits $performed by $author"},
1893 $displaytext);
1895 } else {
1896 return $displaytext;
1900 # format the author name of the given commit with the given tag
1901 # the author name is chopped and escaped according to the other
1902 # optional parameters (see chop_str).
1903 sub format_author_html {
1904 my $tag = shift;
1905 my $co = shift;
1906 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1907 return "<$tag class=\"author\">" .
1908 format_search_author($co->{'author_name'}, "author",
1909 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1910 $author) .
1911 "</$tag>";
1914 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1915 sub format_git_diff_header_line {
1916 my $line = shift;
1917 my $diffinfo = shift;
1918 my ($from, $to) = @_;
1920 if ($diffinfo->{'nparents'}) {
1921 # combined diff
1922 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1923 if ($to->{'href'}) {
1924 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1925 esc_path($to->{'file'}));
1926 } else { # file was deleted (no href)
1927 $line .= esc_path($to->{'file'});
1929 } else {
1930 # "ordinary" diff
1931 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1932 if ($from->{'href'}) {
1933 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1934 'a/' . esc_path($from->{'file'}));
1935 } else { # file was added (no href)
1936 $line .= 'a/' . esc_path($from->{'file'});
1938 $line .= ' ';
1939 if ($to->{'href'}) {
1940 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1941 'b/' . esc_path($to->{'file'}));
1942 } else { # file was deleted
1943 $line .= 'b/' . esc_path($to->{'file'});
1947 return "<div class=\"diff header\">$line</div>\n";
1950 # format extended diff header line, before patch itself
1951 sub format_extended_diff_header_line {
1952 my $line = shift;
1953 my $diffinfo = shift;
1954 my ($from, $to) = @_;
1956 # match <path>
1957 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1958 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1959 esc_path($from->{'file'}));
1961 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1962 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1963 esc_path($to->{'file'}));
1965 # match single <mode>
1966 if ($line =~ m/\s(\d{6})$/) {
1967 $line .= '<span class="info"> (' .
1968 file_type_long($1) .
1969 ')</span>';
1971 # match <hash>
1972 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1973 # can match only for combined diff
1974 $line = 'index ';
1975 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1976 if ($from->{'href'}[$i]) {
1977 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1978 -class=>"hash"},
1979 substr($diffinfo->{'from_id'}[$i],0,7));
1980 } else {
1981 $line .= '0' x 7;
1983 # separator
1984 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1986 $line .= '..';
1987 if ($to->{'href'}) {
1988 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1989 substr($diffinfo->{'to_id'},0,7));
1990 } else {
1991 $line .= '0' x 7;
1994 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1995 # can match only for ordinary diff
1996 my ($from_link, $to_link);
1997 if ($from->{'href'}) {
1998 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1999 substr($diffinfo->{'from_id'},0,7));
2000 } else {
2001 $from_link = '0' x 7;
2003 if ($to->{'href'}) {
2004 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2005 substr($diffinfo->{'to_id'},0,7));
2006 } else {
2007 $to_link = '0' x 7;
2009 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2010 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2013 return $line . "<br/>\n";
2016 # format from-file/to-file diff header
2017 sub format_diff_from_to_header {
2018 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2019 my $line;
2020 my $result = '';
2022 $line = $from_line;
2023 #assert($line =~ m/^---/) if DEBUG;
2024 # no extra formatting for "^--- /dev/null"
2025 if (! $diffinfo->{'nparents'}) {
2026 # ordinary (single parent) diff
2027 if ($line =~ m!^--- "?a/!) {
2028 if ($from->{'href'}) {
2029 $line = '--- a/' .
2030 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2031 esc_path($from->{'file'}));
2032 } else {
2033 $line = '--- a/' .
2034 esc_path($from->{'file'});
2037 $result .= qq!<div class="diff from_file">$line</div>\n!;
2039 } else {
2040 # combined diff (merge commit)
2041 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2042 if ($from->{'href'}[$i]) {
2043 $line = '--- ' .
2044 $cgi->a({-href=>href(action=>"blobdiff",
2045 hash_parent=>$diffinfo->{'from_id'}[$i],
2046 hash_parent_base=>$parents[$i],
2047 file_parent=>$from->{'file'}[$i],
2048 hash=>$diffinfo->{'to_id'},
2049 hash_base=>$hash,
2050 file_name=>$to->{'file'}),
2051 -class=>"path",
2052 -title=>"diff" . ($i+1)},
2053 $i+1) .
2054 '/' .
2055 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2056 esc_path($from->{'file'}[$i]));
2057 } else {
2058 $line = '--- /dev/null';
2060 $result .= qq!<div class="diff from_file">$line</div>\n!;
2064 $line = $to_line;
2065 #assert($line =~ m/^\+\+\+/) if DEBUG;
2066 # no extra formatting for "^+++ /dev/null"
2067 if ($line =~ m!^\+\+\+ "?b/!) {
2068 if ($to->{'href'}) {
2069 $line = '+++ b/' .
2070 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2071 esc_path($to->{'file'}));
2072 } else {
2073 $line = '+++ b/' .
2074 esc_path($to->{'file'});
2077 $result .= qq!<div class="diff to_file">$line</div>\n!;
2079 return $result;
2082 # create note for patch simplified by combined diff
2083 sub format_diff_cc_simplified {
2084 my ($diffinfo, @parents) = @_;
2085 my $result = '';
2087 $result .= "<div class=\"diff header\">" .
2088 "diff --cc ";
2089 if (!is_deleted($diffinfo)) {
2090 $result .= $cgi->a({-href => href(action=>"blob",
2091 hash_base=>$hash,
2092 hash=>$diffinfo->{'to_id'},
2093 file_name=>$diffinfo->{'to_file'}),
2094 -class => "path"},
2095 esc_path($diffinfo->{'to_file'}));
2096 } else {
2097 $result .= esc_path($diffinfo->{'to_file'});
2099 $result .= "</div>\n" . # class="diff header"
2100 "<div class=\"diff nodifferences\">" .
2101 "Simple merge" .
2102 "</div>\n"; # class="diff nodifferences"
2104 return $result;
2107 # format patch (diff) line (not to be used for diff headers)
2108 sub format_diff_line {
2109 my $line = shift;
2110 my ($from, $to) = @_;
2111 my $diff_class = "";
2113 chomp $line;
2115 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2116 # combined diff
2117 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2118 if ($line =~ m/^\@{3}/) {
2119 $diff_class = " chunk_header";
2120 } elsif ($line =~ m/^\\/) {
2121 $diff_class = " incomplete";
2122 } elsif ($prefix =~ tr/+/+/) {
2123 $diff_class = " add";
2124 } elsif ($prefix =~ tr/-/-/) {
2125 $diff_class = " rem";
2127 } else {
2128 # assume ordinary diff
2129 my $char = substr($line, 0, 1);
2130 if ($char eq '+') {
2131 $diff_class = " add";
2132 } elsif ($char eq '-') {
2133 $diff_class = " rem";
2134 } elsif ($char eq '@') {
2135 $diff_class = " chunk_header";
2136 } elsif ($char eq "\\") {
2137 $diff_class = " incomplete";
2140 $line = untabify($line);
2141 if ($from && $to && $line =~ m/^\@{2} /) {
2142 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2143 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2145 $from_lines = 0 unless defined $from_lines;
2146 $to_lines = 0 unless defined $to_lines;
2148 if ($from->{'href'}) {
2149 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2150 -class=>"list"}, $from_text);
2152 if ($to->{'href'}) {
2153 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2154 -class=>"list"}, $to_text);
2156 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2157 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2158 return "<div class=\"diff$diff_class\">$line</div>\n";
2159 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2160 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2161 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2163 @from_text = split(' ', $ranges);
2164 for (my $i = 0; $i < @from_text; ++$i) {
2165 ($from_start[$i], $from_nlines[$i]) =
2166 (split(',', substr($from_text[$i], 1)), 0);
2169 $to_text = pop @from_text;
2170 $to_start = pop @from_start;
2171 $to_nlines = pop @from_nlines;
2173 $line = "<span class=\"chunk_info\">$prefix ";
2174 for (my $i = 0; $i < @from_text; ++$i) {
2175 if ($from->{'href'}[$i]) {
2176 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2177 -class=>"list"}, $from_text[$i]);
2178 } else {
2179 $line .= $from_text[$i];
2181 $line .= " ";
2183 if ($to->{'href'}) {
2184 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2185 -class=>"list"}, $to_text);
2186 } else {
2187 $line .= $to_text;
2189 $line .= " $prefix</span>" .
2190 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2191 return "<div class=\"diff$diff_class\">$line</div>\n";
2193 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2196 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2197 # linked. Pass the hash of the tree/commit to snapshot.
2198 sub format_snapshot_links {
2199 my ($hash) = @_;
2200 my $num_fmts = @snapshot_fmts;
2201 if ($num_fmts > 1) {
2202 # A parenthesized list of links bearing format names.
2203 # e.g. "snapshot (_tar.gz_ _zip_)"
2204 return "snapshot (" . join(' ', map
2205 $cgi->a({
2206 -href => href(
2207 action=>"snapshot",
2208 hash=>$hash,
2209 snapshot_format=>$_
2211 }, $known_snapshot_formats{$_}{'display'})
2212 , @snapshot_fmts) . ")";
2213 } elsif ($num_fmts == 1) {
2214 # A single "snapshot" link whose tooltip bears the format name.
2215 # i.e. "_snapshot_"
2216 my ($fmt) = @snapshot_fmts;
2217 return
2218 $cgi->a({
2219 -href => href(
2220 action=>"snapshot",
2221 hash=>$hash,
2222 snapshot_format=>$fmt
2224 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2225 }, "snapshot");
2226 } else { # $num_fmts == 0
2227 return undef;
2231 ## ......................................................................
2232 ## functions returning values to be passed, perhaps after some
2233 ## transformation, to other functions; e.g. returning arguments to href()
2235 # returns hash to be passed to href to generate gitweb URL
2236 # in -title key it returns description of link
2237 sub get_feed_info {
2238 my $format = shift || 'Atom';
2239 my %res = (action => lc($format));
2241 # feed links are possible only for project views
2242 return unless (defined $project);
2243 # some views should link to OPML, or to generic project feed,
2244 # or don't have specific feed yet (so they should use generic)
2245 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2247 my $branch;
2248 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2249 # from tag links; this also makes possible to detect branch links
2250 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2251 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2252 $branch = $1;
2254 # find log type for feed description (title)
2255 my $type = 'log';
2256 if (defined $file_name) {
2257 $type = "history of $file_name";
2258 $type .= "/" if ($action eq 'tree');
2259 $type .= " on '$branch'" if (defined $branch);
2260 } else {
2261 $type = "log of $branch" if (defined $branch);
2264 $res{-title} = $type;
2265 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2266 $res{'file_name'} = $file_name;
2268 return %res;
2271 ## ----------------------------------------------------------------------
2272 ## git utility subroutines, invoking git commands
2274 # returns path to the core git executable and the --git-dir parameter as list
2275 sub git_cmd {
2276 $number_of_git_cmds++;
2277 return $GIT, '--git-dir='.$git_dir;
2280 # quote the given arguments for passing them to the shell
2281 # quote_command("command", "arg 1", "arg with ' and ! characters")
2282 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2283 # Try to avoid using this function wherever possible.
2284 sub quote_command {
2285 return join(' ',
2286 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2289 # get HEAD ref of given project as hash
2290 sub git_get_head_hash {
2291 return git_get_full_hash(shift, 'HEAD');
2294 sub git_get_full_hash {
2295 return git_get_hash(@_);
2298 sub git_get_short_hash {
2299 return git_get_hash(@_, '--short=7');
2302 sub git_get_hash {
2303 my ($project, $hash, @options) = @_;
2304 my $o_git_dir = $git_dir;
2305 my $retval = undef;
2306 $git_dir = "$projectroot/$project";
2307 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2308 '--verify', '-q', @options, $hash) {
2309 $retval = <$fd>;
2310 chomp $retval if defined $retval;
2311 close $fd;
2313 if (defined $o_git_dir) {
2314 $git_dir = $o_git_dir;
2316 return $retval;
2319 # get type of given object
2320 sub git_get_type {
2321 my $hash = shift;
2323 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2324 my $type = <$fd>;
2325 close $fd or return;
2326 chomp $type;
2327 return $type;
2330 # repository configuration
2331 our $config_file = '';
2332 our %config;
2334 # store multiple values for single key as anonymous array reference
2335 # single values stored directly in the hash, not as [ <value> ]
2336 sub hash_set_multi {
2337 my ($hash, $key, $value) = @_;
2339 if (!exists $hash->{$key}) {
2340 $hash->{$key} = $value;
2341 } elsif (!ref $hash->{$key}) {
2342 $hash->{$key} = [ $hash->{$key}, $value ];
2343 } else {
2344 push @{$hash->{$key}}, $value;
2348 # return hash of git project configuration
2349 # optionally limited to some section, e.g. 'gitweb'
2350 sub git_parse_project_config {
2351 my $section_regexp = shift;
2352 my %config;
2354 local $/ = "\0";
2356 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2357 or return;
2359 while (my $keyval = <$fh>) {
2360 chomp $keyval;
2361 my ($key, $value) = split(/\n/, $keyval, 2);
2363 hash_set_multi(\%config, $key, $value)
2364 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2366 close $fh;
2368 return %config;
2371 # convert config value to boolean: 'true' or 'false'
2372 # no value, number > 0, 'true' and 'yes' values are true
2373 # rest of values are treated as false (never as error)
2374 sub config_to_bool {
2375 my $val = shift;
2377 return 1 if !defined $val; # section.key
2379 # strip leading and trailing whitespace
2380 $val =~ s/^\s+//;
2381 $val =~ s/\s+$//;
2383 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2384 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2387 # convert config value to simple decimal number
2388 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2389 # to be multiplied by 1024, 1048576, or 1073741824
2390 sub config_to_int {
2391 my $val = shift;
2393 # strip leading and trailing whitespace
2394 $val =~ s/^\s+//;
2395 $val =~ s/\s+$//;
2397 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2398 $unit = lc($unit);
2399 # unknown unit is treated as 1
2400 return $num * ($unit eq 'g' ? 1073741824 :
2401 $unit eq 'm' ? 1048576 :
2402 $unit eq 'k' ? 1024 : 1);
2404 return $val;
2407 # convert config value to array reference, if needed
2408 sub config_to_multi {
2409 my $val = shift;
2411 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2414 sub git_get_project_config {
2415 my ($key, $type) = @_;
2417 return unless defined $git_dir;
2419 # key sanity check
2420 return unless ($key);
2421 $key =~ s/^gitweb\.//;
2422 return if ($key =~ m/\W/);
2424 # type sanity check
2425 if (defined $type) {
2426 $type =~ s/^--//;
2427 $type = undef
2428 unless ($type eq 'bool' || $type eq 'int');
2431 # get config
2432 if (!defined $config_file ||
2433 $config_file ne "$git_dir/config") {
2434 %config = git_parse_project_config('gitweb');
2435 $config_file = "$git_dir/config";
2438 # check if config variable (key) exists
2439 return unless exists $config{"gitweb.$key"};
2441 # ensure given type
2442 if (!defined $type) {
2443 return $config{"gitweb.$key"};
2444 } elsif ($type eq 'bool') {
2445 # backward compatibility: 'git config --bool' returns true/false
2446 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2447 } elsif ($type eq 'int') {
2448 return config_to_int($config{"gitweb.$key"});
2450 return $config{"gitweb.$key"};
2453 # get hash of given path at given ref
2454 sub git_get_hash_by_path {
2455 my $base = shift;
2456 my $path = shift || return undef;
2457 my $type = shift;
2459 $path =~ s,/+$,,;
2461 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2462 or die_error(500, "Open git-ls-tree failed");
2463 my $line = <$fd>;
2464 close $fd or return undef;
2466 if (!defined $line) {
2467 # there is no tree or hash given by $path at $base
2468 return undef;
2471 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2472 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2473 if (defined $type && $type ne $2) {
2474 # type doesn't match
2475 return undef;
2477 return $3;
2480 # get path of entry with given hash at given tree-ish (ref)
2481 # used to get 'from' filename for combined diff (merge commit) for renames
2482 sub git_get_path_by_hash {
2483 my $base = shift || return;
2484 my $hash = shift || return;
2486 local $/ = "\0";
2488 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2489 or return undef;
2490 while (my $line = <$fd>) {
2491 chomp $line;
2493 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2494 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2495 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2496 close $fd;
2497 return $1;
2500 close $fd;
2501 return undef;
2504 ## ......................................................................
2505 ## git utility functions, directly accessing git repository
2507 sub git_get_project_description {
2508 my $path = shift;
2510 $git_dir = "$projectroot/$path";
2511 open my $fd, '<', "$git_dir/description"
2512 or return git_get_project_config('description');
2513 my $descr = <$fd>;
2514 close $fd;
2515 if (defined $descr) {
2516 chomp $descr;
2518 return $descr;
2521 sub git_get_project_ctags {
2522 my $path = shift;
2523 my $ctags = {};
2525 $git_dir = "$projectroot/$path";
2526 opendir my $dh, "$git_dir/ctags"
2527 or return $ctags;
2528 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2529 open my $ct, '<', $_ or next;
2530 my $val = <$ct>;
2531 chomp $val;
2532 close $ct;
2533 my $ctag = $_; $ctag =~ s#.*/##;
2534 $ctags->{$ctag} = $val;
2536 closedir $dh;
2537 $ctags;
2540 sub git_populate_project_tagcloud {
2541 my $ctags = shift;
2543 # First, merge different-cased tags; tags vote on casing
2544 my %ctags_lc;
2545 foreach (keys %$ctags) {
2546 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2547 if (not $ctags_lc{lc $_}->{topcount}
2548 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2549 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2550 $ctags_lc{lc $_}->{topname} = $_;
2554 my $cloud;
2555 if (eval { require HTML::TagCloud; 1; }) {
2556 $cloud = HTML::TagCloud->new;
2557 foreach (sort keys %ctags_lc) {
2558 # Pad the title with spaces so that the cloud looks
2559 # less crammed.
2560 my $title = $ctags_lc{$_}->{topname};
2561 $title =~ s/ /&nbsp;/g;
2562 $title =~ s/^/&nbsp;/g;
2563 $title =~ s/$/&nbsp;/g;
2564 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2566 } else {
2567 $cloud = \%ctags_lc;
2569 $cloud;
2572 sub git_show_project_tagcloud {
2573 my ($cloud, $count) = @_;
2574 print STDERR ref($cloud)."..\n";
2575 if (ref $cloud eq 'HTML::TagCloud') {
2576 return $cloud->html_and_css($count);
2577 } else {
2578 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2579 return '<p align="center">' . join (', ', map {
2580 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2581 } splice(@tags, 0, $count)) . '</p>';
2585 sub git_get_project_url_list {
2586 my $path = shift;
2588 $git_dir = "$projectroot/$path";
2589 open my $fd, '<', "$git_dir/cloneurl"
2590 or return wantarray ?
2591 @{ config_to_multi(git_get_project_config('url')) } :
2592 config_to_multi(git_get_project_config('url'));
2593 my @git_project_url_list = map { chomp; $_ } <$fd>;
2594 close $fd;
2596 return wantarray ? @git_project_url_list : \@git_project_url_list;
2599 sub git_get_projects_list {
2600 my ($filter) = @_;
2601 my @list;
2603 $filter ||= '';
2604 $filter =~ s/\.git$//;
2606 my $check_forks = gitweb_check_feature('forks');
2608 if (-d $projects_list) {
2609 # search in directory
2610 my $dir = $projects_list . ($filter ? "/$filter" : '');
2611 # remove the trailing "/"
2612 $dir =~ s!/+$!!;
2613 my $pfxlen = length("$dir");
2614 my $pfxdepth = ($dir =~ tr!/!!);
2616 File::Find::find({
2617 follow_fast => 1, # follow symbolic links
2618 follow_skip => 2, # ignore duplicates
2619 dangling_symlinks => 0, # ignore dangling symlinks, silently
2620 wanted => sub {
2621 # global variables
2622 our $project_maxdepth;
2623 our $projectroot;
2624 # skip project-list toplevel, if we get it.
2625 return if (m!^[/.]$!);
2626 # only directories can be git repositories
2627 return unless (-d $_);
2628 # don't traverse too deep (Find is super slow on os x)
2629 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2630 $File::Find::prune = 1;
2631 return;
2634 my $subdir = substr($File::Find::name, $pfxlen + 1);
2635 # we check related file in $projectroot
2636 my $path = ($filter ? "$filter/" : '') . $subdir;
2637 if (check_export_ok("$projectroot/$path")) {
2638 push @list, { path => $path };
2639 $File::Find::prune = 1;
2642 }, "$dir");
2644 } elsif (-f $projects_list) {
2645 # read from file(url-encoded):
2646 # 'git%2Fgit.git Linus+Torvalds'
2647 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2648 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2649 my %paths;
2650 open my $fd, '<', $projects_list or return;
2651 PROJECT:
2652 while (my $line = <$fd>) {
2653 chomp $line;
2654 my ($path, $owner) = split ' ', $line;
2655 $path = unescape($path);
2656 $owner = unescape($owner);
2657 if (!defined $path) {
2658 next;
2660 if ($filter ne '') {
2661 # looking for forks;
2662 my $pfx = substr($path, 0, length($filter));
2663 if ($pfx ne $filter) {
2664 next PROJECT;
2666 my $sfx = substr($path, length($filter));
2667 if ($sfx !~ /^\/.*\.git$/) {
2668 next PROJECT;
2670 } elsif ($check_forks) {
2671 PATH:
2672 foreach my $filter (keys %paths) {
2673 # looking for forks;
2674 my $pfx = substr($path, 0, length($filter));
2675 if ($pfx ne $filter) {
2676 next PATH;
2678 my $sfx = substr($path, length($filter));
2679 if ($sfx !~ /^\/.*\.git$/) {
2680 next PATH;
2682 # is a fork, don't include it in
2683 # the list
2684 next PROJECT;
2687 if (check_export_ok("$projectroot/$path")) {
2688 my $pr = {
2689 path => $path,
2690 owner => to_utf8($owner),
2692 push @list, $pr;
2693 (my $forks_path = $path) =~ s/\.git$//;
2694 $paths{$forks_path}++;
2697 close $fd;
2699 return @list;
2702 our $gitweb_project_owner = undef;
2703 sub git_get_project_list_from_file {
2705 return if (defined $gitweb_project_owner);
2707 $gitweb_project_owner = {};
2708 # read from file (url-encoded):
2709 # 'git%2Fgit.git Linus+Torvalds'
2710 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2711 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2712 if (-f $projects_list) {
2713 open(my $fd, '<', $projects_list);
2714 while (my $line = <$fd>) {
2715 chomp $line;
2716 my ($pr, $ow) = split ' ', $line;
2717 $pr = unescape($pr);
2718 $ow = unescape($ow);
2719 $gitweb_project_owner->{$pr} = to_utf8($ow);
2721 close $fd;
2725 sub git_get_project_owner {
2726 my $project = shift;
2727 my $owner;
2729 return undef unless $project;
2730 $git_dir = "$projectroot/$project";
2732 if (!defined $gitweb_project_owner) {
2733 git_get_project_list_from_file();
2736 if (exists $gitweb_project_owner->{$project}) {
2737 $owner = $gitweb_project_owner->{$project};
2739 if (!defined $owner){
2740 $owner = git_get_project_config('owner');
2742 if (!defined $owner) {
2743 $owner = get_file_owner("$git_dir");
2746 return $owner;
2749 sub git_get_last_activity {
2750 my ($path) = @_;
2751 my $fd;
2753 $git_dir = "$projectroot/$path";
2754 open($fd, "-|", git_cmd(), 'for-each-ref',
2755 '--format=%(committer)',
2756 '--sort=-committerdate',
2757 '--count=1',
2758 'refs/heads') or return;
2759 my $most_recent = <$fd>;
2760 close $fd or return;
2761 if (defined $most_recent &&
2762 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2763 my $timestamp = $1;
2764 my $age = time - $timestamp;
2765 return ($age, age_string($age));
2767 return (undef, undef);
2770 sub git_get_references {
2771 my $type = shift || "";
2772 my %refs;
2773 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2774 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2775 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2776 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2777 or return;
2779 while (my $line = <$fd>) {
2780 chomp $line;
2781 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2782 if (defined $refs{$1}) {
2783 push @{$refs{$1}}, $2;
2784 } else {
2785 $refs{$1} = [ $2 ];
2789 close $fd or return;
2790 return \%refs;
2793 sub git_get_rev_name_tags {
2794 my $hash = shift || return undef;
2796 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2797 or return;
2798 my $name_rev = <$fd>;
2799 close $fd;
2801 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2802 return $1;
2803 } else {
2804 # catches also '$hash undefined' output
2805 return undef;
2809 ## ----------------------------------------------------------------------
2810 ## parse to hash functions
2812 sub parse_date {
2813 my $epoch = shift;
2814 my $tz = shift || "-0000";
2816 my %date;
2817 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2818 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2819 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2820 $date{'hour'} = $hour;
2821 $date{'minute'} = $min;
2822 $date{'mday'} = $mday;
2823 $date{'day'} = $days[$wday];
2824 $date{'month'} = $months[$mon];
2825 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2826 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2827 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2828 $mday, $months[$mon], $hour ,$min;
2829 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2830 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2832 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2833 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2834 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2835 $date{'hour_local'} = $hour;
2836 $date{'minute_local'} = $min;
2837 $date{'tz_local'} = $tz;
2838 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2839 1900+$year, $mon+1, $mday,
2840 $hour, $min, $sec, $tz);
2841 return %date;
2844 sub parse_tag {
2845 my $tag_id = shift;
2846 my %tag;
2847 my @comment;
2849 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2850 $tag{'id'} = $tag_id;
2851 while (my $line = <$fd>) {
2852 chomp $line;
2853 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2854 $tag{'object'} = $1;
2855 } elsif ($line =~ m/^type (.+)$/) {
2856 $tag{'type'} = $1;
2857 } elsif ($line =~ m/^tag (.+)$/) {
2858 $tag{'name'} = $1;
2859 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2860 $tag{'author'} = $1;
2861 $tag{'author_epoch'} = $2;
2862 $tag{'author_tz'} = $3;
2863 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2864 $tag{'author_name'} = $1;
2865 $tag{'author_email'} = $2;
2866 } else {
2867 $tag{'author_name'} = $tag{'author'};
2869 } elsif ($line =~ m/--BEGIN/) {
2870 push @comment, $line;
2871 last;
2872 } elsif ($line eq "") {
2873 last;
2876 push @comment, <$fd>;
2877 $tag{'comment'} = \@comment;
2878 close $fd or return;
2879 if (!defined $tag{'name'}) {
2880 return
2882 return %tag
2885 sub parse_commit_text {
2886 my ($commit_text, $withparents) = @_;
2887 my @commit_lines = split '\n', $commit_text;
2888 my %co;
2890 pop @commit_lines; # Remove '\0'
2892 if (! @commit_lines) {
2893 return;
2896 my $header = shift @commit_lines;
2897 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2898 return;
2900 ($co{'id'}, my @parents) = split ' ', $header;
2901 while (my $line = shift @commit_lines) {
2902 last if $line eq "\n";
2903 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2904 $co{'tree'} = $1;
2905 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2906 push @parents, $1;
2907 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2908 $co{'author'} = to_utf8($1);
2909 $co{'author_epoch'} = $2;
2910 $co{'author_tz'} = $3;
2911 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2912 $co{'author_name'} = $1;
2913 $co{'author_email'} = $2;
2914 } else {
2915 $co{'author_name'} = $co{'author'};
2917 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2918 $co{'committer'} = to_utf8($1);
2919 $co{'committer_epoch'} = $2;
2920 $co{'committer_tz'} = $3;
2921 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2922 $co{'committer_name'} = $1;
2923 $co{'committer_email'} = $2;
2924 } else {
2925 $co{'committer_name'} = $co{'committer'};
2929 if (!defined $co{'tree'}) {
2930 return;
2932 $co{'parents'} = \@parents;
2933 $co{'parent'} = $parents[0];
2935 foreach my $title (@commit_lines) {
2936 $title =~ s/^ //;
2937 if ($title ne "") {
2938 $co{'title'} = chop_str($title, 80, 5);
2939 # remove leading stuff of merges to make the interesting part visible
2940 if (length($title) > 50) {
2941 $title =~ s/^Automatic //;
2942 $title =~ s/^merge (of|with) /Merge ... /i;
2943 if (length($title) > 50) {
2944 $title =~ s/(http|rsync):\/\///;
2946 if (length($title) > 50) {
2947 $title =~ s/(master|www|rsync)\.//;
2949 if (length($title) > 50) {
2950 $title =~ s/kernel.org:?//;
2952 if (length($title) > 50) {
2953 $title =~ s/\/pub\/scm//;
2956 $co{'title_short'} = chop_str($title, 50, 5);
2957 last;
2960 if (! defined $co{'title'} || $co{'title'} eq "") {
2961 $co{'title'} = $co{'title_short'} = '(no commit message)';
2963 # remove added spaces
2964 foreach my $line (@commit_lines) {
2965 $line =~ s/^ //;
2967 $co{'comment'} = \@commit_lines;
2969 my $age = time - $co{'committer_epoch'};
2970 $co{'age'} = $age;
2971 $co{'age_string'} = age_string($age);
2972 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2973 if ($age > 60*60*24*7*2) {
2974 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2975 $co{'age_string_age'} = $co{'age_string'};
2976 } else {
2977 $co{'age_string_date'} = $co{'age_string'};
2978 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2980 return %co;
2983 sub parse_commit {
2984 my ($commit_id) = @_;
2985 my %co;
2987 local $/ = "\0";
2989 open my $fd, "-|", git_cmd(), "rev-list",
2990 "--parents",
2991 "--header",
2992 "--max-count=1",
2993 $commit_id,
2994 "--",
2995 or die_error(500, "Open git-rev-list failed");
2996 %co = parse_commit_text(<$fd>, 1);
2997 close $fd;
2999 return %co;
3002 sub parse_commits {
3003 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3004 my @cos;
3006 $maxcount ||= 1;
3007 $skip ||= 0;
3009 local $/ = "\0";
3011 open my $fd, "-|", git_cmd(), "rev-list",
3012 "--header",
3013 @args,
3014 ("--max-count=" . $maxcount),
3015 ("--skip=" . $skip),
3016 @extra_options,
3017 $commit_id,
3018 "--",
3019 ($filename ? ($filename) : ())
3020 or die_error(500, "Open git-rev-list failed");
3021 while (my $line = <$fd>) {
3022 my %co = parse_commit_text($line);
3023 push @cos, \%co;
3025 close $fd;
3027 return wantarray ? @cos : \@cos;
3030 # parse line of git-diff-tree "raw" output
3031 sub parse_difftree_raw_line {
3032 my $line = shift;
3033 my %res;
3035 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3036 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3037 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3038 $res{'from_mode'} = $1;
3039 $res{'to_mode'} = $2;
3040 $res{'from_id'} = $3;
3041 $res{'to_id'} = $4;
3042 $res{'status'} = $5;
3043 $res{'similarity'} = $6;
3044 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3045 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3046 } else {
3047 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3050 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3051 # combined diff (for merge commit)
3052 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3053 $res{'nparents'} = length($1);
3054 $res{'from_mode'} = [ split(' ', $2) ];
3055 $res{'to_mode'} = pop @{$res{'from_mode'}};
3056 $res{'from_id'} = [ split(' ', $3) ];
3057 $res{'to_id'} = pop @{$res{'from_id'}};
3058 $res{'status'} = [ split('', $4) ];
3059 $res{'to_file'} = unquote($5);
3061 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3062 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3063 $res{'commit'} = $1;
3066 return wantarray ? %res : \%res;
3069 # wrapper: return parsed line of git-diff-tree "raw" output
3070 # (the argument might be raw line, or parsed info)
3071 sub parsed_difftree_line {
3072 my $line_or_ref = shift;
3074 if (ref($line_or_ref) eq "HASH") {
3075 # pre-parsed (or generated by hand)
3076 return $line_or_ref;
3077 } else {
3078 return parse_difftree_raw_line($line_or_ref);
3082 # parse line of git-ls-tree output
3083 sub parse_ls_tree_line {
3084 my $line = shift;
3085 my %opts = @_;
3086 my %res;
3088 if ($opts{'-l'}) {
3089 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3090 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3092 $res{'mode'} = $1;
3093 $res{'type'} = $2;
3094 $res{'hash'} = $3;
3095 $res{'size'} = $4;
3096 if ($opts{'-z'}) {
3097 $res{'name'} = $5;
3098 } else {
3099 $res{'name'} = unquote($5);
3101 } else {
3102 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3103 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3105 $res{'mode'} = $1;
3106 $res{'type'} = $2;
3107 $res{'hash'} = $3;
3108 if ($opts{'-z'}) {
3109 $res{'name'} = $4;
3110 } else {
3111 $res{'name'} = unquote($4);
3115 return wantarray ? %res : \%res;
3118 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3119 sub parse_from_to_diffinfo {
3120 my ($diffinfo, $from, $to, @parents) = @_;
3122 if ($diffinfo->{'nparents'}) {
3123 # combined diff
3124 $from->{'file'} = [];
3125 $from->{'href'} = [];
3126 fill_from_file_info($diffinfo, @parents)
3127 unless exists $diffinfo->{'from_file'};
3128 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3129 $from->{'file'}[$i] =
3130 defined $diffinfo->{'from_file'}[$i] ?
3131 $diffinfo->{'from_file'}[$i] :
3132 $diffinfo->{'to_file'};
3133 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3134 $from->{'href'}[$i] = href(action=>"blob",
3135 hash_base=>$parents[$i],
3136 hash=>$diffinfo->{'from_id'}[$i],
3137 file_name=>$from->{'file'}[$i]);
3138 } else {
3139 $from->{'href'}[$i] = undef;
3142 } else {
3143 # ordinary (not combined) diff
3144 $from->{'file'} = $diffinfo->{'from_file'};
3145 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3146 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3147 hash=>$diffinfo->{'from_id'},
3148 file_name=>$from->{'file'});
3149 } else {
3150 delete $from->{'href'};
3154 $to->{'file'} = $diffinfo->{'to_file'};
3155 if (!is_deleted($diffinfo)) { # file exists in result
3156 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3157 hash=>$diffinfo->{'to_id'},
3158 file_name=>$to->{'file'});
3159 } else {
3160 delete $to->{'href'};
3164 ## ......................................................................
3165 ## parse to array of hashes functions
3167 sub git_get_heads_list {
3168 my $limit = shift;
3169 my @headslist;
3171 open my $fd, '-|', git_cmd(), 'for-each-ref',
3172 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3173 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3174 'refs/heads'
3175 or return;
3176 while (my $line = <$fd>) {
3177 my %ref_item;
3179 chomp $line;
3180 my ($refinfo, $committerinfo) = split(/\0/, $line);
3181 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3182 my ($committer, $epoch, $tz) =
3183 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3184 $ref_item{'fullname'} = $name;
3185 $name =~ s!^refs/heads/!!;
3187 $ref_item{'name'} = $name;
3188 $ref_item{'id'} = $hash;
3189 $ref_item{'title'} = $title || '(no commit message)';
3190 $ref_item{'epoch'} = $epoch;
3191 if ($epoch) {
3192 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3193 } else {
3194 $ref_item{'age'} = "unknown";
3197 push @headslist, \%ref_item;
3199 close $fd;
3201 return wantarray ? @headslist : \@headslist;
3204 sub git_get_tags_list {
3205 my $limit = shift;
3206 my @tagslist;
3208 open my $fd, '-|', git_cmd(), 'for-each-ref',
3209 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3210 '--format=%(objectname) %(objecttype) %(refname) '.
3211 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3212 'refs/tags'
3213 or return;
3214 while (my $line = <$fd>) {
3215 my %ref_item;
3217 chomp $line;
3218 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3219 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3220 my ($creator, $epoch, $tz) =
3221 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3222 $ref_item{'fullname'} = $name;
3223 $name =~ s!^refs/tags/!!;
3225 $ref_item{'type'} = $type;
3226 $ref_item{'id'} = $id;
3227 $ref_item{'name'} = $name;
3228 if ($type eq "tag") {
3229 $ref_item{'subject'} = $title;
3230 $ref_item{'reftype'} = $reftype;
3231 $ref_item{'refid'} = $refid;
3232 } else {
3233 $ref_item{'reftype'} = $type;
3234 $ref_item{'refid'} = $id;
3237 if ($type eq "tag" || $type eq "commit") {
3238 $ref_item{'epoch'} = $epoch;
3239 if ($epoch) {
3240 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3241 } else {
3242 $ref_item{'age'} = "unknown";
3246 push @tagslist, \%ref_item;
3248 close $fd;
3250 return wantarray ? @tagslist : \@tagslist;
3253 ## ----------------------------------------------------------------------
3254 ## filesystem-related functions
3256 sub get_file_owner {
3257 my $path = shift;
3259 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3260 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3261 if (!defined $gcos) {
3262 return undef;
3264 my $owner = $gcos;
3265 $owner =~ s/[,;].*$//;
3266 return to_utf8($owner);
3269 # assume that file exists
3270 sub insert_file {
3271 my $filename = shift;
3273 open my $fd, '<', $filename;
3274 print map { to_utf8($_) } <$fd>;
3275 close $fd;
3278 ## ......................................................................
3279 ## mimetype related functions
3281 sub mimetype_guess_file {
3282 my $filename = shift;
3283 my $mimemap = shift;
3284 -r $mimemap or return undef;
3286 my %mimemap;
3287 open(my $mh, '<', $mimemap) or return undef;
3288 while (<$mh>) {
3289 next if m/^#/; # skip comments
3290 my ($mimetype, $exts) = split(/\t+/);
3291 if (defined $exts) {
3292 my @exts = split(/\s+/, $exts);
3293 foreach my $ext (@exts) {
3294 $mimemap{$ext} = $mimetype;
3298 close($mh);
3300 $filename =~ /\.([^.]*)$/;
3301 return $mimemap{$1};
3304 sub mimetype_guess {
3305 my $filename = shift;
3306 my $mime;
3307 $filename =~ /\./ or return undef;
3309 if ($mimetypes_file) {
3310 my $file = $mimetypes_file;
3311 if ($file !~ m!^/!) { # if it is relative path
3312 # it is relative to project
3313 $file = "$projectroot/$project/$file";
3315 $mime = mimetype_guess_file($filename, $file);
3317 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3318 return $mime;
3321 sub blob_mimetype {
3322 my $fd = shift;
3323 my $filename = shift;
3325 if ($filename) {
3326 my $mime = mimetype_guess($filename);
3327 $mime and return $mime;
3330 # just in case
3331 return $default_blob_plain_mimetype unless $fd;
3333 if (-T $fd) {
3334 return 'text/plain';
3335 } elsif (! $filename) {
3336 return 'application/octet-stream';
3337 } elsif ($filename =~ m/\.png$/i) {
3338 return 'image/png';
3339 } elsif ($filename =~ m/\.gif$/i) {
3340 return 'image/gif';
3341 } elsif ($filename =~ m/\.jpe?g$/i) {
3342 return 'image/jpeg';
3343 } else {
3344 return 'application/octet-stream';
3348 sub blob_contenttype {
3349 my ($fd, $file_name, $type) = @_;
3351 $type ||= blob_mimetype($fd, $file_name);
3352 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3353 $type .= "; charset=$default_text_plain_charset";
3356 return $type;
3359 # guess file syntax for syntax highlighting; return undef if no highlighting
3360 # the name of syntax can (in the future) depend on syntax highlighter used
3361 sub guess_file_syntax {
3362 my ($highlight, $mimetype, $file_name) = @_;
3363 return undef unless ($highlight && defined $file_name);
3364 my $basename = basename($file_name, '.in');
3365 return $highlight_basename{$basename}
3366 if exists $highlight_basename{$basename};
3368 $basename =~ /\.([^.]*)$/;
3369 my $ext = $1 or return undef;
3370 return $highlight_ext{$ext}
3371 if exists $highlight_ext{$ext};
3373 return undef;
3376 # run highlighter and return FD of its output,
3377 # or return original FD if no highlighting
3378 sub run_highlighter {
3379 my ($fd, $highlight, $syntax) = @_;
3380 return $fd unless ($highlight && defined $syntax);
3382 close $fd
3383 or die_error(404, "Reading blob failed");
3384 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3385 quote_command($highlight_bin).
3386 " --xhtml --fragment --syntax $syntax |"
3387 or die_error(500, "Couldn't open file or run syntax highlighter");
3388 return $fd;
3391 ## ======================================================================
3392 ## functions printing HTML: header, footer, error page
3394 sub get_page_title {
3395 my $title = to_utf8($site_name);
3397 return $title unless (defined $project);
3398 $title .= " - " . to_utf8($project);
3400 return $title unless (defined $action);
3401 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3403 return $title unless (defined $file_name);
3404 $title .= " - " . esc_path($file_name);
3405 if ($action eq "tree" && $file_name !~ m|/$|) {
3406 $title .= "/";
3409 return $title;
3412 sub git_header_html {
3413 my $status = shift || "200 OK";
3414 my $expires = shift;
3415 my %opts = @_;
3417 my $title = get_page_title();
3418 my $content_type;
3419 # require explicit support from the UA if we are to send the page as
3420 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3421 # we have to do this because MSIE sometimes globs '*/*', pretending to
3422 # support xhtml+xml but choking when it gets what it asked for.
3423 if (defined $cgi->http('HTTP_ACCEPT') &&
3424 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3425 $cgi->Accept('application/xhtml+xml') != 0) {
3426 $content_type = 'application/xhtml+xml';
3427 } else {
3428 $content_type = 'text/html';
3430 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3431 -status=> $status, -expires => $expires)
3432 unless ($opts{'-no_http_header'});
3433 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3434 print <<EOF;
3435 <?xml version="1.0" encoding="utf-8"?>
3436 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3437 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3438 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3439 <!-- git core binaries version $git_version -->
3440 <head>
3441 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3442 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3443 <meta name="robots" content="index, nofollow"/>
3444 <title>$title</title>
3446 # the stylesheet, favicon etc urls won't work correctly with path_info
3447 # unless we set the appropriate base URL
3448 if ($ENV{'PATH_INFO'}) {
3449 print "<base href=\"".esc_url($base_url)."\" />\n";
3451 # print out each stylesheet that exist, providing backwards capability
3452 # for those people who defined $stylesheet in a config file
3453 if (defined $stylesheet) {
3454 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3455 } else {
3456 foreach my $stylesheet (@stylesheets) {
3457 next unless $stylesheet;
3458 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3461 if (defined $project) {
3462 my %href_params = get_feed_info();
3463 if (!exists $href_params{'-title'}) {
3464 $href_params{'-title'} = 'log';
3467 foreach my $format qw(RSS Atom) {
3468 my $type = lc($format);
3469 my %link_attr = (
3470 '-rel' => 'alternate',
3471 '-title' => "$project - $href_params{'-title'} - $format feed",
3472 '-type' => "application/$type+xml"
3475 $href_params{'action'} = $type;
3476 $link_attr{'-href'} = href(%href_params);
3477 print "<link ".
3478 "rel=\"$link_attr{'-rel'}\" ".
3479 "title=\"$link_attr{'-title'}\" ".
3480 "href=\"$link_attr{'-href'}\" ".
3481 "type=\"$link_attr{'-type'}\" ".
3482 "/>\n";
3484 $href_params{'extra_options'} = '--no-merges';
3485 $link_attr{'-href'} = href(%href_params);
3486 $link_attr{'-title'} .= ' (no merges)';
3487 print "<link ".
3488 "rel=\"$link_attr{'-rel'}\" ".
3489 "title=\"$link_attr{'-title'}\" ".
3490 "href=\"$link_attr{'-href'}\" ".
3491 "type=\"$link_attr{'-type'}\" ".
3492 "/>\n";
3495 } else {
3496 printf('<link rel="alternate" title="%s projects list" '.
3497 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3498 $site_name, href(project=>undef, action=>"project_index"));
3499 printf('<link rel="alternate" title="%s projects feeds" '.
3500 'href="%s" type="text/x-opml" />'."\n",
3501 $site_name, href(project=>undef, action=>"opml"));
3503 if (defined $favicon) {
3504 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3507 print "</head>\n" .
3508 "<body>\n";
3510 if (defined $site_header && -f $site_header) {
3511 insert_file($site_header);
3514 print "<div class=\"page_header\">\n" .
3515 $cgi->a({-href => esc_url($logo_url),
3516 -title => $logo_label},
3517 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3518 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3519 if (defined $project) {
3520 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3521 if (defined $action) {
3522 print " / $action";
3524 print "\n";
3526 print "</div>\n";
3528 my $have_search = gitweb_check_feature('search');
3529 if (defined $project && $have_search) {
3530 if (!defined $searchtext) {
3531 $searchtext = "";
3533 my $search_hash;
3534 if (defined $hash_base) {
3535 $search_hash = $hash_base;
3536 } elsif (defined $hash) {
3537 $search_hash = $hash;
3538 } else {
3539 $search_hash = "HEAD";
3541 my $action = $my_uri;
3542 my $use_pathinfo = gitweb_check_feature('pathinfo');
3543 if ($use_pathinfo) {
3544 $action .= "/".esc_url($project);
3546 print $cgi->startform(-method => "get", -action => $action) .
3547 "<div class=\"search\">\n" .
3548 (!$use_pathinfo &&
3549 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3550 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3551 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3552 $cgi->popup_menu(-name => 'st', -default => 'commit',
3553 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3554 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3555 " search:\n",
3556 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3557 "<span title=\"Extended regular expression\">" .
3558 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3559 -checked => $search_use_regexp) .
3560 "</span>" .
3561 "</div>" .
3562 $cgi->end_form() . "\n";
3566 sub git_footer_html {
3567 my $feed_class = 'rss_logo';
3569 print "<div class=\"page_footer\">\n";
3570 if (defined $project) {
3571 my $descr = git_get_project_description($project);
3572 if (defined $descr) {
3573 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3576 my %href_params = get_feed_info();
3577 if (!%href_params) {
3578 $feed_class .= ' generic';
3580 $href_params{'-title'} ||= 'log';
3582 foreach my $format qw(RSS Atom) {
3583 $href_params{'action'} = lc($format);
3584 print $cgi->a({-href => href(%href_params),
3585 -title => "$href_params{'-title'} $format feed",
3586 -class => $feed_class}, $format)."\n";
3589 } else {
3590 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3591 -class => $feed_class}, "OPML") . " ";
3592 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3593 -class => $feed_class}, "TXT") . "\n";
3595 print "</div>\n"; # class="page_footer"
3597 if (defined $t0 && gitweb_check_feature('timed')) {
3598 print "<div id=\"generating_info\">\n";
3599 print 'This page took '.
3600 '<span id="generating_time" class="time_span">'.
3601 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3602 ' seconds </span>'.
3603 ' and '.
3604 '<span id="generating_cmd">'.
3605 $number_of_git_cmds.
3606 '</span> git commands '.
3607 " to generate.\n";
3608 print "</div>\n"; # class="page_footer"
3611 if (defined $site_footer && -f $site_footer) {
3612 insert_file($site_footer);
3615 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3616 if (defined $action &&
3617 $action eq 'blame_incremental') {
3618 print qq!<script type="text/javascript">\n!.
3619 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3620 qq! "!. href() .qq!");\n!.
3621 qq!</script>\n!;
3622 } elsif (gitweb_check_feature('javascript-actions')) {
3623 print qq!<script type="text/javascript">\n!.
3624 qq!window.onload = fixLinks;\n!.
3625 qq!</script>\n!;
3628 print "</body>\n" .
3629 "</html>";
3632 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3633 # Example: die_error(404, 'Hash not found')
3634 # By convention, use the following status codes (as defined in RFC 2616):
3635 # 400: Invalid or missing CGI parameters, or
3636 # requested object exists but has wrong type.
3637 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3638 # this server or project.
3639 # 404: Requested object/revision/project doesn't exist.
3640 # 500: The server isn't configured properly, or
3641 # an internal error occurred (e.g. failed assertions caused by bugs), or
3642 # an unknown error occurred (e.g. the git binary died unexpectedly).
3643 # 503: The server is currently unavailable (because it is overloaded,
3644 # or down for maintenance). Generally, this is a temporary state.
3645 sub die_error {
3646 my $status = shift || 500;
3647 my $error = esc_html(shift) || "Internal Server Error";
3648 my $extra = shift;
3649 my %opts = @_;
3651 my %http_responses = (
3652 400 => '400 Bad Request',
3653 403 => '403 Forbidden',
3654 404 => '404 Not Found',
3655 500 => '500 Internal Server Error',
3656 503 => '503 Service Unavailable',
3658 git_header_html($http_responses{$status}, undef, %opts);
3659 print <<EOF;
3660 <div class="page_body">
3661 <br /><br />
3662 $status - $error
3663 <br />
3665 if (defined $extra) {
3666 print "<hr />\n" .
3667 "$extra\n";
3669 print "</div>\n";
3671 git_footer_html();
3672 goto DONE_GITWEB
3673 unless ($opts{'-error_handler'});
3676 ## ----------------------------------------------------------------------
3677 ## functions printing or outputting HTML: navigation
3679 sub git_print_page_nav {
3680 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3681 $extra = '' if !defined $extra; # pager or formats
3683 my @navs = qw(summary shortlog log commit commitdiff tree);
3684 if ($suppress) {
3685 @navs = grep { $_ ne $suppress } @navs;
3688 my %arg = map { $_ => {action=>$_} } @navs;
3689 if (defined $head) {
3690 for (qw(commit commitdiff)) {
3691 $arg{$_}{'hash'} = $head;
3693 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3694 for (qw(shortlog log)) {
3695 $arg{$_}{'hash'} = $head;
3700 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3701 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3703 my @actions = gitweb_get_feature('actions');
3704 my %repl = (
3705 '%' => '%',
3706 'n' => $project, # project name
3707 'f' => $git_dir, # project path within filesystem
3708 'h' => $treehead || '', # current hash ('h' parameter)
3709 'b' => $treebase || '', # hash base ('hb' parameter)
3711 while (@actions) {
3712 my ($label, $link, $pos) = splice(@actions,0,3);
3713 # insert
3714 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3715 # munch munch
3716 $link =~ s/%([%nfhb])/$repl{$1}/g;
3717 $arg{$label}{'_href'} = $link;
3720 print "<div class=\"page_nav\">\n" .
3721 (join " | ",
3722 map { $_ eq $current ?
3723 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3724 } @navs);
3725 print "<br/>\n$extra<br/>\n" .
3726 "</div>\n";
3729 sub format_paging_nav {
3730 my ($action, $page, $has_next_link) = @_;
3731 my $paging_nav;
3734 if ($page > 0) {
3735 $paging_nav .=
3736 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3737 " &sdot; " .
3738 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3739 -accesskey => "p", -title => "Alt-p"}, "prev");
3740 } else {
3741 $paging_nav .= "first &sdot; prev";
3744 if ($has_next_link) {
3745 $paging_nav .= " &sdot; " .
3746 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3747 -accesskey => "n", -title => "Alt-n"}, "next");
3748 } else {
3749 $paging_nav .= " &sdot; next";
3752 return $paging_nav;
3755 ## ......................................................................
3756 ## functions printing or outputting HTML: div
3758 sub git_print_header_div {
3759 my ($action, $title, $hash, $hash_base) = @_;
3760 my %args = ();
3762 $args{'action'} = $action;
3763 $args{'hash'} = $hash if $hash;
3764 $args{'hash_base'} = $hash_base if $hash_base;
3766 print "<div class=\"header\">\n" .
3767 $cgi->a({-href => href(%args), -class => "title"},
3768 $title ? $title : $action) .
3769 "\n</div>\n";
3772 sub print_local_time {
3773 print format_local_time(@_);
3776 sub format_local_time {
3777 my $localtime = '';
3778 my %date = @_;
3779 if ($date{'hour_local'} < 6) {
3780 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3781 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3782 } else {
3783 $localtime .= sprintf(" (%02d:%02d %s)",
3784 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3787 return $localtime;
3790 # Outputs the author name and date in long form
3791 sub git_print_authorship {
3792 my $co = shift;
3793 my %opts = @_;
3794 my $tag = $opts{-tag} || 'div';
3795 my $author = $co->{'author_name'};
3797 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3798 print "<$tag class=\"author_date\">" .
3799 format_search_author($author, "author", esc_html($author)) .
3800 " [$ad{'rfc2822'}";
3801 print_local_time(%ad) if ($opts{-localtime});
3802 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3803 . "</$tag>\n";
3806 # Outputs table rows containing the full author or committer information,
3807 # in the format expected for 'commit' view (& similar).
3808 # Parameters are a commit hash reference, followed by the list of people
3809 # to output information for. If the list is empty it defaults to both
3810 # author and committer.
3811 sub git_print_authorship_rows {
3812 my $co = shift;
3813 # too bad we can't use @people = @_ || ('author', 'committer')
3814 my @people = @_;
3815 @people = ('author', 'committer') unless @people;
3816 foreach my $who (@people) {
3817 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3818 print "<tr><td>$who</td><td>" .
3819 format_search_author($co->{"${who}_name"}, $who,
3820 esc_html($co->{"${who}_name"})) . " " .
3821 format_search_author($co->{"${who}_email"}, $who,
3822 esc_html("<" . $co->{"${who}_email"} . ">")) .
3823 "</td><td rowspan=\"2\">" .
3824 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3825 "</td></tr>\n" .
3826 "<tr>" .
3827 "<td></td><td> $wd{'rfc2822'}";
3828 print_local_time(%wd);
3829 print "</td>" .
3830 "</tr>\n";
3834 sub git_print_page_path {
3835 my $name = shift;
3836 my $type = shift;
3837 my $hb = shift;
3840 print "<div class=\"page_path\">";
3841 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3842 -title => 'tree root'}, to_utf8("[$project]"));
3843 print " / ";
3844 if (defined $name) {
3845 my @dirname = split '/', $name;
3846 my $basename = pop @dirname;
3847 my $fullname = '';
3849 foreach my $dir (@dirname) {
3850 $fullname .= ($fullname ? '/' : '') . $dir;
3851 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3852 hash_base=>$hb),
3853 -title => $fullname}, esc_path($dir));
3854 print " / ";
3856 if (defined $type && $type eq 'blob') {
3857 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3858 hash_base=>$hb),
3859 -title => $name}, esc_path($basename));
3860 } elsif (defined $type && $type eq 'tree') {
3861 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3862 hash_base=>$hb),
3863 -title => $name}, esc_path($basename));
3864 print " / ";
3865 } else {
3866 print esc_path($basename);
3869 print "<br/></div>\n";
3872 sub git_print_log {
3873 my $log = shift;
3874 my %opts = @_;
3876 if ($opts{'-remove_title'}) {
3877 # remove title, i.e. first line of log
3878 shift @$log;
3880 # remove leading empty lines
3881 while (defined $log->[0] && $log->[0] eq "") {
3882 shift @$log;
3885 # print log
3886 my $signoff = 0;
3887 my $empty = 0;
3888 foreach my $line (@$log) {
3889 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3890 $signoff = 1;
3891 $empty = 0;
3892 if (! $opts{'-remove_signoff'}) {
3893 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3894 next;
3895 } else {
3896 # remove signoff lines
3897 next;
3899 } else {
3900 $signoff = 0;
3903 # print only one empty line
3904 # do not print empty line after signoff
3905 if ($line eq "") {
3906 next if ($empty || $signoff);
3907 $empty = 1;
3908 } else {
3909 $empty = 0;
3912 print format_log_line_html($line) . "<br/>\n";
3915 if ($opts{'-final_empty_line'}) {
3916 # end with single empty line
3917 print "<br/>\n" unless $empty;
3921 # return link target (what link points to)
3922 sub git_get_link_target {
3923 my $hash = shift;
3924 my $link_target;
3926 # read link
3927 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3928 or return;
3930 local $/ = undef;
3931 $link_target = <$fd>;
3933 close $fd
3934 or return;
3936 return $link_target;
3939 # given link target, and the directory (basedir) the link is in,
3940 # return target of link relative to top directory (top tree);
3941 # return undef if it is not possible (including absolute links).
3942 sub normalize_link_target {
3943 my ($link_target, $basedir) = @_;
3945 # absolute symlinks (beginning with '/') cannot be normalized
3946 return if (substr($link_target, 0, 1) eq '/');
3948 # normalize link target to path from top (root) tree (dir)
3949 my $path;
3950 if ($basedir) {
3951 $path = $basedir . '/' . $link_target;
3952 } else {
3953 # we are in top (root) tree (dir)
3954 $path = $link_target;
3957 # remove //, /./, and /../
3958 my @path_parts;
3959 foreach my $part (split('/', $path)) {
3960 # discard '.' and ''
3961 next if (!$part || $part eq '.');
3962 # handle '..'
3963 if ($part eq '..') {
3964 if (@path_parts) {
3965 pop @path_parts;
3966 } else {
3967 # link leads outside repository (outside top dir)
3968 return;
3970 } else {
3971 push @path_parts, $part;
3974 $path = join('/', @path_parts);
3976 return $path;
3979 # print tree entry (row of git_tree), but without encompassing <tr> element
3980 sub git_print_tree_entry {
3981 my ($t, $basedir, $hash_base, $have_blame) = @_;
3983 my %base_key = ();
3984 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3986 # The format of a table row is: mode list link. Where mode is
3987 # the mode of the entry, list is the name of the entry, an href,
3988 # and link is the action links of the entry.
3990 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3991 if (exists $t->{'size'}) {
3992 print "<td class=\"size\">$t->{'size'}</td>\n";
3994 if ($t->{'type'} eq "blob") {
3995 print "<td class=\"list\">" .
3996 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3997 file_name=>"$basedir$t->{'name'}", %base_key),
3998 -class => "list"}, esc_path($t->{'name'}));
3999 if (S_ISLNK(oct $t->{'mode'})) {
4000 my $link_target = git_get_link_target($t->{'hash'});
4001 if ($link_target) {
4002 my $norm_target = normalize_link_target($link_target, $basedir);
4003 if (defined $norm_target) {
4004 print " -> " .
4005 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4006 file_name=>$norm_target),
4007 -title => $norm_target}, esc_path($link_target));
4008 } else {
4009 print " -> " . esc_path($link_target);
4013 print "</td>\n";
4014 print "<td class=\"link\">";
4015 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4016 file_name=>"$basedir$t->{'name'}", %base_key)},
4017 "blob");
4018 if ($have_blame) {
4019 print " | " .
4020 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4021 file_name=>"$basedir$t->{'name'}", %base_key)},
4022 "blame");
4024 if (defined $hash_base) {
4025 print " | " .
4026 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4027 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4028 "history");
4030 print " | " .
4031 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4032 file_name=>"$basedir$t->{'name'}")},
4033 "raw");
4034 print "</td>\n";
4036 } elsif ($t->{'type'} eq "tree") {
4037 print "<td class=\"list\">";
4038 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4039 file_name=>"$basedir$t->{'name'}",
4040 %base_key)},
4041 esc_path($t->{'name'}));
4042 print "</td>\n";
4043 print "<td class=\"link\">";
4044 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4045 file_name=>"$basedir$t->{'name'}",
4046 %base_key)},
4047 "tree");
4048 if (defined $hash_base) {
4049 print " | " .
4050 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4051 file_name=>"$basedir$t->{'name'}")},
4052 "history");
4054 print "</td>\n";
4055 } else {
4056 # unknown object: we can only present history for it
4057 # (this includes 'commit' object, i.e. submodule support)
4058 print "<td class=\"list\">" .
4059 esc_path($t->{'name'}) .
4060 "</td>\n";
4061 print "<td class=\"link\">";
4062 if (defined $hash_base) {
4063 print $cgi->a({-href => href(action=>"history",
4064 hash_base=>$hash_base,
4065 file_name=>"$basedir$t->{'name'}")},
4066 "history");
4068 print "</td>\n";
4072 ## ......................................................................
4073 ## functions printing large fragments of HTML
4075 # get pre-image filenames for merge (combined) diff
4076 sub fill_from_file_info {
4077 my ($diff, @parents) = @_;
4079 $diff->{'from_file'} = [ ];
4080 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4081 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4082 if ($diff->{'status'}[$i] eq 'R' ||
4083 $diff->{'status'}[$i] eq 'C') {
4084 $diff->{'from_file'}[$i] =
4085 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4089 return $diff;
4092 # is current raw difftree line of file deletion
4093 sub is_deleted {
4094 my $diffinfo = shift;
4096 return $diffinfo->{'to_id'} eq ('0' x 40);
4099 # does patch correspond to [previous] difftree raw line
4100 # $diffinfo - hashref of parsed raw diff format
4101 # $patchinfo - hashref of parsed patch diff format
4102 # (the same keys as in $diffinfo)
4103 sub is_patch_split {
4104 my ($diffinfo, $patchinfo) = @_;
4106 return defined $diffinfo && defined $patchinfo
4107 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4111 sub git_difftree_body {
4112 my ($difftree, $hash, @parents) = @_;
4113 my ($parent) = $parents[0];
4114 my $have_blame = gitweb_check_feature('blame');
4115 print "<div class=\"list_head\">\n";
4116 if ($#{$difftree} > 10) {
4117 print(($#{$difftree} + 1) . " files changed:\n");
4119 print "</div>\n";
4121 print "<table class=\"" .
4122 (@parents > 1 ? "combined " : "") .
4123 "diff_tree\">\n";
4125 # header only for combined diff in 'commitdiff' view
4126 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4127 if ($has_header) {
4128 # table header
4129 print "<thead><tr>\n" .
4130 "<th></th><th></th>\n"; # filename, patchN link
4131 for (my $i = 0; $i < @parents; $i++) {
4132 my $par = $parents[$i];
4133 print "<th>" .
4134 $cgi->a({-href => href(action=>"commitdiff",
4135 hash=>$hash, hash_parent=>$par),
4136 -title => 'commitdiff to parent number ' .
4137 ($i+1) . ': ' . substr($par,0,7)},
4138 $i+1) .
4139 "&nbsp;</th>\n";
4141 print "</tr></thead>\n<tbody>\n";
4144 my $alternate = 1;
4145 my $patchno = 0;
4146 foreach my $line (@{$difftree}) {
4147 my $diff = parsed_difftree_line($line);
4149 if ($alternate) {
4150 print "<tr class=\"dark\">\n";
4151 } else {
4152 print "<tr class=\"light\">\n";
4154 $alternate ^= 1;
4156 if (exists $diff->{'nparents'}) { # combined diff
4158 fill_from_file_info($diff, @parents)
4159 unless exists $diff->{'from_file'};
4161 if (!is_deleted($diff)) {
4162 # file exists in the result (child) commit
4163 print "<td>" .
4164 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4165 file_name=>$diff->{'to_file'},
4166 hash_base=>$hash),
4167 -class => "list"}, esc_path($diff->{'to_file'})) .
4168 "</td>\n";
4169 } else {
4170 print "<td>" .
4171 esc_path($diff->{'to_file'}) .
4172 "</td>\n";
4175 if ($action eq 'commitdiff') {
4176 # link to patch
4177 $patchno++;
4178 print "<td class=\"link\">" .
4179 $cgi->a({-href => "#patch$patchno"}, "patch") .
4180 " | " .
4181 "</td>\n";
4184 my $has_history = 0;
4185 my $not_deleted = 0;
4186 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4187 my $hash_parent = $parents[$i];
4188 my $from_hash = $diff->{'from_id'}[$i];
4189 my $from_path = $diff->{'from_file'}[$i];
4190 my $status = $diff->{'status'}[$i];
4192 $has_history ||= ($status ne 'A');
4193 $not_deleted ||= ($status ne 'D');
4195 if ($status eq 'A') {
4196 print "<td class=\"link\" align=\"right\"> | </td>\n";
4197 } elsif ($status eq 'D') {
4198 print "<td class=\"link\">" .
4199 $cgi->a({-href => href(action=>"blob",
4200 hash_base=>$hash,
4201 hash=>$from_hash,
4202 file_name=>$from_path)},
4203 "blob" . ($i+1)) .
4204 " | </td>\n";
4205 } else {
4206 if ($diff->{'to_id'} eq $from_hash) {
4207 print "<td class=\"link nochange\">";
4208 } else {
4209 print "<td class=\"link\">";
4211 print $cgi->a({-href => href(action=>"blobdiff",
4212 hash=>$diff->{'to_id'},
4213 hash_parent=>$from_hash,
4214 hash_base=>$hash,
4215 hash_parent_base=>$hash_parent,
4216 file_name=>$diff->{'to_file'},
4217 file_parent=>$from_path)},
4218 "diff" . ($i+1)) .
4219 " | </td>\n";
4223 print "<td class=\"link\">";
4224 if ($not_deleted) {
4225 print $cgi->a({-href => href(action=>"blob",
4226 hash=>$diff->{'to_id'},
4227 file_name=>$diff->{'to_file'},
4228 hash_base=>$hash)},
4229 "blob");
4230 print " | " if ($has_history);
4232 if ($has_history) {
4233 print $cgi->a({-href => href(action=>"history",
4234 file_name=>$diff->{'to_file'},
4235 hash_base=>$hash)},
4236 "history");
4238 print "</td>\n";
4240 print "</tr>\n";
4241 next; # instead of 'else' clause, to avoid extra indent
4243 # else ordinary diff
4245 my ($to_mode_oct, $to_mode_str, $to_file_type);
4246 my ($from_mode_oct, $from_mode_str, $from_file_type);
4247 if ($diff->{'to_mode'} ne ('0' x 6)) {
4248 $to_mode_oct = oct $diff->{'to_mode'};
4249 if (S_ISREG($to_mode_oct)) { # only for regular file
4250 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4252 $to_file_type = file_type($diff->{'to_mode'});
4254 if ($diff->{'from_mode'} ne ('0' x 6)) {
4255 $from_mode_oct = oct $diff->{'from_mode'};
4256 if (S_ISREG($to_mode_oct)) { # only for regular file
4257 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4259 $from_file_type = file_type($diff->{'from_mode'});
4262 if ($diff->{'status'} eq "A") { # created
4263 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4264 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4265 $mode_chng .= "]</span>";
4266 print "<td>";
4267 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4268 hash_base=>$hash, file_name=>$diff->{'file'}),
4269 -class => "list"}, esc_path($diff->{'file'}));
4270 print "</td>\n";
4271 print "<td>$mode_chng</td>\n";
4272 print "<td class=\"link\">";
4273 if ($action eq 'commitdiff') {
4274 # link to patch
4275 $patchno++;
4276 print $cgi->a({-href => "#patch$patchno"}, "patch");
4277 print " | ";
4279 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4280 hash_base=>$hash, file_name=>$diff->{'file'})},
4281 "blob");
4282 print "</td>\n";
4284 } elsif ($diff->{'status'} eq "D") { # deleted
4285 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4286 print "<td>";
4287 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4288 hash_base=>$parent, file_name=>$diff->{'file'}),
4289 -class => "list"}, esc_path($diff->{'file'}));
4290 print "</td>\n";
4291 print "<td>$mode_chng</td>\n";
4292 print "<td class=\"link\">";
4293 if ($action eq 'commitdiff') {
4294 # link to patch
4295 $patchno++;
4296 print $cgi->a({-href => "#patch$patchno"}, "patch");
4297 print " | ";
4299 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4300 hash_base=>$parent, file_name=>$diff->{'file'})},
4301 "blob") . " | ";
4302 if ($have_blame) {
4303 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4304 file_name=>$diff->{'file'})},
4305 "blame") . " | ";
4307 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4308 file_name=>$diff->{'file'})},
4309 "history");
4310 print "</td>\n";
4312 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4313 my $mode_chnge = "";
4314 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4315 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4316 if ($from_file_type ne $to_file_type) {
4317 $mode_chnge .= " from $from_file_type to $to_file_type";
4319 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4320 if ($from_mode_str && $to_mode_str) {
4321 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4322 } elsif ($to_mode_str) {
4323 $mode_chnge .= " mode: $to_mode_str";
4326 $mode_chnge .= "]</span>\n";
4328 print "<td>";
4329 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4330 hash_base=>$hash, file_name=>$diff->{'file'}),
4331 -class => "list"}, esc_path($diff->{'file'}));
4332 print "</td>\n";
4333 print "<td>$mode_chnge</td>\n";
4334 print "<td class=\"link\">";
4335 if ($action eq 'commitdiff') {
4336 # link to patch
4337 $patchno++;
4338 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4339 " | ";
4340 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4341 # "commit" view and modified file (not onlu mode changed)
4342 print $cgi->a({-href => href(action=>"blobdiff",
4343 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4344 hash_base=>$hash, hash_parent_base=>$parent,
4345 file_name=>$diff->{'file'})},
4346 "diff") .
4347 " | ";
4349 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4350 hash_base=>$hash, file_name=>$diff->{'file'})},
4351 "blob") . " | ";
4352 if ($have_blame) {
4353 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4354 file_name=>$diff->{'file'})},
4355 "blame") . " | ";
4357 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4358 file_name=>$diff->{'file'})},
4359 "history");
4360 print "</td>\n";
4362 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4363 my %status_name = ('R' => 'moved', 'C' => 'copied');
4364 my $nstatus = $status_name{$diff->{'status'}};
4365 my $mode_chng = "";
4366 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4367 # mode also for directories, so we cannot use $to_mode_str
4368 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4370 print "<td>" .
4371 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4372 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4373 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4374 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4375 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4376 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4377 -class => "list"}, esc_path($diff->{'from_file'})) .
4378 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4379 "<td class=\"link\">";
4380 if ($action eq 'commitdiff') {
4381 # link to patch
4382 $patchno++;
4383 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4384 " | ";
4385 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4386 # "commit" view and modified file (not only pure rename or copy)
4387 print $cgi->a({-href => href(action=>"blobdiff",
4388 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4389 hash_base=>$hash, hash_parent_base=>$parent,
4390 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4391 "diff") .
4392 " | ";
4394 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4395 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4396 "blob") . " | ";
4397 if ($have_blame) {
4398 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4399 file_name=>$diff->{'to_file'})},
4400 "blame") . " | ";
4402 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4403 file_name=>$diff->{'to_file'})},
4404 "history");
4405 print "</td>\n";
4407 } # we should not encounter Unmerged (U) or Unknown (X) status
4408 print "</tr>\n";
4410 print "</tbody>" if $has_header;
4411 print "</table>\n";
4414 sub git_patchset_body {
4415 my ($fd, $difftree, $hash, @hash_parents) = @_;
4416 my ($hash_parent) = $hash_parents[0];
4418 my $is_combined = (@hash_parents > 1);
4419 my $patch_idx = 0;
4420 my $patch_number = 0;
4421 my $patch_line;
4422 my $diffinfo;
4423 my $to_name;
4424 my (%from, %to);
4426 print "<div class=\"patchset\">\n";
4428 # skip to first patch
4429 while ($patch_line = <$fd>) {
4430 chomp $patch_line;
4432 last if ($patch_line =~ m/^diff /);
4435 PATCH:
4436 while ($patch_line) {
4438 # parse "git diff" header line
4439 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4440 # $1 is from_name, which we do not use
4441 $to_name = unquote($2);
4442 $to_name =~ s!^b/!!;
4443 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4444 # $1 is 'cc' or 'combined', which we do not use
4445 $to_name = unquote($2);
4446 } else {
4447 $to_name = undef;
4450 # check if current patch belong to current raw line
4451 # and parse raw git-diff line if needed
4452 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4453 # this is continuation of a split patch
4454 print "<div class=\"patch cont\">\n";
4455 } else {
4456 # advance raw git-diff output if needed
4457 $patch_idx++ if defined $diffinfo;
4459 # read and prepare patch information
4460 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4462 # compact combined diff output can have some patches skipped
4463 # find which patch (using pathname of result) we are at now;
4464 if ($is_combined) {
4465 while ($to_name ne $diffinfo->{'to_file'}) {
4466 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4467 format_diff_cc_simplified($diffinfo, @hash_parents) .
4468 "</div>\n"; # class="patch"
4470 $patch_idx++;
4471 $patch_number++;
4473 last if $patch_idx > $#$difftree;
4474 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4478 # modifies %from, %to hashes
4479 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4481 # this is first patch for raw difftree line with $patch_idx index
4482 # we index @$difftree array from 0, but number patches from 1
4483 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4486 # git diff header
4487 #assert($patch_line =~ m/^diff /) if DEBUG;
4488 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4489 $patch_number++;
4490 # print "git diff" header
4491 print format_git_diff_header_line($patch_line, $diffinfo,
4492 \%from, \%to);
4494 # print extended diff header
4495 print "<div class=\"diff extended_header\">\n";
4496 EXTENDED_HEADER:
4497 while ($patch_line = <$fd>) {
4498 chomp $patch_line;
4500 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4502 print format_extended_diff_header_line($patch_line, $diffinfo,
4503 \%from, \%to);
4505 print "</div>\n"; # class="diff extended_header"
4507 # from-file/to-file diff header
4508 if (! $patch_line) {
4509 print "</div>\n"; # class="patch"
4510 last PATCH;
4512 next PATCH if ($patch_line =~ m/^diff /);
4513 #assert($patch_line =~ m/^---/) if DEBUG;
4515 my $last_patch_line = $patch_line;
4516 $patch_line = <$fd>;
4517 chomp $patch_line;
4518 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4520 print format_diff_from_to_header($last_patch_line, $patch_line,
4521 $diffinfo, \%from, \%to,
4522 @hash_parents);
4524 # the patch itself
4525 LINE:
4526 while ($patch_line = <$fd>) {
4527 chomp $patch_line;
4529 next PATCH if ($patch_line =~ m/^diff /);
4531 print format_diff_line($patch_line, \%from, \%to);
4534 } continue {
4535 print "</div>\n"; # class="patch"
4538 # for compact combined (--cc) format, with chunk and patch simplification
4539 # the patchset might be empty, but there might be unprocessed raw lines
4540 for (++$patch_idx if $patch_number > 0;
4541 $patch_idx < @$difftree;
4542 ++$patch_idx) {
4543 # read and prepare patch information
4544 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4546 # generate anchor for "patch" links in difftree / whatchanged part
4547 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4548 format_diff_cc_simplified($diffinfo, @hash_parents) .
4549 "</div>\n"; # class="patch"
4551 $patch_number++;
4554 if ($patch_number == 0) {
4555 if (@hash_parents > 1) {
4556 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4557 } else {
4558 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4562 print "</div>\n"; # class="patchset"
4565 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4567 # fills project list info (age, description, owner, forks) for each
4568 # project in the list, removing invalid projects from returned list
4569 # NOTE: modifies $projlist, but does not remove entries from it
4570 sub fill_project_list_info {
4571 my ($projlist, $check_forks) = @_;
4572 my @projects;
4574 my $show_ctags = gitweb_check_feature('ctags');
4575 PROJECT:
4576 foreach my $pr (@$projlist) {
4577 my (@activity) = git_get_last_activity($pr->{'path'});
4578 unless (@activity) {
4579 next PROJECT;
4581 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4582 if (!defined $pr->{'descr'}) {
4583 my $descr = git_get_project_description($pr->{'path'}) || "";
4584 $descr = to_utf8($descr);
4585 $pr->{'descr_long'} = $descr;
4586 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4588 if (!defined $pr->{'owner'}) {
4589 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4591 if ($check_forks) {
4592 my $pname = $pr->{'path'};
4593 if (($pname =~ s/\.git$//) &&
4594 ($pname !~ /\/$/) &&
4595 (-d "$projectroot/$pname")) {
4596 $pr->{'forks'} = "-d $projectroot/$pname";
4597 } else {
4598 $pr->{'forks'} = 0;
4601 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4602 push @projects, $pr;
4605 return @projects;
4608 # print 'sort by' <th> element, generating 'sort by $name' replay link
4609 # if that order is not selected
4610 sub print_sort_th {
4611 print format_sort_th(@_);
4614 sub format_sort_th {
4615 my ($name, $order, $header) = @_;
4616 my $sort_th = "";
4617 $header ||= ucfirst($name);
4619 if ($order eq $name) {
4620 $sort_th .= "<th>$header</th>\n";
4621 } else {
4622 $sort_th .= "<th>" .
4623 $cgi->a({-href => href(-replay=>1, order=>$name),
4624 -class => "header"}, $header) .
4625 "</th>\n";
4628 return $sort_th;
4631 sub git_project_list_body {
4632 # actually uses global variable $project
4633 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4635 my $check_forks = gitweb_check_feature('forks');
4636 my @projects = fill_project_list_info($projlist, $check_forks);
4638 $order ||= $default_projects_order;
4639 $from = 0 unless defined $from;
4640 $to = $#projects if (!defined $to || $#projects < $to);
4642 my %order_info = (
4643 project => { key => 'path', type => 'str' },
4644 descr => { key => 'descr_long', type => 'str' },
4645 owner => { key => 'owner', type => 'str' },
4646 age => { key => 'age', type => 'num' }
4648 my $oi = $order_info{$order};
4649 if ($oi->{'type'} eq 'str') {
4650 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4651 } else {
4652 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4655 my $show_ctags = gitweb_check_feature('ctags');
4656 if ($show_ctags) {
4657 my %ctags;
4658 foreach my $p (@projects) {
4659 foreach my $ct (keys %{$p->{'ctags'}}) {
4660 $ctags{$ct} += $p->{'ctags'}->{$ct};
4663 my $cloud = git_populate_project_tagcloud(\%ctags);
4664 print git_show_project_tagcloud($cloud, 64);
4667 print "<table class=\"project_list\">\n";
4668 unless ($no_header) {
4669 print "<tr>\n";
4670 if ($check_forks) {
4671 print "<th></th>\n";
4673 print_sort_th('project', $order, 'Project');
4674 print_sort_th('descr', $order, 'Description');
4675 print_sort_th('owner', $order, 'Owner');
4676 print_sort_th('age', $order, 'Last Change');
4677 print "<th></th>\n" . # for links
4678 "</tr>\n";
4680 my $alternate = 1;
4681 my $tagfilter = $cgi->param('by_tag');
4682 for (my $i = $from; $i <= $to; $i++) {
4683 my $pr = $projects[$i];
4685 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4686 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4687 and not $pr->{'descr_long'} =~ /$searchtext/;
4688 # Weed out forks or non-matching entries of search
4689 if ($check_forks) {
4690 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4691 $forkbase="^$forkbase" if $forkbase;
4692 next if not $searchtext and not $tagfilter and $show_ctags
4693 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4696 if ($alternate) {
4697 print "<tr class=\"dark\">\n";
4698 } else {
4699 print "<tr class=\"light\">\n";
4701 $alternate ^= 1;
4702 if ($check_forks) {
4703 print "<td>";
4704 if ($pr->{'forks'}) {
4705 print "<!-- $pr->{'forks'} -->\n";
4706 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4708 print "</td>\n";
4710 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4711 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4712 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4713 -class => "list", -title => $pr->{'descr_long'}},
4714 esc_html($pr->{'descr'})) . "</td>\n" .
4715 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4716 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4717 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4718 "<td class=\"link\">" .
4719 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4720 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4721 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4722 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4723 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4724 "</td>\n" .
4725 "</tr>\n";
4727 if (defined $extra) {
4728 print "<tr>\n";
4729 if ($check_forks) {
4730 print "<td></td>\n";
4732 print "<td colspan=\"5\">$extra</td>\n" .
4733 "</tr>\n";
4735 print "</table>\n";
4738 sub git_log_body {
4739 # uses global variable $project
4740 my ($commitlist, $from, $to, $refs, $extra) = @_;
4742 $from = 0 unless defined $from;
4743 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4745 for (my $i = 0; $i <= $to; $i++) {
4746 my %co = %{$commitlist->[$i]};
4747 next if !%co;
4748 my $commit = $co{'id'};
4749 my $ref = format_ref_marker($refs, $commit);
4750 my %ad = parse_date($co{'author_epoch'});
4751 git_print_header_div('commit',
4752 "<span class=\"age\">$co{'age_string'}</span>" .
4753 esc_html($co{'title'}) . $ref,
4754 $commit);
4755 print "<div class=\"title_text\">\n" .
4756 "<div class=\"log_link\">\n" .
4757 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4758 " | " .
4759 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4760 " | " .
4761 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4762 "<br/>\n" .
4763 "</div>\n";
4764 git_print_authorship(\%co, -tag => 'span');
4765 print "<br/>\n</div>\n";
4767 print "<div class=\"log_body\">\n";
4768 git_print_log($co{'comment'}, -final_empty_line=> 1);
4769 print "</div>\n";
4771 if ($extra) {
4772 print "<div class=\"page_nav\">\n";
4773 print "$extra\n";
4774 print "</div>\n";
4778 sub git_shortlog_body {
4779 # uses global variable $project
4780 my ($commitlist, $from, $to, $refs, $extra) = @_;
4782 $from = 0 unless defined $from;
4783 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4785 print "<table class=\"shortlog\">\n";
4786 my $alternate = 1;
4787 for (my $i = $from; $i <= $to; $i++) {
4788 my %co = %{$commitlist->[$i]};
4789 my $commit = $co{'id'};
4790 my $ref = format_ref_marker($refs, $commit);
4791 if ($alternate) {
4792 print "<tr class=\"dark\">\n";
4793 } else {
4794 print "<tr class=\"light\">\n";
4796 $alternate ^= 1;
4797 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4798 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4799 format_author_html('td', \%co, 10) . "<td>";
4800 print format_subject_html($co{'title'}, $co{'title_short'},
4801 href(action=>"commit", hash=>$commit), $ref);
4802 print "</td>\n" .
4803 "<td class=\"link\">" .
4804 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4805 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4806 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4807 my $snapshot_links = format_snapshot_links($commit);
4808 if (defined $snapshot_links) {
4809 print " | " . $snapshot_links;
4811 print "</td>\n" .
4812 "</tr>\n";
4814 if (defined $extra) {
4815 print "<tr>\n" .
4816 "<td colspan=\"4\">$extra</td>\n" .
4817 "</tr>\n";
4819 print "</table>\n";
4822 sub git_history_body {
4823 # Warning: assumes constant type (blob or tree) during history
4824 my ($commitlist, $from, $to, $refs, $extra,
4825 $file_name, $file_hash, $ftype) = @_;
4827 $from = 0 unless defined $from;
4828 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4830 print "<table class=\"history\">\n";
4831 my $alternate = 1;
4832 for (my $i = $from; $i <= $to; $i++) {
4833 my %co = %{$commitlist->[$i]};
4834 if (!%co) {
4835 next;
4837 my $commit = $co{'id'};
4839 my $ref = format_ref_marker($refs, $commit);
4841 if ($alternate) {
4842 print "<tr class=\"dark\">\n";
4843 } else {
4844 print "<tr class=\"light\">\n";
4846 $alternate ^= 1;
4847 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4848 # shortlog: format_author_html('td', \%co, 10)
4849 format_author_html('td', \%co, 15, 3) . "<td>";
4850 # originally git_history used chop_str($co{'title'}, 50)
4851 print format_subject_html($co{'title'}, $co{'title_short'},
4852 href(action=>"commit", hash=>$commit), $ref);
4853 print "</td>\n" .
4854 "<td class=\"link\">" .
4855 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4856 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4858 if ($ftype eq 'blob') {
4859 my $blob_current = $file_hash;
4860 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4861 if (defined $blob_current && defined $blob_parent &&
4862 $blob_current ne $blob_parent) {
4863 print " | " .
4864 $cgi->a({-href => href(action=>"blobdiff",
4865 hash=>$blob_current, hash_parent=>$blob_parent,
4866 hash_base=>$hash_base, hash_parent_base=>$commit,
4867 file_name=>$file_name)},
4868 "diff to current");
4871 print "</td>\n" .
4872 "</tr>\n";
4874 if (defined $extra) {
4875 print "<tr>\n" .
4876 "<td colspan=\"4\">$extra</td>\n" .
4877 "</tr>\n";
4879 print "</table>\n";
4882 sub git_tags_body {
4883 # uses global variable $project
4884 my ($taglist, $from, $to, $extra) = @_;
4885 $from = 0 unless defined $from;
4886 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4888 print "<table class=\"tags\">\n";
4889 my $alternate = 1;
4890 for (my $i = $from; $i <= $to; $i++) {
4891 my $entry = $taglist->[$i];
4892 my %tag = %$entry;
4893 my $comment = $tag{'subject'};
4894 my $comment_short;
4895 if (defined $comment) {
4896 $comment_short = chop_str($comment, 30, 5);
4898 if ($alternate) {
4899 print "<tr class=\"dark\">\n";
4900 } else {
4901 print "<tr class=\"light\">\n";
4903 $alternate ^= 1;
4904 if (defined $tag{'age'}) {
4905 print "<td><i>$tag{'age'}</i></td>\n";
4906 } else {
4907 print "<td></td>\n";
4909 print "<td>" .
4910 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4911 -class => "list name"}, esc_html($tag{'name'})) .
4912 "</td>\n" .
4913 "<td>";
4914 if (defined $comment) {
4915 print format_subject_html($comment, $comment_short,
4916 href(action=>"tag", hash=>$tag{'id'}));
4918 print "</td>\n" .
4919 "<td class=\"selflink\">";
4920 if ($tag{'type'} eq "tag") {
4921 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4922 } else {
4923 print "&nbsp;";
4925 print "</td>\n" .
4926 "<td class=\"link\">" . " | " .
4927 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4928 if ($tag{'reftype'} eq "commit") {
4929 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4930 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4931 } elsif ($tag{'reftype'} eq "blob") {
4932 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4934 print "</td>\n" .
4935 "</tr>";
4937 if (defined $extra) {
4938 print "<tr>\n" .
4939 "<td colspan=\"5\">$extra</td>\n" .
4940 "</tr>\n";
4942 print "</table>\n";
4945 sub git_heads_body {
4946 # uses global variable $project
4947 my ($headlist, $head, $from, $to, $extra) = @_;
4948 $from = 0 unless defined $from;
4949 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4951 print "<table class=\"heads\">\n";
4952 my $alternate = 1;
4953 for (my $i = $from; $i <= $to; $i++) {
4954 my $entry = $headlist->[$i];
4955 my %ref = %$entry;
4956 my $curr = $ref{'id'} eq $head;
4957 if ($alternate) {
4958 print "<tr class=\"dark\">\n";
4959 } else {
4960 print "<tr class=\"light\">\n";
4962 $alternate ^= 1;
4963 print "<td><i>$ref{'age'}</i></td>\n" .
4964 ($curr ? "<td class=\"current_head\">" : "<td>") .
4965 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4966 -class => "list name"},esc_html($ref{'name'})) .
4967 "</td>\n" .
4968 "<td class=\"link\">" .
4969 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4970 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4971 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4972 "</td>\n" .
4973 "</tr>";
4975 if (defined $extra) {
4976 print "<tr>\n" .
4977 "<td colspan=\"3\">$extra</td>\n" .
4978 "</tr>\n";
4980 print "</table>\n";
4983 sub git_search_grep_body {
4984 my ($commitlist, $from, $to, $extra) = @_;
4985 $from = 0 unless defined $from;
4986 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4988 print "<table class=\"commit_search\">\n";
4989 my $alternate = 1;
4990 for (my $i = $from; $i <= $to; $i++) {
4991 my %co = %{$commitlist->[$i]};
4992 if (!%co) {
4993 next;
4995 my $commit = $co{'id'};
4996 if ($alternate) {
4997 print "<tr class=\"dark\">\n";
4998 } else {
4999 print "<tr class=\"light\">\n";
5001 $alternate ^= 1;
5002 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5003 format_author_html('td', \%co, 15, 5) .
5004 "<td>" .
5005 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5006 -class => "list subject"},
5007 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5008 my $comment = $co{'comment'};
5009 foreach my $line (@$comment) {
5010 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5011 my ($lead, $match, $trail) = ($1, $2, $3);
5012 $match = chop_str($match, 70, 5, 'center');
5013 my $contextlen = int((80 - length($match))/2);
5014 $contextlen = 30 if ($contextlen > 30);
5015 $lead = chop_str($lead, $contextlen, 10, 'left');
5016 $trail = chop_str($trail, $contextlen, 10, 'right');
5018 $lead = esc_html($lead);
5019 $match = esc_html($match);
5020 $trail = esc_html($trail);
5022 print "$lead<span class=\"match\">$match</span>$trail<br />";
5025 print "</td>\n" .
5026 "<td class=\"link\">" .
5027 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5028 " | " .
5029 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5030 " | " .
5031 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5032 print "</td>\n" .
5033 "</tr>\n";
5035 if (defined $extra) {
5036 print "<tr>\n" .
5037 "<td colspan=\"3\">$extra</td>\n" .
5038 "</tr>\n";
5040 print "</table>\n";
5043 ## ======================================================================
5044 ## ======================================================================
5045 ## actions
5047 sub git_project_list {
5048 my $order = $input_params{'order'};
5049 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5050 die_error(400, "Unknown order parameter");
5053 my @list = git_get_projects_list();
5054 if (!@list) {
5055 die_error(404, "No projects found");
5058 git_header_html();
5059 if (defined $home_text && -f $home_text) {
5060 print "<div class=\"index_include\">\n";
5061 insert_file($home_text);
5062 print "</div>\n";
5064 print $cgi->startform(-method => "get") .
5065 "<p class=\"projsearch\">Search:\n" .
5066 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5067 "</p>" .
5068 $cgi->end_form() . "\n";
5069 git_project_list_body(\@list, $order);
5070 git_footer_html();
5073 sub git_forks {
5074 my $order = $input_params{'order'};
5075 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5076 die_error(400, "Unknown order parameter");
5079 my @list = git_get_projects_list($project);
5080 if (!@list) {
5081 die_error(404, "No forks found");
5084 git_header_html();
5085 git_print_page_nav('','');
5086 git_print_header_div('summary', "$project forks");
5087 git_project_list_body(\@list, $order);
5088 git_footer_html();
5091 sub git_project_index {
5092 my @projects = git_get_projects_list($project);
5094 print $cgi->header(
5095 -type => 'text/plain',
5096 -charset => 'utf-8',
5097 -content_disposition => 'inline; filename="index.aux"');
5099 foreach my $pr (@projects) {
5100 if (!exists $pr->{'owner'}) {
5101 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5104 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5105 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5106 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5107 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5108 $path =~ s/ /\+/g;
5109 $owner =~ s/ /\+/g;
5111 print "$path $owner\n";
5115 sub git_summary {
5116 my $descr = git_get_project_description($project) || "none";
5117 my %co = parse_commit("HEAD");
5118 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5119 my $head = $co{'id'};
5121 my $owner = git_get_project_owner($project);
5123 my $refs = git_get_references();
5124 # These get_*_list functions return one more to allow us to see if
5125 # there are more ...
5126 my @taglist = git_get_tags_list(16);
5127 my @headlist = git_get_heads_list(16);
5128 my @forklist;
5129 my $check_forks = gitweb_check_feature('forks');
5131 if ($check_forks) {
5132 @forklist = git_get_projects_list($project);
5135 git_header_html();
5136 git_print_page_nav('summary','', $head);
5138 print "<div class=\"title\">&nbsp;</div>\n";
5139 print "<table class=\"projects_list\">\n" .
5140 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5141 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5142 if (defined $cd{'rfc2822'}) {
5143 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5146 # use per project git URL list in $projectroot/$project/cloneurl
5147 # or make project git URL from git base URL and project name
5148 my $url_tag = "URL";
5149 my @url_list = git_get_project_url_list($project);
5150 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5151 foreach my $git_url (@url_list) {
5152 next unless $git_url;
5153 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5154 $url_tag = "";
5157 # Tag cloud
5158 my $show_ctags = gitweb_check_feature('ctags');
5159 if ($show_ctags) {
5160 my $ctags = git_get_project_ctags($project);
5161 my $cloud = git_populate_project_tagcloud($ctags);
5162 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5163 print "</td>\n<td>" unless %$ctags;
5164 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5165 print "</td>\n<td>" if %$ctags;
5166 print git_show_project_tagcloud($cloud, 48);
5167 print "</td></tr>";
5170 print "</table>\n";
5172 # If XSS prevention is on, we don't include README.html.
5173 # TODO: Allow a readme in some safe format.
5174 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5175 print "<div class=\"title\">readme</div>\n" .
5176 "<div class=\"readme\">\n";
5177 insert_file("$projectroot/$project/README.html");
5178 print "\n</div>\n"; # class="readme"
5181 # we need to request one more than 16 (0..15) to check if
5182 # those 16 are all
5183 my @commitlist = $head ? parse_commits($head, 17) : ();
5184 if (@commitlist) {
5185 git_print_header_div('shortlog');
5186 git_shortlog_body(\@commitlist, 0, 15, $refs,
5187 $#commitlist <= 15 ? undef :
5188 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5191 if (@taglist) {
5192 git_print_header_div('tags');
5193 git_tags_body(\@taglist, 0, 15,
5194 $#taglist <= 15 ? undef :
5195 $cgi->a({-href => href(action=>"tags")}, "..."));
5198 if (@headlist) {
5199 git_print_header_div('heads');
5200 git_heads_body(\@headlist, $head, 0, 15,
5201 $#headlist <= 15 ? undef :
5202 $cgi->a({-href => href(action=>"heads")}, "..."));
5205 if (@forklist) {
5206 git_print_header_div('forks');
5207 git_project_list_body(\@forklist, 'age', 0, 15,
5208 $#forklist <= 15 ? undef :
5209 $cgi->a({-href => href(action=>"forks")}, "..."),
5210 'no_header');
5213 git_footer_html();
5216 sub git_tag {
5217 my %tag = parse_tag($hash);
5219 if (! %tag) {
5220 die_error(404, "Unknown tag object");
5223 my $head = git_get_head_hash($project);
5224 git_header_html();
5225 git_print_page_nav('','', $head,undef,$head);
5226 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5227 print "<div class=\"title_text\">\n" .
5228 "<table class=\"object_header\">\n" .
5229 "<tr>\n" .
5230 "<td>object</td>\n" .
5231 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5232 $tag{'object'}) . "</td>\n" .
5233 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5234 $tag{'type'}) . "</td>\n" .
5235 "</tr>\n";
5236 if (defined($tag{'author'})) {
5237 git_print_authorship_rows(\%tag, 'author');
5239 print "</table>\n\n" .
5240 "</div>\n";
5241 print "<div class=\"page_body\">";
5242 my $comment = $tag{'comment'};
5243 foreach my $line (@$comment) {
5244 chomp $line;
5245 print esc_html($line, -nbsp=>1) . "<br/>\n";
5247 print "</div>\n";
5248 git_footer_html();
5251 sub git_blame_common {
5252 my $format = shift || 'porcelain';
5253 if ($format eq 'porcelain' && $cgi->param('js')) {
5254 $format = 'incremental';
5255 $action = 'blame_incremental'; # for page title etc
5258 # permissions
5259 gitweb_check_feature('blame')
5260 or die_error(403, "Blame view not allowed");
5262 # error checking
5263 die_error(400, "No file name given") unless $file_name;
5264 $hash_base ||= git_get_head_hash($project);
5265 die_error(404, "Couldn't find base commit") unless $hash_base;
5266 my %co = parse_commit($hash_base)
5267 or die_error(404, "Commit not found");
5268 my $ftype = "blob";
5269 if (!defined $hash) {
5270 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5271 or die_error(404, "Error looking up file");
5272 } else {
5273 $ftype = git_get_type($hash);
5274 if ($ftype !~ "blob") {
5275 die_error(400, "Object is not a blob");
5279 my $fd;
5280 if ($format eq 'incremental') {
5281 # get file contents (as base)
5282 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5283 or die_error(500, "Open git-cat-file failed");
5284 } elsif ($format eq 'data') {
5285 # run git-blame --incremental
5286 open $fd, "-|", git_cmd(), "blame", "--incremental",
5287 $hash_base, "--", $file_name
5288 or die_error(500, "Open git-blame --incremental failed");
5289 } else {
5290 # run git-blame --porcelain
5291 open $fd, "-|", git_cmd(), "blame", '-p',
5292 $hash_base, '--', $file_name
5293 or die_error(500, "Open git-blame --porcelain failed");
5296 # incremental blame data returns early
5297 if ($format eq 'data') {
5298 print $cgi->header(
5299 -type=>"text/plain", -charset => "utf-8",
5300 -status=> "200 OK");
5301 local $| = 1; # output autoflush
5302 print while <$fd>;
5303 close $fd
5304 or print "ERROR $!\n";
5306 print 'END';
5307 if (defined $t0 && gitweb_check_feature('timed')) {
5308 print ' '.
5309 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5310 ' '.$number_of_git_cmds;
5312 print "\n";
5314 return;
5317 # page header
5318 git_header_html();
5319 my $formats_nav =
5320 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5321 "blob") .
5322 " | ";
5323 if ($format eq 'incremental') {
5324 $formats_nav .=
5325 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5326 "blame") . " (non-incremental)";
5327 } else {
5328 $formats_nav .=
5329 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5330 "blame") . " (incremental)";
5332 $formats_nav .=
5333 " | " .
5334 $cgi->a({-href => href(action=>"history", -replay=>1)},
5335 "history") .
5336 " | " .
5337 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5338 "HEAD");
5339 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5340 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5341 git_print_page_path($file_name, $ftype, $hash_base);
5343 # page body
5344 if ($format eq 'incremental') {
5345 print "<noscript>\n<div class=\"error\"><center><b>\n".
5346 "This page requires JavaScript to run.\n Use ".
5347 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5348 'this page').
5349 " instead.\n".
5350 "</b></center></div>\n</noscript>\n";
5352 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5355 print qq!<div class="page_body">\n!;
5356 print qq!<div id="progress_info">... / ...</div>\n!
5357 if ($format eq 'incremental');
5358 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5359 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5360 qq!<thead>\n!.
5361 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5362 qq!</thead>\n!.
5363 qq!<tbody>\n!;
5365 my @rev_color = qw(light dark);
5366 my $num_colors = scalar(@rev_color);
5367 my $current_color = 0;
5369 if ($format eq 'incremental') {
5370 my $color_class = $rev_color[$current_color];
5372 #contents of a file
5373 my $linenr = 0;
5374 LINE:
5375 while (my $line = <$fd>) {
5376 chomp $line;
5377 $linenr++;
5379 print qq!<tr id="l$linenr" class="$color_class">!.
5380 qq!<td class="sha1"><a href=""> </a></td>!.
5381 qq!<td class="linenr">!.
5382 qq!<a class="linenr" href="">$linenr</a></td>!;
5383 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5384 print qq!</tr>\n!;
5387 } else { # porcelain, i.e. ordinary blame
5388 my %metainfo = (); # saves information about commits
5390 # blame data
5391 LINE:
5392 while (my $line = <$fd>) {
5393 chomp $line;
5394 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5395 # no <lines in group> for subsequent lines in group of lines
5396 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5397 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5398 if (!exists $metainfo{$full_rev}) {
5399 $metainfo{$full_rev} = { 'nprevious' => 0 };
5401 my $meta = $metainfo{$full_rev};
5402 my $data;
5403 while ($data = <$fd>) {
5404 chomp $data;
5405 last if ($data =~ s/^\t//); # contents of line
5406 if ($data =~ /^(\S+)(?: (.*))?$/) {
5407 $meta->{$1} = $2 unless exists $meta->{$1};
5409 if ($data =~ /^previous /) {
5410 $meta->{'nprevious'}++;
5413 my $short_rev = substr($full_rev, 0, 8);
5414 my $author = $meta->{'author'};
5415 my %date =
5416 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5417 my $date = $date{'iso-tz'};
5418 if ($group_size) {
5419 $current_color = ($current_color + 1) % $num_colors;
5421 my $tr_class = $rev_color[$current_color];
5422 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5423 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5424 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5425 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5426 if ($group_size) {
5427 print "<td class=\"sha1\"";
5428 print " title=\"". esc_html($author) . ", $date\"";
5429 print " rowspan=\"$group_size\"" if ($group_size > 1);
5430 print ">";
5431 print $cgi->a({-href => href(action=>"commit",
5432 hash=>$full_rev,
5433 file_name=>$file_name)},
5434 esc_html($short_rev));
5435 if ($group_size >= 2) {
5436 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5437 if (@author_initials) {
5438 print "<br />" .
5439 esc_html(join('', @author_initials));
5440 # or join('.', ...)
5443 print "</td>\n";
5445 # 'previous' <sha1 of parent commit> <filename at commit>
5446 if (exists $meta->{'previous'} &&
5447 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5448 $meta->{'parent'} = $1;
5449 $meta->{'file_parent'} = unquote($2);
5451 my $linenr_commit =
5452 exists($meta->{'parent'}) ?
5453 $meta->{'parent'} : $full_rev;
5454 my $linenr_filename =
5455 exists($meta->{'file_parent'}) ?
5456 $meta->{'file_parent'} : unquote($meta->{'filename'});
5457 my $blamed = href(action => 'blame',
5458 file_name => $linenr_filename,
5459 hash_base => $linenr_commit);
5460 print "<td class=\"linenr\">";
5461 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5462 -class => "linenr" },
5463 esc_html($lineno));
5464 print "</td>";
5465 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5466 print "</tr>\n";
5467 } # end while
5471 # footer
5472 print "</tbody>\n".
5473 "</table>\n"; # class="blame"
5474 print "</div>\n"; # class="blame_body"
5475 close $fd
5476 or print "Reading blob failed\n";
5478 git_footer_html();
5481 sub git_blame {
5482 git_blame_common();
5485 sub git_blame_incremental {
5486 git_blame_common('incremental');
5489 sub git_blame_data {
5490 git_blame_common('data');
5493 sub git_tags {
5494 my $head = git_get_head_hash($project);
5495 git_header_html();
5496 git_print_page_nav('','', $head,undef,$head);
5497 git_print_header_div('summary', $project);
5499 my @tagslist = git_get_tags_list();
5500 if (@tagslist) {
5501 git_tags_body(\@tagslist);
5503 git_footer_html();
5506 sub git_heads {
5507 my $head = git_get_head_hash($project);
5508 git_header_html();
5509 git_print_page_nav('','', $head,undef,$head);
5510 git_print_header_div('summary', $project);
5512 my @headslist = git_get_heads_list();
5513 if (@headslist) {
5514 git_heads_body(\@headslist, $head);
5516 git_footer_html();
5519 sub git_blob_plain {
5520 my $type = shift;
5521 my $expires;
5523 if (!defined $hash) {
5524 if (defined $file_name) {
5525 my $base = $hash_base || git_get_head_hash($project);
5526 $hash = git_get_hash_by_path($base, $file_name, "blob")
5527 or die_error(404, "Cannot find file");
5528 } else {
5529 die_error(400, "No file name defined");
5531 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5532 # blobs defined by non-textual hash id's can be cached
5533 $expires = "+1d";
5536 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5537 or die_error(500, "Open git-cat-file blob '$hash' failed");
5539 # content-type (can include charset)
5540 $type = blob_contenttype($fd, $file_name, $type);
5542 # "save as" filename, even when no $file_name is given
5543 my $save_as = "$hash";
5544 if (defined $file_name) {
5545 $save_as = $file_name;
5546 } elsif ($type =~ m/^text\//) {
5547 $save_as .= '.txt';
5550 # With XSS prevention on, blobs of all types except a few known safe
5551 # ones are served with "Content-Disposition: attachment" to make sure
5552 # they don't run in our security domain. For certain image types,
5553 # blob view writes an <img> tag referring to blob_plain view, and we
5554 # want to be sure not to break that by serving the image as an
5555 # attachment (though Firefox 3 doesn't seem to care).
5556 my $sandbox = $prevent_xss &&
5557 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5559 print $cgi->header(
5560 -type => $type,
5561 -expires => $expires,
5562 -content_disposition =>
5563 ($sandbox ? 'attachment' : 'inline')
5564 . '; filename="' . $save_as . '"');
5565 local $/ = undef;
5566 binmode STDOUT, ':raw';
5567 print <$fd>;
5568 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5569 close $fd;
5572 sub git_blob {
5573 my $expires;
5575 if (!defined $hash) {
5576 if (defined $file_name) {
5577 my $base = $hash_base || git_get_head_hash($project);
5578 $hash = git_get_hash_by_path($base, $file_name, "blob")
5579 or die_error(404, "Cannot find file");
5580 } else {
5581 die_error(400, "No file name defined");
5583 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5584 # blobs defined by non-textual hash id's can be cached
5585 $expires = "+1d";
5588 my $have_blame = gitweb_check_feature('blame');
5589 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5590 or die_error(500, "Couldn't cat $file_name, $hash");
5591 my $mimetype = blob_mimetype($fd, $file_name);
5592 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5593 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5594 close $fd;
5595 return git_blob_plain($mimetype);
5597 # we can have blame only for text/* mimetype
5598 $have_blame &&= ($mimetype =~ m!^text/!);
5600 my $highlight = gitweb_check_feature('highlight');
5601 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5602 $fd = run_highlighter($fd, $highlight, $syntax)
5603 if $syntax;
5605 git_header_html(undef, $expires);
5606 my $formats_nav = '';
5607 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5608 if (defined $file_name) {
5609 if ($have_blame) {
5610 $formats_nav .=
5611 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5612 "blame") .
5613 " | ";
5615 $formats_nav .=
5616 $cgi->a({-href => href(action=>"history", -replay=>1)},
5617 "history") .
5618 " | " .
5619 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5620 "raw") .
5621 " | " .
5622 $cgi->a({-href => href(action=>"blob",
5623 hash_base=>"HEAD", file_name=>$file_name)},
5624 "HEAD");
5625 } else {
5626 $formats_nav .=
5627 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5628 "raw");
5630 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5631 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5632 } else {
5633 print "<div class=\"page_nav\">\n" .
5634 "<br/><br/></div>\n" .
5635 "<div class=\"title\">$hash</div>\n";
5637 git_print_page_path($file_name, "blob", $hash_base);
5638 print "<div class=\"page_body\">\n";
5639 if ($mimetype =~ m!^image/!) {
5640 print qq!<img type="$mimetype"!;
5641 if ($file_name) {
5642 print qq! alt="$file_name" title="$file_name"!;
5644 print qq! src="! .
5645 href(action=>"blob_plain", hash=>$hash,
5646 hash_base=>$hash_base, file_name=>$file_name) .
5647 qq!" />\n!;
5648 } else {
5649 my $nr;
5650 while (my $line = <$fd>) {
5651 chomp $line;
5652 $nr++;
5653 $line = untabify($line);
5654 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5655 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5658 close $fd
5659 or print "Reading blob failed.\n";
5660 print "</div>";
5661 git_footer_html();
5664 sub git_tree {
5665 if (!defined $hash_base) {
5666 $hash_base = "HEAD";
5668 if (!defined $hash) {
5669 if (defined $file_name) {
5670 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5671 } else {
5672 $hash = $hash_base;
5675 die_error(404, "No such tree") unless defined($hash);
5677 my $show_sizes = gitweb_check_feature('show-sizes');
5678 my $have_blame = gitweb_check_feature('blame');
5680 my @entries = ();
5682 local $/ = "\0";
5683 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5684 ($show_sizes ? '-l' : ()), @extra_options, $hash
5685 or die_error(500, "Open git-ls-tree failed");
5686 @entries = map { chomp; $_ } <$fd>;
5687 close $fd
5688 or die_error(404, "Reading tree failed");
5691 my $refs = git_get_references();
5692 my $ref = format_ref_marker($refs, $hash_base);
5693 git_header_html();
5694 my $basedir = '';
5695 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5696 my @views_nav = ();
5697 if (defined $file_name) {
5698 push @views_nav,
5699 $cgi->a({-href => href(action=>"history", -replay=>1)},
5700 "history"),
5701 $cgi->a({-href => href(action=>"tree",
5702 hash_base=>"HEAD", file_name=>$file_name)},
5703 "HEAD"),
5705 my $snapshot_links = format_snapshot_links($hash);
5706 if (defined $snapshot_links) {
5707 # FIXME: Should be available when we have no hash base as well.
5708 push @views_nav, $snapshot_links;
5710 git_print_page_nav('tree','', $hash_base, undef, undef,
5711 join(' | ', @views_nav));
5712 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5713 } else {
5714 undef $hash_base;
5715 print "<div class=\"page_nav\">\n";
5716 print "<br/><br/></div>\n";
5717 print "<div class=\"title\">$hash</div>\n";
5719 if (defined $file_name) {
5720 $basedir = $file_name;
5721 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5722 $basedir .= '/';
5724 git_print_page_path($file_name, 'tree', $hash_base);
5726 print "<div class=\"page_body\">\n";
5727 print "<table class=\"tree\">\n";
5728 my $alternate = 1;
5729 # '..' (top directory) link if possible
5730 if (defined $hash_base &&
5731 defined $file_name && $file_name =~ m![^/]+$!) {
5732 if ($alternate) {
5733 print "<tr class=\"dark\">\n";
5734 } else {
5735 print "<tr class=\"light\">\n";
5737 $alternate ^= 1;
5739 my $up = $file_name;
5740 $up =~ s!/?[^/]+$!!;
5741 undef $up unless $up;
5742 # based on git_print_tree_entry
5743 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5744 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5745 print '<td class="list">';
5746 print $cgi->a({-href => href(action=>"tree",
5747 hash_base=>$hash_base,
5748 file_name=>$up)},
5749 "..");
5750 print "</td>\n";
5751 print "<td class=\"link\"></td>\n";
5753 print "</tr>\n";
5755 foreach my $line (@entries) {
5756 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5758 if ($alternate) {
5759 print "<tr class=\"dark\">\n";
5760 } else {
5761 print "<tr class=\"light\">\n";
5763 $alternate ^= 1;
5765 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5767 print "</tr>\n";
5769 print "</table>\n" .
5770 "</div>";
5771 git_footer_html();
5774 sub snapshot_name {
5775 my ($project, $hash) = @_;
5777 # path/to/project.git -> project
5778 # path/to/project/.git -> project
5779 my $name = to_utf8($project);
5780 $name =~ s,([^/])/*\.git$,$1,;
5781 $name = basename($name);
5782 # sanitize name
5783 $name =~ s/[[:cntrl:]]/?/g;
5785 my $ver = $hash;
5786 if ($hash =~ /^[0-9a-fA-F]+$/) {
5787 # shorten SHA-1 hash
5788 my $full_hash = git_get_full_hash($project, $hash);
5789 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5790 $ver = git_get_short_hash($project, $hash);
5792 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5793 # tags don't need shortened SHA-1 hash
5794 $ver = $1;
5795 } else {
5796 # branches and other need shortened SHA-1 hash
5797 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5798 $ver = $1;
5800 $ver .= '-' . git_get_short_hash($project, $hash);
5802 # in case of hierarchical branch names
5803 $ver =~ s!/!.!g;
5805 # name = project-version_string
5806 $name = "$name-$ver";
5808 return wantarray ? ($name, $name) : $name;
5811 sub git_snapshot {
5812 my $format = $input_params{'snapshot_format'};
5813 if (!@snapshot_fmts) {
5814 die_error(403, "Snapshots not allowed");
5816 # default to first supported snapshot format
5817 $format ||= $snapshot_fmts[0];
5818 if ($format !~ m/^[a-z0-9]+$/) {
5819 die_error(400, "Invalid snapshot format parameter");
5820 } elsif (!exists($known_snapshot_formats{$format})) {
5821 die_error(400, "Unknown snapshot format");
5822 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5823 die_error(403, "Snapshot format not allowed");
5824 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5825 die_error(403, "Unsupported snapshot format");
5828 my $type = git_get_type("$hash^{}");
5829 if (!$type) {
5830 die_error(404, 'Object does not exist');
5831 } elsif ($type eq 'blob') {
5832 die_error(400, 'Object is not a tree-ish');
5835 my ($name, $prefix) = snapshot_name($project, $hash);
5836 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
5837 my $cmd = quote_command(
5838 git_cmd(), 'archive',
5839 "--format=$known_snapshot_formats{$format}{'format'}",
5840 "--prefix=$prefix/", $hash);
5841 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5842 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5845 $filename =~ s/(["\\])/\\$1/g;
5846 print $cgi->header(
5847 -type => $known_snapshot_formats{$format}{'type'},
5848 -content_disposition => 'inline; filename="' . $filename . '"',
5849 -status => '200 OK');
5851 open my $fd, "-|", $cmd
5852 or die_error(500, "Execute git-archive failed");
5853 binmode STDOUT, ':raw';
5854 print <$fd>;
5855 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5856 close $fd;
5859 sub git_log_generic {
5860 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
5862 my $head = git_get_head_hash($project);
5863 if (!defined $base) {
5864 $base = $head;
5866 if (!defined $page) {
5867 $page = 0;
5869 my $refs = git_get_references();
5871 my $commit_hash = $base;
5872 if (defined $parent) {
5873 $commit_hash = "$parent..$base";
5875 my @commitlist =
5876 parse_commits($commit_hash, 101, (100 * $page),
5877 defined $file_name ? ($file_name, "--full-history") : ());
5879 my $ftype;
5880 if (!defined $file_hash && defined $file_name) {
5881 # some commits could have deleted file in question,
5882 # and not have it in tree, but one of them has to have it
5883 for (my $i = 0; $i < @commitlist; $i++) {
5884 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5885 last if defined $file_hash;
5888 if (defined $file_hash) {
5889 $ftype = git_get_type($file_hash);
5891 if (defined $file_name && !defined $ftype) {
5892 die_error(500, "Unknown type of object");
5894 my %co;
5895 if (defined $file_name) {
5896 %co = parse_commit($base)
5897 or die_error(404, "Unknown commit object");
5901 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
5902 my $next_link = '';
5903 if ($#commitlist >= 100) {
5904 $next_link =
5905 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5906 -accesskey => "n", -title => "Alt-n"}, "next");
5908 my $patch_max = gitweb_get_feature('patches');
5909 if ($patch_max && !defined $file_name) {
5910 if ($patch_max < 0 || @commitlist <= $patch_max) {
5911 $paging_nav .= " &sdot; " .
5912 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5913 "patches");
5917 git_header_html();
5918 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
5919 if (defined $file_name) {
5920 git_print_header_div('commit', esc_html($co{'title'}), $base);
5921 } else {
5922 git_print_header_div('summary', $project)
5924 git_print_page_path($file_name, $ftype, $hash_base)
5925 if (defined $file_name);
5927 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
5928 $file_name, $file_hash, $ftype);
5930 git_footer_html();
5933 sub git_log {
5934 git_log_generic('log', \&git_log_body,
5935 $hash, $hash_parent);
5938 sub git_commit {
5939 $hash ||= $hash_base || "HEAD";
5940 my %co = parse_commit($hash)
5941 or die_error(404, "Unknown commit object");
5943 my $parent = $co{'parent'};
5944 my $parents = $co{'parents'}; # listref
5946 # we need to prepare $formats_nav before any parameter munging
5947 my $formats_nav;
5948 if (!defined $parent) {
5949 # --root commitdiff
5950 $formats_nav .= '(initial)';
5951 } elsif (@$parents == 1) {
5952 # single parent commit
5953 $formats_nav .=
5954 '(parent: ' .
5955 $cgi->a({-href => href(action=>"commit",
5956 hash=>$parent)},
5957 esc_html(substr($parent, 0, 7))) .
5958 ')';
5959 } else {
5960 # merge commit
5961 $formats_nav .=
5962 '(merge: ' .
5963 join(' ', map {
5964 $cgi->a({-href => href(action=>"commit",
5965 hash=>$_)},
5966 esc_html(substr($_, 0, 7)));
5967 } @$parents ) .
5968 ')';
5970 if (gitweb_check_feature('patches') && @$parents <= 1) {
5971 $formats_nav .= " | " .
5972 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5973 "patch");
5976 if (!defined $parent) {
5977 $parent = "--root";
5979 my @difftree;
5980 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5981 @diff_opts,
5982 (@$parents <= 1 ? $parent : '-c'),
5983 $hash, "--"
5984 or die_error(500, "Open git-diff-tree failed");
5985 @difftree = map { chomp; $_ } <$fd>;
5986 close $fd or die_error(404, "Reading git-diff-tree failed");
5988 # non-textual hash id's can be cached
5989 my $expires;
5990 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5991 $expires = "+1d";
5993 my $refs = git_get_references();
5994 my $ref = format_ref_marker($refs, $co{'id'});
5996 git_header_html(undef, $expires);
5997 git_print_page_nav('commit', '',
5998 $hash, $co{'tree'}, $hash,
5999 $formats_nav);
6001 if (defined $co{'parent'}) {
6002 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6003 } else {
6004 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6006 print "<div class=\"title_text\">\n" .
6007 "<table class=\"object_header\">\n";
6008 git_print_authorship_rows(\%co);
6009 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6010 print "<tr>" .
6011 "<td>tree</td>" .
6012 "<td class=\"sha1\">" .
6013 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6014 class => "list"}, $co{'tree'}) .
6015 "</td>" .
6016 "<td class=\"link\">" .
6017 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6018 "tree");
6019 my $snapshot_links = format_snapshot_links($hash);
6020 if (defined $snapshot_links) {
6021 print " | " . $snapshot_links;
6023 print "</td>" .
6024 "</tr>\n";
6026 foreach my $par (@$parents) {
6027 print "<tr>" .
6028 "<td>parent</td>" .
6029 "<td class=\"sha1\">" .
6030 $cgi->a({-href => href(action=>"commit", hash=>$par),
6031 class => "list"}, $par) .
6032 "</td>" .
6033 "<td class=\"link\">" .
6034 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6035 " | " .
6036 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6037 "</td>" .
6038 "</tr>\n";
6040 print "</table>".
6041 "</div>\n";
6043 print "<div class=\"page_body\">\n";
6044 git_print_log($co{'comment'});
6045 print "</div>\n";
6047 git_difftree_body(\@difftree, $hash, @$parents);
6049 git_footer_html();
6052 sub git_object {
6053 # object is defined by:
6054 # - hash or hash_base alone
6055 # - hash_base and file_name
6056 my $type;
6058 # - hash or hash_base alone
6059 if ($hash || ($hash_base && !defined $file_name)) {
6060 my $object_id = $hash || $hash_base;
6062 open my $fd, "-|", quote_command(
6063 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6064 or die_error(404, "Object does not exist");
6065 $type = <$fd>;
6066 chomp $type;
6067 close $fd
6068 or die_error(404, "Object does not exist");
6070 # - hash_base and file_name
6071 } elsif ($hash_base && defined $file_name) {
6072 $file_name =~ s,/+$,,;
6074 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6075 or die_error(404, "Base object does not exist");
6077 # here errors should not hapen
6078 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6079 or die_error(500, "Open git-ls-tree failed");
6080 my $line = <$fd>;
6081 close $fd;
6083 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6084 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6085 die_error(404, "File or directory for given base does not exist");
6087 $type = $2;
6088 $hash = $3;
6089 } else {
6090 die_error(400, "Not enough information to find object");
6093 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6094 hash=>$hash, hash_base=>$hash_base,
6095 file_name=>$file_name),
6096 -status => '302 Found');
6099 sub git_blobdiff {
6100 my $format = shift || 'html';
6102 my $fd;
6103 my @difftree;
6104 my %diffinfo;
6105 my $expires;
6107 # preparing $fd and %diffinfo for git_patchset_body
6108 # new style URI
6109 if (defined $hash_base && defined $hash_parent_base) {
6110 if (defined $file_name) {
6111 # read raw output
6112 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6113 $hash_parent_base, $hash_base,
6114 "--", (defined $file_parent ? $file_parent : ()), $file_name
6115 or die_error(500, "Open git-diff-tree failed");
6116 @difftree = map { chomp; $_ } <$fd>;
6117 close $fd
6118 or die_error(404, "Reading git-diff-tree failed");
6119 @difftree
6120 or die_error(404, "Blob diff not found");
6122 } elsif (defined $hash &&
6123 $hash =~ /[0-9a-fA-F]{40}/) {
6124 # try to find filename from $hash
6126 # read filtered raw output
6127 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6128 $hash_parent_base, $hash_base, "--"
6129 or die_error(500, "Open git-diff-tree failed");
6130 @difftree =
6131 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6132 # $hash == to_id
6133 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6134 map { chomp; $_ } <$fd>;
6135 close $fd
6136 or die_error(404, "Reading git-diff-tree failed");
6137 @difftree
6138 or die_error(404, "Blob diff not found");
6140 } else {
6141 die_error(400, "Missing one of the blob diff parameters");
6144 if (@difftree > 1) {
6145 die_error(400, "Ambiguous blob diff specification");
6148 %diffinfo = parse_difftree_raw_line($difftree[0]);
6149 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6150 $file_name ||= $diffinfo{'to_file'};
6152 $hash_parent ||= $diffinfo{'from_id'};
6153 $hash ||= $diffinfo{'to_id'};
6155 # non-textual hash id's can be cached
6156 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6157 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6158 $expires = '+1d';
6161 # open patch output
6162 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6163 '-p', ($format eq 'html' ? "--full-index" : ()),
6164 $hash_parent_base, $hash_base,
6165 "--", (defined $file_parent ? $file_parent : ()), $file_name
6166 or die_error(500, "Open git-diff-tree failed");
6169 # old/legacy style URI -- not generated anymore since 1.4.3.
6170 if (!%diffinfo) {
6171 die_error('404 Not Found', "Missing one of the blob diff parameters")
6174 # header
6175 if ($format eq 'html') {
6176 my $formats_nav =
6177 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6178 "raw");
6179 git_header_html(undef, $expires);
6180 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6181 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6182 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6183 } else {
6184 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6185 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6187 if (defined $file_name) {
6188 git_print_page_path($file_name, "blob", $hash_base);
6189 } else {
6190 print "<div class=\"page_path\"></div>\n";
6193 } elsif ($format eq 'plain') {
6194 print $cgi->header(
6195 -type => 'text/plain',
6196 -charset => 'utf-8',
6197 -expires => $expires,
6198 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6200 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6202 } else {
6203 die_error(400, "Unknown blobdiff format");
6206 # patch
6207 if ($format eq 'html') {
6208 print "<div class=\"page_body\">\n";
6210 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6211 close $fd;
6213 print "</div>\n"; # class="page_body"
6214 git_footer_html();
6216 } else {
6217 while (my $line = <$fd>) {
6218 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6219 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6221 print $line;
6223 last if $line =~ m!^\+\+\+!;
6225 local $/ = undef;
6226 print <$fd>;
6227 close $fd;
6231 sub git_blobdiff_plain {
6232 git_blobdiff('plain');
6235 sub git_commitdiff {
6236 my %params = @_;
6237 my $format = $params{-format} || 'html';
6239 my ($patch_max) = gitweb_get_feature('patches');
6240 if ($format eq 'patch') {
6241 die_error(403, "Patch view not allowed") unless $patch_max;
6244 $hash ||= $hash_base || "HEAD";
6245 my %co = parse_commit($hash)
6246 or die_error(404, "Unknown commit object");
6248 # choose format for commitdiff for merge
6249 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6250 $hash_parent = '--cc';
6252 # we need to prepare $formats_nav before almost any parameter munging
6253 my $formats_nav;
6254 if ($format eq 'html') {
6255 $formats_nav =
6256 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6257 "raw");
6258 if ($patch_max && @{$co{'parents'}} <= 1) {
6259 $formats_nav .= " | " .
6260 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6261 "patch");
6264 if (defined $hash_parent &&
6265 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6266 # commitdiff with two commits given
6267 my $hash_parent_short = $hash_parent;
6268 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6269 $hash_parent_short = substr($hash_parent, 0, 7);
6271 $formats_nav .=
6272 ' (from';
6273 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6274 if ($co{'parents'}[$i] eq $hash_parent) {
6275 $formats_nav .= ' parent ' . ($i+1);
6276 last;
6279 $formats_nav .= ': ' .
6280 $cgi->a({-href => href(action=>"commitdiff",
6281 hash=>$hash_parent)},
6282 esc_html($hash_parent_short)) .
6283 ')';
6284 } elsif (!$co{'parent'}) {
6285 # --root commitdiff
6286 $formats_nav .= ' (initial)';
6287 } elsif (scalar @{$co{'parents'}} == 1) {
6288 # single parent commit
6289 $formats_nav .=
6290 ' (parent: ' .
6291 $cgi->a({-href => href(action=>"commitdiff",
6292 hash=>$co{'parent'})},
6293 esc_html(substr($co{'parent'}, 0, 7))) .
6294 ')';
6295 } else {
6296 # merge commit
6297 if ($hash_parent eq '--cc') {
6298 $formats_nav .= ' | ' .
6299 $cgi->a({-href => href(action=>"commitdiff",
6300 hash=>$hash, hash_parent=>'-c')},
6301 'combined');
6302 } else { # $hash_parent eq '-c'
6303 $formats_nav .= ' | ' .
6304 $cgi->a({-href => href(action=>"commitdiff",
6305 hash=>$hash, hash_parent=>'--cc')},
6306 'compact');
6308 $formats_nav .=
6309 ' (merge: ' .
6310 join(' ', map {
6311 $cgi->a({-href => href(action=>"commitdiff",
6312 hash=>$_)},
6313 esc_html(substr($_, 0, 7)));
6314 } @{$co{'parents'}} ) .
6315 ')';
6319 my $hash_parent_param = $hash_parent;
6320 if (!defined $hash_parent_param) {
6321 # --cc for multiple parents, --root for parentless
6322 $hash_parent_param =
6323 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6326 # read commitdiff
6327 my $fd;
6328 my @difftree;
6329 if ($format eq 'html') {
6330 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6331 "--no-commit-id", "--patch-with-raw", "--full-index",
6332 $hash_parent_param, $hash, "--"
6333 or die_error(500, "Open git-diff-tree failed");
6335 while (my $line = <$fd>) {
6336 chomp $line;
6337 # empty line ends raw part of diff-tree output
6338 last unless $line;
6339 push @difftree, scalar parse_difftree_raw_line($line);
6342 } elsif ($format eq 'plain') {
6343 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6344 '-p', $hash_parent_param, $hash, "--"
6345 or die_error(500, "Open git-diff-tree failed");
6346 } elsif ($format eq 'patch') {
6347 # For commit ranges, we limit the output to the number of
6348 # patches specified in the 'patches' feature.
6349 # For single commits, we limit the output to a single patch,
6350 # diverging from the git-format-patch default.
6351 my @commit_spec = ();
6352 if ($hash_parent) {
6353 if ($patch_max > 0) {
6354 push @commit_spec, "-$patch_max";
6356 push @commit_spec, '-n', "$hash_parent..$hash";
6357 } else {
6358 if ($params{-single}) {
6359 push @commit_spec, '-1';
6360 } else {
6361 if ($patch_max > 0) {
6362 push @commit_spec, "-$patch_max";
6364 push @commit_spec, "-n";
6366 push @commit_spec, '--root', $hash;
6368 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6369 '--encoding=utf8', '--stdout', @commit_spec
6370 or die_error(500, "Open git-format-patch failed");
6371 } else {
6372 die_error(400, "Unknown commitdiff format");
6375 # non-textual hash id's can be cached
6376 my $expires;
6377 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6378 $expires = "+1d";
6381 # write commit message
6382 if ($format eq 'html') {
6383 my $refs = git_get_references();
6384 my $ref = format_ref_marker($refs, $co{'id'});
6386 git_header_html(undef, $expires);
6387 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6388 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6389 print "<div class=\"title_text\">\n" .
6390 "<table class=\"object_header\">\n";
6391 git_print_authorship_rows(\%co);
6392 print "</table>".
6393 "</div>\n";
6394 print "<div class=\"page_body\">\n";
6395 if (@{$co{'comment'}} > 1) {
6396 print "<div class=\"log\">\n";
6397 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6398 print "</div>\n"; # class="log"
6401 } elsif ($format eq 'plain') {
6402 my $refs = git_get_references("tags");
6403 my $tagname = git_get_rev_name_tags($hash);
6404 my $filename = basename($project) . "-$hash.patch";
6406 print $cgi->header(
6407 -type => 'text/plain',
6408 -charset => 'utf-8',
6409 -expires => $expires,
6410 -content_disposition => 'inline; filename="' . "$filename" . '"');
6411 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6412 print "From: " . to_utf8($co{'author'}) . "\n";
6413 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6414 print "Subject: " . to_utf8($co{'title'}) . "\n";
6416 print "X-Git-Tag: $tagname\n" if $tagname;
6417 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6419 foreach my $line (@{$co{'comment'}}) {
6420 print to_utf8($line) . "\n";
6422 print "---\n\n";
6423 } elsif ($format eq 'patch') {
6424 my $filename = basename($project) . "-$hash.patch";
6426 print $cgi->header(
6427 -type => 'text/plain',
6428 -charset => 'utf-8',
6429 -expires => $expires,
6430 -content_disposition => 'inline; filename="' . "$filename" . '"');
6433 # write patch
6434 if ($format eq 'html') {
6435 my $use_parents = !defined $hash_parent ||
6436 $hash_parent eq '-c' || $hash_parent eq '--cc';
6437 git_difftree_body(\@difftree, $hash,
6438 $use_parents ? @{$co{'parents'}} : $hash_parent);
6439 print "<br/>\n";
6441 git_patchset_body($fd, \@difftree, $hash,
6442 $use_parents ? @{$co{'parents'}} : $hash_parent);
6443 close $fd;
6444 print "</div>\n"; # class="page_body"
6445 git_footer_html();
6447 } elsif ($format eq 'plain') {
6448 local $/ = undef;
6449 print <$fd>;
6450 close $fd
6451 or print "Reading git-diff-tree failed\n";
6452 } elsif ($format eq 'patch') {
6453 local $/ = undef;
6454 print <$fd>;
6455 close $fd
6456 or print "Reading git-format-patch failed\n";
6460 sub git_commitdiff_plain {
6461 git_commitdiff(-format => 'plain');
6464 # format-patch-style patches
6465 sub git_patch {
6466 git_commitdiff(-format => 'patch', -single => 1);
6469 sub git_patches {
6470 git_commitdiff(-format => 'patch');
6473 sub git_history {
6474 git_log_generic('history', \&git_history_body,
6475 $hash_base, $hash_parent_base,
6476 $file_name, $hash);
6479 sub git_search {
6480 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6481 if (!defined $searchtext) {
6482 die_error(400, "Text field is empty");
6484 if (!defined $hash) {
6485 $hash = git_get_head_hash($project);
6487 my %co = parse_commit($hash);
6488 if (!%co) {
6489 die_error(404, "Unknown commit object");
6491 if (!defined $page) {
6492 $page = 0;
6495 $searchtype ||= 'commit';
6496 if ($searchtype eq 'pickaxe') {
6497 # pickaxe may take all resources of your box and run for several minutes
6498 # with every query - so decide by yourself how public you make this feature
6499 gitweb_check_feature('pickaxe')
6500 or die_error(403, "Pickaxe is disabled");
6502 if ($searchtype eq 'grep') {
6503 gitweb_check_feature('grep')
6504 or die_error(403, "Grep is disabled");
6507 git_header_html();
6509 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6510 my $greptype;
6511 if ($searchtype eq 'commit') {
6512 $greptype = "--grep=";
6513 } elsif ($searchtype eq 'author') {
6514 $greptype = "--author=";
6515 } elsif ($searchtype eq 'committer') {
6516 $greptype = "--committer=";
6518 $greptype .= $searchtext;
6519 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6520 $greptype, '--regexp-ignore-case',
6521 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6523 my $paging_nav = '';
6524 if ($page > 0) {
6525 $paging_nav .=
6526 $cgi->a({-href => href(action=>"search", hash=>$hash,
6527 searchtext=>$searchtext,
6528 searchtype=>$searchtype)},
6529 "first");
6530 $paging_nav .= " &sdot; " .
6531 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6532 -accesskey => "p", -title => "Alt-p"}, "prev");
6533 } else {
6534 $paging_nav .= "first";
6535 $paging_nav .= " &sdot; prev";
6537 my $next_link = '';
6538 if ($#commitlist >= 100) {
6539 $next_link =
6540 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6541 -accesskey => "n", -title => "Alt-n"}, "next");
6542 $paging_nav .= " &sdot; $next_link";
6543 } else {
6544 $paging_nav .= " &sdot; next";
6547 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6548 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6549 if ($page == 0 && !@commitlist) {
6550 print "<p>No match.</p>\n";
6551 } else {
6552 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6556 if ($searchtype eq 'pickaxe') {
6557 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6558 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6560 print "<table class=\"pickaxe search\">\n";
6561 my $alternate = 1;
6562 local $/ = "\n";
6563 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6564 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6565 ($search_use_regexp ? '--pickaxe-regex' : ());
6566 undef %co;
6567 my @files;
6568 while (my $line = <$fd>) {
6569 chomp $line;
6570 next unless $line;
6572 my %set = parse_difftree_raw_line($line);
6573 if (defined $set{'commit'}) {
6574 # finish previous commit
6575 if (%co) {
6576 print "</td>\n" .
6577 "<td class=\"link\">" .
6578 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6579 " | " .
6580 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6581 print "</td>\n" .
6582 "</tr>\n";
6585 if ($alternate) {
6586 print "<tr class=\"dark\">\n";
6587 } else {
6588 print "<tr class=\"light\">\n";
6590 $alternate ^= 1;
6591 %co = parse_commit($set{'commit'});
6592 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6593 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6594 "<td><i>$author</i></td>\n" .
6595 "<td>" .
6596 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6597 -class => "list subject"},
6598 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6599 } elsif (defined $set{'to_id'}) {
6600 next if ($set{'to_id'} =~ m/^0{40}$/);
6602 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6603 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6604 -class => "list"},
6605 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6606 "<br/>\n";
6609 close $fd;
6611 # finish last commit (warning: repetition!)
6612 if (%co) {
6613 print "</td>\n" .
6614 "<td class=\"link\">" .
6615 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6616 " | " .
6617 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6618 print "</td>\n" .
6619 "</tr>\n";
6622 print "</table>\n";
6625 if ($searchtype eq 'grep') {
6626 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6627 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6629 print "<table class=\"grep_search\">\n";
6630 my $alternate = 1;
6631 my $matches = 0;
6632 local $/ = "\n";
6633 open my $fd, "-|", git_cmd(), 'grep', '-n',
6634 $search_use_regexp ? ('-E', '-i') : '-F',
6635 $searchtext, $co{'tree'};
6636 my $lastfile = '';
6637 while (my $line = <$fd>) {
6638 chomp $line;
6639 my ($file, $lno, $ltext, $binary);
6640 last if ($matches++ > 1000);
6641 if ($line =~ /^Binary file (.+) matches$/) {
6642 $file = $1;
6643 $binary = 1;
6644 } else {
6645 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6647 if ($file ne $lastfile) {
6648 $lastfile and print "</td></tr>\n";
6649 if ($alternate++) {
6650 print "<tr class=\"dark\">\n";
6651 } else {
6652 print "<tr class=\"light\">\n";
6654 print "<td class=\"list\">".
6655 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6656 file_name=>"$file"),
6657 -class => "list"}, esc_path($file));
6658 print "</td><td>\n";
6659 $lastfile = $file;
6661 if ($binary) {
6662 print "<div class=\"binary\">Binary file</div>\n";
6663 } else {
6664 $ltext = untabify($ltext);
6665 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6666 $ltext = esc_html($1, -nbsp=>1);
6667 $ltext .= '<span class="match">';
6668 $ltext .= esc_html($2, -nbsp=>1);
6669 $ltext .= '</span>';
6670 $ltext .= esc_html($3, -nbsp=>1);
6671 } else {
6672 $ltext = esc_html($ltext, -nbsp=>1);
6674 print "<div class=\"pre\">" .
6675 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6676 file_name=>"$file").'#l'.$lno,
6677 -class => "linenr"}, sprintf('%4i', $lno))
6678 . ' ' . $ltext . "</div>\n";
6681 if ($lastfile) {
6682 print "</td></tr>\n";
6683 if ($matches > 1000) {
6684 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6686 } else {
6687 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6689 close $fd;
6691 print "</table>\n";
6693 git_footer_html();
6696 sub git_search_help {
6697 git_header_html();
6698 git_print_page_nav('','', $hash,$hash,$hash);
6699 print <<EOT;
6700 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6701 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6702 the pattern entered is recognized as the POSIX extended
6703 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6704 insensitive).</p>
6705 <dl>
6706 <dt><b>commit</b></dt>
6707 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6709 my $have_grep = gitweb_check_feature('grep');
6710 if ($have_grep) {
6711 print <<EOT;
6712 <dt><b>grep</b></dt>
6713 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6714 a different one) are searched for the given pattern. On large trees, this search can take
6715 a while and put some strain on the server, so please use it with some consideration. Note that
6716 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6717 case-sensitive.</dd>
6720 print <<EOT;
6721 <dt><b>author</b></dt>
6722 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6723 <dt><b>committer</b></dt>
6724 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6726 my $have_pickaxe = gitweb_check_feature('pickaxe');
6727 if ($have_pickaxe) {
6728 print <<EOT;
6729 <dt><b>pickaxe</b></dt>
6730 <dd>All commits that caused the string to appear or disappear from any file (changes that
6731 added, removed or "modified" the string) will be listed. This search can take a while and
6732 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6733 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6736 print "</dl>\n";
6737 git_footer_html();
6740 sub git_shortlog {
6741 git_log_generic('shortlog', \&git_shortlog_body,
6742 $hash, $hash_parent);
6745 ## ......................................................................
6746 ## feeds (RSS, Atom; OPML)
6748 sub git_feed {
6749 my $format = shift || 'atom';
6750 my $have_blame = gitweb_check_feature('blame');
6752 # Atom: http://www.atomenabled.org/developers/syndication/
6753 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6754 if ($format ne 'rss' && $format ne 'atom') {
6755 die_error(400, "Unknown web feed format");
6758 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6759 my $head = $hash || 'HEAD';
6760 my @commitlist = parse_commits($head, 150, 0, $file_name);
6762 my %latest_commit;
6763 my %latest_date;
6764 my $content_type = "application/$format+xml";
6765 if (defined $cgi->http('HTTP_ACCEPT') &&
6766 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6767 # browser (feed reader) prefers text/xml
6768 $content_type = 'text/xml';
6770 if (defined($commitlist[0])) {
6771 %latest_commit = %{$commitlist[0]};
6772 my $latest_epoch = $latest_commit{'committer_epoch'};
6773 %latest_date = parse_date($latest_epoch);
6774 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6775 if (defined $if_modified) {
6776 my $since;
6777 if (eval { require HTTP::Date; 1; }) {
6778 $since = HTTP::Date::str2time($if_modified);
6779 } elsif (eval { require Time::ParseDate; 1; }) {
6780 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6782 if (defined $since && $latest_epoch <= $since) {
6783 print $cgi->header(
6784 -type => $content_type,
6785 -charset => 'utf-8',
6786 -last_modified => $latest_date{'rfc2822'},
6787 -status => '304 Not Modified');
6788 return;
6791 print $cgi->header(
6792 -type => $content_type,
6793 -charset => 'utf-8',
6794 -last_modified => $latest_date{'rfc2822'});
6795 } else {
6796 print $cgi->header(
6797 -type => $content_type,
6798 -charset => 'utf-8');
6801 # Optimization: skip generating the body if client asks only
6802 # for Last-Modified date.
6803 return if ($cgi->request_method() eq 'HEAD');
6805 # header variables
6806 my $title = "$site_name - $project/$action";
6807 my $feed_type = 'log';
6808 if (defined $hash) {
6809 $title .= " - '$hash'";
6810 $feed_type = 'branch log';
6811 if (defined $file_name) {
6812 $title .= " :: $file_name";
6813 $feed_type = 'history';
6815 } elsif (defined $file_name) {
6816 $title .= " - $file_name";
6817 $feed_type = 'history';
6819 $title .= " $feed_type";
6820 my $descr = git_get_project_description($project);
6821 if (defined $descr) {
6822 $descr = esc_html($descr);
6823 } else {
6824 $descr = "$project " .
6825 ($format eq 'rss' ? 'RSS' : 'Atom') .
6826 " feed";
6828 my $owner = git_get_project_owner($project);
6829 $owner = esc_html($owner);
6831 #header
6832 my $alt_url;
6833 if (defined $file_name) {
6834 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6835 } elsif (defined $hash) {
6836 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6837 } else {
6838 $alt_url = href(-full=>1, action=>"summary");
6840 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6841 if ($format eq 'rss') {
6842 print <<XML;
6843 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6844 <channel>
6846 print "<title>$title</title>\n" .
6847 "<link>$alt_url</link>\n" .
6848 "<description>$descr</description>\n" .
6849 "<language>en</language>\n" .
6850 # project owner is responsible for 'editorial' content
6851 "<managingEditor>$owner</managingEditor>\n";
6852 if (defined $logo || defined $favicon) {
6853 # prefer the logo to the favicon, since RSS
6854 # doesn't allow both
6855 my $img = esc_url($logo || $favicon);
6856 print "<image>\n" .
6857 "<url>$img</url>\n" .
6858 "<title>$title</title>\n" .
6859 "<link>$alt_url</link>\n" .
6860 "</image>\n";
6862 if (%latest_date) {
6863 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6864 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6866 print "<generator>gitweb v.$version/$git_version</generator>\n";
6867 } elsif ($format eq 'atom') {
6868 print <<XML;
6869 <feed xmlns="http://www.w3.org/2005/Atom">
6871 print "<title>$title</title>\n" .
6872 "<subtitle>$descr</subtitle>\n" .
6873 '<link rel="alternate" type="text/html" href="' .
6874 $alt_url . '" />' . "\n" .
6875 '<link rel="self" type="' . $content_type . '" href="' .
6876 $cgi->self_url() . '" />' . "\n" .
6877 "<id>" . href(-full=>1) . "</id>\n" .
6878 # use project owner for feed author
6879 "<author><name>$owner</name></author>\n";
6880 if (defined $favicon) {
6881 print "<icon>" . esc_url($favicon) . "</icon>\n";
6883 if (defined $logo_url) {
6884 # not twice as wide as tall: 72 x 27 pixels
6885 print "<logo>" . esc_url($logo) . "</logo>\n";
6887 if (! %latest_date) {
6888 # dummy date to keep the feed valid until commits trickle in:
6889 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6890 } else {
6891 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6893 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6896 # contents
6897 for (my $i = 0; $i <= $#commitlist; $i++) {
6898 my %co = %{$commitlist[$i]};
6899 my $commit = $co{'id'};
6900 # we read 150, we always show 30 and the ones more recent than 48 hours
6901 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6902 last;
6904 my %cd = parse_date($co{'author_epoch'});
6906 # get list of changed files
6907 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6908 $co{'parent'} || "--root",
6909 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6910 or next;
6911 my @difftree = map { chomp; $_ } <$fd>;
6912 close $fd
6913 or next;
6915 # print element (entry, item)
6916 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6917 if ($format eq 'rss') {
6918 print "<item>\n" .
6919 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6920 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6921 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6922 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6923 "<link>$co_url</link>\n" .
6924 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6925 "<content:encoded>" .
6926 "<![CDATA[\n";
6927 } elsif ($format eq 'atom') {
6928 print "<entry>\n" .
6929 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6930 "<updated>$cd{'iso-8601'}</updated>\n" .
6931 "<author>\n" .
6932 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6933 if ($co{'author_email'}) {
6934 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6936 print "</author>\n" .
6937 # use committer for contributor
6938 "<contributor>\n" .
6939 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6940 if ($co{'committer_email'}) {
6941 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6943 print "</contributor>\n" .
6944 "<published>$cd{'iso-8601'}</published>\n" .
6945 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6946 "<id>$co_url</id>\n" .
6947 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6948 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6950 my $comment = $co{'comment'};
6951 print "<pre>\n";
6952 foreach my $line (@$comment) {
6953 $line = esc_html($line);
6954 print "$line\n";
6956 print "</pre><ul>\n";
6957 foreach my $difftree_line (@difftree) {
6958 my %difftree = parse_difftree_raw_line($difftree_line);
6959 next if !$difftree{'from_id'};
6961 my $file = $difftree{'file'} || $difftree{'to_file'};
6963 print "<li>" .
6964 "[" .
6965 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6966 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6967 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6968 file_name=>$file, file_parent=>$difftree{'from_file'}),
6969 -title => "diff"}, 'D');
6970 if ($have_blame) {
6971 print $cgi->a({-href => href(-full=>1, action=>"blame",
6972 file_name=>$file, hash_base=>$commit),
6973 -title => "blame"}, 'B');
6975 # if this is not a feed of a file history
6976 if (!defined $file_name || $file_name ne $file) {
6977 print $cgi->a({-href => href(-full=>1, action=>"history",
6978 file_name=>$file, hash=>$commit),
6979 -title => "history"}, 'H');
6981 $file = esc_path($file);
6982 print "] ".
6983 "$file</li>\n";
6985 if ($format eq 'rss') {
6986 print "</ul>]]>\n" .
6987 "</content:encoded>\n" .
6988 "</item>\n";
6989 } elsif ($format eq 'atom') {
6990 print "</ul>\n</div>\n" .
6991 "</content>\n" .
6992 "</entry>\n";
6996 # end of feed
6997 if ($format eq 'rss') {
6998 print "</channel>\n</rss>\n";
6999 } elsif ($format eq 'atom') {
7000 print "</feed>\n";
7004 sub git_rss {
7005 git_feed('rss');
7008 sub git_atom {
7009 git_feed('atom');
7012 sub git_opml {
7013 my @list = git_get_projects_list();
7015 print $cgi->header(
7016 -type => 'text/xml',
7017 -charset => 'utf-8',
7018 -content_disposition => 'inline; filename="opml.xml"');
7020 print <<XML;
7021 <?xml version="1.0" encoding="utf-8"?>
7022 <opml version="1.0">
7023 <head>
7024 <title>$site_name OPML Export</title>
7025 </head>
7026 <body>
7027 <outline text="git RSS feeds">
7030 foreach my $pr (@list) {
7031 my %proj = %$pr;
7032 my $head = git_get_head_hash($proj{'path'});
7033 if (!defined $head) {
7034 next;
7036 $git_dir = "$projectroot/$proj{'path'}";
7037 my %co = parse_commit($head);
7038 if (!%co) {
7039 next;
7042 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7043 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7044 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7045 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7047 print <<XML;
7048 </outline>
7049 </body>
7050 </opml>