gitweb: Allow line number toggling with Javascript
[git/mingw/4msysgit.git] / gitweb / gitweb.perl
blob7e6cff04482e930b1e0127078143bbe77e366352
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 strict;
11 use warnings;
12 use CGI qw(:standard :escapeHTML -nosticky);
13 use CGI::Util qw(unescape);
14 use CGI::Carp qw(fatalsToBrowser set_message);
15 use Encode;
16 use Fcntl ':mode';
17 use File::Find qw();
18 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
21 our $t0;
22 if (eval { require Time::HiRes; 1; }) {
23 $t0 = [Time::HiRes::gettimeofday()];
25 our $number_of_git_cmds = 0;
27 BEGIN {
28 CGI->compile() if $ENV{'MOD_PERL'};
31 our $version = "++GIT_VERSION++";
33 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
34 sub evaluate_uri {
35 our $cgi;
37 our $my_url = $cgi->url();
38 our $my_uri = $cgi->url(-absolute => 1);
40 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
41 # needed and used only for URLs with nonempty PATH_INFO
42 our $base_url = $my_url;
44 # When the script is used as DirectoryIndex, the URL does not contain the name
45 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
46 # have to do it ourselves. We make $path_info global because it's also used
47 # later on.
49 # Another issue with the script being the DirectoryIndex is that the resulting
50 # $my_url data is not the full script URL: this is good, because we want
51 # generated links to keep implying the script name if it wasn't explicitly
52 # indicated in the URL we're handling, but it means that $my_url cannot be used
53 # as base URL.
54 # Therefore, if we needed to strip PATH_INFO, then we know that we have
55 # to build the base URL ourselves:
56 our $path_info = $ENV{"PATH_INFO"};
57 if ($path_info) {
58 if ($my_url =~ s,\Q$path_info\E$,, &&
59 $my_uri =~ s,\Q$path_info\E$,, &&
60 defined $ENV{'SCRIPT_NAME'}) {
61 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
65 # target of the home link on top of all pages
66 our $home_link = $my_uri || "/";
69 # core git executable to use
70 # this can just be "git" if your webserver has a sensible PATH
71 our $GIT = "++GIT_BINDIR++/git";
73 # absolute fs-path which will be prepended to the project path
74 #our $projectroot = "/pub/scm";
75 our $projectroot = "++GITWEB_PROJECTROOT++";
77 # fs traversing limit for getting project list
78 # the number is relative to the projectroot
79 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
81 # string of the home link on top of all pages
82 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
84 # name of your site or organization to appear in page titles
85 # replace this with something more descriptive for clearer bookmarks
86 our $site_name = "++GITWEB_SITENAME++"
87 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
89 # filename of html text to include at top of each page
90 our $site_header = "++GITWEB_SITE_HEADER++";
91 # html text to include at home page
92 our $home_text = "++GITWEB_HOMETEXT++";
93 # filename of html text to include at bottom of each page
94 our $site_footer = "++GITWEB_SITE_FOOTER++";
96 # URI of stylesheets
97 our @stylesheets = ("++GITWEB_CSS++");
98 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
99 our $stylesheet = undef;
100 # URI of GIT logo (72x27 size)
101 our $logo = "++GITWEB_LOGO++";
102 # URI of GIT favicon, assumed to be image/png type
103 our $favicon = "++GITWEB_FAVICON++";
104 # URI of gitweb.js (JavaScript code for gitweb)
105 our $javascript = "++GITWEB_JS++";
107 # URI and label (title) of GIT logo link
108 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
109 #our $logo_label = "git documentation";
110 our $logo_url = "http://git-scm.com/";
111 our $logo_label = "git homepage";
113 # source of projects list
114 our $projects_list = "++GITWEB_LIST++";
116 # the width (in characters) of the projects list "Description" column
117 our $projects_list_description_width = 25;
119 # default order of projects list
120 # valid values are none, project, descr, owner, and age
121 our $default_projects_order = "project";
123 # show repository only if this file exists
124 # (only effective if this variable evaluates to true)
125 our $export_ok = "++GITWEB_EXPORT_OK++";
127 # show repository only if this subroutine returns true
128 # when given the path to the project, for example:
129 # sub { return -e "$_[0]/git-daemon-export-ok"; }
130 our $export_auth_hook = undef;
132 # only allow viewing of repositories also shown on the overview page
133 our $strict_export = "++GITWEB_STRICT_EXPORT++";
135 # list of git base URLs used for URL to where fetch project from,
136 # i.e. full URL is "$git_base_url/$project"
137 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
139 # default blob_plain mimetype and default charset for text/plain blob
140 our $default_blob_plain_mimetype = 'text/plain';
141 our $default_text_plain_charset = undef;
143 # file to use for guessing MIME types before trying /etc/mime.types
144 # (relative to the current git repository)
145 our $mimetypes_file = undef;
147 # assume this charset if line contains non-UTF-8 characters;
148 # it should be valid encoding (see Encoding::Supported(3pm) for list),
149 # for which encoding all byte sequences are valid, for example
150 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
151 # could be even 'utf-8' for the old behavior)
152 our $fallback_encoding = 'latin1';
154 # rename detection options for git-diff and git-diff-tree
155 # - default is '-M', with the cost proportional to
156 # (number of removed files) * (number of new files).
157 # - more costly is '-C' (which implies '-M'), with the cost proportional to
158 # (number of changed files + number of removed files) * (number of new files)
159 # - even more costly is '-C', '--find-copies-harder' with cost
160 # (number of files in the original tree) * (number of new files)
161 # - one might want to include '-B' option, e.g. '-B', '-M'
162 our @diff_opts = ('-M'); # taken from git_commit
164 # Disables features that would allow repository owners to inject script into
165 # the gitweb domain.
166 our $prevent_xss = 0;
168 # information about snapshot formats that gitweb is capable of serving
169 our %known_snapshot_formats = (
170 # name => {
171 # 'display' => display name,
172 # 'type' => mime type,
173 # 'suffix' => filename suffix,
174 # 'format' => --format for git-archive,
175 # 'compressor' => [compressor command and arguments]
176 # (array reference, optional)
177 # 'disabled' => boolean (optional)}
179 'tgz' => {
180 'display' => 'tar.gz',
181 'type' => 'application/x-gzip',
182 'suffix' => '.tar.gz',
183 'format' => 'tar',
184 'compressor' => ['gzip']},
186 'tbz2' => {
187 'display' => 'tar.bz2',
188 'type' => 'application/x-bzip2',
189 'suffix' => '.tar.bz2',
190 'format' => 'tar',
191 'compressor' => ['bzip2']},
193 'txz' => {
194 'display' => 'tar.xz',
195 'type' => 'application/x-xz',
196 'suffix' => '.tar.xz',
197 'format' => 'tar',
198 'compressor' => ['xz'],
199 'disabled' => 1},
201 'zip' => {
202 'display' => 'zip',
203 'type' => 'application/x-zip',
204 'suffix' => '.zip',
205 'format' => 'zip'},
208 # Aliases so we understand old gitweb.snapshot values in repository
209 # configuration.
210 our %known_snapshot_format_aliases = (
211 'gzip' => 'tgz',
212 'bzip2' => 'tbz2',
213 'xz' => 'txz',
215 # backward compatibility: legacy gitweb config support
216 'x-gzip' => undef, 'gz' => undef,
217 'x-bzip2' => undef, 'bz2' => undef,
218 'x-zip' => undef, '' => undef,
221 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
222 # are changed, it may be appropriate to change these values too via
223 # $GITWEB_CONFIG.
224 our %avatar_size = (
225 'default' => 16,
226 'double' => 32
229 # Used to set the maximum load that we will still respond to gitweb queries.
230 # If server load exceed this value then return "503 server busy" error.
231 # If gitweb cannot determined server load, it is taken to be 0.
232 # Leave it undefined (or set to 'undef') to turn off load checking.
233 our $maxload = 300;
235 # configuration for 'highlight' (http://www.andre-simon.de/)
236 # match by basename
237 our %highlight_basename = (
238 #'Program' => 'py',
239 #'Library' => 'py',
240 'SConstruct' => 'py', # SCons equivalent of Makefile
241 'Makefile' => 'make',
243 # match by extension
244 our %highlight_ext = (
245 # main extensions, defining name of syntax;
246 # see files in /usr/share/highlight/langDefs/ directory
247 map { $_ => $_ }
248 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl),
249 # alternate extensions, see /etc/highlight/filetypes.conf
250 'h' => 'c',
251 map { $_ => 'cpp' } qw(cxx c++ cc),
252 map { $_ => 'php' } qw(php3 php4),
253 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
254 'mak' => 'make',
255 map { $_ => 'xml' } qw(xhtml html htm),
258 # You define site-wide feature defaults here; override them with
259 # $GITWEB_CONFIG as necessary.
260 our %feature = (
261 # feature => {
262 # 'sub' => feature-sub (subroutine),
263 # 'override' => allow-override (boolean),
264 # 'default' => [ default options...] (array reference)}
266 # if feature is overridable (it means that allow-override has true value),
267 # then feature-sub will be called with default options as parameters;
268 # return value of feature-sub indicates if to enable specified feature
270 # if there is no 'sub' key (no feature-sub), then feature cannot be
271 # overridden
273 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
274 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
275 # is enabled
277 # Enable the 'blame' blob view, showing the last commit that modified
278 # each line in the file. This can be very CPU-intensive.
280 # To enable system wide have in $GITWEB_CONFIG
281 # $feature{'blame'}{'default'} = [1];
282 # To have project specific config enable override in $GITWEB_CONFIG
283 # $feature{'blame'}{'override'} = 1;
284 # and in project config gitweb.blame = 0|1;
285 'blame' => {
286 'sub' => sub { feature_bool('blame', @_) },
287 'override' => 0,
288 'default' => [0]},
290 # Enable the 'snapshot' link, providing a compressed archive of any
291 # tree. This can potentially generate high traffic if you have large
292 # project.
294 # Value is a list of formats defined in %known_snapshot_formats that
295 # you wish to offer.
296 # To disable system wide have in $GITWEB_CONFIG
297 # $feature{'snapshot'}{'default'} = [];
298 # To have project specific config enable override in $GITWEB_CONFIG
299 # $feature{'snapshot'}{'override'} = 1;
300 # and in project config, a comma-separated list of formats or "none"
301 # to disable. Example: gitweb.snapshot = tbz2,zip;
302 'snapshot' => {
303 'sub' => \&feature_snapshot,
304 'override' => 0,
305 'default' => ['tgz']},
307 # Enable text search, which will list the commits which match author,
308 # committer or commit text to a given string. Enabled by default.
309 # Project specific override is not supported.
310 'search' => {
311 'override' => 0,
312 'default' => [1]},
314 # Enable grep search, which will list the files in currently selected
315 # tree containing the given string. Enabled by default. This can be
316 # potentially CPU-intensive, of course.
318 # To enable system wide have in $GITWEB_CONFIG
319 # $feature{'grep'}{'default'} = [1];
320 # To have project specific config enable override in $GITWEB_CONFIG
321 # $feature{'grep'}{'override'} = 1;
322 # and in project config gitweb.grep = 0|1;
323 'grep' => {
324 'sub' => sub { feature_bool('grep', @_) },
325 'override' => 0,
326 'default' => [1]},
328 # Enable the pickaxe search, which will list the commits that modified
329 # a given string in a file. This can be practical and quite faster
330 # alternative to 'blame', but still potentially CPU-intensive.
332 # To enable system wide have in $GITWEB_CONFIG
333 # $feature{'pickaxe'}{'default'} = [1];
334 # To have project specific config enable override in $GITWEB_CONFIG
335 # $feature{'pickaxe'}{'override'} = 1;
336 # and in project config gitweb.pickaxe = 0|1;
337 'pickaxe' => {
338 'sub' => sub { feature_bool('pickaxe', @_) },
339 'override' => 0,
340 'default' => [1]},
342 # Enable showing size of blobs in a 'tree' view, in a separate
343 # column, similar to what 'ls -l' does. This cost a bit of IO.
345 # To disable system wide have in $GITWEB_CONFIG
346 # $feature{'show-sizes'}{'default'} = [0];
347 # To have project specific config enable override in $GITWEB_CONFIG
348 # $feature{'show-sizes'}{'override'} = 1;
349 # and in project config gitweb.showsizes = 0|1;
350 'show-sizes' => {
351 'sub' => sub { feature_bool('showsizes', @_) },
352 'override' => 0,
353 'default' => [1]},
355 # Make gitweb use an alternative format of the URLs which can be
356 # more readable and natural-looking: project name is embedded
357 # directly in the path and the query string contains other
358 # auxiliary information. All gitweb installations recognize
359 # URL in either format; this configures in which formats gitweb
360 # generates links.
362 # To enable system wide have in $GITWEB_CONFIG
363 # $feature{'pathinfo'}{'default'} = [1];
364 # Project specific override is not supported.
366 # Note that you will need to change the default location of CSS,
367 # favicon, logo and possibly other files to an absolute URL. Also,
368 # if gitweb.cgi serves as your indexfile, you will need to force
369 # $my_uri to contain the script name in your $GITWEB_CONFIG.
370 'pathinfo' => {
371 'override' => 0,
372 'default' => [0]},
374 # Make gitweb consider projects in project root subdirectories
375 # to be forks of existing projects. Given project $projname.git,
376 # projects matching $projname/*.git will not be shown in the main
377 # projects list, instead a '+' mark will be added to $projname
378 # there and a 'forks' view will be enabled for the project, listing
379 # all the forks. If project list is taken from a file, forks have
380 # to be listed after the main project.
382 # To enable system wide have in $GITWEB_CONFIG
383 # $feature{'forks'}{'default'} = [1];
384 # Project specific override is not supported.
385 'forks' => {
386 'override' => 0,
387 'default' => [0]},
389 # Insert custom links to the action bar of all project pages.
390 # This enables you mainly to link to third-party scripts integrating
391 # into gitweb; e.g. git-browser for graphical history representation
392 # or custom web-based repository administration interface.
394 # The 'default' value consists of a list of triplets in the form
395 # (label, link, position) where position is the label after which
396 # to insert the link and link is a format string where %n expands
397 # to the project name, %f to the project path within the filesystem,
398 # %h to the current hash (h gitweb parameter) and %b to the current
399 # hash base (hb gitweb parameter); %% expands to %.
401 # To enable system wide have in $GITWEB_CONFIG e.g.
402 # $feature{'actions'}{'default'} = [('graphiclog',
403 # '/git-browser/by-commit.html?r=%n', 'summary')];
404 # Project specific override is not supported.
405 'actions' => {
406 'override' => 0,
407 'default' => []},
409 # Allow gitweb scan project content tags described in ctags/
410 # of project repository, and display the popular Web 2.0-ish
411 # "tag cloud" near the project list. Note that this is something
412 # COMPLETELY different from the normal Git tags.
414 # gitweb by itself can show existing tags, but it does not handle
415 # tagging itself; you need an external application for that.
416 # For an example script, check Girocco's cgi/tagproj.cgi.
417 # You may want to install the HTML::TagCloud Perl module to get
418 # a pretty tag cloud instead of just a list of tags.
420 # To enable system wide have in $GITWEB_CONFIG
421 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
422 # Project specific override is not supported.
423 'ctags' => {
424 'override' => 0,
425 'default' => [0]},
427 # The maximum number of patches in a patchset generated in patch
428 # view. Set this to 0 or undef to disable patch view, or to a
429 # negative number to remove any limit.
431 # To disable system wide have in $GITWEB_CONFIG
432 # $feature{'patches'}{'default'} = [0];
433 # To have project specific config enable override in $GITWEB_CONFIG
434 # $feature{'patches'}{'override'} = 1;
435 # and in project config gitweb.patches = 0|n;
436 # where n is the maximum number of patches allowed in a patchset.
437 'patches' => {
438 'sub' => \&feature_patches,
439 'override' => 0,
440 'default' => [16]},
442 # Avatar support. When this feature is enabled, views such as
443 # shortlog or commit will display an avatar associated with
444 # the email of the committer(s) and/or author(s).
446 # Currently available providers are gravatar and picon.
447 # If an unknown provider is specified, the feature is disabled.
449 # Gravatar depends on Digest::MD5.
450 # Picon currently relies on the indiana.edu database.
452 # To enable system wide have in $GITWEB_CONFIG
453 # $feature{'avatar'}{'default'} = ['<provider>'];
454 # where <provider> is either gravatar or picon.
455 # To have project specific config enable override in $GITWEB_CONFIG
456 # $feature{'avatar'}{'override'} = 1;
457 # and in project config gitweb.avatar = <provider>;
458 'avatar' => {
459 'sub' => \&feature_avatar,
460 'override' => 0,
461 'default' => ['']},
463 # Enable displaying how much time and how many git commands
464 # it took to generate and display page. Disabled by default.
465 # Project specific override is not supported.
466 'timed' => {
467 'override' => 0,
468 'default' => [0]},
470 # Enable turning some links into links to actions which require
471 # JavaScript to run (like 'blame_incremental'). Not enabled by
472 # default. Project specific override is currently not supported.
473 'javascript-actions' => {
474 'override' => 0,
475 'default' => [0]},
477 # Syntax highlighting support. This is based on Daniel Svensson's
478 # and Sham Chukoury's work in gitweb-xmms2.git.
479 # It requires the 'highlight' program present in $PATH,
480 # and therefore is disabled by default.
482 # To enable system wide have in $GITWEB_CONFIG
483 # $feature{'highlight'}{'default'} = [1];
485 'highlight' => {
486 'sub' => sub { feature_bool('highlight', @_) },
487 'override' => 0,
488 'default' => [0]},
491 sub gitweb_get_feature {
492 my ($name) = @_;
493 return unless exists $feature{$name};
494 my ($sub, $override, @defaults) = (
495 $feature{$name}{'sub'},
496 $feature{$name}{'override'},
497 @{$feature{$name}{'default'}});
498 # project specific override is possible only if we have project
499 our $git_dir; # global variable, declared later
500 if (!$override || !defined $git_dir) {
501 return @defaults;
503 if (!defined $sub) {
504 warn "feature $name is not overridable";
505 return @defaults;
507 return $sub->(@defaults);
510 # A wrapper to check if a given feature is enabled.
511 # With this, you can say
513 # my $bool_feat = gitweb_check_feature('bool_feat');
514 # gitweb_check_feature('bool_feat') or somecode;
516 # instead of
518 # my ($bool_feat) = gitweb_get_feature('bool_feat');
519 # (gitweb_get_feature('bool_feat'))[0] or somecode;
521 sub gitweb_check_feature {
522 return (gitweb_get_feature(@_))[0];
526 sub feature_bool {
527 my $key = shift;
528 my ($val) = git_get_project_config($key, '--bool');
530 if (!defined $val) {
531 return ($_[0]);
532 } elsif ($val eq 'true') {
533 return (1);
534 } elsif ($val eq 'false') {
535 return (0);
539 sub feature_snapshot {
540 my (@fmts) = @_;
542 my ($val) = git_get_project_config('snapshot');
544 if ($val) {
545 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
548 return @fmts;
551 sub feature_patches {
552 my @val = (git_get_project_config('patches', '--int'));
554 if (@val) {
555 return @val;
558 return ($_[0]);
561 sub feature_avatar {
562 my @val = (git_get_project_config('avatar'));
564 return @val ? @val : @_;
567 # checking HEAD file with -e is fragile if the repository was
568 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
569 # and then pruned.
570 sub check_head_link {
571 my ($dir) = @_;
572 my $headfile = "$dir/HEAD";
573 return ((-e $headfile) ||
574 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
577 sub check_export_ok {
578 my ($dir) = @_;
579 return (check_head_link($dir) &&
580 (!$export_ok || -e "$dir/$export_ok") &&
581 (!$export_auth_hook || $export_auth_hook->($dir)));
584 # process alternate names for backward compatibility
585 # filter out unsupported (unknown) snapshot formats
586 sub filter_snapshot_fmts {
587 my @fmts = @_;
589 @fmts = map {
590 exists $known_snapshot_format_aliases{$_} ?
591 $known_snapshot_format_aliases{$_} : $_} @fmts;
592 @fmts = grep {
593 exists $known_snapshot_formats{$_} &&
594 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
597 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
598 sub evaluate_gitweb_config {
599 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
600 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
601 # die if there are errors parsing config file
602 if (-e $GITWEB_CONFIG) {
603 do $GITWEB_CONFIG;
604 die $@ if $@;
605 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
606 do $GITWEB_CONFIG_SYSTEM;
607 die $@ if $@;
611 # Get loadavg of system, to compare against $maxload.
612 # Currently it requires '/proc/loadavg' present to get loadavg;
613 # if it is not present it returns 0, which means no load checking.
614 sub get_loadavg {
615 if( -e '/proc/loadavg' ){
616 open my $fd, '<', '/proc/loadavg'
617 or return 0;
618 my @load = split(/\s+/, scalar <$fd>);
619 close $fd;
621 # The first three columns measure CPU and IO utilization of the last one,
622 # five, and 10 minute periods. The fourth column shows the number of
623 # currently running processes and the total number of processes in the m/n
624 # format. The last column displays the last process ID used.
625 return $load[0] || 0;
627 # additional checks for load average should go here for things that don't export
628 # /proc/loadavg
630 return 0;
633 # version of the core git binary
634 our $git_version;
635 sub evaluate_git_version {
636 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
637 $number_of_git_cmds++;
640 sub check_loadavg {
641 if (defined $maxload && get_loadavg() > $maxload) {
642 die_error(503, "The load average on the server is too high");
646 # ======================================================================
647 # input validation and dispatch
649 # input parameters can be collected from a variety of sources (presently, CGI
650 # and PATH_INFO), so we define an %input_params hash that collects them all
651 # together during validation: this allows subsequent uses (e.g. href()) to be
652 # agnostic of the parameter origin
654 our %input_params = ();
656 # input parameters are stored with the long parameter name as key. This will
657 # also be used in the href subroutine to convert parameters to their CGI
658 # equivalent, and since the href() usage is the most frequent one, we store
659 # the name -> CGI key mapping here, instead of the reverse.
661 # XXX: Warning: If you touch this, check the search form for updating,
662 # too.
664 our @cgi_param_mapping = (
665 project => "p",
666 action => "a",
667 file_name => "f",
668 file_parent => "fp",
669 hash => "h",
670 hash_parent => "hp",
671 hash_base => "hb",
672 hash_parent_base => "hpb",
673 page => "pg",
674 order => "o",
675 searchtext => "s",
676 searchtype => "st",
677 snapshot_format => "sf",
678 extra_options => "opt",
679 search_use_regexp => "sr",
680 # this must be last entry (for manipulation from JavaScript)
681 javascript => "js"
683 our %cgi_param_mapping = @cgi_param_mapping;
685 # we will also need to know the possible actions, for validation
686 our %actions = (
687 "blame" => \&git_blame,
688 "blame_incremental" => \&git_blame_incremental,
689 "blame_data" => \&git_blame_data,
690 "blobdiff" => \&git_blobdiff,
691 "blobdiff_plain" => \&git_blobdiff_plain,
692 "blob" => \&git_blob,
693 "blob_plain" => \&git_blob_plain,
694 "commitdiff" => \&git_commitdiff,
695 "commitdiff_plain" => \&git_commitdiff_plain,
696 "commit" => \&git_commit,
697 "forks" => \&git_forks,
698 "heads" => \&git_heads,
699 "history" => \&git_history,
700 "log" => \&git_log,
701 "patch" => \&git_patch,
702 "patches" => \&git_patches,
703 "rss" => \&git_rss,
704 "atom" => \&git_atom,
705 "search" => \&git_search,
706 "search_help" => \&git_search_help,
707 "shortlog" => \&git_shortlog,
708 "summary" => \&git_summary,
709 "tag" => \&git_tag,
710 "tags" => \&git_tags,
711 "tree" => \&git_tree,
712 "snapshot" => \&git_snapshot,
713 "object" => \&git_object,
714 # those below don't need $project
715 "opml" => \&git_opml,
716 "project_list" => \&git_project_list,
717 "project_index" => \&git_project_index,
720 # finally, we have the hash of allowed extra_options for the commands that
721 # allow them
722 our %allowed_options = (
723 "--no-merges" => [ qw(rss atom log shortlog history) ],
726 # fill %input_params with the CGI parameters. All values except for 'opt'
727 # should be single values, but opt can be an array. We should probably
728 # build an array of parameters that can be multi-valued, but since for the time
729 # being it's only this one, we just single it out
730 sub evaluate_query_params {
731 our $cgi;
733 while (my ($name, $symbol) = each %cgi_param_mapping) {
734 if ($symbol eq 'opt') {
735 $input_params{$name} = [ $cgi->param($symbol) ];
736 } else {
737 $input_params{$name} = $cgi->param($symbol);
742 # now read PATH_INFO and update the parameter list for missing parameters
743 sub evaluate_path_info {
744 return if defined $input_params{'project'};
745 return if !$path_info;
746 $path_info =~ s,^/+,,;
747 return if !$path_info;
749 # find which part of PATH_INFO is project
750 my $project = $path_info;
751 $project =~ s,/+$,,;
752 while ($project && !check_head_link("$projectroot/$project")) {
753 $project =~ s,/*[^/]*$,,;
755 return unless $project;
756 $input_params{'project'} = $project;
758 # do not change any parameters if an action is given using the query string
759 return if $input_params{'action'};
760 $path_info =~ s,^\Q$project\E/*,,;
762 # next, check if we have an action
763 my $action = $path_info;
764 $action =~ s,/.*$,,;
765 if (exists $actions{$action}) {
766 $path_info =~ s,^$action/*,,;
767 $input_params{'action'} = $action;
770 # list of actions that want hash_base instead of hash, but can have no
771 # pathname (f) parameter
772 my @wants_base = (
773 'tree',
774 'history',
777 # we want to catch
778 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
779 my ($parentrefname, $parentpathname, $refname, $pathname) =
780 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
782 # first, analyze the 'current' part
783 if (defined $pathname) {
784 # we got "branch:filename" or "branch:dir/"
785 # we could use git_get_type(branch:pathname), but:
786 # - it needs $git_dir
787 # - it does a git() call
788 # - the convention of terminating directories with a slash
789 # makes it superfluous
790 # - embedding the action in the PATH_INFO would make it even
791 # more superfluous
792 $pathname =~ s,^/+,,;
793 if (!$pathname || substr($pathname, -1) eq "/") {
794 $input_params{'action'} ||= "tree";
795 $pathname =~ s,/$,,;
796 } else {
797 # the default action depends on whether we had parent info
798 # or not
799 if ($parentrefname) {
800 $input_params{'action'} ||= "blobdiff_plain";
801 } else {
802 $input_params{'action'} ||= "blob_plain";
805 $input_params{'hash_base'} ||= $refname;
806 $input_params{'file_name'} ||= $pathname;
807 } elsif (defined $refname) {
808 # we got "branch". In this case we have to choose if we have to
809 # set hash or hash_base.
811 # Most of the actions without a pathname only want hash to be
812 # set, except for the ones specified in @wants_base that want
813 # hash_base instead. It should also be noted that hand-crafted
814 # links having 'history' as an action and no pathname or hash
815 # set will fail, but that happens regardless of PATH_INFO.
816 $input_params{'action'} ||= "shortlog";
817 if (grep { $_ eq $input_params{'action'} } @wants_base) {
818 $input_params{'hash_base'} ||= $refname;
819 } else {
820 $input_params{'hash'} ||= $refname;
824 # next, handle the 'parent' part, if present
825 if (defined $parentrefname) {
826 # a missing pathspec defaults to the 'current' filename, allowing e.g.
827 # someproject/blobdiff/oldrev..newrev:/filename
828 if ($parentpathname) {
829 $parentpathname =~ s,^/+,,;
830 $parentpathname =~ s,/$,,;
831 $input_params{'file_parent'} ||= $parentpathname;
832 } else {
833 $input_params{'file_parent'} ||= $input_params{'file_name'};
835 # we assume that hash_parent_base is wanted if a path was specified,
836 # or if the action wants hash_base instead of hash
837 if (defined $input_params{'file_parent'} ||
838 grep { $_ eq $input_params{'action'} } @wants_base) {
839 $input_params{'hash_parent_base'} ||= $parentrefname;
840 } else {
841 $input_params{'hash_parent'} ||= $parentrefname;
845 # for the snapshot action, we allow URLs in the form
846 # $project/snapshot/$hash.ext
847 # where .ext determines the snapshot and gets removed from the
848 # passed $refname to provide the $hash.
850 # To be able to tell that $refname includes the format extension, we
851 # require the following two conditions to be satisfied:
852 # - the hash input parameter MUST have been set from the $refname part
853 # of the URL (i.e. they must be equal)
854 # - the snapshot format MUST NOT have been defined already (e.g. from
855 # CGI parameter sf)
856 # It's also useless to try any matching unless $refname has a dot,
857 # so we check for that too
858 if (defined $input_params{'action'} &&
859 $input_params{'action'} eq 'snapshot' &&
860 defined $refname && index($refname, '.') != -1 &&
861 $refname eq $input_params{'hash'} &&
862 !defined $input_params{'snapshot_format'}) {
863 # We loop over the known snapshot formats, checking for
864 # extensions. Allowed extensions are both the defined suffix
865 # (which includes the initial dot already) and the snapshot
866 # format key itself, with a prepended dot
867 while (my ($fmt, $opt) = each %known_snapshot_formats) {
868 my $hash = $refname;
869 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
870 next;
872 my $sfx = $1;
873 # a valid suffix was found, so set the snapshot format
874 # and reset the hash parameter
875 $input_params{'snapshot_format'} = $fmt;
876 $input_params{'hash'} = $hash;
877 # we also set the format suffix to the one requested
878 # in the URL: this way a request for e.g. .tgz returns
879 # a .tgz instead of a .tar.gz
880 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
881 last;
886 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
887 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
888 $searchtext, $search_regexp);
889 sub evaluate_and_validate_params {
890 our $action = $input_params{'action'};
891 if (defined $action) {
892 if (!validate_action($action)) {
893 die_error(400, "Invalid action parameter");
897 # parameters which are pathnames
898 our $project = $input_params{'project'};
899 if (defined $project) {
900 if (!validate_project($project)) {
901 undef $project;
902 die_error(404, "No such project");
906 our $file_name = $input_params{'file_name'};
907 if (defined $file_name) {
908 if (!validate_pathname($file_name)) {
909 die_error(400, "Invalid file parameter");
913 our $file_parent = $input_params{'file_parent'};
914 if (defined $file_parent) {
915 if (!validate_pathname($file_parent)) {
916 die_error(400, "Invalid file parent parameter");
920 # parameters which are refnames
921 our $hash = $input_params{'hash'};
922 if (defined $hash) {
923 if (!validate_refname($hash)) {
924 die_error(400, "Invalid hash parameter");
928 our $hash_parent = $input_params{'hash_parent'};
929 if (defined $hash_parent) {
930 if (!validate_refname($hash_parent)) {
931 die_error(400, "Invalid hash parent parameter");
935 our $hash_base = $input_params{'hash_base'};
936 if (defined $hash_base) {
937 if (!validate_refname($hash_base)) {
938 die_error(400, "Invalid hash base parameter");
942 our @extra_options = @{$input_params{'extra_options'}};
943 # @extra_options is always defined, since it can only be (currently) set from
944 # CGI, and $cgi->param() returns the empty array in array context if the param
945 # is not set
946 foreach my $opt (@extra_options) {
947 if (not exists $allowed_options{$opt}) {
948 die_error(400, "Invalid option parameter");
950 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
951 die_error(400, "Invalid option parameter for this action");
955 our $hash_parent_base = $input_params{'hash_parent_base'};
956 if (defined $hash_parent_base) {
957 if (!validate_refname($hash_parent_base)) {
958 die_error(400, "Invalid hash parent base parameter");
962 # other parameters
963 our $page = $input_params{'page'};
964 if (defined $page) {
965 if ($page =~ m/[^0-9]/) {
966 die_error(400, "Invalid page parameter");
970 our $searchtype = $input_params{'searchtype'};
971 if (defined $searchtype) {
972 if ($searchtype =~ m/[^a-z]/) {
973 die_error(400, "Invalid searchtype parameter");
977 our $search_use_regexp = $input_params{'search_use_regexp'};
979 our $searchtext = $input_params{'searchtext'};
980 our $search_regexp;
981 if (defined $searchtext) {
982 if (length($searchtext) < 2) {
983 die_error(403, "At least two characters are required for search parameter");
985 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
989 # path to the current git repository
990 our $git_dir;
991 sub evaluate_git_dir {
992 our $git_dir = "$projectroot/$project" if $project;
995 our (@snapshot_fmts, $git_avatar);
996 sub configure_gitweb_features {
997 # list of supported snapshot formats
998 our @snapshot_fmts = gitweb_get_feature('snapshot');
999 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1001 # check that the avatar feature is set to a known provider name,
1002 # and for each provider check if the dependencies are satisfied.
1003 # if the provider name is invalid or the dependencies are not met,
1004 # reset $git_avatar to the empty string.
1005 our ($git_avatar) = gitweb_get_feature('avatar');
1006 if ($git_avatar eq 'gravatar') {
1007 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1008 } elsif ($git_avatar eq 'picon') {
1009 # no dependencies
1010 } else {
1011 $git_avatar = '';
1015 # custom error handler: 'die <message>' is Internal Server Error
1016 sub handle_errors_html {
1017 my $msg = shift; # it is already HTML escaped
1019 # to avoid infinite loop where error occurs in die_error,
1020 # change handler to default handler, disabling handle_errors_html
1021 set_message("Error occured when inside die_error:\n$msg");
1023 # you cannot jump out of die_error when called as error handler;
1024 # the subroutine set via CGI::Carp::set_message is called _after_
1025 # HTTP headers are already written, so it cannot write them itself
1026 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1028 set_message(\&handle_errors_html);
1030 # dispatch
1031 sub dispatch {
1032 if (!defined $action) {
1033 if (defined $hash) {
1034 $action = git_get_type($hash);
1035 } elsif (defined $hash_base && defined $file_name) {
1036 $action = git_get_type("$hash_base:$file_name");
1037 } elsif (defined $project) {
1038 $action = 'summary';
1039 } else {
1040 $action = 'project_list';
1043 if (!defined($actions{$action})) {
1044 die_error(400, "Unknown action");
1046 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1047 !$project) {
1048 die_error(400, "Project needed");
1050 $actions{$action}->();
1053 sub reset_timer {
1054 our $t0 = [Time::HiRes::gettimeofday()]
1055 if defined $t0;
1056 our $number_of_git_cmds = 0;
1059 sub run_request {
1060 reset_timer();
1062 evaluate_uri();
1063 evaluate_gitweb_config();
1064 check_loadavg();
1066 # $projectroot and $projects_list might be set in gitweb config file
1067 $projects_list ||= $projectroot;
1069 evaluate_query_params();
1070 evaluate_path_info();
1071 evaluate_and_validate_params();
1072 evaluate_git_dir();
1074 configure_gitweb_features();
1076 dispatch();
1079 our $is_last_request = sub { 1 };
1080 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1081 our $CGI = 'CGI';
1082 our $cgi;
1083 sub configure_as_fcgi {
1084 require CGI::Fast;
1085 our $CGI = 'CGI::Fast';
1087 my $request_number = 0;
1088 # let each child service 100 requests
1089 our $is_last_request = sub { ++$request_number > 100 };
1091 sub evaluate_argv {
1092 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1093 configure_as_fcgi()
1094 if $script_name =~ /\.fcgi$/;
1096 return unless (@ARGV);
1098 require Getopt::Long;
1099 Getopt::Long::GetOptions(
1100 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1101 'nproc|n=i' => sub {
1102 my ($arg, $val) = @_;
1103 return unless eval { require FCGI::ProcManager; 1; };
1104 my $proc_manager = FCGI::ProcManager->new({
1105 n_processes => $val,
1107 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1108 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1109 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1114 sub run {
1115 evaluate_argv();
1116 evaluate_git_version();
1118 $pre_listen_hook->()
1119 if $pre_listen_hook;
1121 REQUEST:
1122 while ($cgi = $CGI->new()) {
1123 $pre_dispatch_hook->()
1124 if $pre_dispatch_hook;
1126 run_request();
1128 $post_dispatch_hook->()
1129 if $post_dispatch_hook;
1131 last REQUEST if ($is_last_request->());
1134 DONE_GITWEB:
1138 run();
1140 if (defined caller) {
1141 # wrapped in a subroutine processing requests,
1142 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1143 return;
1144 } else {
1145 # pure CGI script, serving single request
1146 exit;
1149 ## ======================================================================
1150 ## action links
1152 # possible values of extra options
1153 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1154 # -replay => 1 - start from a current view (replay with modifications)
1155 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1156 sub href {
1157 my %params = @_;
1158 # default is to use -absolute url() i.e. $my_uri
1159 my $href = $params{-full} ? $my_url : $my_uri;
1161 $params{'project'} = $project unless exists $params{'project'};
1163 if ($params{-replay}) {
1164 while (my ($name, $symbol) = each %cgi_param_mapping) {
1165 if (!exists $params{$name}) {
1166 $params{$name} = $input_params{$name};
1171 my $use_pathinfo = gitweb_check_feature('pathinfo');
1172 if (defined $params{'project'} &&
1173 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1174 # try to put as many parameters as possible in PATH_INFO:
1175 # - project name
1176 # - action
1177 # - hash_parent or hash_parent_base:/file_parent
1178 # - hash or hash_base:/filename
1179 # - the snapshot_format as an appropriate suffix
1181 # When the script is the root DirectoryIndex for the domain,
1182 # $href here would be something like http://gitweb.example.com/
1183 # Thus, we strip any trailing / from $href, to spare us double
1184 # slashes in the final URL
1185 $href =~ s,/$,,;
1187 # Then add the project name, if present
1188 $href .= "/".esc_url($params{'project'});
1189 delete $params{'project'};
1191 # since we destructively absorb parameters, we keep this
1192 # boolean that remembers if we're handling a snapshot
1193 my $is_snapshot = $params{'action'} eq 'snapshot';
1195 # Summary just uses the project path URL, any other action is
1196 # added to the URL
1197 if (defined $params{'action'}) {
1198 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1199 delete $params{'action'};
1202 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1203 # stripping nonexistent or useless pieces
1204 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1205 || $params{'hash_parent'} || $params{'hash'});
1206 if (defined $params{'hash_base'}) {
1207 if (defined $params{'hash_parent_base'}) {
1208 $href .= esc_url($params{'hash_parent_base'});
1209 # skip the file_parent if it's the same as the file_name
1210 if (defined $params{'file_parent'}) {
1211 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1212 delete $params{'file_parent'};
1213 } elsif ($params{'file_parent'} !~ /\.\./) {
1214 $href .= ":/".esc_url($params{'file_parent'});
1215 delete $params{'file_parent'};
1218 $href .= "..";
1219 delete $params{'hash_parent'};
1220 delete $params{'hash_parent_base'};
1221 } elsif (defined $params{'hash_parent'}) {
1222 $href .= esc_url($params{'hash_parent'}). "..";
1223 delete $params{'hash_parent'};
1226 $href .= esc_url($params{'hash_base'});
1227 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1228 $href .= ":/".esc_url($params{'file_name'});
1229 delete $params{'file_name'};
1231 delete $params{'hash'};
1232 delete $params{'hash_base'};
1233 } elsif (defined $params{'hash'}) {
1234 $href .= esc_url($params{'hash'});
1235 delete $params{'hash'};
1238 # If the action was a snapshot, we can absorb the
1239 # snapshot_format parameter too
1240 if ($is_snapshot) {
1241 my $fmt = $params{'snapshot_format'};
1242 # snapshot_format should always be defined when href()
1243 # is called, but just in case some code forgets, we
1244 # fall back to the default
1245 $fmt ||= $snapshot_fmts[0];
1246 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1247 delete $params{'snapshot_format'};
1251 # now encode the parameters explicitly
1252 my @result = ();
1253 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1254 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1255 if (defined $params{$name}) {
1256 if (ref($params{$name}) eq "ARRAY") {
1257 foreach my $par (@{$params{$name}}) {
1258 push @result, $symbol . "=" . esc_param($par);
1260 } else {
1261 push @result, $symbol . "=" . esc_param($params{$name});
1265 $href .= "?" . join(';', @result) if scalar @result;
1267 return $href;
1271 ## ======================================================================
1272 ## validation, quoting/unquoting and escaping
1274 sub validate_action {
1275 my $input = shift || return undef;
1276 return undef unless exists $actions{$input};
1277 return $input;
1280 sub validate_project {
1281 my $input = shift || return undef;
1282 if (!validate_pathname($input) ||
1283 !(-d "$projectroot/$input") ||
1284 !check_export_ok("$projectroot/$input") ||
1285 ($strict_export && !project_in_list($input))) {
1286 return undef;
1287 } else {
1288 return $input;
1292 sub validate_pathname {
1293 my $input = shift || return undef;
1295 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1296 # at the beginning, at the end, and between slashes.
1297 # also this catches doubled slashes
1298 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1299 return undef;
1301 # no null characters
1302 if ($input =~ m!\0!) {
1303 return undef;
1305 return $input;
1308 sub validate_refname {
1309 my $input = shift || return undef;
1311 # textual hashes are O.K.
1312 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1313 return $input;
1315 # it must be correct pathname
1316 $input = validate_pathname($input)
1317 or return undef;
1318 # restrictions on ref name according to git-check-ref-format
1319 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1320 return undef;
1322 return $input;
1325 # decode sequences of octets in utf8 into Perl's internal form,
1326 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1327 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1328 sub to_utf8 {
1329 my $str = shift;
1330 return undef unless defined $str;
1331 if (utf8::valid($str)) {
1332 utf8::decode($str);
1333 return $str;
1334 } else {
1335 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1339 # quote unsafe chars, but keep the slash, even when it's not
1340 # correct, but quoted slashes look too horrible in bookmarks
1341 sub esc_param {
1342 my $str = shift;
1343 return undef unless defined $str;
1344 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1345 $str =~ s/ /\+/g;
1346 return $str;
1349 # quote unsafe chars in whole URL, so some characters cannot be quoted
1350 sub esc_url {
1351 my $str = shift;
1352 return undef unless defined $str;
1353 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1354 $str =~ s/ /\+/g;
1355 return $str;
1358 # replace invalid utf8 character with SUBSTITUTION sequence
1359 sub esc_html {
1360 my $str = shift;
1361 my %opts = @_;
1363 return undef unless defined $str;
1365 $str = to_utf8($str);
1366 $str = $cgi->escapeHTML($str);
1367 if ($opts{'-nbsp'}) {
1368 $str =~ s/ /&nbsp;/g;
1370 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1371 return $str;
1374 # quote control characters and escape filename to HTML
1375 sub esc_path {
1376 my $str = shift;
1377 my %opts = @_;
1379 return undef unless defined $str;
1381 $str = to_utf8($str);
1382 $str = $cgi->escapeHTML($str);
1383 if ($opts{'-nbsp'}) {
1384 $str =~ s/ /&nbsp;/g;
1386 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1387 return $str;
1390 # Make control characters "printable", using character escape codes (CEC)
1391 sub quot_cec {
1392 my $cntrl = shift;
1393 my %opts = @_;
1394 my %es = ( # character escape codes, aka escape sequences
1395 "\t" => '\t', # tab (HT)
1396 "\n" => '\n', # line feed (LF)
1397 "\r" => '\r', # carrige return (CR)
1398 "\f" => '\f', # form feed (FF)
1399 "\b" => '\b', # backspace (BS)
1400 "\a" => '\a', # alarm (bell) (BEL)
1401 "\e" => '\e', # escape (ESC)
1402 "\013" => '\v', # vertical tab (VT)
1403 "\000" => '\0', # nul character (NUL)
1405 my $chr = ( (exists $es{$cntrl})
1406 ? $es{$cntrl}
1407 : sprintf('\%2x', ord($cntrl)) );
1408 if ($opts{-nohtml}) {
1409 return $chr;
1410 } else {
1411 return "<span class=\"cntrl\">$chr</span>";
1415 # Alternatively use unicode control pictures codepoints,
1416 # Unicode "printable representation" (PR)
1417 sub quot_upr {
1418 my $cntrl = shift;
1419 my %opts = @_;
1421 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1422 if ($opts{-nohtml}) {
1423 return $chr;
1424 } else {
1425 return "<span class=\"cntrl\">$chr</span>";
1429 # git may return quoted and escaped filenames
1430 sub unquote {
1431 my $str = shift;
1433 sub unq {
1434 my $seq = shift;
1435 my %es = ( # character escape codes, aka escape sequences
1436 't' => "\t", # tab (HT, TAB)
1437 'n' => "\n", # newline (NL)
1438 'r' => "\r", # return (CR)
1439 'f' => "\f", # form feed (FF)
1440 'b' => "\b", # backspace (BS)
1441 'a' => "\a", # alarm (bell) (BEL)
1442 'e' => "\e", # escape (ESC)
1443 'v' => "\013", # vertical tab (VT)
1446 if ($seq =~ m/^[0-7]{1,3}$/) {
1447 # octal char sequence
1448 return chr(oct($seq));
1449 } elsif (exists $es{$seq}) {
1450 # C escape sequence, aka character escape code
1451 return $es{$seq};
1453 # quoted ordinary character
1454 return $seq;
1457 if ($str =~ m/^"(.*)"$/) {
1458 # needs unquoting
1459 $str = $1;
1460 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1462 return $str;
1465 # escape tabs (convert tabs to spaces)
1466 sub untabify {
1467 my $line = shift;
1469 while ((my $pos = index($line, "\t")) != -1) {
1470 if (my $count = (8 - ($pos % 8))) {
1471 my $spaces = ' ' x $count;
1472 $line =~ s/\t/$spaces/;
1476 return $line;
1479 sub project_in_list {
1480 my $project = shift;
1481 my @list = git_get_projects_list();
1482 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1485 ## ----------------------------------------------------------------------
1486 ## HTML aware string manipulation
1488 # Try to chop given string on a word boundary between position
1489 # $len and $len+$add_len. If there is no word boundary there,
1490 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1491 # (marking chopped part) would be longer than given string.
1492 sub chop_str {
1493 my $str = shift;
1494 my $len = shift;
1495 my $add_len = shift || 10;
1496 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1498 # Make sure perl knows it is utf8 encoded so we don't
1499 # cut in the middle of a utf8 multibyte char.
1500 $str = to_utf8($str);
1502 # allow only $len chars, but don't cut a word if it would fit in $add_len
1503 # if it doesn't fit, cut it if it's still longer than the dots we would add
1504 # remove chopped character entities entirely
1506 # when chopping in the middle, distribute $len into left and right part
1507 # return early if chopping wouldn't make string shorter
1508 if ($where eq 'center') {
1509 return $str if ($len + 5 >= length($str)); # filler is length 5
1510 $len = int($len/2);
1511 } else {
1512 return $str if ($len + 4 >= length($str)); # filler is length 4
1515 # regexps: ending and beginning with word part up to $add_len
1516 my $endre = qr/.{$len}\w{0,$add_len}/;
1517 my $begre = qr/\w{0,$add_len}.{$len}/;
1519 if ($where eq 'left') {
1520 $str =~ m/^(.*?)($begre)$/;
1521 my ($lead, $body) = ($1, $2);
1522 if (length($lead) > 4) {
1523 $lead = " ...";
1525 return "$lead$body";
1527 } elsif ($where eq 'center') {
1528 $str =~ m/^($endre)(.*)$/;
1529 my ($left, $str) = ($1, $2);
1530 $str =~ m/^(.*?)($begre)$/;
1531 my ($mid, $right) = ($1, $2);
1532 if (length($mid) > 5) {
1533 $mid = " ... ";
1535 return "$left$mid$right";
1537 } else {
1538 $str =~ m/^($endre)(.*)$/;
1539 my $body = $1;
1540 my $tail = $2;
1541 if (length($tail) > 4) {
1542 $tail = "... ";
1544 return "$body$tail";
1548 # takes the same arguments as chop_str, but also wraps a <span> around the
1549 # result with a title attribute if it does get chopped. Additionally, the
1550 # string is HTML-escaped.
1551 sub chop_and_escape_str {
1552 my ($str) = @_;
1554 my $chopped = chop_str(@_);
1555 if ($chopped eq $str) {
1556 return esc_html($chopped);
1557 } else {
1558 $str =~ s/[[:cntrl:]]/?/g;
1559 return $cgi->span({-title=>$str}, esc_html($chopped));
1563 ## ----------------------------------------------------------------------
1564 ## functions returning short strings
1566 # CSS class for given age value (in seconds)
1567 sub age_class {
1568 my $age = shift;
1570 if (!defined $age) {
1571 return "noage";
1572 } elsif ($age < 60*60*2) {
1573 return "age0";
1574 } elsif ($age < 60*60*24*2) {
1575 return "age1";
1576 } else {
1577 return "age2";
1581 # convert age in seconds to "nn units ago" string
1582 sub age_string {
1583 my $age = shift;
1584 my $age_str;
1586 if ($age > 60*60*24*365*2) {
1587 $age_str = (int $age/60/60/24/365);
1588 $age_str .= " years ago";
1589 } elsif ($age > 60*60*24*(365/12)*2) {
1590 $age_str = int $age/60/60/24/(365/12);
1591 $age_str .= " months ago";
1592 } elsif ($age > 60*60*24*7*2) {
1593 $age_str = int $age/60/60/24/7;
1594 $age_str .= " weeks ago";
1595 } elsif ($age > 60*60*24*2) {
1596 $age_str = int $age/60/60/24;
1597 $age_str .= " days ago";
1598 } elsif ($age > 60*60*2) {
1599 $age_str = int $age/60/60;
1600 $age_str .= " hours ago";
1601 } elsif ($age > 60*2) {
1602 $age_str = int $age/60;
1603 $age_str .= " min ago";
1604 } elsif ($age > 2) {
1605 $age_str = int $age;
1606 $age_str .= " sec ago";
1607 } else {
1608 $age_str .= " right now";
1610 return $age_str;
1613 use constant {
1614 S_IFINVALID => 0030000,
1615 S_IFGITLINK => 0160000,
1618 # submodule/subproject, a commit object reference
1619 sub S_ISGITLINK {
1620 my $mode = shift;
1622 return (($mode & S_IFMT) == S_IFGITLINK)
1625 # convert file mode in octal to symbolic file mode string
1626 sub mode_str {
1627 my $mode = oct shift;
1629 if (S_ISGITLINK($mode)) {
1630 return 'm---------';
1631 } elsif (S_ISDIR($mode & S_IFMT)) {
1632 return 'drwxr-xr-x';
1633 } elsif (S_ISLNK($mode)) {
1634 return 'lrwxrwxrwx';
1635 } elsif (S_ISREG($mode)) {
1636 # git cares only about the executable bit
1637 if ($mode & S_IXUSR) {
1638 return '-rwxr-xr-x';
1639 } else {
1640 return '-rw-r--r--';
1642 } else {
1643 return '----------';
1647 # convert file mode in octal to file type string
1648 sub file_type {
1649 my $mode = shift;
1651 if ($mode !~ m/^[0-7]+$/) {
1652 return $mode;
1653 } else {
1654 $mode = oct $mode;
1657 if (S_ISGITLINK($mode)) {
1658 return "submodule";
1659 } elsif (S_ISDIR($mode & S_IFMT)) {
1660 return "directory";
1661 } elsif (S_ISLNK($mode)) {
1662 return "symlink";
1663 } elsif (S_ISREG($mode)) {
1664 return "file";
1665 } else {
1666 return "unknown";
1670 # convert file mode in octal to file type description string
1671 sub file_type_long {
1672 my $mode = shift;
1674 if ($mode !~ m/^[0-7]+$/) {
1675 return $mode;
1676 } else {
1677 $mode = oct $mode;
1680 if (S_ISGITLINK($mode)) {
1681 return "submodule";
1682 } elsif (S_ISDIR($mode & S_IFMT)) {
1683 return "directory";
1684 } elsif (S_ISLNK($mode)) {
1685 return "symlink";
1686 } elsif (S_ISREG($mode)) {
1687 if ($mode & S_IXUSR) {
1688 return "executable";
1689 } else {
1690 return "file";
1692 } else {
1693 return "unknown";
1698 ## ----------------------------------------------------------------------
1699 ## functions returning short HTML fragments, or transforming HTML fragments
1700 ## which don't belong to other sections
1702 # format line of commit message.
1703 sub format_log_line_html {
1704 my $line = shift;
1706 $line = esc_html($line, -nbsp=>1);
1707 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1708 $cgi->a({-href => href(action=>"object", hash=>$1),
1709 -class => "text"}, $1);
1710 }eg;
1712 return $line;
1715 # format marker of refs pointing to given object
1717 # the destination action is chosen based on object type and current context:
1718 # - for annotated tags, we choose the tag view unless it's the current view
1719 # already, in which case we go to shortlog view
1720 # - for other refs, we keep the current view if we're in history, shortlog or
1721 # log view, and select shortlog otherwise
1722 sub format_ref_marker {
1723 my ($refs, $id) = @_;
1724 my $markers = '';
1726 if (defined $refs->{$id}) {
1727 foreach my $ref (@{$refs->{$id}}) {
1728 # this code exploits the fact that non-lightweight tags are the
1729 # only indirect objects, and that they are the only objects for which
1730 # we want to use tag instead of shortlog as action
1731 my ($type, $name) = qw();
1732 my $indirect = ($ref =~ s/\^\{\}$//);
1733 # e.g. tags/v2.6.11 or heads/next
1734 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1735 $type = $1;
1736 $name = $2;
1737 } else {
1738 $type = "ref";
1739 $name = $ref;
1742 my $class = $type;
1743 $class .= " indirect" if $indirect;
1745 my $dest_action = "shortlog";
1747 if ($indirect) {
1748 $dest_action = "tag" unless $action eq "tag";
1749 } elsif ($action =~ /^(history|(short)?log)$/) {
1750 $dest_action = $action;
1753 my $dest = "";
1754 $dest .= "refs/" unless $ref =~ m!^refs/!;
1755 $dest .= $ref;
1757 my $link = $cgi->a({
1758 -href => href(
1759 action=>$dest_action,
1760 hash=>$dest
1761 )}, $name);
1763 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1764 $link . "</span>";
1768 if ($markers) {
1769 return ' <span class="refs">'. $markers . '</span>';
1770 } else {
1771 return "";
1775 # format, perhaps shortened and with markers, title line
1776 sub format_subject_html {
1777 my ($long, $short, $href, $extra) = @_;
1778 $extra = '' unless defined($extra);
1780 if (length($short) < length($long)) {
1781 $long =~ s/[[:cntrl:]]/?/g;
1782 return $cgi->a({-href => $href, -class => "list subject",
1783 -title => to_utf8($long)},
1784 esc_html($short)) . $extra;
1785 } else {
1786 return $cgi->a({-href => $href, -class => "list subject"},
1787 esc_html($long)) . $extra;
1791 # Rather than recomputing the url for an email multiple times, we cache it
1792 # after the first hit. This gives a visible benefit in views where the avatar
1793 # for the same email is used repeatedly (e.g. shortlog).
1794 # The cache is shared by all avatar engines (currently gravatar only), which
1795 # are free to use it as preferred. Since only one avatar engine is used for any
1796 # given page, there's no risk for cache conflicts.
1797 our %avatar_cache = ();
1799 # Compute the picon url for a given email, by using the picon search service over at
1800 # http://www.cs.indiana.edu/picons/search.html
1801 sub picon_url {
1802 my $email = lc shift;
1803 if (!$avatar_cache{$email}) {
1804 my ($user, $domain) = split('@', $email);
1805 $avatar_cache{$email} =
1806 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1807 "$domain/$user/" .
1808 "users+domains+unknown/up/single";
1810 return $avatar_cache{$email};
1813 # Compute the gravatar url for a given email, if it's not in the cache already.
1814 # Gravatar stores only the part of the URL before the size, since that's the
1815 # one computationally more expensive. This also allows reuse of the cache for
1816 # different sizes (for this particular engine).
1817 sub gravatar_url {
1818 my $email = lc shift;
1819 my $size = shift;
1820 $avatar_cache{$email} ||=
1821 "http://www.gravatar.com/avatar/" .
1822 Digest::MD5::md5_hex($email) . "?s=";
1823 return $avatar_cache{$email} . $size;
1826 # Insert an avatar for the given $email at the given $size if the feature
1827 # is enabled.
1828 sub git_get_avatar {
1829 my ($email, %opts) = @_;
1830 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1831 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1832 $opts{-size} ||= 'default';
1833 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1834 my $url = "";
1835 if ($git_avatar eq 'gravatar') {
1836 $url = gravatar_url($email, $size);
1837 } elsif ($git_avatar eq 'picon') {
1838 $url = picon_url($email);
1840 # Other providers can be added by extending the if chain, defining $url
1841 # as needed. If no variant puts something in $url, we assume avatars
1842 # are completely disabled/unavailable.
1843 if ($url) {
1844 return $pre_white .
1845 "<img width=\"$size\" " .
1846 "class=\"avatar\" " .
1847 "src=\"$url\" " .
1848 "alt=\"\" " .
1849 "/>" . $post_white;
1850 } else {
1851 return "";
1855 sub format_search_author {
1856 my ($author, $searchtype, $displaytext) = @_;
1857 my $have_search = gitweb_check_feature('search');
1859 if ($have_search) {
1860 my $performed = "";
1861 if ($searchtype eq 'author') {
1862 $performed = "authored";
1863 } elsif ($searchtype eq 'committer') {
1864 $performed = "committed";
1867 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1868 searchtext=>$author,
1869 searchtype=>$searchtype), class=>"list",
1870 title=>"Search for commits $performed by $author"},
1871 $displaytext);
1873 } else {
1874 return $displaytext;
1878 # format the author name of the given commit with the given tag
1879 # the author name is chopped and escaped according to the other
1880 # optional parameters (see chop_str).
1881 sub format_author_html {
1882 my $tag = shift;
1883 my $co = shift;
1884 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1885 return "<$tag class=\"author\">" .
1886 format_search_author($co->{'author_name'}, "author",
1887 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1888 $author) .
1889 "</$tag>";
1892 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1893 sub format_git_diff_header_line {
1894 my $line = shift;
1895 my $diffinfo = shift;
1896 my ($from, $to) = @_;
1898 if ($diffinfo->{'nparents'}) {
1899 # combined diff
1900 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1901 if ($to->{'href'}) {
1902 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1903 esc_path($to->{'file'}));
1904 } else { # file was deleted (no href)
1905 $line .= esc_path($to->{'file'});
1907 } else {
1908 # "ordinary" diff
1909 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1910 if ($from->{'href'}) {
1911 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1912 'a/' . esc_path($from->{'file'}));
1913 } else { # file was added (no href)
1914 $line .= 'a/' . esc_path($from->{'file'});
1916 $line .= ' ';
1917 if ($to->{'href'}) {
1918 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1919 'b/' . esc_path($to->{'file'}));
1920 } else { # file was deleted
1921 $line .= 'b/' . esc_path($to->{'file'});
1925 return "<div class=\"diff header\">$line</div>\n";
1928 # format extended diff header line, before patch itself
1929 sub format_extended_diff_header_line {
1930 my $line = shift;
1931 my $diffinfo = shift;
1932 my ($from, $to) = @_;
1934 # match <path>
1935 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1936 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1937 esc_path($from->{'file'}));
1939 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1940 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1941 esc_path($to->{'file'}));
1943 # match single <mode>
1944 if ($line =~ m/\s(\d{6})$/) {
1945 $line .= '<span class="info"> (' .
1946 file_type_long($1) .
1947 ')</span>';
1949 # match <hash>
1950 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1951 # can match only for combined diff
1952 $line = 'index ';
1953 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1954 if ($from->{'href'}[$i]) {
1955 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1956 -class=>"hash"},
1957 substr($diffinfo->{'from_id'}[$i],0,7));
1958 } else {
1959 $line .= '0' x 7;
1961 # separator
1962 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1964 $line .= '..';
1965 if ($to->{'href'}) {
1966 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1967 substr($diffinfo->{'to_id'},0,7));
1968 } else {
1969 $line .= '0' x 7;
1972 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1973 # can match only for ordinary diff
1974 my ($from_link, $to_link);
1975 if ($from->{'href'}) {
1976 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1977 substr($diffinfo->{'from_id'},0,7));
1978 } else {
1979 $from_link = '0' x 7;
1981 if ($to->{'href'}) {
1982 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1983 substr($diffinfo->{'to_id'},0,7));
1984 } else {
1985 $to_link = '0' x 7;
1987 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1988 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1991 return $line . "<br/>\n";
1994 # format from-file/to-file diff header
1995 sub format_diff_from_to_header {
1996 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1997 my $line;
1998 my $result = '';
2000 $line = $from_line;
2001 #assert($line =~ m/^---/) if DEBUG;
2002 # no extra formatting for "^--- /dev/null"
2003 if (! $diffinfo->{'nparents'}) {
2004 # ordinary (single parent) diff
2005 if ($line =~ m!^--- "?a/!) {
2006 if ($from->{'href'}) {
2007 $line = '--- a/' .
2008 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2009 esc_path($from->{'file'}));
2010 } else {
2011 $line = '--- a/' .
2012 esc_path($from->{'file'});
2015 $result .= qq!<div class="diff from_file">$line</div>\n!;
2017 } else {
2018 # combined diff (merge commit)
2019 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2020 if ($from->{'href'}[$i]) {
2021 $line = '--- ' .
2022 $cgi->a({-href=>href(action=>"blobdiff",
2023 hash_parent=>$diffinfo->{'from_id'}[$i],
2024 hash_parent_base=>$parents[$i],
2025 file_parent=>$from->{'file'}[$i],
2026 hash=>$diffinfo->{'to_id'},
2027 hash_base=>$hash,
2028 file_name=>$to->{'file'}),
2029 -class=>"path",
2030 -title=>"diff" . ($i+1)},
2031 $i+1) .
2032 '/' .
2033 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2034 esc_path($from->{'file'}[$i]));
2035 } else {
2036 $line = '--- /dev/null';
2038 $result .= qq!<div class="diff from_file">$line</div>\n!;
2042 $line = $to_line;
2043 #assert($line =~ m/^\+\+\+/) if DEBUG;
2044 # no extra formatting for "^+++ /dev/null"
2045 if ($line =~ m!^\+\+\+ "?b/!) {
2046 if ($to->{'href'}) {
2047 $line = '+++ b/' .
2048 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2049 esc_path($to->{'file'}));
2050 } else {
2051 $line = '+++ b/' .
2052 esc_path($to->{'file'});
2055 $result .= qq!<div class="diff to_file">$line</div>\n!;
2057 return $result;
2060 # create note for patch simplified by combined diff
2061 sub format_diff_cc_simplified {
2062 my ($diffinfo, @parents) = @_;
2063 my $result = '';
2065 $result .= "<div class=\"diff header\">" .
2066 "diff --cc ";
2067 if (!is_deleted($diffinfo)) {
2068 $result .= $cgi->a({-href => href(action=>"blob",
2069 hash_base=>$hash,
2070 hash=>$diffinfo->{'to_id'},
2071 file_name=>$diffinfo->{'to_file'}),
2072 -class => "path"},
2073 esc_path($diffinfo->{'to_file'}));
2074 } else {
2075 $result .= esc_path($diffinfo->{'to_file'});
2077 $result .= "</div>\n" . # class="diff header"
2078 "<div class=\"diff nodifferences\">" .
2079 "Simple merge" .
2080 "</div>\n"; # class="diff nodifferences"
2082 return $result;
2085 # format patch (diff) line (not to be used for diff headers)
2086 sub format_diff_line {
2087 my $line = shift;
2088 my ($from, $to) = @_;
2089 my $diff_class = "";
2091 chomp $line;
2093 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2094 # combined diff
2095 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2096 if ($line =~ m/^\@{3}/) {
2097 $diff_class = " chunk_header";
2098 } elsif ($line =~ m/^\\/) {
2099 $diff_class = " incomplete";
2100 } elsif ($prefix =~ tr/+/+/) {
2101 $diff_class = " add";
2102 } elsif ($prefix =~ tr/-/-/) {
2103 $diff_class = " rem";
2105 } else {
2106 # assume ordinary diff
2107 my $char = substr($line, 0, 1);
2108 if ($char eq '+') {
2109 $diff_class = " add";
2110 } elsif ($char eq '-') {
2111 $diff_class = " rem";
2112 } elsif ($char eq '@') {
2113 $diff_class = " chunk_header";
2114 } elsif ($char eq "\\") {
2115 $diff_class = " incomplete";
2118 $line = untabify($line);
2119 if ($from && $to && $line =~ m/^\@{2} /) {
2120 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2121 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2123 $from_lines = 0 unless defined $from_lines;
2124 $to_lines = 0 unless defined $to_lines;
2126 if ($from->{'href'}) {
2127 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2128 -class=>"list"}, $from_text);
2130 if ($to->{'href'}) {
2131 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2132 -class=>"list"}, $to_text);
2134 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2135 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2136 return "<div class=\"diff$diff_class\">$line</div>\n";
2137 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2138 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2139 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2141 @from_text = split(' ', $ranges);
2142 for (my $i = 0; $i < @from_text; ++$i) {
2143 ($from_start[$i], $from_nlines[$i]) =
2144 (split(',', substr($from_text[$i], 1)), 0);
2147 $to_text = pop @from_text;
2148 $to_start = pop @from_start;
2149 $to_nlines = pop @from_nlines;
2151 $line = "<span class=\"chunk_info\">$prefix ";
2152 for (my $i = 0; $i < @from_text; ++$i) {
2153 if ($from->{'href'}[$i]) {
2154 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2155 -class=>"list"}, $from_text[$i]);
2156 } else {
2157 $line .= $from_text[$i];
2159 $line .= " ";
2161 if ($to->{'href'}) {
2162 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2163 -class=>"list"}, $to_text);
2164 } else {
2165 $line .= $to_text;
2167 $line .= " $prefix</span>" .
2168 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2169 return "<div class=\"diff$diff_class\">$line</div>\n";
2171 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2174 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2175 # linked. Pass the hash of the tree/commit to snapshot.
2176 sub format_snapshot_links {
2177 my ($hash) = @_;
2178 my $num_fmts = @snapshot_fmts;
2179 if ($num_fmts > 1) {
2180 # A parenthesized list of links bearing format names.
2181 # e.g. "snapshot (_tar.gz_ _zip_)"
2182 return "snapshot (" . join(' ', map
2183 $cgi->a({
2184 -href => href(
2185 action=>"snapshot",
2186 hash=>$hash,
2187 snapshot_format=>$_
2189 }, $known_snapshot_formats{$_}{'display'})
2190 , @snapshot_fmts) . ")";
2191 } elsif ($num_fmts == 1) {
2192 # A single "snapshot" link whose tooltip bears the format name.
2193 # i.e. "_snapshot_"
2194 my ($fmt) = @snapshot_fmts;
2195 return
2196 $cgi->a({
2197 -href => href(
2198 action=>"snapshot",
2199 hash=>$hash,
2200 snapshot_format=>$fmt
2202 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2203 }, "snapshot");
2204 } else { # $num_fmts == 0
2205 return undef;
2209 ## ......................................................................
2210 ## functions returning values to be passed, perhaps after some
2211 ## transformation, to other functions; e.g. returning arguments to href()
2213 # returns hash to be passed to href to generate gitweb URL
2214 # in -title key it returns description of link
2215 sub get_feed_info {
2216 my $format = shift || 'Atom';
2217 my %res = (action => lc($format));
2219 # feed links are possible only for project views
2220 return unless (defined $project);
2221 # some views should link to OPML, or to generic project feed,
2222 # or don't have specific feed yet (so they should use generic)
2223 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2225 my $branch;
2226 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2227 # from tag links; this also makes possible to detect branch links
2228 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2229 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2230 $branch = $1;
2232 # find log type for feed description (title)
2233 my $type = 'log';
2234 if (defined $file_name) {
2235 $type = "history of $file_name";
2236 $type .= "/" if ($action eq 'tree');
2237 $type .= " on '$branch'" if (defined $branch);
2238 } else {
2239 $type = "log of $branch" if (defined $branch);
2242 $res{-title} = $type;
2243 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2244 $res{'file_name'} = $file_name;
2246 return %res;
2249 ## ----------------------------------------------------------------------
2250 ## git utility subroutines, invoking git commands
2252 # returns path to the core git executable and the --git-dir parameter as list
2253 sub git_cmd {
2254 $number_of_git_cmds++;
2255 return $GIT, '--git-dir='.$git_dir;
2258 # quote the given arguments for passing them to the shell
2259 # quote_command("command", "arg 1", "arg with ' and ! characters")
2260 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2261 # Try to avoid using this function wherever possible.
2262 sub quote_command {
2263 return join(' ',
2264 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2267 # get HEAD ref of given project as hash
2268 sub git_get_head_hash {
2269 return git_get_full_hash(shift, 'HEAD');
2272 sub git_get_full_hash {
2273 return git_get_hash(@_);
2276 sub git_get_short_hash {
2277 return git_get_hash(@_, '--short=7');
2280 sub git_get_hash {
2281 my ($project, $hash, @options) = @_;
2282 my $o_git_dir = $git_dir;
2283 my $retval = undef;
2284 $git_dir = "$projectroot/$project";
2285 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2286 '--verify', '-q', @options, $hash) {
2287 $retval = <$fd>;
2288 chomp $retval if defined $retval;
2289 close $fd;
2291 if (defined $o_git_dir) {
2292 $git_dir = $o_git_dir;
2294 return $retval;
2297 # get type of given object
2298 sub git_get_type {
2299 my $hash = shift;
2301 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2302 my $type = <$fd>;
2303 close $fd or return;
2304 chomp $type;
2305 return $type;
2308 # repository configuration
2309 our $config_file = '';
2310 our %config;
2312 # store multiple values for single key as anonymous array reference
2313 # single values stored directly in the hash, not as [ <value> ]
2314 sub hash_set_multi {
2315 my ($hash, $key, $value) = @_;
2317 if (!exists $hash->{$key}) {
2318 $hash->{$key} = $value;
2319 } elsif (!ref $hash->{$key}) {
2320 $hash->{$key} = [ $hash->{$key}, $value ];
2321 } else {
2322 push @{$hash->{$key}}, $value;
2326 # return hash of git project configuration
2327 # optionally limited to some section, e.g. 'gitweb'
2328 sub git_parse_project_config {
2329 my $section_regexp = shift;
2330 my %config;
2332 local $/ = "\0";
2334 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2335 or return;
2337 while (my $keyval = <$fh>) {
2338 chomp $keyval;
2339 my ($key, $value) = split(/\n/, $keyval, 2);
2341 hash_set_multi(\%config, $key, $value)
2342 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2344 close $fh;
2346 return %config;
2349 # convert config value to boolean: 'true' or 'false'
2350 # no value, number > 0, 'true' and 'yes' values are true
2351 # rest of values are treated as false (never as error)
2352 sub config_to_bool {
2353 my $val = shift;
2355 return 1 if !defined $val; # section.key
2357 # strip leading and trailing whitespace
2358 $val =~ s/^\s+//;
2359 $val =~ s/\s+$//;
2361 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2362 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2365 # convert config value to simple decimal number
2366 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2367 # to be multiplied by 1024, 1048576, or 1073741824
2368 sub config_to_int {
2369 my $val = shift;
2371 # strip leading and trailing whitespace
2372 $val =~ s/^\s+//;
2373 $val =~ s/\s+$//;
2375 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2376 $unit = lc($unit);
2377 # unknown unit is treated as 1
2378 return $num * ($unit eq 'g' ? 1073741824 :
2379 $unit eq 'm' ? 1048576 :
2380 $unit eq 'k' ? 1024 : 1);
2382 return $val;
2385 # convert config value to array reference, if needed
2386 sub config_to_multi {
2387 my $val = shift;
2389 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2392 sub git_get_project_config {
2393 my ($key, $type) = @_;
2395 return unless defined $git_dir;
2397 # key sanity check
2398 return unless ($key);
2399 $key =~ s/^gitweb\.//;
2400 return if ($key =~ m/\W/);
2402 # type sanity check
2403 if (defined $type) {
2404 $type =~ s/^--//;
2405 $type = undef
2406 unless ($type eq 'bool' || $type eq 'int');
2409 # get config
2410 if (!defined $config_file ||
2411 $config_file ne "$git_dir/config") {
2412 %config = git_parse_project_config('gitweb');
2413 $config_file = "$git_dir/config";
2416 # check if config variable (key) exists
2417 return unless exists $config{"gitweb.$key"};
2419 # ensure given type
2420 if (!defined $type) {
2421 return $config{"gitweb.$key"};
2422 } elsif ($type eq 'bool') {
2423 # backward compatibility: 'git config --bool' returns true/false
2424 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2425 } elsif ($type eq 'int') {
2426 return config_to_int($config{"gitweb.$key"});
2428 return $config{"gitweb.$key"};
2431 # get hash of given path at given ref
2432 sub git_get_hash_by_path {
2433 my $base = shift;
2434 my $path = shift || return undef;
2435 my $type = shift;
2437 $path =~ s,/+$,,;
2439 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2440 or die_error(500, "Open git-ls-tree failed");
2441 my $line = <$fd>;
2442 close $fd or return undef;
2444 if (!defined $line) {
2445 # there is no tree or hash given by $path at $base
2446 return undef;
2449 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2450 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2451 if (defined $type && $type ne $2) {
2452 # type doesn't match
2453 return undef;
2455 return $3;
2458 # get path of entry with given hash at given tree-ish (ref)
2459 # used to get 'from' filename for combined diff (merge commit) for renames
2460 sub git_get_path_by_hash {
2461 my $base = shift || return;
2462 my $hash = shift || return;
2464 local $/ = "\0";
2466 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2467 or return undef;
2468 while (my $line = <$fd>) {
2469 chomp $line;
2471 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2472 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2473 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2474 close $fd;
2475 return $1;
2478 close $fd;
2479 return undef;
2482 ## ......................................................................
2483 ## git utility functions, directly accessing git repository
2485 sub git_get_project_description {
2486 my $path = shift;
2488 $git_dir = "$projectroot/$path";
2489 open my $fd, '<', "$git_dir/description"
2490 or return git_get_project_config('description');
2491 my $descr = <$fd>;
2492 close $fd;
2493 if (defined $descr) {
2494 chomp $descr;
2496 return $descr;
2499 sub git_get_project_ctags {
2500 my $path = shift;
2501 my $ctags = {};
2503 $git_dir = "$projectroot/$path";
2504 opendir my $dh, "$git_dir/ctags"
2505 or return $ctags;
2506 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2507 open my $ct, '<', $_ or next;
2508 my $val = <$ct>;
2509 chomp $val;
2510 close $ct;
2511 my $ctag = $_; $ctag =~ s#.*/##;
2512 $ctags->{$ctag} = $val;
2514 closedir $dh;
2515 $ctags;
2518 sub git_populate_project_tagcloud {
2519 my $ctags = shift;
2521 # First, merge different-cased tags; tags vote on casing
2522 my %ctags_lc;
2523 foreach (keys %$ctags) {
2524 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2525 if (not $ctags_lc{lc $_}->{topcount}
2526 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2527 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2528 $ctags_lc{lc $_}->{topname} = $_;
2532 my $cloud;
2533 if (eval { require HTML::TagCloud; 1; }) {
2534 $cloud = HTML::TagCloud->new;
2535 foreach (sort keys %ctags_lc) {
2536 # Pad the title with spaces so that the cloud looks
2537 # less crammed.
2538 my $title = $ctags_lc{$_}->{topname};
2539 $title =~ s/ /&nbsp;/g;
2540 $title =~ s/^/&nbsp;/g;
2541 $title =~ s/$/&nbsp;/g;
2542 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2544 } else {
2545 $cloud = \%ctags_lc;
2547 $cloud;
2550 sub git_show_project_tagcloud {
2551 my ($cloud, $count) = @_;
2552 print STDERR ref($cloud)."..\n";
2553 if (ref $cloud eq 'HTML::TagCloud') {
2554 return $cloud->html_and_css($count);
2555 } else {
2556 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2557 return '<p align="center">' . join (', ', map {
2558 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2559 } splice(@tags, 0, $count)) . '</p>';
2563 sub git_get_project_url_list {
2564 my $path = shift;
2566 $git_dir = "$projectroot/$path";
2567 open my $fd, '<', "$git_dir/cloneurl"
2568 or return wantarray ?
2569 @{ config_to_multi(git_get_project_config('url')) } :
2570 config_to_multi(git_get_project_config('url'));
2571 my @git_project_url_list = map { chomp; $_ } <$fd>;
2572 close $fd;
2574 return wantarray ? @git_project_url_list : \@git_project_url_list;
2577 sub git_get_projects_list {
2578 my ($filter) = @_;
2579 my @list;
2581 $filter ||= '';
2582 $filter =~ s/\.git$//;
2584 my $check_forks = gitweb_check_feature('forks');
2586 if (-d $projects_list) {
2587 # search in directory
2588 my $dir = $projects_list . ($filter ? "/$filter" : '');
2589 # remove the trailing "/"
2590 $dir =~ s!/+$!!;
2591 my $pfxlen = length("$dir");
2592 my $pfxdepth = ($dir =~ tr!/!!);
2594 File::Find::find({
2595 follow_fast => 1, # follow symbolic links
2596 follow_skip => 2, # ignore duplicates
2597 dangling_symlinks => 0, # ignore dangling symlinks, silently
2598 wanted => sub {
2599 # global variables
2600 our $project_maxdepth;
2601 our $projectroot;
2602 # skip project-list toplevel, if we get it.
2603 return if (m!^[/.]$!);
2604 # only directories can be git repositories
2605 return unless (-d $_);
2606 # don't traverse too deep (Find is super slow on os x)
2607 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2608 $File::Find::prune = 1;
2609 return;
2612 my $subdir = substr($File::Find::name, $pfxlen + 1);
2613 # we check related file in $projectroot
2614 my $path = ($filter ? "$filter/" : '') . $subdir;
2615 if (check_export_ok("$projectroot/$path")) {
2616 push @list, { path => $path };
2617 $File::Find::prune = 1;
2620 }, "$dir");
2622 } elsif (-f $projects_list) {
2623 # read from file(url-encoded):
2624 # 'git%2Fgit.git Linus+Torvalds'
2625 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2626 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2627 my %paths;
2628 open my $fd, '<', $projects_list or return;
2629 PROJECT:
2630 while (my $line = <$fd>) {
2631 chomp $line;
2632 my ($path, $owner) = split ' ', $line;
2633 $path = unescape($path);
2634 $owner = unescape($owner);
2635 if (!defined $path) {
2636 next;
2638 if ($filter ne '') {
2639 # looking for forks;
2640 my $pfx = substr($path, 0, length($filter));
2641 if ($pfx ne $filter) {
2642 next PROJECT;
2644 my $sfx = substr($path, length($filter));
2645 if ($sfx !~ /^\/.*\.git$/) {
2646 next PROJECT;
2648 } elsif ($check_forks) {
2649 PATH:
2650 foreach my $filter (keys %paths) {
2651 # looking for forks;
2652 my $pfx = substr($path, 0, length($filter));
2653 if ($pfx ne $filter) {
2654 next PATH;
2656 my $sfx = substr($path, length($filter));
2657 if ($sfx !~ /^\/.*\.git$/) {
2658 next PATH;
2660 # is a fork, don't include it in
2661 # the list
2662 next PROJECT;
2665 if (check_export_ok("$projectroot/$path")) {
2666 my $pr = {
2667 path => $path,
2668 owner => to_utf8($owner),
2670 push @list, $pr;
2671 (my $forks_path = $path) =~ s/\.git$//;
2672 $paths{$forks_path}++;
2675 close $fd;
2677 return @list;
2680 our $gitweb_project_owner = undef;
2681 sub git_get_project_list_from_file {
2683 return if (defined $gitweb_project_owner);
2685 $gitweb_project_owner = {};
2686 # read from file (url-encoded):
2687 # 'git%2Fgit.git Linus+Torvalds'
2688 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2689 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2690 if (-f $projects_list) {
2691 open(my $fd, '<', $projects_list);
2692 while (my $line = <$fd>) {
2693 chomp $line;
2694 my ($pr, $ow) = split ' ', $line;
2695 $pr = unescape($pr);
2696 $ow = unescape($ow);
2697 $gitweb_project_owner->{$pr} = to_utf8($ow);
2699 close $fd;
2703 sub git_get_project_owner {
2704 my $project = shift;
2705 my $owner;
2707 return undef unless $project;
2708 $git_dir = "$projectroot/$project";
2710 if (!defined $gitweb_project_owner) {
2711 git_get_project_list_from_file();
2714 if (exists $gitweb_project_owner->{$project}) {
2715 $owner = $gitweb_project_owner->{$project};
2717 if (!defined $owner){
2718 $owner = git_get_project_config('owner');
2720 if (!defined $owner) {
2721 $owner = get_file_owner("$git_dir");
2724 return $owner;
2727 sub git_get_last_activity {
2728 my ($path) = @_;
2729 my $fd;
2731 $git_dir = "$projectroot/$path";
2732 open($fd, "-|", git_cmd(), 'for-each-ref',
2733 '--format=%(committer)',
2734 '--sort=-committerdate',
2735 '--count=1',
2736 'refs/heads') or return;
2737 my $most_recent = <$fd>;
2738 close $fd or return;
2739 if (defined $most_recent &&
2740 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2741 my $timestamp = $1;
2742 my $age = time - $timestamp;
2743 return ($age, age_string($age));
2745 return (undef, undef);
2748 sub git_get_references {
2749 my $type = shift || "";
2750 my %refs;
2751 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2752 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2753 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2754 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2755 or return;
2757 while (my $line = <$fd>) {
2758 chomp $line;
2759 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2760 if (defined $refs{$1}) {
2761 push @{$refs{$1}}, $2;
2762 } else {
2763 $refs{$1} = [ $2 ];
2767 close $fd or return;
2768 return \%refs;
2771 sub git_get_rev_name_tags {
2772 my $hash = shift || return undef;
2774 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2775 or return;
2776 my $name_rev = <$fd>;
2777 close $fd;
2779 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2780 return $1;
2781 } else {
2782 # catches also '$hash undefined' output
2783 return undef;
2787 ## ----------------------------------------------------------------------
2788 ## parse to hash functions
2790 sub parse_date {
2791 my $epoch = shift;
2792 my $tz = shift || "-0000";
2794 my %date;
2795 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2796 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2797 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2798 $date{'hour'} = $hour;
2799 $date{'minute'} = $min;
2800 $date{'mday'} = $mday;
2801 $date{'day'} = $days[$wday];
2802 $date{'month'} = $months[$mon];
2803 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2804 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2805 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2806 $mday, $months[$mon], $hour ,$min;
2807 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2808 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2810 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2811 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2812 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2813 $date{'hour_local'} = $hour;
2814 $date{'minute_local'} = $min;
2815 $date{'tz_local'} = $tz;
2816 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2817 1900+$year, $mon+1, $mday,
2818 $hour, $min, $sec, $tz);
2819 return %date;
2822 sub parse_tag {
2823 my $tag_id = shift;
2824 my %tag;
2825 my @comment;
2827 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2828 $tag{'id'} = $tag_id;
2829 while (my $line = <$fd>) {
2830 chomp $line;
2831 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2832 $tag{'object'} = $1;
2833 } elsif ($line =~ m/^type (.+)$/) {
2834 $tag{'type'} = $1;
2835 } elsif ($line =~ m/^tag (.+)$/) {
2836 $tag{'name'} = $1;
2837 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2838 $tag{'author'} = $1;
2839 $tag{'author_epoch'} = $2;
2840 $tag{'author_tz'} = $3;
2841 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2842 $tag{'author_name'} = $1;
2843 $tag{'author_email'} = $2;
2844 } else {
2845 $tag{'author_name'} = $tag{'author'};
2847 } elsif ($line =~ m/--BEGIN/) {
2848 push @comment, $line;
2849 last;
2850 } elsif ($line eq "") {
2851 last;
2854 push @comment, <$fd>;
2855 $tag{'comment'} = \@comment;
2856 close $fd or return;
2857 if (!defined $tag{'name'}) {
2858 return
2860 return %tag
2863 sub parse_commit_text {
2864 my ($commit_text, $withparents) = @_;
2865 my @commit_lines = split '\n', $commit_text;
2866 my %co;
2868 pop @commit_lines; # Remove '\0'
2870 if (! @commit_lines) {
2871 return;
2874 my $header = shift @commit_lines;
2875 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2876 return;
2878 ($co{'id'}, my @parents) = split ' ', $header;
2879 while (my $line = shift @commit_lines) {
2880 last if $line eq "\n";
2881 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2882 $co{'tree'} = $1;
2883 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2884 push @parents, $1;
2885 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2886 $co{'author'} = to_utf8($1);
2887 $co{'author_epoch'} = $2;
2888 $co{'author_tz'} = $3;
2889 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2890 $co{'author_name'} = $1;
2891 $co{'author_email'} = $2;
2892 } else {
2893 $co{'author_name'} = $co{'author'};
2895 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2896 $co{'committer'} = to_utf8($1);
2897 $co{'committer_epoch'} = $2;
2898 $co{'committer_tz'} = $3;
2899 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2900 $co{'committer_name'} = $1;
2901 $co{'committer_email'} = $2;
2902 } else {
2903 $co{'committer_name'} = $co{'committer'};
2907 if (!defined $co{'tree'}) {
2908 return;
2910 $co{'parents'} = \@parents;
2911 $co{'parent'} = $parents[0];
2913 foreach my $title (@commit_lines) {
2914 $title =~ s/^ //;
2915 if ($title ne "") {
2916 $co{'title'} = chop_str($title, 80, 5);
2917 # remove leading stuff of merges to make the interesting part visible
2918 if (length($title) > 50) {
2919 $title =~ s/^Automatic //;
2920 $title =~ s/^merge (of|with) /Merge ... /i;
2921 if (length($title) > 50) {
2922 $title =~ s/(http|rsync):\/\///;
2924 if (length($title) > 50) {
2925 $title =~ s/(master|www|rsync)\.//;
2927 if (length($title) > 50) {
2928 $title =~ s/kernel.org:?//;
2930 if (length($title) > 50) {
2931 $title =~ s/\/pub\/scm//;
2934 $co{'title_short'} = chop_str($title, 50, 5);
2935 last;
2938 if (! defined $co{'title'} || $co{'title'} eq "") {
2939 $co{'title'} = $co{'title_short'} = '(no commit message)';
2941 # remove added spaces
2942 foreach my $line (@commit_lines) {
2943 $line =~ s/^ //;
2945 $co{'comment'} = \@commit_lines;
2947 my $age = time - $co{'committer_epoch'};
2948 $co{'age'} = $age;
2949 $co{'age_string'} = age_string($age);
2950 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2951 if ($age > 60*60*24*7*2) {
2952 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2953 $co{'age_string_age'} = $co{'age_string'};
2954 } else {
2955 $co{'age_string_date'} = $co{'age_string'};
2956 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2958 return %co;
2961 sub parse_commit {
2962 my ($commit_id) = @_;
2963 my %co;
2965 local $/ = "\0";
2967 open my $fd, "-|", git_cmd(), "rev-list",
2968 "--parents",
2969 "--header",
2970 "--max-count=1",
2971 $commit_id,
2972 "--",
2973 or die_error(500, "Open git-rev-list failed");
2974 %co = parse_commit_text(<$fd>, 1);
2975 close $fd;
2977 return %co;
2980 sub parse_commits {
2981 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2982 my @cos;
2984 $maxcount ||= 1;
2985 $skip ||= 0;
2987 local $/ = "\0";
2989 open my $fd, "-|", git_cmd(), "rev-list",
2990 "--header",
2991 @args,
2992 ("--max-count=" . $maxcount),
2993 ("--skip=" . $skip),
2994 @extra_options,
2995 $commit_id,
2996 "--",
2997 ($filename ? ($filename) : ())
2998 or die_error(500, "Open git-rev-list failed");
2999 while (my $line = <$fd>) {
3000 my %co = parse_commit_text($line);
3001 push @cos, \%co;
3003 close $fd;
3005 return wantarray ? @cos : \@cos;
3008 # parse line of git-diff-tree "raw" output
3009 sub parse_difftree_raw_line {
3010 my $line = shift;
3011 my %res;
3013 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3014 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3015 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3016 $res{'from_mode'} = $1;
3017 $res{'to_mode'} = $2;
3018 $res{'from_id'} = $3;
3019 $res{'to_id'} = $4;
3020 $res{'status'} = $5;
3021 $res{'similarity'} = $6;
3022 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3023 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3024 } else {
3025 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3028 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3029 # combined diff (for merge commit)
3030 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3031 $res{'nparents'} = length($1);
3032 $res{'from_mode'} = [ split(' ', $2) ];
3033 $res{'to_mode'} = pop @{$res{'from_mode'}};
3034 $res{'from_id'} = [ split(' ', $3) ];
3035 $res{'to_id'} = pop @{$res{'from_id'}};
3036 $res{'status'} = [ split('', $4) ];
3037 $res{'to_file'} = unquote($5);
3039 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3040 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3041 $res{'commit'} = $1;
3044 return wantarray ? %res : \%res;
3047 # wrapper: return parsed line of git-diff-tree "raw" output
3048 # (the argument might be raw line, or parsed info)
3049 sub parsed_difftree_line {
3050 my $line_or_ref = shift;
3052 if (ref($line_or_ref) eq "HASH") {
3053 # pre-parsed (or generated by hand)
3054 return $line_or_ref;
3055 } else {
3056 return parse_difftree_raw_line($line_or_ref);
3060 # parse line of git-ls-tree output
3061 sub parse_ls_tree_line {
3062 my $line = shift;
3063 my %opts = @_;
3064 my %res;
3066 if ($opts{'-l'}) {
3067 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3068 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3070 $res{'mode'} = $1;
3071 $res{'type'} = $2;
3072 $res{'hash'} = $3;
3073 $res{'size'} = $4;
3074 if ($opts{'-z'}) {
3075 $res{'name'} = $5;
3076 } else {
3077 $res{'name'} = unquote($5);
3079 } else {
3080 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3081 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3083 $res{'mode'} = $1;
3084 $res{'type'} = $2;
3085 $res{'hash'} = $3;
3086 if ($opts{'-z'}) {
3087 $res{'name'} = $4;
3088 } else {
3089 $res{'name'} = unquote($4);
3093 return wantarray ? %res : \%res;
3096 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3097 sub parse_from_to_diffinfo {
3098 my ($diffinfo, $from, $to, @parents) = @_;
3100 if ($diffinfo->{'nparents'}) {
3101 # combined diff
3102 $from->{'file'} = [];
3103 $from->{'href'} = [];
3104 fill_from_file_info($diffinfo, @parents)
3105 unless exists $diffinfo->{'from_file'};
3106 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3107 $from->{'file'}[$i] =
3108 defined $diffinfo->{'from_file'}[$i] ?
3109 $diffinfo->{'from_file'}[$i] :
3110 $diffinfo->{'to_file'};
3111 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3112 $from->{'href'}[$i] = href(action=>"blob",
3113 hash_base=>$parents[$i],
3114 hash=>$diffinfo->{'from_id'}[$i],
3115 file_name=>$from->{'file'}[$i]);
3116 } else {
3117 $from->{'href'}[$i] = undef;
3120 } else {
3121 # ordinary (not combined) diff
3122 $from->{'file'} = $diffinfo->{'from_file'};
3123 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3124 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3125 hash=>$diffinfo->{'from_id'},
3126 file_name=>$from->{'file'});
3127 } else {
3128 delete $from->{'href'};
3132 $to->{'file'} = $diffinfo->{'to_file'};
3133 if (!is_deleted($diffinfo)) { # file exists in result
3134 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3135 hash=>$diffinfo->{'to_id'},
3136 file_name=>$to->{'file'});
3137 } else {
3138 delete $to->{'href'};
3142 ## ......................................................................
3143 ## parse to array of hashes functions
3145 sub git_get_heads_list {
3146 my $limit = shift;
3147 my @headslist;
3149 open my $fd, '-|', git_cmd(), 'for-each-ref',
3150 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3151 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3152 'refs/heads'
3153 or return;
3154 while (my $line = <$fd>) {
3155 my %ref_item;
3157 chomp $line;
3158 my ($refinfo, $committerinfo) = split(/\0/, $line);
3159 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3160 my ($committer, $epoch, $tz) =
3161 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3162 $ref_item{'fullname'} = $name;
3163 $name =~ s!^refs/heads/!!;
3165 $ref_item{'name'} = $name;
3166 $ref_item{'id'} = $hash;
3167 $ref_item{'title'} = $title || '(no commit message)';
3168 $ref_item{'epoch'} = $epoch;
3169 if ($epoch) {
3170 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3171 } else {
3172 $ref_item{'age'} = "unknown";
3175 push @headslist, \%ref_item;
3177 close $fd;
3179 return wantarray ? @headslist : \@headslist;
3182 sub git_get_tags_list {
3183 my $limit = shift;
3184 my @tagslist;
3186 open my $fd, '-|', git_cmd(), 'for-each-ref',
3187 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3188 '--format=%(objectname) %(objecttype) %(refname) '.
3189 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3190 'refs/tags'
3191 or return;
3192 while (my $line = <$fd>) {
3193 my %ref_item;
3195 chomp $line;
3196 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3197 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3198 my ($creator, $epoch, $tz) =
3199 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3200 $ref_item{'fullname'} = $name;
3201 $name =~ s!^refs/tags/!!;
3203 $ref_item{'type'} = $type;
3204 $ref_item{'id'} = $id;
3205 $ref_item{'name'} = $name;
3206 if ($type eq "tag") {
3207 $ref_item{'subject'} = $title;
3208 $ref_item{'reftype'} = $reftype;
3209 $ref_item{'refid'} = $refid;
3210 } else {
3211 $ref_item{'reftype'} = $type;
3212 $ref_item{'refid'} = $id;
3215 if ($type eq "tag" || $type eq "commit") {
3216 $ref_item{'epoch'} = $epoch;
3217 if ($epoch) {
3218 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3219 } else {
3220 $ref_item{'age'} = "unknown";
3224 push @tagslist, \%ref_item;
3226 close $fd;
3228 return wantarray ? @tagslist : \@tagslist;
3231 ## ----------------------------------------------------------------------
3232 ## filesystem-related functions
3234 sub get_file_owner {
3235 my $path = shift;
3237 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3238 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3239 if (!defined $gcos) {
3240 return undef;
3242 my $owner = $gcos;
3243 $owner =~ s/[,;].*$//;
3244 return to_utf8($owner);
3247 # assume that file exists
3248 sub insert_file {
3249 my $filename = shift;
3251 open my $fd, '<', $filename;
3252 print map { to_utf8($_) } <$fd>;
3253 close $fd;
3256 ## ......................................................................
3257 ## mimetype related functions
3259 sub mimetype_guess_file {
3260 my $filename = shift;
3261 my $mimemap = shift;
3262 -r $mimemap or return undef;
3264 my %mimemap;
3265 open(my $mh, '<', $mimemap) or return undef;
3266 while (<$mh>) {
3267 next if m/^#/; # skip comments
3268 my ($mimetype, $exts) = split(/\t+/);
3269 if (defined $exts) {
3270 my @exts = split(/\s+/, $exts);
3271 foreach my $ext (@exts) {
3272 $mimemap{$ext} = $mimetype;
3276 close($mh);
3278 $filename =~ /\.([^.]*)$/;
3279 return $mimemap{$1};
3282 sub mimetype_guess {
3283 my $filename = shift;
3284 my $mime;
3285 $filename =~ /\./ or return undef;
3287 if ($mimetypes_file) {
3288 my $file = $mimetypes_file;
3289 if ($file !~ m!^/!) { # if it is relative path
3290 # it is relative to project
3291 $file = "$projectroot/$project/$file";
3293 $mime = mimetype_guess_file($filename, $file);
3295 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3296 return $mime;
3299 sub blob_mimetype {
3300 my $fd = shift;
3301 my $filename = shift;
3303 if ($filename) {
3304 my $mime = mimetype_guess($filename);
3305 $mime and return $mime;
3308 # just in case
3309 return $default_blob_plain_mimetype unless $fd;
3311 if (-T $fd) {
3312 return 'text/plain';
3313 } elsif (! $filename) {
3314 return 'application/octet-stream';
3315 } elsif ($filename =~ m/\.png$/i) {
3316 return 'image/png';
3317 } elsif ($filename =~ m/\.gif$/i) {
3318 return 'image/gif';
3319 } elsif ($filename =~ m/\.jpe?g$/i) {
3320 return 'image/jpeg';
3321 } else {
3322 return 'application/octet-stream';
3326 sub blob_contenttype {
3327 my ($fd, $file_name, $type) = @_;
3329 $type ||= blob_mimetype($fd, $file_name);
3330 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3331 $type .= "; charset=$default_text_plain_charset";
3334 return $type;
3337 # guess file syntax for syntax highlighting; return undef if no highlighting
3338 # the name of syntax can (in the future) depend on syntax highlighter used
3339 sub guess_file_syntax {
3340 my ($highlight, $mimetype, $file_name) = @_;
3341 return undef unless ($highlight && defined $file_name);
3342 my $basename = basename($file_name, '.in');
3343 return $highlight_basename{$basename}
3344 if exists $highlight_basename{$basename};
3346 $basename =~ /\.([^.]*)$/;
3347 my $ext = $1 or return undef;
3348 return $highlight_ext{$ext}
3349 if exists $highlight_ext{$ext};
3351 return undef;
3354 # run highlighter and return FD of its output,
3355 # or return original FD if no highlighting
3356 sub run_highlighter {
3357 my ($fd, $highlight, $syntax) = @_;
3358 return $fd unless ($highlight && defined $syntax);
3360 close $fd
3361 or die_error(404, "Reading blob failed");
3362 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3363 "highlight --xhtml --fragment --syntax $syntax |"
3364 or die_error(500, "Couldn't open file or run syntax highlighter");
3365 return $fd;
3368 ## ======================================================================
3369 ## functions printing HTML: header, footer, error page
3371 sub get_page_title {
3372 my $title = to_utf8($site_name);
3374 return $title unless (defined $project);
3375 $title .= " - " . to_utf8($project);
3377 return $title unless (defined $action);
3378 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3380 return $title unless (defined $file_name);
3381 $title .= " - " . esc_path($file_name);
3382 if ($action eq "tree" && $file_name !~ m|/$|) {
3383 $title .= "/";
3386 return $title;
3389 sub git_header_html {
3390 my $status = shift || "200 OK";
3391 my $expires = shift;
3392 my %opts = @_;
3394 my $title = get_page_title();
3395 my $content_type;
3396 # require explicit support from the UA if we are to send the page as
3397 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3398 # we have to do this because MSIE sometimes globs '*/*', pretending to
3399 # support xhtml+xml but choking when it gets what it asked for.
3400 if (defined $cgi->http('HTTP_ACCEPT') &&
3401 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3402 $cgi->Accept('application/xhtml+xml') != 0) {
3403 $content_type = 'application/xhtml+xml';
3404 } else {
3405 $content_type = 'text/html';
3407 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3408 -status=> $status, -expires => $expires)
3409 unless ($opts{'-no_http_header'});
3410 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3411 print <<EOF;
3412 <?xml version="1.0" encoding="utf-8"?>
3413 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3414 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3415 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3416 <!-- git core binaries version $git_version -->
3417 <head>
3418 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3419 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3420 <meta name="robots" content="index, nofollow"/>
3421 <title>$title</title>
3423 # the stylesheet, favicon etc urls won't work correctly with path_info
3424 # unless we set the appropriate base URL
3425 if ($ENV{'PATH_INFO'}) {
3426 print "<base href=\"".esc_url($base_url)."\" />\n";
3428 # print out each stylesheet that exist, providing backwards capability
3429 # for those people who defined $stylesheet in a config file
3430 if (defined $stylesheet) {
3431 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3432 } else {
3433 foreach my $stylesheet (@stylesheets) {
3434 next unless $stylesheet;
3435 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3438 if (defined $project) {
3439 my %href_params = get_feed_info();
3440 if (!exists $href_params{'-title'}) {
3441 $href_params{'-title'} = 'log';
3444 foreach my $format qw(RSS Atom) {
3445 my $type = lc($format);
3446 my %link_attr = (
3447 '-rel' => 'alternate',
3448 '-title' => "$project - $href_params{'-title'} - $format feed",
3449 '-type' => "application/$type+xml"
3452 $href_params{'action'} = $type;
3453 $link_attr{'-href'} = href(%href_params);
3454 print "<link ".
3455 "rel=\"$link_attr{'-rel'}\" ".
3456 "title=\"$link_attr{'-title'}\" ".
3457 "href=\"$link_attr{'-href'}\" ".
3458 "type=\"$link_attr{'-type'}\" ".
3459 "/>\n";
3461 $href_params{'extra_options'} = '--no-merges';
3462 $link_attr{'-href'} = href(%href_params);
3463 $link_attr{'-title'} .= ' (no merges)';
3464 print "<link ".
3465 "rel=\"$link_attr{'-rel'}\" ".
3466 "title=\"$link_attr{'-title'}\" ".
3467 "href=\"$link_attr{'-href'}\" ".
3468 "type=\"$link_attr{'-type'}\" ".
3469 "/>\n";
3472 } else {
3473 printf('<link rel="alternate" title="%s projects list" '.
3474 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3475 $site_name, href(project=>undef, action=>"project_index"));
3476 printf('<link rel="alternate" title="%s projects feeds" '.
3477 'href="%s" type="text/x-opml" />'."\n",
3478 $site_name, href(project=>undef, action=>"opml"));
3480 if (defined $favicon) {
3481 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3484 print "</head>\n" .
3485 "<body>\n";
3487 if (defined $site_header && -f $site_header) {
3488 insert_file($site_header);
3491 print "<div class=\"page_header\">\n" .
3492 $cgi->a({-href => esc_url($logo_url),
3493 -title => $logo_label},
3494 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3495 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3496 if (defined $project) {
3497 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3498 if (defined $action) {
3499 print " / $action";
3501 print "\n";
3503 print "</div>\n";
3505 my $have_search = gitweb_check_feature('search');
3506 if (defined $project && $have_search) {
3507 if (!defined $searchtext) {
3508 $searchtext = "";
3510 my $search_hash;
3511 if (defined $hash_base) {
3512 $search_hash = $hash_base;
3513 } elsif (defined $hash) {
3514 $search_hash = $hash;
3515 } else {
3516 $search_hash = "HEAD";
3518 my $action = $my_uri;
3519 my $use_pathinfo = gitweb_check_feature('pathinfo');
3520 if ($use_pathinfo) {
3521 $action .= "/".esc_url($project);
3523 print $cgi->startform(-method => "get", -action => $action) .
3524 "<div class=\"search\">\n" .
3525 (!$use_pathinfo &&
3526 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3527 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3528 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3529 $cgi->popup_menu(-name => 'st', -default => 'commit',
3530 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3531 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3532 " search:\n",
3533 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3534 "<span title=\"Extended regular expression\">" .
3535 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3536 -checked => $search_use_regexp) .
3537 "</span>" .
3538 "</div>" .
3539 $cgi->end_form() . "\n";
3543 sub git_footer_html {
3544 my $feed_class = 'rss_logo';
3546 print "<div class=\"page_footer\">\n";
3547 if (defined $project) {
3548 my $descr = git_get_project_description($project);
3549 if (defined $descr) {
3550 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3553 my %href_params = get_feed_info();
3554 if (!%href_params) {
3555 $feed_class .= ' generic';
3557 $href_params{'-title'} ||= 'log';
3559 foreach my $format qw(RSS Atom) {
3560 $href_params{'action'} = lc($format);
3561 print $cgi->a({-href => href(%href_params),
3562 -title => "$href_params{'-title'} $format feed",
3563 -class => $feed_class}, $format)."\n";
3566 } else {
3567 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3568 -class => $feed_class}, "OPML") . " ";
3569 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3570 -class => $feed_class}, "TXT") . "\n";
3572 print "</div>\n"; # class="page_footer"
3574 if (defined $t0 && gitweb_check_feature('timed')) {
3575 print "<div id=\"generating_info\">\n";
3576 print 'This page took '.
3577 '<span id="generating_time" class="time_span">'.
3578 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3579 ' seconds </span>'.
3580 ' and '.
3581 '<span id="generating_cmd">'.
3582 $number_of_git_cmds.
3583 '</span> git commands '.
3584 " to generate.\n";
3585 print "</div>\n"; # class="page_footer"
3588 if (defined $site_footer && -f $site_footer) {
3589 insert_file($site_footer);
3592 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3593 if (defined $action &&
3594 $action eq 'blame_incremental') {
3595 print qq!<script type="text/javascript">\n!.
3596 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3597 qq! "!. href() .qq!");\n!.
3598 qq!</script>\n!;
3599 } elsif (gitweb_check_feature('javascript-actions')) {
3600 print qq!<script type="text/javascript">\n!.
3601 qq!window.onload = fixLinks;\n!.
3602 qq!</script>\n!;
3605 print "</body>\n" .
3606 "</html>";
3609 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3610 # Example: die_error(404, 'Hash not found')
3611 # By convention, use the following status codes (as defined in RFC 2616):
3612 # 400: Invalid or missing CGI parameters, or
3613 # requested object exists but has wrong type.
3614 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3615 # this server or project.
3616 # 404: Requested object/revision/project doesn't exist.
3617 # 500: The server isn't configured properly, or
3618 # an internal error occurred (e.g. failed assertions caused by bugs), or
3619 # an unknown error occurred (e.g. the git binary died unexpectedly).
3620 # 503: The server is currently unavailable (because it is overloaded,
3621 # or down for maintenance). Generally, this is a temporary state.
3622 sub die_error {
3623 my $status = shift || 500;
3624 my $error = esc_html(shift) || "Internal Server Error";
3625 my $extra = shift;
3626 my %opts = @_;
3628 my %http_responses = (
3629 400 => '400 Bad Request',
3630 403 => '403 Forbidden',
3631 404 => '404 Not Found',
3632 500 => '500 Internal Server Error',
3633 503 => '503 Service Unavailable',
3635 git_header_html($http_responses{$status}, undef, %opts);
3636 print <<EOF;
3637 <div class="page_body">
3638 <br /><br />
3639 $status - $error
3640 <br />
3642 if (defined $extra) {
3643 print "<hr />\n" .
3644 "$extra\n";
3646 print "</div>\n";
3648 git_footer_html();
3649 goto DONE_GITWEB
3650 unless ($opts{'-error_handler'});
3653 ## ----------------------------------------------------------------------
3654 ## functions printing or outputting HTML: navigation
3656 sub git_print_page_nav {
3657 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3658 $extra = '' if !defined $extra; # pager or formats
3660 my @navs = qw(summary shortlog log commit commitdiff tree);
3661 if ($suppress) {
3662 @navs = grep { $_ ne $suppress } @navs;
3665 my %arg = map { $_ => {action=>$_} } @navs;
3666 if (defined $head) {
3667 for (qw(commit commitdiff)) {
3668 $arg{$_}{'hash'} = $head;
3670 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3671 for (qw(shortlog log)) {
3672 $arg{$_}{'hash'} = $head;
3677 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3678 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3680 my @actions = gitweb_get_feature('actions');
3681 my %repl = (
3682 '%' => '%',
3683 'n' => $project, # project name
3684 'f' => $git_dir, # project path within filesystem
3685 'h' => $treehead || '', # current hash ('h' parameter)
3686 'b' => $treebase || '', # hash base ('hb' parameter)
3688 while (@actions) {
3689 my ($label, $link, $pos) = splice(@actions,0,3);
3690 # insert
3691 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3692 # munch munch
3693 $link =~ s/%([%nfhb])/$repl{$1}/g;
3694 $arg{$label}{'_href'} = $link;
3697 print "<div class=\"page_nav\">\n" .
3698 (join " | ",
3699 map { $_ eq $current ?
3700 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3701 } @navs);
3702 print "<br/>\n$extra<br/>\n" .
3703 "</div>\n";
3706 sub format_paging_nav {
3707 my ($action, $page, $has_next_link) = @_;
3708 my $paging_nav;
3711 if ($page > 0) {
3712 $paging_nav .=
3713 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3714 " &sdot; " .
3715 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3716 -accesskey => "p", -title => "Alt-p"}, "prev");
3717 } else {
3718 $paging_nav .= "first &sdot; prev";
3721 if ($has_next_link) {
3722 $paging_nav .= " &sdot; " .
3723 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3724 -accesskey => "n", -title => "Alt-n"}, "next");
3725 } else {
3726 $paging_nav .= " &sdot; next";
3729 return $paging_nav;
3732 ## ......................................................................
3733 ## functions printing or outputting HTML: div
3735 sub git_print_header_div {
3736 my ($action, $title, $hash, $hash_base) = @_;
3737 my %args = ();
3739 $args{'action'} = $action;
3740 $args{'hash'} = $hash if $hash;
3741 $args{'hash_base'} = $hash_base if $hash_base;
3743 print "<div class=\"header\">\n" .
3744 $cgi->a({-href => href(%args), -class => "title"},
3745 $title ? $title : $action) .
3746 "\n</div>\n";
3749 sub print_local_time {
3750 print format_local_time(@_);
3753 sub format_local_time {
3754 my $localtime = '';
3755 my %date = @_;
3756 if ($date{'hour_local'} < 6) {
3757 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3758 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3759 } else {
3760 $localtime .= sprintf(" (%02d:%02d %s)",
3761 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3764 return $localtime;
3767 # Outputs the author name and date in long form
3768 sub git_print_authorship {
3769 my $co = shift;
3770 my %opts = @_;
3771 my $tag = $opts{-tag} || 'div';
3772 my $author = $co->{'author_name'};
3774 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3775 print "<$tag class=\"author_date\">" .
3776 format_search_author($author, "author", esc_html($author)) .
3777 " [$ad{'rfc2822'}";
3778 print_local_time(%ad) if ($opts{-localtime});
3779 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3780 . "</$tag>\n";
3783 # Outputs table rows containing the full author or committer information,
3784 # in the format expected for 'commit' view (& similar).
3785 # Parameters are a commit hash reference, followed by the list of people
3786 # to output information for. If the list is empty it defaults to both
3787 # author and committer.
3788 sub git_print_authorship_rows {
3789 my $co = shift;
3790 # too bad we can't use @people = @_ || ('author', 'committer')
3791 my @people = @_;
3792 @people = ('author', 'committer') unless @people;
3793 foreach my $who (@people) {
3794 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3795 print "<tr><td>$who</td><td>" .
3796 format_search_author($co->{"${who}_name"}, $who,
3797 esc_html($co->{"${who}_name"})) . " " .
3798 format_search_author($co->{"${who}_email"}, $who,
3799 esc_html("<" . $co->{"${who}_email"} . ">")) .
3800 "</td><td rowspan=\"2\">" .
3801 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3802 "</td></tr>\n" .
3803 "<tr>" .
3804 "<td></td><td> $wd{'rfc2822'}";
3805 print_local_time(%wd);
3806 print "</td>" .
3807 "</tr>\n";
3811 sub git_print_page_path {
3812 my $name = shift;
3813 my $type = shift;
3814 my $hb = shift;
3817 print "<div class=\"page_path\">";
3818 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3819 -title => 'tree root'}, to_utf8("[$project]"));
3820 print " / ";
3821 if (defined $name) {
3822 my @dirname = split '/', $name;
3823 my $basename = pop @dirname;
3824 my $fullname = '';
3826 foreach my $dir (@dirname) {
3827 $fullname .= ($fullname ? '/' : '') . $dir;
3828 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3829 hash_base=>$hb),
3830 -title => $fullname}, esc_path($dir));
3831 print " / ";
3833 if (defined $type && $type eq 'blob') {
3834 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3835 hash_base=>$hb),
3836 -title => $name}, esc_path($basename));
3837 print '&nbsp;&nbsp;&nbsp;&nbsp;
3838 <a id="lineNoToggle" href="#" onclick="toggleLineNumbers();"></a>
3839 <script>
3840 function toggleLineNumbers() {
3841 e = document.getElementById("lineNoStyle");
3842 e2 = document.getElementById("lineNoToggle");
3843 if (e2.innerHTML == "[Hide line numbers]") {
3844 e.innerHTML = ".linenr { display:none; }";
3845 e2.innerHTML = "[Show line numbers]";
3847 else {
3848 e.innerHTML = "";
3849 e2.innerHTML = "[Hide line numbers]";
3852 document.getElementsByTagName("head")[0].innerHTML += "<style id=\'lineNoStyle\'></style>";
3853 toggleLineNumbers();
3854 </script>
3856 } elsif (defined $type && $type eq 'tree') {
3857 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3858 hash_base=>$hb),
3859 -title => $name}, esc_path($basename));
3860 print " / ";
3861 } else {
3862 print esc_path($basename);
3865 print "<br/></div>\n";
3868 sub git_print_log {
3869 my $log = shift;
3870 my %opts = @_;
3872 if ($opts{'-remove_title'}) {
3873 # remove title, i.e. first line of log
3874 shift @$log;
3876 # remove leading empty lines
3877 while (defined $log->[0] && $log->[0] eq "") {
3878 shift @$log;
3881 # print log
3882 my $signoff = 0;
3883 my $empty = 0;
3884 foreach my $line (@$log) {
3885 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3886 $signoff = 1;
3887 $empty = 0;
3888 if (! $opts{'-remove_signoff'}) {
3889 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3890 next;
3891 } else {
3892 # remove signoff lines
3893 next;
3895 } else {
3896 $signoff = 0;
3899 # print only one empty line
3900 # do not print empty line after signoff
3901 if ($line eq "") {
3902 next if ($empty || $signoff);
3903 $empty = 1;
3904 } else {
3905 $empty = 0;
3908 print format_log_line_html($line) . "<br/>\n";
3911 if ($opts{'-final_empty_line'}) {
3912 # end with single empty line
3913 print "<br/>\n" unless $empty;
3917 # return link target (what link points to)
3918 sub git_get_link_target {
3919 my $hash = shift;
3920 my $link_target;
3922 # read link
3923 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3924 or return;
3926 local $/ = undef;
3927 $link_target = <$fd>;
3929 close $fd
3930 or return;
3932 return $link_target;
3935 # given link target, and the directory (basedir) the link is in,
3936 # return target of link relative to top directory (top tree);
3937 # return undef if it is not possible (including absolute links).
3938 sub normalize_link_target {
3939 my ($link_target, $basedir) = @_;
3941 # absolute symlinks (beginning with '/') cannot be normalized
3942 return if (substr($link_target, 0, 1) eq '/');
3944 # normalize link target to path from top (root) tree (dir)
3945 my $path;
3946 if ($basedir) {
3947 $path = $basedir . '/' . $link_target;
3948 } else {
3949 # we are in top (root) tree (dir)
3950 $path = $link_target;
3953 # remove //, /./, and /../
3954 my @path_parts;
3955 foreach my $part (split('/', $path)) {
3956 # discard '.' and ''
3957 next if (!$part || $part eq '.');
3958 # handle '..'
3959 if ($part eq '..') {
3960 if (@path_parts) {
3961 pop @path_parts;
3962 } else {
3963 # link leads outside repository (outside top dir)
3964 return;
3966 } else {
3967 push @path_parts, $part;
3970 $path = join('/', @path_parts);
3972 return $path;
3975 # print tree entry (row of git_tree), but without encompassing <tr> element
3976 sub git_print_tree_entry {
3977 my ($t, $basedir, $hash_base, $have_blame) = @_;
3979 my %base_key = ();
3980 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3982 # The format of a table row is: mode list link. Where mode is
3983 # the mode of the entry, list is the name of the entry, an href,
3984 # and link is the action links of the entry.
3986 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3987 if (exists $t->{'size'}) {
3988 print "<td class=\"size\">$t->{'size'}</td>\n";
3990 if ($t->{'type'} eq "blob") {
3991 print "<td class=\"list\">" .
3992 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3993 file_name=>"$basedir$t->{'name'}", %base_key),
3994 -class => "list"}, esc_path($t->{'name'}));
3995 if (S_ISLNK(oct $t->{'mode'})) {
3996 my $link_target = git_get_link_target($t->{'hash'});
3997 if ($link_target) {
3998 my $norm_target = normalize_link_target($link_target, $basedir);
3999 if (defined $norm_target) {
4000 print " -> " .
4001 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4002 file_name=>$norm_target),
4003 -title => $norm_target}, esc_path($link_target));
4004 } else {
4005 print " -> " . esc_path($link_target);
4009 print "</td>\n";
4010 print "<td class=\"link\">";
4011 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4012 file_name=>"$basedir$t->{'name'}", %base_key)},
4013 "blob");
4014 if ($have_blame) {
4015 print " | " .
4016 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4017 file_name=>"$basedir$t->{'name'}", %base_key)},
4018 "blame");
4020 if (defined $hash_base) {
4021 print " | " .
4022 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4023 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4024 "history");
4026 print " | " .
4027 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4028 file_name=>"$basedir$t->{'name'}")},
4029 "raw");
4030 print "</td>\n";
4032 } elsif ($t->{'type'} eq "tree") {
4033 print "<td class=\"list\">";
4034 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4035 file_name=>"$basedir$t->{'name'}",
4036 %base_key)},
4037 esc_path($t->{'name'}));
4038 print "</td>\n";
4039 print "<td class=\"link\">";
4040 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4041 file_name=>"$basedir$t->{'name'}",
4042 %base_key)},
4043 "tree");
4044 if (defined $hash_base) {
4045 print " | " .
4046 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4047 file_name=>"$basedir$t->{'name'}")},
4048 "history");
4050 print "</td>\n";
4051 } else {
4052 # unknown object: we can only present history for it
4053 # (this includes 'commit' object, i.e. submodule support)
4054 print "<td class=\"list\">" .
4055 esc_path($t->{'name'}) .
4056 "</td>\n";
4057 print "<td class=\"link\">";
4058 if (defined $hash_base) {
4059 print $cgi->a({-href => href(action=>"history",
4060 hash_base=>$hash_base,
4061 file_name=>"$basedir$t->{'name'}")},
4062 "history");
4064 print "</td>\n";
4068 ## ......................................................................
4069 ## functions printing large fragments of HTML
4071 # get pre-image filenames for merge (combined) diff
4072 sub fill_from_file_info {
4073 my ($diff, @parents) = @_;
4075 $diff->{'from_file'} = [ ];
4076 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4077 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4078 if ($diff->{'status'}[$i] eq 'R' ||
4079 $diff->{'status'}[$i] eq 'C') {
4080 $diff->{'from_file'}[$i] =
4081 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4085 return $diff;
4088 # is current raw difftree line of file deletion
4089 sub is_deleted {
4090 my $diffinfo = shift;
4092 return $diffinfo->{'to_id'} eq ('0' x 40);
4095 # does patch correspond to [previous] difftree raw line
4096 # $diffinfo - hashref of parsed raw diff format
4097 # $patchinfo - hashref of parsed patch diff format
4098 # (the same keys as in $diffinfo)
4099 sub is_patch_split {
4100 my ($diffinfo, $patchinfo) = @_;
4102 return defined $diffinfo && defined $patchinfo
4103 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4107 sub git_difftree_body {
4108 my ($difftree, $hash, @parents) = @_;
4109 my ($parent) = $parents[0];
4110 my $have_blame = gitweb_check_feature('blame');
4111 print "<div class=\"list_head\">\n";
4112 if ($#{$difftree} > 10) {
4113 print(($#{$difftree} + 1) . " files changed:\n");
4115 print "</div>\n";
4117 print "<table class=\"" .
4118 (@parents > 1 ? "combined " : "") .
4119 "diff_tree\">\n";
4121 # header only for combined diff in 'commitdiff' view
4122 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4123 if ($has_header) {
4124 # table header
4125 print "<thead><tr>\n" .
4126 "<th></th><th></th>\n"; # filename, patchN link
4127 for (my $i = 0; $i < @parents; $i++) {
4128 my $par = $parents[$i];
4129 print "<th>" .
4130 $cgi->a({-href => href(action=>"commitdiff",
4131 hash=>$hash, hash_parent=>$par),
4132 -title => 'commitdiff to parent number ' .
4133 ($i+1) . ': ' . substr($par,0,7)},
4134 $i+1) .
4135 "&nbsp;</th>\n";
4137 print "</tr></thead>\n<tbody>\n";
4140 my $alternate = 1;
4141 my $patchno = 0;
4142 foreach my $line (@{$difftree}) {
4143 my $diff = parsed_difftree_line($line);
4145 if ($alternate) {
4146 print "<tr class=\"dark\">\n";
4147 } else {
4148 print "<tr class=\"light\">\n";
4150 $alternate ^= 1;
4152 if (exists $diff->{'nparents'}) { # combined diff
4154 fill_from_file_info($diff, @parents)
4155 unless exists $diff->{'from_file'};
4157 if (!is_deleted($diff)) {
4158 # file exists in the result (child) commit
4159 print "<td>" .
4160 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4161 file_name=>$diff->{'to_file'},
4162 hash_base=>$hash),
4163 -class => "list"}, esc_path($diff->{'to_file'})) .
4164 "</td>\n";
4165 } else {
4166 print "<td>" .
4167 esc_path($diff->{'to_file'}) .
4168 "</td>\n";
4171 if ($action eq 'commitdiff') {
4172 # link to patch
4173 $patchno++;
4174 print "<td class=\"link\">" .
4175 $cgi->a({-href => "#patch$patchno"}, "patch") .
4176 " | " .
4177 "</td>\n";
4180 my $has_history = 0;
4181 my $not_deleted = 0;
4182 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4183 my $hash_parent = $parents[$i];
4184 my $from_hash = $diff->{'from_id'}[$i];
4185 my $from_path = $diff->{'from_file'}[$i];
4186 my $status = $diff->{'status'}[$i];
4188 $has_history ||= ($status ne 'A');
4189 $not_deleted ||= ($status ne 'D');
4191 if ($status eq 'A') {
4192 print "<td class=\"link\" align=\"right\"> | </td>\n";
4193 } elsif ($status eq 'D') {
4194 print "<td class=\"link\">" .
4195 $cgi->a({-href => href(action=>"blob",
4196 hash_base=>$hash,
4197 hash=>$from_hash,
4198 file_name=>$from_path)},
4199 "blob" . ($i+1)) .
4200 " | </td>\n";
4201 } else {
4202 if ($diff->{'to_id'} eq $from_hash) {
4203 print "<td class=\"link nochange\">";
4204 } else {
4205 print "<td class=\"link\">";
4207 print $cgi->a({-href => href(action=>"blobdiff",
4208 hash=>$diff->{'to_id'},
4209 hash_parent=>$from_hash,
4210 hash_base=>$hash,
4211 hash_parent_base=>$hash_parent,
4212 file_name=>$diff->{'to_file'},
4213 file_parent=>$from_path)},
4214 "diff" . ($i+1)) .
4215 " | </td>\n";
4219 print "<td class=\"link\">";
4220 if ($not_deleted) {
4221 print $cgi->a({-href => href(action=>"blob",
4222 hash=>$diff->{'to_id'},
4223 file_name=>$diff->{'to_file'},
4224 hash_base=>$hash)},
4225 "blob");
4226 print " | " if ($has_history);
4228 if ($has_history) {
4229 print $cgi->a({-href => href(action=>"history",
4230 file_name=>$diff->{'to_file'},
4231 hash_base=>$hash)},
4232 "history");
4234 print "</td>\n";
4236 print "</tr>\n";
4237 next; # instead of 'else' clause, to avoid extra indent
4239 # else ordinary diff
4241 my ($to_mode_oct, $to_mode_str, $to_file_type);
4242 my ($from_mode_oct, $from_mode_str, $from_file_type);
4243 if ($diff->{'to_mode'} ne ('0' x 6)) {
4244 $to_mode_oct = oct $diff->{'to_mode'};
4245 if (S_ISREG($to_mode_oct)) { # only for regular file
4246 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4248 $to_file_type = file_type($diff->{'to_mode'});
4250 if ($diff->{'from_mode'} ne ('0' x 6)) {
4251 $from_mode_oct = oct $diff->{'from_mode'};
4252 if (S_ISREG($to_mode_oct)) { # only for regular file
4253 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4255 $from_file_type = file_type($diff->{'from_mode'});
4258 if ($diff->{'status'} eq "A") { # created
4259 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4260 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4261 $mode_chng .= "]</span>";
4262 print "<td>";
4263 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4264 hash_base=>$hash, file_name=>$diff->{'file'}),
4265 -class => "list"}, esc_path($diff->{'file'}));
4266 print "</td>\n";
4267 print "<td>$mode_chng</td>\n";
4268 print "<td class=\"link\">";
4269 if ($action eq 'commitdiff') {
4270 # link to patch
4271 $patchno++;
4272 print $cgi->a({-href => "#patch$patchno"}, "patch");
4273 print " | ";
4275 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4276 hash_base=>$hash, file_name=>$diff->{'file'})},
4277 "blob");
4278 print "</td>\n";
4280 } elsif ($diff->{'status'} eq "D") { # deleted
4281 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4282 print "<td>";
4283 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4284 hash_base=>$parent, file_name=>$diff->{'file'}),
4285 -class => "list"}, esc_path($diff->{'file'}));
4286 print "</td>\n";
4287 print "<td>$mode_chng</td>\n";
4288 print "<td class=\"link\">";
4289 if ($action eq 'commitdiff') {
4290 # link to patch
4291 $patchno++;
4292 print $cgi->a({-href => "#patch$patchno"}, "patch");
4293 print " | ";
4295 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4296 hash_base=>$parent, file_name=>$diff->{'file'})},
4297 "blob") . " | ";
4298 if ($have_blame) {
4299 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4300 file_name=>$diff->{'file'})},
4301 "blame") . " | ";
4303 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4304 file_name=>$diff->{'file'})},
4305 "history");
4306 print "</td>\n";
4308 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4309 my $mode_chnge = "";
4310 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4311 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4312 if ($from_file_type ne $to_file_type) {
4313 $mode_chnge .= " from $from_file_type to $to_file_type";
4315 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4316 if ($from_mode_str && $to_mode_str) {
4317 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4318 } elsif ($to_mode_str) {
4319 $mode_chnge .= " mode: $to_mode_str";
4322 $mode_chnge .= "]</span>\n";
4324 print "<td>";
4325 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4326 hash_base=>$hash, file_name=>$diff->{'file'}),
4327 -class => "list"}, esc_path($diff->{'file'}));
4328 print "</td>\n";
4329 print "<td>$mode_chnge</td>\n";
4330 print "<td class=\"link\">";
4331 if ($action eq 'commitdiff') {
4332 # link to patch
4333 $patchno++;
4334 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4335 " | ";
4336 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4337 # "commit" view and modified file (not onlu mode changed)
4338 print $cgi->a({-href => href(action=>"blobdiff",
4339 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4340 hash_base=>$hash, hash_parent_base=>$parent,
4341 file_name=>$diff->{'file'})},
4342 "diff") .
4343 " | ";
4345 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4346 hash_base=>$hash, file_name=>$diff->{'file'})},
4347 "blob") . " | ";
4348 if ($have_blame) {
4349 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4350 file_name=>$diff->{'file'})},
4351 "blame") . " | ";
4353 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4354 file_name=>$diff->{'file'})},
4355 "history");
4356 print "</td>\n";
4358 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4359 my %status_name = ('R' => 'moved', 'C' => 'copied');
4360 my $nstatus = $status_name{$diff->{'status'}};
4361 my $mode_chng = "";
4362 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4363 # mode also for directories, so we cannot use $to_mode_str
4364 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4366 print "<td>" .
4367 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4368 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4369 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4370 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4371 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4372 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4373 -class => "list"}, esc_path($diff->{'from_file'})) .
4374 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4375 "<td class=\"link\">";
4376 if ($action eq 'commitdiff') {
4377 # link to patch
4378 $patchno++;
4379 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4380 " | ";
4381 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4382 # "commit" view and modified file (not only pure rename or copy)
4383 print $cgi->a({-href => href(action=>"blobdiff",
4384 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4385 hash_base=>$hash, hash_parent_base=>$parent,
4386 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4387 "diff") .
4388 " | ";
4390 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4391 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4392 "blob") . " | ";
4393 if ($have_blame) {
4394 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4395 file_name=>$diff->{'to_file'})},
4396 "blame") . " | ";
4398 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4399 file_name=>$diff->{'to_file'})},
4400 "history");
4401 print "</td>\n";
4403 } # we should not encounter Unmerged (U) or Unknown (X) status
4404 print "</tr>\n";
4406 print "</tbody>" if $has_header;
4407 print "</table>\n";
4410 sub git_patchset_body {
4411 my ($fd, $difftree, $hash, @hash_parents) = @_;
4412 my ($hash_parent) = $hash_parents[0];
4414 my $is_combined = (@hash_parents > 1);
4415 my $patch_idx = 0;
4416 my $patch_number = 0;
4417 my $patch_line;
4418 my $diffinfo;
4419 my $to_name;
4420 my (%from, %to);
4422 print "<div class=\"patchset\">\n";
4424 # skip to first patch
4425 while ($patch_line = <$fd>) {
4426 chomp $patch_line;
4428 last if ($patch_line =~ m/^diff /);
4431 PATCH:
4432 while ($patch_line) {
4434 # parse "git diff" header line
4435 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4436 # $1 is from_name, which we do not use
4437 $to_name = unquote($2);
4438 $to_name =~ s!^b/!!;
4439 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4440 # $1 is 'cc' or 'combined', which we do not use
4441 $to_name = unquote($2);
4442 } else {
4443 $to_name = undef;
4446 # check if current patch belong to current raw line
4447 # and parse raw git-diff line if needed
4448 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4449 # this is continuation of a split patch
4450 print "<div class=\"patch cont\">\n";
4451 } else {
4452 # advance raw git-diff output if needed
4453 $patch_idx++ if defined $diffinfo;
4455 # read and prepare patch information
4456 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4458 # compact combined diff output can have some patches skipped
4459 # find which patch (using pathname of result) we are at now;
4460 if ($is_combined) {
4461 while ($to_name ne $diffinfo->{'to_file'}) {
4462 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4463 format_diff_cc_simplified($diffinfo, @hash_parents) .
4464 "</div>\n"; # class="patch"
4466 $patch_idx++;
4467 $patch_number++;
4469 last if $patch_idx > $#$difftree;
4470 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4474 # modifies %from, %to hashes
4475 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4477 # this is first patch for raw difftree line with $patch_idx index
4478 # we index @$difftree array from 0, but number patches from 1
4479 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4482 # git diff header
4483 #assert($patch_line =~ m/^diff /) if DEBUG;
4484 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4485 $patch_number++;
4486 # print "git diff" header
4487 print format_git_diff_header_line($patch_line, $diffinfo,
4488 \%from, \%to);
4490 # print extended diff header
4491 print "<div class=\"diff extended_header\">\n";
4492 EXTENDED_HEADER:
4493 while ($patch_line = <$fd>) {
4494 chomp $patch_line;
4496 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4498 print format_extended_diff_header_line($patch_line, $diffinfo,
4499 \%from, \%to);
4501 print "</div>\n"; # class="diff extended_header"
4503 # from-file/to-file diff header
4504 if (! $patch_line) {
4505 print "</div>\n"; # class="patch"
4506 last PATCH;
4508 next PATCH if ($patch_line =~ m/^diff /);
4509 #assert($patch_line =~ m/^---/) if DEBUG;
4511 my $last_patch_line = $patch_line;
4512 $patch_line = <$fd>;
4513 chomp $patch_line;
4514 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4516 print format_diff_from_to_header($last_patch_line, $patch_line,
4517 $diffinfo, \%from, \%to,
4518 @hash_parents);
4520 # the patch itself
4521 LINE:
4522 while ($patch_line = <$fd>) {
4523 chomp $patch_line;
4525 next PATCH if ($patch_line =~ m/^diff /);
4527 print format_diff_line($patch_line, \%from, \%to);
4530 } continue {
4531 print "</div>\n"; # class="patch"
4534 # for compact combined (--cc) format, with chunk and patch simplification
4535 # the patchset might be empty, but there might be unprocessed raw lines
4536 for (++$patch_idx if $patch_number > 0;
4537 $patch_idx < @$difftree;
4538 ++$patch_idx) {
4539 # read and prepare patch information
4540 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4542 # generate anchor for "patch" links in difftree / whatchanged part
4543 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4544 format_diff_cc_simplified($diffinfo, @hash_parents) .
4545 "</div>\n"; # class="patch"
4547 $patch_number++;
4550 if ($patch_number == 0) {
4551 if (@hash_parents > 1) {
4552 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4553 } else {
4554 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4558 print "</div>\n"; # class="patchset"
4561 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4563 # fills project list info (age, description, owner, forks) for each
4564 # project in the list, removing invalid projects from returned list
4565 # NOTE: modifies $projlist, but does not remove entries from it
4566 sub fill_project_list_info {
4567 my ($projlist, $check_forks) = @_;
4568 my @projects;
4570 my $show_ctags = gitweb_check_feature('ctags');
4571 PROJECT:
4572 foreach my $pr (@$projlist) {
4573 my (@activity) = git_get_last_activity($pr->{'path'});
4574 unless (@activity) {
4575 next PROJECT;
4577 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4578 if (!defined $pr->{'descr'}) {
4579 my $descr = git_get_project_description($pr->{'path'}) || "";
4580 $descr = to_utf8($descr);
4581 $pr->{'descr_long'} = $descr;
4582 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4584 if (!defined $pr->{'owner'}) {
4585 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4587 if ($check_forks) {
4588 my $pname = $pr->{'path'};
4589 if (($pname =~ s/\.git$//) &&
4590 ($pname !~ /\/$/) &&
4591 (-d "$projectroot/$pname")) {
4592 $pr->{'forks'} = "-d $projectroot/$pname";
4593 } else {
4594 $pr->{'forks'} = 0;
4597 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4598 push @projects, $pr;
4601 return @projects;
4604 # print 'sort by' <th> element, generating 'sort by $name' replay link
4605 # if that order is not selected
4606 sub print_sort_th {
4607 print format_sort_th(@_);
4610 sub format_sort_th {
4611 my ($name, $order, $header) = @_;
4612 my $sort_th = "";
4613 $header ||= ucfirst($name);
4615 if ($order eq $name) {
4616 $sort_th .= "<th>$header</th>\n";
4617 } else {
4618 $sort_th .= "<th>" .
4619 $cgi->a({-href => href(-replay=>1, order=>$name),
4620 -class => "header"}, $header) .
4621 "</th>\n";
4624 return $sort_th;
4627 sub git_project_list_body {
4628 # actually uses global variable $project
4629 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4631 my $check_forks = gitweb_check_feature('forks');
4632 my @projects = fill_project_list_info($projlist, $check_forks);
4634 $order ||= $default_projects_order;
4635 $from = 0 unless defined $from;
4636 $to = $#projects if (!defined $to || $#projects < $to);
4638 my %order_info = (
4639 project => { key => 'path', type => 'str' },
4640 descr => { key => 'descr_long', type => 'str' },
4641 owner => { key => 'owner', type => 'str' },
4642 age => { key => 'age', type => 'num' }
4644 my $oi = $order_info{$order};
4645 if ($oi->{'type'} eq 'str') {
4646 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4647 } else {
4648 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4651 my $show_ctags = gitweb_check_feature('ctags');
4652 if ($show_ctags) {
4653 my %ctags;
4654 foreach my $p (@projects) {
4655 foreach my $ct (keys %{$p->{'ctags'}}) {
4656 $ctags{$ct} += $p->{'ctags'}->{$ct};
4659 my $cloud = git_populate_project_tagcloud(\%ctags);
4660 print git_show_project_tagcloud($cloud, 64);
4663 print "<table class=\"project_list\">\n";
4664 unless ($no_header) {
4665 print "<tr>\n";
4666 if ($check_forks) {
4667 print "<th></th>\n";
4669 print_sort_th('project', $order, 'Project');
4670 print_sort_th('descr', $order, 'Description');
4671 print_sort_th('owner', $order, 'Owner');
4672 print_sort_th('age', $order, 'Last Change');
4673 print "<th></th>\n" . # for links
4674 "</tr>\n";
4676 my $alternate = 1;
4677 my $tagfilter = $cgi->param('by_tag');
4678 for (my $i = $from; $i <= $to; $i++) {
4679 my $pr = $projects[$i];
4681 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4682 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4683 and not $pr->{'descr_long'} =~ /$searchtext/;
4684 # Weed out forks or non-matching entries of search
4685 if ($check_forks) {
4686 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4687 $forkbase="^$forkbase" if $forkbase;
4688 next if not $searchtext and not $tagfilter and $show_ctags
4689 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4692 if ($alternate) {
4693 print "<tr class=\"dark\">\n";
4694 } else {
4695 print "<tr class=\"light\">\n";
4697 $alternate ^= 1;
4698 if ($check_forks) {
4699 print "<td>";
4700 if ($pr->{'forks'}) {
4701 print "<!-- $pr->{'forks'} -->\n";
4702 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4704 print "</td>\n";
4706 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4707 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4708 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4709 -class => "list", -title => $pr->{'descr_long'}},
4710 esc_html($pr->{'descr'})) . "</td>\n" .
4711 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4712 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4713 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4714 "<td class=\"link\">" .
4715 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4716 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4717 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4718 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4719 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4720 "</td>\n" .
4721 "</tr>\n";
4723 if (defined $extra) {
4724 print "<tr>\n";
4725 if ($check_forks) {
4726 print "<td></td>\n";
4728 print "<td colspan=\"5\">$extra</td>\n" .
4729 "</tr>\n";
4731 print "</table>\n";
4734 sub git_log_body {
4735 # uses global variable $project
4736 my ($commitlist, $from, $to, $refs, $extra) = @_;
4738 $from = 0 unless defined $from;
4739 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4741 for (my $i = 0; $i <= $to; $i++) {
4742 my %co = %{$commitlist->[$i]};
4743 next if !%co;
4744 my $commit = $co{'id'};
4745 my $ref = format_ref_marker($refs, $commit);
4746 my %ad = parse_date($co{'author_epoch'});
4747 git_print_header_div('commit',
4748 "<span class=\"age\">$co{'age_string'}</span>" .
4749 esc_html($co{'title'}) . $ref,
4750 $commit);
4751 print "<div class=\"title_text\">\n" .
4752 "<div class=\"log_link\">\n" .
4753 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4754 " | " .
4755 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4756 " | " .
4757 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4758 "<br/>\n" .
4759 "</div>\n";
4760 git_print_authorship(\%co, -tag => 'span');
4761 print "<br/>\n</div>\n";
4763 print "<div class=\"log_body\">\n";
4764 git_print_log($co{'comment'}, -final_empty_line=> 1);
4765 print "</div>\n";
4767 if ($extra) {
4768 print "<div class=\"page_nav\">\n";
4769 print "$extra\n";
4770 print "</div>\n";
4774 sub git_shortlog_body {
4775 # uses global variable $project
4776 my ($commitlist, $from, $to, $refs, $extra) = @_;
4778 $from = 0 unless defined $from;
4779 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4781 print "<table class=\"shortlog\">\n";
4782 my $alternate = 1;
4783 for (my $i = $from; $i <= $to; $i++) {
4784 my %co = %{$commitlist->[$i]};
4785 my $commit = $co{'id'};
4786 my $ref = format_ref_marker($refs, $commit);
4787 if ($alternate) {
4788 print "<tr class=\"dark\">\n";
4789 } else {
4790 print "<tr class=\"light\">\n";
4792 $alternate ^= 1;
4793 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4794 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4795 format_author_html('td', \%co, 10) . "<td>";
4796 print format_subject_html($co{'title'}, $co{'title_short'},
4797 href(action=>"commit", hash=>$commit), $ref);
4798 print "</td>\n" .
4799 "<td class=\"link\">" .
4800 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4801 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4802 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4803 my $snapshot_links = format_snapshot_links($commit);
4804 if (defined $snapshot_links) {
4805 print " | " . $snapshot_links;
4807 print "</td>\n" .
4808 "</tr>\n";
4810 if (defined $extra) {
4811 print "<tr>\n" .
4812 "<td colspan=\"4\">$extra</td>\n" .
4813 "</tr>\n";
4815 print "</table>\n";
4818 sub git_history_body {
4819 # Warning: assumes constant type (blob or tree) during history
4820 my ($commitlist, $from, $to, $refs, $extra,
4821 $file_name, $file_hash, $ftype) = @_;
4823 $from = 0 unless defined $from;
4824 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4826 print "<table class=\"history\">\n";
4827 my $alternate = 1;
4828 for (my $i = $from; $i <= $to; $i++) {
4829 my %co = %{$commitlist->[$i]};
4830 if (!%co) {
4831 next;
4833 my $commit = $co{'id'};
4835 my $ref = format_ref_marker($refs, $commit);
4837 if ($alternate) {
4838 print "<tr class=\"dark\">\n";
4839 } else {
4840 print "<tr class=\"light\">\n";
4842 $alternate ^= 1;
4843 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4844 # shortlog: format_author_html('td', \%co, 10)
4845 format_author_html('td', \%co, 15, 3) . "<td>";
4846 # originally git_history used chop_str($co{'title'}, 50)
4847 print format_subject_html($co{'title'}, $co{'title_short'},
4848 href(action=>"commit", hash=>$commit), $ref);
4849 print "</td>\n" .
4850 "<td class=\"link\">" .
4851 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4852 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4854 if ($ftype eq 'blob') {
4855 my $blob_current = $file_hash;
4856 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4857 if (defined $blob_current && defined $blob_parent &&
4858 $blob_current ne $blob_parent) {
4859 print " | " .
4860 $cgi->a({-href => href(action=>"blobdiff",
4861 hash=>$blob_current, hash_parent=>$blob_parent,
4862 hash_base=>$hash_base, hash_parent_base=>$commit,
4863 file_name=>$file_name)},
4864 "diff to current");
4867 print "</td>\n" .
4868 "</tr>\n";
4870 if (defined $extra) {
4871 print "<tr>\n" .
4872 "<td colspan=\"4\">$extra</td>\n" .
4873 "</tr>\n";
4875 print "</table>\n";
4878 sub git_tags_body {
4879 # uses global variable $project
4880 my ($taglist, $from, $to, $extra) = @_;
4881 $from = 0 unless defined $from;
4882 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4884 print "<table class=\"tags\">\n";
4885 my $alternate = 1;
4886 for (my $i = $from; $i <= $to; $i++) {
4887 my $entry = $taglist->[$i];
4888 my %tag = %$entry;
4889 my $comment = $tag{'subject'};
4890 my $comment_short;
4891 if (defined $comment) {
4892 $comment_short = chop_str($comment, 30, 5);
4894 if ($alternate) {
4895 print "<tr class=\"dark\">\n";
4896 } else {
4897 print "<tr class=\"light\">\n";
4899 $alternate ^= 1;
4900 if (defined $tag{'age'}) {
4901 print "<td><i>$tag{'age'}</i></td>\n";
4902 } else {
4903 print "<td></td>\n";
4905 print "<td>" .
4906 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4907 -class => "list name"}, esc_html($tag{'name'})) .
4908 "</td>\n" .
4909 "<td>";
4910 if (defined $comment) {
4911 print format_subject_html($comment, $comment_short,
4912 href(action=>"tag", hash=>$tag{'id'}));
4914 print "</td>\n" .
4915 "<td class=\"selflink\">";
4916 if ($tag{'type'} eq "tag") {
4917 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4918 } else {
4919 print "&nbsp;";
4921 print "</td>\n" .
4922 "<td class=\"link\">" . " | " .
4923 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4924 if ($tag{'reftype'} eq "commit") {
4925 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4926 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4927 } elsif ($tag{'reftype'} eq "blob") {
4928 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4930 print "</td>\n" .
4931 "</tr>";
4933 if (defined $extra) {
4934 print "<tr>\n" .
4935 "<td colspan=\"5\">$extra</td>\n" .
4936 "</tr>\n";
4938 print "</table>\n";
4941 sub git_heads_body {
4942 # uses global variable $project
4943 my ($headlist, $head, $from, $to, $extra) = @_;
4944 $from = 0 unless defined $from;
4945 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4947 print "<table class=\"heads\">\n";
4948 my $alternate = 1;
4949 for (my $i = $from; $i <= $to; $i++) {
4950 my $entry = $headlist->[$i];
4951 my %ref = %$entry;
4952 my $curr = $ref{'id'} eq $head;
4953 if ($alternate) {
4954 print "<tr class=\"dark\">\n";
4955 } else {
4956 print "<tr class=\"light\">\n";
4958 $alternate ^= 1;
4959 print "<td><i>$ref{'age'}</i></td>\n" .
4960 ($curr ? "<td class=\"current_head\">" : "<td>") .
4961 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4962 -class => "list name"},esc_html($ref{'name'})) .
4963 "</td>\n" .
4964 "<td class=\"link\">" .
4965 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4966 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4967 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4968 "</td>\n" .
4969 "</tr>";
4971 if (defined $extra) {
4972 print "<tr>\n" .
4973 "<td colspan=\"3\">$extra</td>\n" .
4974 "</tr>\n";
4976 print "</table>\n";
4979 sub git_search_grep_body {
4980 my ($commitlist, $from, $to, $extra) = @_;
4981 $from = 0 unless defined $from;
4982 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4984 print "<table class=\"commit_search\">\n";
4985 my $alternate = 1;
4986 for (my $i = $from; $i <= $to; $i++) {
4987 my %co = %{$commitlist->[$i]};
4988 if (!%co) {
4989 next;
4991 my $commit = $co{'id'};
4992 if ($alternate) {
4993 print "<tr class=\"dark\">\n";
4994 } else {
4995 print "<tr class=\"light\">\n";
4997 $alternate ^= 1;
4998 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4999 format_author_html('td', \%co, 15, 5) .
5000 "<td>" .
5001 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5002 -class => "list subject"},
5003 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5004 my $comment = $co{'comment'};
5005 foreach my $line (@$comment) {
5006 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5007 my ($lead, $match, $trail) = ($1, $2, $3);
5008 $match = chop_str($match, 70, 5, 'center');
5009 my $contextlen = int((80 - length($match))/2);
5010 $contextlen = 30 if ($contextlen > 30);
5011 $lead = chop_str($lead, $contextlen, 10, 'left');
5012 $trail = chop_str($trail, $contextlen, 10, 'right');
5014 $lead = esc_html($lead);
5015 $match = esc_html($match);
5016 $trail = esc_html($trail);
5018 print "$lead<span class=\"match\">$match</span>$trail<br />";
5021 print "</td>\n" .
5022 "<td class=\"link\">" .
5023 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5024 " | " .
5025 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5026 " | " .
5027 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5028 print "</td>\n" .
5029 "</tr>\n";
5031 if (defined $extra) {
5032 print "<tr>\n" .
5033 "<td colspan=\"3\">$extra</td>\n" .
5034 "</tr>\n";
5036 print "</table>\n";
5039 ## ======================================================================
5040 ## ======================================================================
5041 ## actions
5043 sub git_project_list {
5044 my $order = $input_params{'order'};
5045 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5046 die_error(400, "Unknown order parameter");
5049 my @list = git_get_projects_list();
5050 if (!@list) {
5051 die_error(404, "No projects found");
5054 git_header_html();
5055 if (defined $home_text && -f $home_text) {
5056 print "<div class=\"index_include\">\n";
5057 insert_file($home_text);
5058 print "</div>\n";
5060 print $cgi->startform(-method => "get") .
5061 "<p class=\"projsearch\">Search:\n" .
5062 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5063 "</p>" .
5064 $cgi->end_form() . "\n";
5065 git_project_list_body(\@list, $order);
5066 git_footer_html();
5069 sub git_forks {
5070 my $order = $input_params{'order'};
5071 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5072 die_error(400, "Unknown order parameter");
5075 my @list = git_get_projects_list($project);
5076 if (!@list) {
5077 die_error(404, "No forks found");
5080 git_header_html();
5081 git_print_page_nav('','');
5082 git_print_header_div('summary', "$project forks");
5083 git_project_list_body(\@list, $order);
5084 git_footer_html();
5087 sub git_project_index {
5088 my @projects = git_get_projects_list($project);
5090 print $cgi->header(
5091 -type => 'text/plain',
5092 -charset => 'utf-8',
5093 -content_disposition => 'inline; filename="index.aux"');
5095 foreach my $pr (@projects) {
5096 if (!exists $pr->{'owner'}) {
5097 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5100 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5101 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5102 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5103 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5104 $path =~ s/ /\+/g;
5105 $owner =~ s/ /\+/g;
5107 print "$path $owner\n";
5111 sub git_summary {
5112 my $descr = git_get_project_description($project) || "none";
5113 my %co = parse_commit("HEAD");
5114 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5115 my $head = $co{'id'};
5117 my $owner = git_get_project_owner($project);
5119 my $refs = git_get_references();
5120 # These get_*_list functions return one more to allow us to see if
5121 # there are more ...
5122 my @taglist = git_get_tags_list(16);
5123 my @headlist = git_get_heads_list(16);
5124 my @forklist;
5125 my $check_forks = gitweb_check_feature('forks');
5127 if ($check_forks) {
5128 @forklist = git_get_projects_list($project);
5131 git_header_html();
5132 git_print_page_nav('summary','', $head);
5134 print "<div class=\"title\">&nbsp;</div>\n";
5135 print "<table class=\"projects_list\">\n" .
5136 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5137 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5138 if (defined $cd{'rfc2822'}) {
5139 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5142 # use per project git URL list in $projectroot/$project/cloneurl
5143 # or make project git URL from git base URL and project name
5144 my $url_tag = "URL";
5145 my @url_list = git_get_project_url_list($project);
5146 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5147 foreach my $git_url (@url_list) {
5148 next unless $git_url;
5149 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5150 $url_tag = "";
5153 # Tag cloud
5154 my $show_ctags = gitweb_check_feature('ctags');
5155 if ($show_ctags) {
5156 my $ctags = git_get_project_ctags($project);
5157 my $cloud = git_populate_project_tagcloud($ctags);
5158 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5159 print "</td>\n<td>" unless %$ctags;
5160 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5161 print "</td>\n<td>" if %$ctags;
5162 print git_show_project_tagcloud($cloud, 48);
5163 print "</td></tr>";
5166 print "</table>\n";
5168 # If XSS prevention is on, we don't include README.html.
5169 # TODO: Allow a readme in some safe format.
5170 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5171 print "<div class=\"title\">readme</div>\n" .
5172 "<div class=\"readme\">\n";
5173 insert_file("$projectroot/$project/README.html");
5174 print "\n</div>\n"; # class="readme"
5177 # we need to request one more than 16 (0..15) to check if
5178 # those 16 are all
5179 my @commitlist = $head ? parse_commits($head, 17) : ();
5180 if (@commitlist) {
5181 git_print_header_div('shortlog');
5182 git_shortlog_body(\@commitlist, 0, 15, $refs,
5183 $#commitlist <= 15 ? undef :
5184 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5187 if (@taglist) {
5188 git_print_header_div('tags');
5189 git_tags_body(\@taglist, 0, 15,
5190 $#taglist <= 15 ? undef :
5191 $cgi->a({-href => href(action=>"tags")}, "..."));
5194 if (@headlist) {
5195 git_print_header_div('heads');
5196 git_heads_body(\@headlist, $head, 0, 15,
5197 $#headlist <= 15 ? undef :
5198 $cgi->a({-href => href(action=>"heads")}, "..."));
5201 if (@forklist) {
5202 git_print_header_div('forks');
5203 git_project_list_body(\@forklist, 'age', 0, 15,
5204 $#forklist <= 15 ? undef :
5205 $cgi->a({-href => href(action=>"forks")}, "..."),
5206 'no_header');
5209 git_footer_html();
5212 sub git_tag {
5213 my %tag = parse_tag($hash);
5215 if (! %tag) {
5216 die_error(404, "Unknown tag object");
5219 my $head = git_get_head_hash($project);
5220 git_header_html();
5221 git_print_page_nav('','', $head,undef,$head);
5222 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5223 print "<div class=\"title_text\">\n" .
5224 "<table class=\"object_header\">\n" .
5225 "<tr>\n" .
5226 "<td>object</td>\n" .
5227 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5228 $tag{'object'}) . "</td>\n" .
5229 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5230 $tag{'type'}) . "</td>\n" .
5231 "</tr>\n";
5232 if (defined($tag{'author'})) {
5233 git_print_authorship_rows(\%tag, 'author');
5235 print "</table>\n\n" .
5236 "</div>\n";
5237 print "<div class=\"page_body\">";
5238 my $comment = $tag{'comment'};
5239 foreach my $line (@$comment) {
5240 chomp $line;
5241 print esc_html($line, -nbsp=>1) . "<br/>\n";
5243 print "</div>\n";
5244 git_footer_html();
5247 sub git_blame_common {
5248 my $format = shift || 'porcelain';
5249 if ($format eq 'porcelain' && $cgi->param('js')) {
5250 $format = 'incremental';
5251 $action = 'blame_incremental'; # for page title etc
5254 # permissions
5255 gitweb_check_feature('blame')
5256 or die_error(403, "Blame view not allowed");
5258 # error checking
5259 die_error(400, "No file name given") unless $file_name;
5260 $hash_base ||= git_get_head_hash($project);
5261 die_error(404, "Couldn't find base commit") unless $hash_base;
5262 my %co = parse_commit($hash_base)
5263 or die_error(404, "Commit not found");
5264 my $ftype = "blob";
5265 if (!defined $hash) {
5266 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5267 or die_error(404, "Error looking up file");
5268 } else {
5269 $ftype = git_get_type($hash);
5270 if ($ftype !~ "blob") {
5271 die_error(400, "Object is not a blob");
5275 my $fd;
5276 if ($format eq 'incremental') {
5277 # get file contents (as base)
5278 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5279 or die_error(500, "Open git-cat-file failed");
5280 } elsif ($format eq 'data') {
5281 # run git-blame --incremental
5282 open $fd, "-|", git_cmd(), "blame", "--incremental",
5283 $hash_base, "--", $file_name
5284 or die_error(500, "Open git-blame --incremental failed");
5285 } else {
5286 # run git-blame --porcelain
5287 open $fd, "-|", git_cmd(), "blame", '-p',
5288 $hash_base, '--', $file_name
5289 or die_error(500, "Open git-blame --porcelain failed");
5292 # incremental blame data returns early
5293 if ($format eq 'data') {
5294 print $cgi->header(
5295 -type=>"text/plain", -charset => "utf-8",
5296 -status=> "200 OK");
5297 local $| = 1; # output autoflush
5298 print while <$fd>;
5299 close $fd
5300 or print "ERROR $!\n";
5302 print 'END';
5303 if (defined $t0 && gitweb_check_feature('timed')) {
5304 print ' '.
5305 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5306 ' '.$number_of_git_cmds;
5308 print "\n";
5310 return;
5313 # page header
5314 git_header_html();
5315 my $formats_nav =
5316 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5317 "blob") .
5318 " | ";
5319 if ($format eq 'incremental') {
5320 $formats_nav .=
5321 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5322 "blame") . " (non-incremental)";
5323 } else {
5324 $formats_nav .=
5325 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5326 "blame") . " (incremental)";
5328 $formats_nav .=
5329 " | " .
5330 $cgi->a({-href => href(action=>"history", -replay=>1)},
5331 "history") .
5332 " | " .
5333 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5334 "HEAD");
5335 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5336 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5337 git_print_page_path($file_name, $ftype, $hash_base);
5339 # page body
5340 if ($format eq 'incremental') {
5341 print "<noscript>\n<div class=\"error\"><center><b>\n".
5342 "This page requires JavaScript to run.\n Use ".
5343 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5344 'this page').
5345 " instead.\n".
5346 "</b></center></div>\n</noscript>\n";
5348 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5351 print qq!<div class="page_body">\n!;
5352 print qq!<div id="progress_info">... / ...</div>\n!
5353 if ($format eq 'incremental');
5354 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5355 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5356 qq!<thead>\n!.
5357 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5358 qq!</thead>\n!.
5359 qq!<tbody>\n!;
5361 my @rev_color = qw(light dark);
5362 my $num_colors = scalar(@rev_color);
5363 my $current_color = 0;
5365 if ($format eq 'incremental') {
5366 my $color_class = $rev_color[$current_color];
5368 #contents of a file
5369 my $linenr = 0;
5370 LINE:
5371 while (my $line = <$fd>) {
5372 chomp $line;
5373 $linenr++;
5375 print qq!<tr id="l$linenr" class="$color_class">!.
5376 qq!<td class="sha1"><a href=""> </a></td>!.
5377 qq!<td class="linenr">!.
5378 qq!<a class="linenr" href="">$linenr</a></td>!;
5379 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5380 print qq!</tr>\n!;
5383 } else { # porcelain, i.e. ordinary blame
5384 my %metainfo = (); # saves information about commits
5386 # blame data
5387 LINE:
5388 while (my $line = <$fd>) {
5389 chomp $line;
5390 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5391 # no <lines in group> for subsequent lines in group of lines
5392 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5393 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5394 if (!exists $metainfo{$full_rev}) {
5395 $metainfo{$full_rev} = { 'nprevious' => 0 };
5397 my $meta = $metainfo{$full_rev};
5398 my $data;
5399 while ($data = <$fd>) {
5400 chomp $data;
5401 last if ($data =~ s/^\t//); # contents of line
5402 if ($data =~ /^(\S+)(?: (.*))?$/) {
5403 $meta->{$1} = $2 unless exists $meta->{$1};
5405 if ($data =~ /^previous /) {
5406 $meta->{'nprevious'}++;
5409 my $short_rev = substr($full_rev, 0, 8);
5410 my $author = $meta->{'author'};
5411 my %date =
5412 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5413 my $date = $date{'iso-tz'};
5414 if ($group_size) {
5415 $current_color = ($current_color + 1) % $num_colors;
5417 my $tr_class = $rev_color[$current_color];
5418 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5419 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5420 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5421 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5422 if ($group_size) {
5423 print "<td class=\"sha1\"";
5424 print " title=\"". esc_html($author) . ", $date\"";
5425 print " rowspan=\"$group_size\"" if ($group_size > 1);
5426 print ">";
5427 print $cgi->a({-href => href(action=>"commit",
5428 hash=>$full_rev,
5429 file_name=>$file_name)},
5430 esc_html($short_rev));
5431 if ($group_size >= 2) {
5432 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5433 if (@author_initials) {
5434 print "<br />" .
5435 esc_html(join('', @author_initials));
5436 # or join('.', ...)
5439 print "</td>\n";
5441 # 'previous' <sha1 of parent commit> <filename at commit>
5442 if (exists $meta->{'previous'} &&
5443 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5444 $meta->{'parent'} = $1;
5445 $meta->{'file_parent'} = unquote($2);
5447 my $linenr_commit =
5448 exists($meta->{'parent'}) ?
5449 $meta->{'parent'} : $full_rev;
5450 my $linenr_filename =
5451 exists($meta->{'file_parent'}) ?
5452 $meta->{'file_parent'} : unquote($meta->{'filename'});
5453 my $blamed = href(action => 'blame',
5454 file_name => $linenr_filename,
5455 hash_base => $linenr_commit);
5456 print "<td class=\"linenr\">";
5457 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5458 -class => "linenr" },
5459 esc_html($lineno));
5460 print "</td>";
5461 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5462 print "</tr>\n";
5463 } # end while
5467 # footer
5468 print "</tbody>\n".
5469 "</table>\n"; # class="blame"
5470 print "</div>\n"; # class="blame_body"
5471 close $fd
5472 or print "Reading blob failed\n";
5474 git_footer_html();
5477 sub git_blame {
5478 git_blame_common();
5481 sub git_blame_incremental {
5482 git_blame_common('incremental');
5485 sub git_blame_data {
5486 git_blame_common('data');
5489 sub git_tags {
5490 my $head = git_get_head_hash($project);
5491 git_header_html();
5492 git_print_page_nav('','', $head,undef,$head);
5493 git_print_header_div('summary', $project);
5495 my @tagslist = git_get_tags_list();
5496 if (@tagslist) {
5497 git_tags_body(\@tagslist);
5499 git_footer_html();
5502 sub git_heads {
5503 my $head = git_get_head_hash($project);
5504 git_header_html();
5505 git_print_page_nav('','', $head,undef,$head);
5506 git_print_header_div('summary', $project);
5508 my @headslist = git_get_heads_list();
5509 if (@headslist) {
5510 git_heads_body(\@headslist, $head);
5512 git_footer_html();
5515 sub git_blob_plain {
5516 my $type = shift;
5517 my $expires;
5519 if (!defined $hash) {
5520 if (defined $file_name) {
5521 my $base = $hash_base || git_get_head_hash($project);
5522 $hash = git_get_hash_by_path($base, $file_name, "blob")
5523 or die_error(404, "Cannot find file");
5524 } else {
5525 die_error(400, "No file name defined");
5527 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5528 # blobs defined by non-textual hash id's can be cached
5529 $expires = "+1d";
5532 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5533 or die_error(500, "Open git-cat-file blob '$hash' failed");
5535 # content-type (can include charset)
5536 $type = blob_contenttype($fd, $file_name, $type);
5538 # "save as" filename, even when no $file_name is given
5539 my $save_as = "$hash";
5540 if (defined $file_name) {
5541 $save_as = $file_name;
5542 } elsif ($type =~ m/^text\//) {
5543 $save_as .= '.txt';
5546 # With XSS prevention on, blobs of all types except a few known safe
5547 # ones are served with "Content-Disposition: attachment" to make sure
5548 # they don't run in our security domain. For certain image types,
5549 # blob view writes an <img> tag referring to blob_plain view, and we
5550 # want to be sure not to break that by serving the image as an
5551 # attachment (though Firefox 3 doesn't seem to care).
5552 my $sandbox = $prevent_xss &&
5553 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5555 print $cgi->header(
5556 -type => $type,
5557 -expires => $expires,
5558 -content_disposition =>
5559 ($sandbox ? 'attachment' : 'inline')
5560 . '; filename="' . $save_as . '"');
5561 local $/ = undef;
5562 binmode STDOUT, ':raw';
5563 print <$fd>;
5564 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5565 close $fd;
5568 sub git_blob {
5569 my $expires;
5571 if (!defined $hash) {
5572 if (defined $file_name) {
5573 my $base = $hash_base || git_get_head_hash($project);
5574 $hash = git_get_hash_by_path($base, $file_name, "blob")
5575 or die_error(404, "Cannot find file");
5576 } else {
5577 die_error(400, "No file name defined");
5579 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5580 # blobs defined by non-textual hash id's can be cached
5581 $expires = "+1d";
5584 my $have_blame = gitweb_check_feature('blame');
5585 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5586 or die_error(500, "Couldn't cat $file_name, $hash");
5587 my $mimetype = blob_mimetype($fd, $file_name);
5588 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5589 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5590 close $fd;
5591 return git_blob_plain($mimetype);
5593 # we can have blame only for text/* mimetype
5594 $have_blame &&= ($mimetype =~ m!^text/!);
5596 my $highlight = gitweb_check_feature('highlight');
5597 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5598 $fd = run_highlighter($fd, $highlight, $syntax)
5599 if $syntax;
5601 git_header_html(undef, $expires);
5602 my $formats_nav = '';
5603 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5604 if (defined $file_name) {
5605 if ($have_blame) {
5606 $formats_nav .=
5607 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5608 "blame") .
5609 " | ";
5611 $formats_nav .=
5612 $cgi->a({-href => href(action=>"history", -replay=>1)},
5613 "history") .
5614 " | " .
5615 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5616 "raw") .
5617 " | " .
5618 $cgi->a({-href => href(action=>"blob",
5619 hash_base=>"HEAD", file_name=>$file_name)},
5620 "HEAD");
5621 } else {
5622 $formats_nav .=
5623 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5624 "raw");
5626 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5627 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5628 } else {
5629 print "<div class=\"page_nav\">\n" .
5630 "<br/><br/></div>\n" .
5631 "<div class=\"title\">$hash</div>\n";
5633 git_print_page_path($file_name, "blob", $hash_base);
5634 print "<div class=\"page_body\">\n";
5635 if ($mimetype =~ m!^image/!) {
5636 print qq!<img type="$mimetype"!;
5637 if ($file_name) {
5638 print qq! alt="$file_name" title="$file_name"!;
5640 print qq! src="! .
5641 href(action=>"blob_plain", hash=>$hash,
5642 hash_base=>$hash_base, file_name=>$file_name) .
5643 qq!" />\n!;
5644 } else {
5645 my $nr;
5646 while (my $line = <$fd>) {
5647 chomp $line;
5648 $nr++;
5649 $line = untabify($line);
5650 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5651 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5654 close $fd
5655 or print "Reading blob failed.\n";
5656 print "</div>";
5657 git_footer_html();
5660 sub git_tree {
5661 if (!defined $hash_base) {
5662 $hash_base = "HEAD";
5664 if (!defined $hash) {
5665 if (defined $file_name) {
5666 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5667 } else {
5668 $hash = $hash_base;
5671 die_error(404, "No such tree") unless defined($hash);
5673 my $show_sizes = gitweb_check_feature('show-sizes');
5674 my $have_blame = gitweb_check_feature('blame');
5676 my @entries = ();
5678 local $/ = "\0";
5679 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5680 ($show_sizes ? '-l' : ()), @extra_options, $hash
5681 or die_error(500, "Open git-ls-tree failed");
5682 @entries = map { chomp; $_ } <$fd>;
5683 close $fd
5684 or die_error(404, "Reading tree failed");
5687 my $refs = git_get_references();
5688 my $ref = format_ref_marker($refs, $hash_base);
5689 git_header_html();
5690 my $basedir = '';
5691 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5692 my @views_nav = ();
5693 if (defined $file_name) {
5694 push @views_nav,
5695 $cgi->a({-href => href(action=>"history", -replay=>1)},
5696 "history"),
5697 $cgi->a({-href => href(action=>"tree",
5698 hash_base=>"HEAD", file_name=>$file_name)},
5699 "HEAD"),
5701 my $snapshot_links = format_snapshot_links($hash);
5702 if (defined $snapshot_links) {
5703 # FIXME: Should be available when we have no hash base as well.
5704 push @views_nav, $snapshot_links;
5706 git_print_page_nav('tree','', $hash_base, undef, undef,
5707 join(' | ', @views_nav));
5708 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5709 } else {
5710 undef $hash_base;
5711 print "<div class=\"page_nav\">\n";
5712 print "<br/><br/></div>\n";
5713 print "<div class=\"title\">$hash</div>\n";
5715 if (defined $file_name) {
5716 $basedir = $file_name;
5717 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5718 $basedir .= '/';
5720 git_print_page_path($file_name, 'tree', $hash_base);
5722 print "<div class=\"page_body\">\n";
5723 print "<table class=\"tree\">\n";
5724 my $alternate = 1;
5725 # '..' (top directory) link if possible
5726 if (defined $hash_base &&
5727 defined $file_name && $file_name =~ m![^/]+$!) {
5728 if ($alternate) {
5729 print "<tr class=\"dark\">\n";
5730 } else {
5731 print "<tr class=\"light\">\n";
5733 $alternate ^= 1;
5735 my $up = $file_name;
5736 $up =~ s!/?[^/]+$!!;
5737 undef $up unless $up;
5738 # based on git_print_tree_entry
5739 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5740 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5741 print '<td class="list">';
5742 print $cgi->a({-href => href(action=>"tree",
5743 hash_base=>$hash_base,
5744 file_name=>$up)},
5745 "..");
5746 print "</td>\n";
5747 print "<td class=\"link\"></td>\n";
5749 print "</tr>\n";
5751 foreach my $line (@entries) {
5752 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5754 if ($alternate) {
5755 print "<tr class=\"dark\">\n";
5756 } else {
5757 print "<tr class=\"light\">\n";
5759 $alternate ^= 1;
5761 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5763 print "</tr>\n";
5765 print "</table>\n" .
5766 "</div>";
5767 git_footer_html();
5770 sub snapshot_name {
5771 my ($project, $hash) = @_;
5773 # path/to/project.git -> project
5774 # path/to/project/.git -> project
5775 my $name = to_utf8($project);
5776 $name =~ s,([^/])/*\.git$,$1,;
5777 $name = basename($name);
5778 # sanitize name
5779 $name =~ s/[[:cntrl:]]/?/g;
5781 my $ver = $hash;
5782 if ($hash =~ /^[0-9a-fA-F]+$/) {
5783 # shorten SHA-1 hash
5784 my $full_hash = git_get_full_hash($project, $hash);
5785 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5786 $ver = git_get_short_hash($project, $hash);
5788 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5789 # tags don't need shortened SHA-1 hash
5790 $ver = $1;
5791 } else {
5792 # branches and other need shortened SHA-1 hash
5793 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5794 $ver = $1;
5796 $ver .= '-' . git_get_short_hash($project, $hash);
5798 # in case of hierarchical branch names
5799 $ver =~ s!/!.!g;
5801 # name = project-version_string
5802 $name = "$name-$ver";
5804 return wantarray ? ($name, $name) : $name;
5807 sub git_snapshot {
5808 my $format = $input_params{'snapshot_format'};
5809 if (!@snapshot_fmts) {
5810 die_error(403, "Snapshots not allowed");
5812 # default to first supported snapshot format
5813 $format ||= $snapshot_fmts[0];
5814 if ($format !~ m/^[a-z0-9]+$/) {
5815 die_error(400, "Invalid snapshot format parameter");
5816 } elsif (!exists($known_snapshot_formats{$format})) {
5817 die_error(400, "Unknown snapshot format");
5818 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5819 die_error(403, "Snapshot format not allowed");
5820 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5821 die_error(403, "Unsupported snapshot format");
5824 my $type = git_get_type("$hash^{}");
5825 if (!$type) {
5826 die_error(404, 'Object does not exist');
5827 } elsif ($type eq 'blob') {
5828 die_error(400, 'Object is not a tree-ish');
5831 my ($name, $prefix) = snapshot_name($project, $hash);
5832 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
5833 my $cmd = quote_command(
5834 git_cmd(), 'archive',
5835 "--format=$known_snapshot_formats{$format}{'format'}",
5836 "--prefix=$prefix/", $hash);
5837 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5838 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5841 $filename =~ s/(["\\])/\\$1/g;
5842 print $cgi->header(
5843 -type => $known_snapshot_formats{$format}{'type'},
5844 -content_disposition => 'inline; filename="' . $filename . '"',
5845 -status => '200 OK');
5847 open my $fd, "-|", $cmd
5848 or die_error(500, "Execute git-archive failed");
5849 binmode STDOUT, ':raw';
5850 print <$fd>;
5851 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5852 close $fd;
5855 sub git_log_generic {
5856 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
5858 my $head = git_get_head_hash($project);
5859 if (!defined $base) {
5860 $base = $head;
5862 if (!defined $page) {
5863 $page = 0;
5865 my $refs = git_get_references();
5867 my $commit_hash = $base;
5868 if (defined $parent) {
5869 $commit_hash = "$parent..$base";
5871 my @commitlist =
5872 parse_commits($commit_hash, 101, (100 * $page),
5873 defined $file_name ? ($file_name, "--full-history") : ());
5875 my $ftype;
5876 if (!defined $file_hash && defined $file_name) {
5877 # some commits could have deleted file in question,
5878 # and not have it in tree, but one of them has to have it
5879 for (my $i = 0; $i < @commitlist; $i++) {
5880 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5881 last if defined $file_hash;
5884 if (defined $file_hash) {
5885 $ftype = git_get_type($file_hash);
5887 if (defined $file_name && !defined $ftype) {
5888 die_error(500, "Unknown type of object");
5890 my %co;
5891 if (defined $file_name) {
5892 %co = parse_commit($base)
5893 or die_error(404, "Unknown commit object");
5897 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
5898 my $next_link = '';
5899 if ($#commitlist >= 100) {
5900 $next_link =
5901 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5902 -accesskey => "n", -title => "Alt-n"}, "next");
5904 my $patch_max = gitweb_get_feature('patches');
5905 if ($patch_max && !defined $file_name) {
5906 if ($patch_max < 0 || @commitlist <= $patch_max) {
5907 $paging_nav .= " &sdot; " .
5908 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5909 "patches");
5913 git_header_html();
5914 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
5915 if (defined $file_name) {
5916 git_print_header_div('commit', esc_html($co{'title'}), $base);
5917 } else {
5918 git_print_header_div('summary', $project)
5920 git_print_page_path($file_name, $ftype, $hash_base)
5921 if (defined $file_name);
5923 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
5924 $file_name, $file_hash, $ftype);
5926 git_footer_html();
5929 sub git_log {
5930 git_log_generic('log', \&git_log_body,
5931 $hash, $hash_parent);
5934 sub git_commit {
5935 $hash ||= $hash_base || "HEAD";
5936 my %co = parse_commit($hash)
5937 or die_error(404, "Unknown commit object");
5939 my $parent = $co{'parent'};
5940 my $parents = $co{'parents'}; # listref
5942 # we need to prepare $formats_nav before any parameter munging
5943 my $formats_nav;
5944 if (!defined $parent) {
5945 # --root commitdiff
5946 $formats_nav .= '(initial)';
5947 } elsif (@$parents == 1) {
5948 # single parent commit
5949 $formats_nav .=
5950 '(parent: ' .
5951 $cgi->a({-href => href(action=>"commit",
5952 hash=>$parent)},
5953 esc_html(substr($parent, 0, 7))) .
5954 ')';
5955 } else {
5956 # merge commit
5957 $formats_nav .=
5958 '(merge: ' .
5959 join(' ', map {
5960 $cgi->a({-href => href(action=>"commit",
5961 hash=>$_)},
5962 esc_html(substr($_, 0, 7)));
5963 } @$parents ) .
5964 ')';
5966 if (gitweb_check_feature('patches') && @$parents <= 1) {
5967 $formats_nav .= " | " .
5968 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5969 "patch");
5972 if (!defined $parent) {
5973 $parent = "--root";
5975 my @difftree;
5976 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5977 @diff_opts,
5978 (@$parents <= 1 ? $parent : '-c'),
5979 $hash, "--"
5980 or die_error(500, "Open git-diff-tree failed");
5981 @difftree = map { chomp; $_ } <$fd>;
5982 close $fd or die_error(404, "Reading git-diff-tree failed");
5984 # non-textual hash id's can be cached
5985 my $expires;
5986 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5987 $expires = "+1d";
5989 my $refs = git_get_references();
5990 my $ref = format_ref_marker($refs, $co{'id'});
5992 git_header_html(undef, $expires);
5993 git_print_page_nav('commit', '',
5994 $hash, $co{'tree'}, $hash,
5995 $formats_nav);
5997 if (defined $co{'parent'}) {
5998 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5999 } else {
6000 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6002 print "<div class=\"title_text\">\n" .
6003 "<table class=\"object_header\">\n";
6004 git_print_authorship_rows(\%co);
6005 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6006 print "<tr>" .
6007 "<td>tree</td>" .
6008 "<td class=\"sha1\">" .
6009 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6010 class => "list"}, $co{'tree'}) .
6011 "</td>" .
6012 "<td class=\"link\">" .
6013 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6014 "tree");
6015 my $snapshot_links = format_snapshot_links($hash);
6016 if (defined $snapshot_links) {
6017 print " | " . $snapshot_links;
6019 print "</td>" .
6020 "</tr>\n";
6022 foreach my $par (@$parents) {
6023 print "<tr>" .
6024 "<td>parent</td>" .
6025 "<td class=\"sha1\">" .
6026 $cgi->a({-href => href(action=>"commit", hash=>$par),
6027 class => "list"}, $par) .
6028 "</td>" .
6029 "<td class=\"link\">" .
6030 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6031 " | " .
6032 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6033 "</td>" .
6034 "</tr>\n";
6036 print "</table>".
6037 "</div>\n";
6039 print "<div class=\"page_body\">\n";
6040 git_print_log($co{'comment'});
6041 print "</div>\n";
6043 git_difftree_body(\@difftree, $hash, @$parents);
6045 git_footer_html();
6048 sub git_object {
6049 # object is defined by:
6050 # - hash or hash_base alone
6051 # - hash_base and file_name
6052 my $type;
6054 # - hash or hash_base alone
6055 if ($hash || ($hash_base && !defined $file_name)) {
6056 my $object_id = $hash || $hash_base;
6058 open my $fd, "-|", quote_command(
6059 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6060 or die_error(404, "Object does not exist");
6061 $type = <$fd>;
6062 chomp $type;
6063 close $fd
6064 or die_error(404, "Object does not exist");
6066 # - hash_base and file_name
6067 } elsif ($hash_base && defined $file_name) {
6068 $file_name =~ s,/+$,,;
6070 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6071 or die_error(404, "Base object does not exist");
6073 # here errors should not hapen
6074 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6075 or die_error(500, "Open git-ls-tree failed");
6076 my $line = <$fd>;
6077 close $fd;
6079 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6080 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6081 die_error(404, "File or directory for given base does not exist");
6083 $type = $2;
6084 $hash = $3;
6085 } else {
6086 die_error(400, "Not enough information to find object");
6089 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6090 hash=>$hash, hash_base=>$hash_base,
6091 file_name=>$file_name),
6092 -status => '302 Found');
6095 sub git_blobdiff {
6096 my $format = shift || 'html';
6098 my $fd;
6099 my @difftree;
6100 my %diffinfo;
6101 my $expires;
6103 # preparing $fd and %diffinfo for git_patchset_body
6104 # new style URI
6105 if (defined $hash_base && defined $hash_parent_base) {
6106 if (defined $file_name) {
6107 # read raw output
6108 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6109 $hash_parent_base, $hash_base,
6110 "--", (defined $file_parent ? $file_parent : ()), $file_name
6111 or die_error(500, "Open git-diff-tree failed");
6112 @difftree = map { chomp; $_ } <$fd>;
6113 close $fd
6114 or die_error(404, "Reading git-diff-tree failed");
6115 @difftree
6116 or die_error(404, "Blob diff not found");
6118 } elsif (defined $hash &&
6119 $hash =~ /[0-9a-fA-F]{40}/) {
6120 # try to find filename from $hash
6122 # read filtered raw output
6123 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6124 $hash_parent_base, $hash_base, "--"
6125 or die_error(500, "Open git-diff-tree failed");
6126 @difftree =
6127 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6128 # $hash == to_id
6129 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6130 map { chomp; $_ } <$fd>;
6131 close $fd
6132 or die_error(404, "Reading git-diff-tree failed");
6133 @difftree
6134 or die_error(404, "Blob diff not found");
6136 } else {
6137 die_error(400, "Missing one of the blob diff parameters");
6140 if (@difftree > 1) {
6141 die_error(400, "Ambiguous blob diff specification");
6144 %diffinfo = parse_difftree_raw_line($difftree[0]);
6145 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6146 $file_name ||= $diffinfo{'to_file'};
6148 $hash_parent ||= $diffinfo{'from_id'};
6149 $hash ||= $diffinfo{'to_id'};
6151 # non-textual hash id's can be cached
6152 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6153 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6154 $expires = '+1d';
6157 # open patch output
6158 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6159 '-p', ($format eq 'html' ? "--full-index" : ()),
6160 $hash_parent_base, $hash_base,
6161 "--", (defined $file_parent ? $file_parent : ()), $file_name
6162 or die_error(500, "Open git-diff-tree failed");
6165 # old/legacy style URI -- not generated anymore since 1.4.3.
6166 if (!%diffinfo) {
6167 die_error('404 Not Found', "Missing one of the blob diff parameters")
6170 # header
6171 if ($format eq 'html') {
6172 my $formats_nav =
6173 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6174 "raw");
6175 git_header_html(undef, $expires);
6176 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6177 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6178 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6179 } else {
6180 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6181 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6183 if (defined $file_name) {
6184 git_print_page_path($file_name, "blob", $hash_base);
6185 } else {
6186 print "<div class=\"page_path\"></div>\n";
6189 } elsif ($format eq 'plain') {
6190 print $cgi->header(
6191 -type => 'text/plain',
6192 -charset => 'utf-8',
6193 -expires => $expires,
6194 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6196 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6198 } else {
6199 die_error(400, "Unknown blobdiff format");
6202 # patch
6203 if ($format eq 'html') {
6204 print "<div class=\"page_body\">\n";
6206 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6207 close $fd;
6209 print "</div>\n"; # class="page_body"
6210 git_footer_html();
6212 } else {
6213 while (my $line = <$fd>) {
6214 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6215 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6217 print $line;
6219 last if $line =~ m!^\+\+\+!;
6221 local $/ = undef;
6222 print <$fd>;
6223 close $fd;
6227 sub git_blobdiff_plain {
6228 git_blobdiff('plain');
6231 sub git_commitdiff {
6232 my %params = @_;
6233 my $format = $params{-format} || 'html';
6235 my ($patch_max) = gitweb_get_feature('patches');
6236 if ($format eq 'patch') {
6237 die_error(403, "Patch view not allowed") unless $patch_max;
6240 $hash ||= $hash_base || "HEAD";
6241 my %co = parse_commit($hash)
6242 or die_error(404, "Unknown commit object");
6244 # choose format for commitdiff for merge
6245 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6246 $hash_parent = '--cc';
6248 # we need to prepare $formats_nav before almost any parameter munging
6249 my $formats_nav;
6250 if ($format eq 'html') {
6251 $formats_nav =
6252 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6253 "raw");
6254 if ($patch_max && @{$co{'parents'}} <= 1) {
6255 $formats_nav .= " | " .
6256 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6257 "patch");
6260 if (defined $hash_parent &&
6261 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6262 # commitdiff with two commits given
6263 my $hash_parent_short = $hash_parent;
6264 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6265 $hash_parent_short = substr($hash_parent, 0, 7);
6267 $formats_nav .=
6268 ' (from';
6269 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6270 if ($co{'parents'}[$i] eq $hash_parent) {
6271 $formats_nav .= ' parent ' . ($i+1);
6272 last;
6275 $formats_nav .= ': ' .
6276 $cgi->a({-href => href(action=>"commitdiff",
6277 hash=>$hash_parent)},
6278 esc_html($hash_parent_short)) .
6279 ')';
6280 } elsif (!$co{'parent'}) {
6281 # --root commitdiff
6282 $formats_nav .= ' (initial)';
6283 } elsif (scalar @{$co{'parents'}} == 1) {
6284 # single parent commit
6285 $formats_nav .=
6286 ' (parent: ' .
6287 $cgi->a({-href => href(action=>"commitdiff",
6288 hash=>$co{'parent'})},
6289 esc_html(substr($co{'parent'}, 0, 7))) .
6290 ')';
6291 } else {
6292 # merge commit
6293 if ($hash_parent eq '--cc') {
6294 $formats_nav .= ' | ' .
6295 $cgi->a({-href => href(action=>"commitdiff",
6296 hash=>$hash, hash_parent=>'-c')},
6297 'combined');
6298 } else { # $hash_parent eq '-c'
6299 $formats_nav .= ' | ' .
6300 $cgi->a({-href => href(action=>"commitdiff",
6301 hash=>$hash, hash_parent=>'--cc')},
6302 'compact');
6304 $formats_nav .=
6305 ' (merge: ' .
6306 join(' ', map {
6307 $cgi->a({-href => href(action=>"commitdiff",
6308 hash=>$_)},
6309 esc_html(substr($_, 0, 7)));
6310 } @{$co{'parents'}} ) .
6311 ')';
6315 my $hash_parent_param = $hash_parent;
6316 if (!defined $hash_parent_param) {
6317 # --cc for multiple parents, --root for parentless
6318 $hash_parent_param =
6319 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6322 # read commitdiff
6323 my $fd;
6324 my @difftree;
6325 if ($format eq 'html') {
6326 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6327 "--no-commit-id", "--patch-with-raw", "--full-index",
6328 $hash_parent_param, $hash, "--"
6329 or die_error(500, "Open git-diff-tree failed");
6331 while (my $line = <$fd>) {
6332 chomp $line;
6333 # empty line ends raw part of diff-tree output
6334 last unless $line;
6335 push @difftree, scalar parse_difftree_raw_line($line);
6338 } elsif ($format eq 'plain') {
6339 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6340 '-p', $hash_parent_param, $hash, "--"
6341 or die_error(500, "Open git-diff-tree failed");
6342 } elsif ($format eq 'patch') {
6343 # For commit ranges, we limit the output to the number of
6344 # patches specified in the 'patches' feature.
6345 # For single commits, we limit the output to a single patch,
6346 # diverging from the git-format-patch default.
6347 my @commit_spec = ();
6348 if ($hash_parent) {
6349 if ($patch_max > 0) {
6350 push @commit_spec, "-$patch_max";
6352 push @commit_spec, '-n', "$hash_parent..$hash";
6353 } else {
6354 if ($params{-single}) {
6355 push @commit_spec, '-1';
6356 } else {
6357 if ($patch_max > 0) {
6358 push @commit_spec, "-$patch_max";
6360 push @commit_spec, "-n";
6362 push @commit_spec, '--root', $hash;
6364 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6365 '--encoding=utf8', '--stdout', @commit_spec
6366 or die_error(500, "Open git-format-patch failed");
6367 } else {
6368 die_error(400, "Unknown commitdiff format");
6371 # non-textual hash id's can be cached
6372 my $expires;
6373 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6374 $expires = "+1d";
6377 # write commit message
6378 if ($format eq 'html') {
6379 my $refs = git_get_references();
6380 my $ref = format_ref_marker($refs, $co{'id'});
6382 git_header_html(undef, $expires);
6383 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6384 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6385 print "<div class=\"title_text\">\n" .
6386 "<table class=\"object_header\">\n";
6387 git_print_authorship_rows(\%co);
6388 print "</table>".
6389 "</div>\n";
6390 print "<div class=\"page_body\">\n";
6391 if (@{$co{'comment'}} > 1) {
6392 print "<div class=\"log\">\n";
6393 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6394 print "</div>\n"; # class="log"
6397 } elsif ($format eq 'plain') {
6398 my $refs = git_get_references("tags");
6399 my $tagname = git_get_rev_name_tags($hash);
6400 my $filename = basename($project) . "-$hash.patch";
6402 print $cgi->header(
6403 -type => 'text/plain',
6404 -charset => 'utf-8',
6405 -expires => $expires,
6406 -content_disposition => 'inline; filename="' . "$filename" . '"');
6407 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6408 print "From: " . to_utf8($co{'author'}) . "\n";
6409 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6410 print "Subject: " . to_utf8($co{'title'}) . "\n";
6412 print "X-Git-Tag: $tagname\n" if $tagname;
6413 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6415 foreach my $line (@{$co{'comment'}}) {
6416 print to_utf8($line) . "\n";
6418 print "---\n\n";
6419 } elsif ($format eq 'patch') {
6420 my $filename = basename($project) . "-$hash.patch";
6422 print $cgi->header(
6423 -type => 'text/plain',
6424 -charset => 'utf-8',
6425 -expires => $expires,
6426 -content_disposition => 'inline; filename="' . "$filename" . '"');
6429 # write patch
6430 if ($format eq 'html') {
6431 my $use_parents = !defined $hash_parent ||
6432 $hash_parent eq '-c' || $hash_parent eq '--cc';
6433 git_difftree_body(\@difftree, $hash,
6434 $use_parents ? @{$co{'parents'}} : $hash_parent);
6435 print "<br/>\n";
6437 git_patchset_body($fd, \@difftree, $hash,
6438 $use_parents ? @{$co{'parents'}} : $hash_parent);
6439 close $fd;
6440 print "</div>\n"; # class="page_body"
6441 git_footer_html();
6443 } elsif ($format eq 'plain') {
6444 local $/ = undef;
6445 print <$fd>;
6446 close $fd
6447 or print "Reading git-diff-tree failed\n";
6448 } elsif ($format eq 'patch') {
6449 local $/ = undef;
6450 print <$fd>;
6451 close $fd
6452 or print "Reading git-format-patch failed\n";
6456 sub git_commitdiff_plain {
6457 git_commitdiff(-format => 'plain');
6460 # format-patch-style patches
6461 sub git_patch {
6462 git_commitdiff(-format => 'patch', -single => 1);
6465 sub git_patches {
6466 git_commitdiff(-format => 'patch');
6469 sub git_history {
6470 git_log_generic('history', \&git_history_body,
6471 $hash_base, $hash_parent_base,
6472 $file_name, $hash);
6475 sub git_search {
6476 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6477 if (!defined $searchtext) {
6478 die_error(400, "Text field is empty");
6480 if (!defined $hash) {
6481 $hash = git_get_head_hash($project);
6483 my %co = parse_commit($hash);
6484 if (!%co) {
6485 die_error(404, "Unknown commit object");
6487 if (!defined $page) {
6488 $page = 0;
6491 $searchtype ||= 'commit';
6492 if ($searchtype eq 'pickaxe') {
6493 # pickaxe may take all resources of your box and run for several minutes
6494 # with every query - so decide by yourself how public you make this feature
6495 gitweb_check_feature('pickaxe')
6496 or die_error(403, "Pickaxe is disabled");
6498 if ($searchtype eq 'grep') {
6499 gitweb_check_feature('grep')
6500 or die_error(403, "Grep is disabled");
6503 git_header_html();
6505 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6506 my $greptype;
6507 if ($searchtype eq 'commit') {
6508 $greptype = "--grep=";
6509 } elsif ($searchtype eq 'author') {
6510 $greptype = "--author=";
6511 } elsif ($searchtype eq 'committer') {
6512 $greptype = "--committer=";
6514 $greptype .= $searchtext;
6515 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6516 $greptype, '--regexp-ignore-case',
6517 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6519 my $paging_nav = '';
6520 if ($page > 0) {
6521 $paging_nav .=
6522 $cgi->a({-href => href(action=>"search", hash=>$hash,
6523 searchtext=>$searchtext,
6524 searchtype=>$searchtype)},
6525 "first");
6526 $paging_nav .= " &sdot; " .
6527 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6528 -accesskey => "p", -title => "Alt-p"}, "prev");
6529 } else {
6530 $paging_nav .= "first";
6531 $paging_nav .= " &sdot; prev";
6533 my $next_link = '';
6534 if ($#commitlist >= 100) {
6535 $next_link =
6536 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6537 -accesskey => "n", -title => "Alt-n"}, "next");
6538 $paging_nav .= " &sdot; $next_link";
6539 } else {
6540 $paging_nav .= " &sdot; next";
6543 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6544 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6545 if ($page == 0 && !@commitlist) {
6546 print "<p>No match.</p>\n";
6547 } else {
6548 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6552 if ($searchtype eq 'pickaxe') {
6553 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6554 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6556 print "<table class=\"pickaxe search\">\n";
6557 my $alternate = 1;
6558 local $/ = "\n";
6559 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6560 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6561 ($search_use_regexp ? '--pickaxe-regex' : ());
6562 undef %co;
6563 my @files;
6564 while (my $line = <$fd>) {
6565 chomp $line;
6566 next unless $line;
6568 my %set = parse_difftree_raw_line($line);
6569 if (defined $set{'commit'}) {
6570 # finish previous commit
6571 if (%co) {
6572 print "</td>\n" .
6573 "<td class=\"link\">" .
6574 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6575 " | " .
6576 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6577 print "</td>\n" .
6578 "</tr>\n";
6581 if ($alternate) {
6582 print "<tr class=\"dark\">\n";
6583 } else {
6584 print "<tr class=\"light\">\n";
6586 $alternate ^= 1;
6587 %co = parse_commit($set{'commit'});
6588 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6589 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6590 "<td><i>$author</i></td>\n" .
6591 "<td>" .
6592 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6593 -class => "list subject"},
6594 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6595 } elsif (defined $set{'to_id'}) {
6596 next if ($set{'to_id'} =~ m/^0{40}$/);
6598 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6599 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6600 -class => "list"},
6601 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6602 "<br/>\n";
6605 close $fd;
6607 # finish last commit (warning: repetition!)
6608 if (%co) {
6609 print "</td>\n" .
6610 "<td class=\"link\">" .
6611 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6612 " | " .
6613 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6614 print "</td>\n" .
6615 "</tr>\n";
6618 print "</table>\n";
6621 if ($searchtype eq 'grep') {
6622 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6623 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6625 print "<table class=\"grep_search\">\n";
6626 my $alternate = 1;
6627 my $matches = 0;
6628 local $/ = "\n";
6629 open my $fd, "-|", git_cmd(), 'grep', '-n',
6630 $search_use_regexp ? ('-E', '-i') : '-F',
6631 $searchtext, $co{'tree'};
6632 my $lastfile = '';
6633 while (my $line = <$fd>) {
6634 chomp $line;
6635 my ($file, $lno, $ltext, $binary);
6636 last if ($matches++ > 1000);
6637 if ($line =~ /^Binary file (.+) matches$/) {
6638 $file = $1;
6639 $binary = 1;
6640 } else {
6641 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6643 if ($file ne $lastfile) {
6644 $lastfile and print "</td></tr>\n";
6645 if ($alternate++) {
6646 print "<tr class=\"dark\">\n";
6647 } else {
6648 print "<tr class=\"light\">\n";
6650 print "<td class=\"list\">".
6651 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6652 file_name=>"$file"),
6653 -class => "list"}, esc_path($file));
6654 print "</td><td>\n";
6655 $lastfile = $file;
6657 if ($binary) {
6658 print "<div class=\"binary\">Binary file</div>\n";
6659 } else {
6660 $ltext = untabify($ltext);
6661 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6662 $ltext = esc_html($1, -nbsp=>1);
6663 $ltext .= '<span class="match">';
6664 $ltext .= esc_html($2, -nbsp=>1);
6665 $ltext .= '</span>';
6666 $ltext .= esc_html($3, -nbsp=>1);
6667 } else {
6668 $ltext = esc_html($ltext, -nbsp=>1);
6670 print "<div class=\"pre\">" .
6671 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6672 file_name=>"$file").'#l'.$lno,
6673 -class => "linenr"}, sprintf('%4i', $lno))
6674 . ' ' . $ltext . "</div>\n";
6677 if ($lastfile) {
6678 print "</td></tr>\n";
6679 if ($matches > 1000) {
6680 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6682 } else {
6683 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6685 close $fd;
6687 print "</table>\n";
6689 git_footer_html();
6692 sub git_search_help {
6693 git_header_html();
6694 git_print_page_nav('','', $hash,$hash,$hash);
6695 print <<EOT;
6696 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6697 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6698 the pattern entered is recognized as the POSIX extended
6699 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6700 insensitive).</p>
6701 <dl>
6702 <dt><b>commit</b></dt>
6703 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6705 my $have_grep = gitweb_check_feature('grep');
6706 if ($have_grep) {
6707 print <<EOT;
6708 <dt><b>grep</b></dt>
6709 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6710 a different one) are searched for the given pattern. On large trees, this search can take
6711 a while and put some strain on the server, so please use it with some consideration. Note that
6712 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6713 case-sensitive.</dd>
6716 print <<EOT;
6717 <dt><b>author</b></dt>
6718 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6719 <dt><b>committer</b></dt>
6720 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6722 my $have_pickaxe = gitweb_check_feature('pickaxe');
6723 if ($have_pickaxe) {
6724 print <<EOT;
6725 <dt><b>pickaxe</b></dt>
6726 <dd>All commits that caused the string to appear or disappear from any file (changes that
6727 added, removed or "modified" the string) will be listed. This search can take a while and
6728 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6729 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6732 print "</dl>\n";
6733 git_footer_html();
6736 sub git_shortlog {
6737 git_log_generic('shortlog', \&git_shortlog_body,
6738 $hash, $hash_parent);
6741 ## ......................................................................
6742 ## feeds (RSS, Atom; OPML)
6744 sub git_feed {
6745 my $format = shift || 'atom';
6746 my $have_blame = gitweb_check_feature('blame');
6748 # Atom: http://www.atomenabled.org/developers/syndication/
6749 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6750 if ($format ne 'rss' && $format ne 'atom') {
6751 die_error(400, "Unknown web feed format");
6754 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6755 my $head = $hash || 'HEAD';
6756 my @commitlist = parse_commits($head, 150, 0, $file_name);
6758 my %latest_commit;
6759 my %latest_date;
6760 my $content_type = "application/$format+xml";
6761 if (defined $cgi->http('HTTP_ACCEPT') &&
6762 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6763 # browser (feed reader) prefers text/xml
6764 $content_type = 'text/xml';
6766 if (defined($commitlist[0])) {
6767 %latest_commit = %{$commitlist[0]};
6768 my $latest_epoch = $latest_commit{'committer_epoch'};
6769 %latest_date = parse_date($latest_epoch);
6770 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6771 if (defined $if_modified) {
6772 my $since;
6773 if (eval { require HTTP::Date; 1; }) {
6774 $since = HTTP::Date::str2time($if_modified);
6775 } elsif (eval { require Time::ParseDate; 1; }) {
6776 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6778 if (defined $since && $latest_epoch <= $since) {
6779 print $cgi->header(
6780 -type => $content_type,
6781 -charset => 'utf-8',
6782 -last_modified => $latest_date{'rfc2822'},
6783 -status => '304 Not Modified');
6784 return;
6787 print $cgi->header(
6788 -type => $content_type,
6789 -charset => 'utf-8',
6790 -last_modified => $latest_date{'rfc2822'});
6791 } else {
6792 print $cgi->header(
6793 -type => $content_type,
6794 -charset => 'utf-8');
6797 # Optimization: skip generating the body if client asks only
6798 # for Last-Modified date.
6799 return if ($cgi->request_method() eq 'HEAD');
6801 # header variables
6802 my $title = "$site_name - $project/$action";
6803 my $feed_type = 'log';
6804 if (defined $hash) {
6805 $title .= " - '$hash'";
6806 $feed_type = 'branch log';
6807 if (defined $file_name) {
6808 $title .= " :: $file_name";
6809 $feed_type = 'history';
6811 } elsif (defined $file_name) {
6812 $title .= " - $file_name";
6813 $feed_type = 'history';
6815 $title .= " $feed_type";
6816 my $descr = git_get_project_description($project);
6817 if (defined $descr) {
6818 $descr = esc_html($descr);
6819 } else {
6820 $descr = "$project " .
6821 ($format eq 'rss' ? 'RSS' : 'Atom') .
6822 " feed";
6824 my $owner = git_get_project_owner($project);
6825 $owner = esc_html($owner);
6827 #header
6828 my $alt_url;
6829 if (defined $file_name) {
6830 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6831 } elsif (defined $hash) {
6832 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6833 } else {
6834 $alt_url = href(-full=>1, action=>"summary");
6836 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6837 if ($format eq 'rss') {
6838 print <<XML;
6839 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6840 <channel>
6842 print "<title>$title</title>\n" .
6843 "<link>$alt_url</link>\n" .
6844 "<description>$descr</description>\n" .
6845 "<language>en</language>\n" .
6846 # project owner is responsible for 'editorial' content
6847 "<managingEditor>$owner</managingEditor>\n";
6848 if (defined $logo || defined $favicon) {
6849 # prefer the logo to the favicon, since RSS
6850 # doesn't allow both
6851 my $img = esc_url($logo || $favicon);
6852 print "<image>\n" .
6853 "<url>$img</url>\n" .
6854 "<title>$title</title>\n" .
6855 "<link>$alt_url</link>\n" .
6856 "</image>\n";
6858 if (%latest_date) {
6859 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6860 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6862 print "<generator>gitweb v.$version/$git_version</generator>\n";
6863 } elsif ($format eq 'atom') {
6864 print <<XML;
6865 <feed xmlns="http://www.w3.org/2005/Atom">
6867 print "<title>$title</title>\n" .
6868 "<subtitle>$descr</subtitle>\n" .
6869 '<link rel="alternate" type="text/html" href="' .
6870 $alt_url . '" />' . "\n" .
6871 '<link rel="self" type="' . $content_type . '" href="' .
6872 $cgi->self_url() . '" />' . "\n" .
6873 "<id>" . href(-full=>1) . "</id>\n" .
6874 # use project owner for feed author
6875 "<author><name>$owner</name></author>\n";
6876 if (defined $favicon) {
6877 print "<icon>" . esc_url($favicon) . "</icon>\n";
6879 if (defined $logo_url) {
6880 # not twice as wide as tall: 72 x 27 pixels
6881 print "<logo>" . esc_url($logo) . "</logo>\n";
6883 if (! %latest_date) {
6884 # dummy date to keep the feed valid until commits trickle in:
6885 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6886 } else {
6887 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6889 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6892 # contents
6893 for (my $i = 0; $i <= $#commitlist; $i++) {
6894 my %co = %{$commitlist[$i]};
6895 my $commit = $co{'id'};
6896 # we read 150, we always show 30 and the ones more recent than 48 hours
6897 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6898 last;
6900 my %cd = parse_date($co{'author_epoch'});
6902 # get list of changed files
6903 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6904 $co{'parent'} || "--root",
6905 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6906 or next;
6907 my @difftree = map { chomp; $_ } <$fd>;
6908 close $fd
6909 or next;
6911 # print element (entry, item)
6912 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6913 if ($format eq 'rss') {
6914 print "<item>\n" .
6915 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6916 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6917 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6918 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6919 "<link>$co_url</link>\n" .
6920 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6921 "<content:encoded>" .
6922 "<![CDATA[\n";
6923 } elsif ($format eq 'atom') {
6924 print "<entry>\n" .
6925 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6926 "<updated>$cd{'iso-8601'}</updated>\n" .
6927 "<author>\n" .
6928 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6929 if ($co{'author_email'}) {
6930 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6932 print "</author>\n" .
6933 # use committer for contributor
6934 "<contributor>\n" .
6935 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6936 if ($co{'committer_email'}) {
6937 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6939 print "</contributor>\n" .
6940 "<published>$cd{'iso-8601'}</published>\n" .
6941 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6942 "<id>$co_url</id>\n" .
6943 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6944 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6946 my $comment = $co{'comment'};
6947 print "<pre>\n";
6948 foreach my $line (@$comment) {
6949 $line = esc_html($line);
6950 print "$line\n";
6952 print "</pre><ul>\n";
6953 foreach my $difftree_line (@difftree) {
6954 my %difftree = parse_difftree_raw_line($difftree_line);
6955 next if !$difftree{'from_id'};
6957 my $file = $difftree{'file'} || $difftree{'to_file'};
6959 print "<li>" .
6960 "[" .
6961 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6962 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6963 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6964 file_name=>$file, file_parent=>$difftree{'from_file'}),
6965 -title => "diff"}, 'D');
6966 if ($have_blame) {
6967 print $cgi->a({-href => href(-full=>1, action=>"blame",
6968 file_name=>$file, hash_base=>$commit),
6969 -title => "blame"}, 'B');
6971 # if this is not a feed of a file history
6972 if (!defined $file_name || $file_name ne $file) {
6973 print $cgi->a({-href => href(-full=>1, action=>"history",
6974 file_name=>$file, hash=>$commit),
6975 -title => "history"}, 'H');
6977 $file = esc_path($file);
6978 print "] ".
6979 "$file</li>\n";
6981 if ($format eq 'rss') {
6982 print "</ul>]]>\n" .
6983 "</content:encoded>\n" .
6984 "</item>\n";
6985 } elsif ($format eq 'atom') {
6986 print "</ul>\n</div>\n" .
6987 "</content>\n" .
6988 "</entry>\n";
6992 # end of feed
6993 if ($format eq 'rss') {
6994 print "</channel>\n</rss>\n";
6995 } elsif ($format eq 'atom') {
6996 print "</feed>\n";
7000 sub git_rss {
7001 git_feed('rss');
7004 sub git_atom {
7005 git_feed('atom');
7008 sub git_opml {
7009 my @list = git_get_projects_list();
7011 print $cgi->header(
7012 -type => 'text/xml',
7013 -charset => 'utf-8',
7014 -content_disposition => 'inline; filename="opml.xml"');
7016 print <<XML;
7017 <?xml version="1.0" encoding="utf-8"?>
7018 <opml version="1.0">
7019 <head>
7020 <title>$site_name OPML Export</title>
7021 </head>
7022 <body>
7023 <outline text="git RSS feeds">
7026 foreach my $pr (@list) {
7027 my %proj = %$pr;
7028 my $head = git_get_head_hash($proj{'path'});
7029 if (!defined $head) {
7030 next;
7032 $git_dir = "$projectroot/$proj{'path'}";
7033 my %co = parse_commit($head);
7034 if (!%co) {
7035 next;
7038 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7039 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7040 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7041 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7043 print <<XML;
7044 </outline>
7045 </body>
7046 </opml>