gitweb: clarify search results page when no matching commit found
[git/gitweb.git] / gitweb / gitweb.perl
blobede867bc1806b9c759ebb157c37d7b67541a80b9
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 use File::Spec;
20 binmode STDOUT, ':utf8';
22 BEGIN {
23 CGI->compile() if $ENV{'MOD_PERL'};
26 # Only allow GET and HEAD methods
27 if (!$ENV{'REQUEST_METHOD'} || ($ENV{'REQUEST_METHOD'} ne 'GET' && $ENV{'REQUEST_METHOD'} ne 'HEAD')) {
28 print <<EOT;
29 Status: 405 Method Not Allowed
30 Content-Type: text/plain
32 405 Method Not Allowed
33 EOT
34 exit;
37 our $cgi = new CGI;
38 our $version = "++GIT_VERSION++";
39 our $my_url = $cgi->url();
40 our $my_uri = $cgi->url(-absolute => 1);
42 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
43 # needed and used only for URLs with nonempty PATH_INFO
44 our $base_url = $my_url;
46 # When the script is used as DirectoryIndex, the URL does not contain the name
47 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
48 # have to do it ourselves. We make $path_info global because it's also used
49 # later on.
51 # Another issue with the script being the DirectoryIndex is that the resulting
52 # $my_url data is not the full script URL: this is good, because we want
53 # generated links to keep implying the script name if it wasn't explicitly
54 # indicated in the URL we're handling, but it means that $my_url cannot be used
55 # as base URL.
56 # Therefore, if we needed to strip PATH_INFO, then we know that we have
57 # to build the base URL ourselves:
58 our $path_info = $ENV{"PATH_INFO"};
59 if ($path_info) {
60 if ($my_url =~ s,\Q$path_info\E$,, &&
61 $my_uri =~ s,\Q$path_info\E$,, &&
62 defined $ENV{'SCRIPT_NAME'}) {
63 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
67 # core git executable to use
68 # this can just be "git" if your webserver has a sensible PATH
69 our $GIT = "++GIT_BINDIR++/git";
71 # absolute fs-path which will be prepended to the project path
72 #our $projectroot = "/pub/scm";
73 our $projectroot = "++GITWEB_PROJECTROOT++";
75 # fs traversing limit for getting project list
76 # the number is relative to the projectroot
77 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
79 # target of the home link on top of all pages
80 our $home_link = $my_uri || "/";
82 # string of the home link on top of all pages
83 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
85 # name of your site or organization to appear in page titles
86 # replace this with something more descriptive for clearer bookmarks
87 our $site_name = "++GITWEB_SITENAME++"
88 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
90 # filename of html text to include at top of each page
91 our $site_header = "++GITWEB_SITE_HEADER++";
92 # html text to include at home page
93 our $home_text = "++GITWEB_HOMETEXT++";
94 # filename of html text to include at bottom of each page
95 our $site_footer = "++GITWEB_SITE_FOOTER++";
97 # URI of stylesheets
98 our @stylesheets = ("++GITWEB_CSS++");
99 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
100 our $stylesheet = undef;
101 # URI of GIT logo (72x27 size)
102 our $logo = "++GITWEB_LOGO++";
103 # URI of GIT favicon, assumed to be image/png type
104 our $favicon = "++GITWEB_FAVICON++";
105 # URI of gitweb.js (JavaScript code for gitweb)
106 our $gitwebjs = "++GITWEB_JS++";
108 # URI and label (title) of GIT logo link
109 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
110 #our $logo_label = "git documentation";
111 our $logo_url = "http://git-scm.com/";
112 our $logo_label = "git homepage";
114 # source of projects list
115 our $projects_list = "++GITWEB_LIST++";
117 # the width (in characters) of the projects list "Description" column
118 our $projects_list_description_width = 25;
120 # default order of projects list
121 # valid values are none, project, descr, owner, and age
122 our $default_projects_order = "project";
124 # show repository only if this file exists
125 # (only effective if this variable evaluates to true)
126 our $export_ok = "++GITWEB_EXPORT_OK++";
128 # show repository only if this subroutine returns true
129 # when given the path to the project, for example:
130 # sub { return -e "$_[0]/git-daemon-export-ok"; }
131 our $export_auth_hook = undef;
133 # only allow viewing of repositories also shown on the overview page
134 our $strict_export = "++GITWEB_STRICT_EXPORT++";
136 # list of git base URLs used for URL to where fetch project from,
137 # i.e. full URL is "$git_base_url/$project"
138 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
140 # URLs designated for pushing new changes, extended by the
141 # project name (i.e. "$git_base_push_url[0]/$project")
142 our @git_base_push_urls = ();
144 # https hint html inserted right after any https push URL (undef for none)
145 our $https_hint_html = undef;
147 # owner link hook given owner name (full and NOT obfuscated)
148 # should return full URL-escaped link to attach to owner, for example:
149 # sub { return "/showowner.cgi?owner=".CGI::Util::escape($_[0]); }
150 our $owner_link_hook = undef;
152 # default blob_plain mimetype and default charset for text/plain blob
153 our $default_blob_plain_mimetype = 'text/plain';
154 our $default_text_plain_charset = undef;
156 # file to use for guessing MIME types before trying /etc/mime.types
157 # (relative to the current git repository)
158 our $mimetypes_file = undef;
160 # assume this charset if line contains non-UTF-8 characters;
161 # it should be valid encoding (see Encoding::Supported(3pm) for list),
162 # for which encoding all byte sequences are valid, for example
163 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
164 # could be even 'utf-8' for the old behavior)
165 our $fallback_encoding = 'latin1';
167 # rename detection options for git-diff and git-diff-tree
168 # - default is '-M', with the cost proportional to
169 # (number of removed files) * (number of new files).
170 # - more costly is '-C' (which implies '-M'), with the cost proportional to
171 # (number of changed files + number of removed files) * (number of new files)
172 # - even more costly is '-C', '--find-copies-harder' with cost
173 # (number of files in the original tree) * (number of new files)
174 # - one might want to include '-B' option, e.g. '-B', '-M'
175 our @diff_opts = ('-M'); # taken from git_commit
177 # Disables features that would allow repository owners to inject script into
178 # the gitweb domain.
179 our $prevent_xss = 0;
181 # Whether to include project list on the gitweb front page; 0 means yes,
182 # 1 means no list but show tag cloud if enabled (all projects still need
183 # to be scanned, unless the info is cached), 2 means no list and no tag cloud
184 # (very fast)
185 our $frontpage_no_project_list = 0;
187 # projects list cache for busy sites with many projects;
188 # if you set this to non-zero, it will be used as the cached
189 # index lifetime in minutes
191 # the cached list version is stored in $cache_dir/$cache_name and can
192 # be tweaked by other scripts running with the same uid as gitweb -
193 # use this ONLY at secure installations; only single gitweb project
194 # root per system is supported, unless you tweak configuration!
195 our $projlist_cache_lifetime = 0; # in minutes
196 # FHS compliant $cache_dir would be "/var/cache/gitweb"
197 our $cache_dir =
198 (defined $ENV{'TMPDIR'} ? $ENV{'TMPDIR'} : '/tmp').'/gitweb';
199 our $projlist_cache_name = 'gitweb.index.cache';
200 our $cache_grpshared = 0;
202 # information about snapshot formats that gitweb is capable of serving
203 our %known_snapshot_formats = (
204 # name => {
205 # 'display' => display name,
206 # 'type' => mime type,
207 # 'suffix' => filename suffix,
208 # 'format' => --format for git-archive,
209 # 'compressor' => [compressor command and arguments]
210 # (array reference, optional)
211 # 'disabled' => boolean (optional)}
213 'tgz' => {
214 'display' => 'tar.gz',
215 'type' => 'application/x-gzip',
216 'suffix' => '.tar.gz',
217 'format' => 'tar',
218 'compressor' => ['gzip']},
220 'tbz2' => {
221 'display' => 'tar.bz2',
222 'type' => 'application/x-bzip2',
223 'suffix' => '.tar.bz2',
224 'format' => 'tar',
225 'compressor' => ['bzip2']},
227 'txz' => {
228 'display' => 'tar.xz',
229 'type' => 'application/x-xz',
230 'suffix' => '.tar.xz',
231 'format' => 'tar',
232 'compressor' => ['xz'],
233 'disabled' => 1},
235 'zip' => {
236 'display' => 'zip',
237 'type' => 'application/x-zip',
238 'suffix' => '.zip',
239 'format' => 'zip'},
242 # Aliases so we understand old gitweb.snapshot values in repository
243 # configuration.
244 our %known_snapshot_format_aliases = (
245 'gzip' => 'tgz',
246 'bzip2' => 'tbz2',
247 'xz' => 'txz',
249 # backward compatibility: legacy gitweb config support
250 'x-gzip' => undef, 'gz' => undef,
251 'x-bzip2' => undef, 'bz2' => undef,
252 'x-zip' => undef, '' => undef,
255 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
256 # are changed, it may be appropriate to change these values too via
257 # $GITWEB_CONFIG.
258 our %avatar_size = (
259 'default' => 16,
260 'double' => 32
263 # You define site-wide feature defaults here; override them with
264 # $GITWEB_CONFIG as necessary.
265 our %feature = (
266 # feature => {
267 # 'sub' => feature-sub (subroutine),
268 # 'override' => allow-override (boolean),
269 # 'default' => [ default options...] (array reference)}
271 # if feature is overridable (it means that allow-override has true value),
272 # then feature-sub will be called with default options as parameters;
273 # return value of feature-sub indicates if to enable specified feature
275 # if there is no 'sub' key (no feature-sub), then feature cannot be
276 # overriden
278 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
279 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
280 # is enabled
282 # Enable the 'blame' blob view, showing the last commit that modified
283 # each line in the file. This can be very CPU-intensive.
285 # To enable system wide have in $GITWEB_CONFIG
286 # $feature{'blame'}{'default'} = [1];
287 # To have project specific config enable override in $GITWEB_CONFIG
288 # $feature{'blame'}{'override'} = 1;
289 # and in project config gitweb.blame = 0|1;
290 'blame' => {
291 'sub' => sub { feature_bool('blame', @_) },
292 'override' => 0,
293 'default' => [0]},
295 # Enable the 'incremental blame' blob view, which uses javascript to
296 # incrementally show the revisions of lines as they are discovered
297 # in the history. It is better for large histories, files and slow
298 # servers, but requires javascript in the client, can slow down the
299 # browser on large files and does not show author initials.
301 # To enable system wide have in $GITWEB_CONFIG
302 # $feature{'blame_incremental'}{'default'} = [1];
303 # To have project specific config enable override in $GITWEB_CONFIG
304 # $feature{'blame_incremental'}{'override'} = 1;
305 # and in project config gitweb.blame_incremental = 0|1;
306 'blame_incremental' => {
307 'sub' => sub { feature_bool('blame_incremental', @_) },
308 'override' => 0,
309 'default' => [0]},
311 # Enable the 'snapshot' link, providing a compressed archive of any
312 # tree. This can potentially generate high traffic if you have large
313 # project.
315 # Value is a list of formats defined in %known_snapshot_formats that
316 # you wish to offer.
317 # To disable system wide have in $GITWEB_CONFIG
318 # $feature{'snapshot'}{'default'} = [];
319 # To have project specific config enable override in $GITWEB_CONFIG
320 # $feature{'snapshot'}{'override'} = 1;
321 # and in project config, a comma-separated list of formats or "none"
322 # to disable. Example: gitweb.snapshot = tbz2,zip;
323 'snapshot' => {
324 'sub' => \&feature_snapshot,
325 'override' => 0,
326 'default' => ['tgz']},
328 # Enable text search, which will list the commits which match author,
329 # committer or commit text to a given string. Enabled by default.
330 # Project specific override is not supported.
331 'search' => {
332 'override' => 0,
333 'default' => [1]},
335 # Enable grep search, which will list the files in currently selected
336 # tree containing the given string. Enabled by default. This can be
337 # potentially CPU-intensive, of course.
339 # To enable system wide have in $GITWEB_CONFIG
340 # $feature{'grep'}{'default'} = [1];
341 # To have project specific config enable override in $GITWEB_CONFIG
342 # $feature{'grep'}{'override'} = 1;
343 # and in project config gitweb.grep = 0|1;
344 'grep' => {
345 'sub' => sub { feature_bool('grep', @_) },
346 'override' => 0,
347 'default' => [1]},
349 # Enable the pickaxe search, which will list the commits that modified
350 # a given string in a file. This can be practical and quite faster
351 # alternative to 'blame', but still potentially CPU-intensive.
353 # To enable system wide have in $GITWEB_CONFIG
354 # $feature{'pickaxe'}{'default'} = [1];
355 # To have project specific config enable override in $GITWEB_CONFIG
356 # $feature{'pickaxe'}{'override'} = 1;
357 # and in project config gitweb.pickaxe = 0|1;
358 'pickaxe' => {
359 'sub' => sub { feature_bool('pickaxe', @_) },
360 'override' => 0,
361 'default' => [1]},
363 # Enable showing size of blobs in a 'tree' view, in a separate
364 # column, similar to what 'ls -l' does. This cost a bit of IO.
366 # To disable system wide have in $GITWEB_CONFIG
367 # $feature{'show-sizes'}{'default'} = [0];
368 # To have project specific config enable override in $GITWEB_CONFIG
369 # $feature{'show-sizes'}{'override'} = 1;
370 # and in project config gitweb.showsizes = 0|1;
371 'show-sizes' => {
372 'sub' => sub { feature_bool('showsizes', @_) },
373 'override' => 0,
374 'default' => [1]},
376 # Make gitweb use an alternative format of the URLs which can be
377 # more readable and natural-looking: project name is embedded
378 # directly in the path and the query string contains other
379 # auxiliary information. All gitweb installations recognize
380 # URL in either format; this configures in which formats gitweb
381 # generates links.
383 # To enable system wide have in $GITWEB_CONFIG
384 # $feature{'pathinfo'}{'default'} = [1];
385 # Project specific override is not supported.
387 # Note that you will need to change the default location of CSS,
388 # favicon, logo and possibly other files to an absolute URL. Also,
389 # if gitweb.cgi serves as your indexfile, you will need to force
390 # $my_uri to contain the script name in your $GITWEB_CONFIG.
391 'pathinfo' => {
392 'override' => 0,
393 'default' => [0]},
395 # Make gitweb consider projects in project root subdirectories
396 # to be forks of existing projects. Given project $projname.git,
397 # projects matching $projname/*.git will not be shown in the main
398 # projects list, instead a '+' mark will be added to $projname
399 # there and a 'forks' view will be enabled for the project, listing
400 # all the forks. If project list is taken from a file, forks have
401 # to be listed after the main project.
403 # To enable system wide have in $GITWEB_CONFIG
404 # $feature{'forks'}{'default'} = [1];
405 # Project specific override is not supported.
406 'forks' => {
407 'override' => 0,
408 'default' => [0]},
410 # Insert custom links to the action bar of all project pages.
411 # This enables you mainly to link to third-party scripts integrating
412 # into gitweb; e.g. git-browser for graphical history representation
413 # or custom web-based repository administration interface.
415 # The 'default' value consists of a list of triplets in the form
416 # (label, link, position) where position is the label after which
417 # to insert the link and link is a format string where %n expands
418 # to the project name, %f to the project path within the filesystem,
419 # %h to the current hash (h gitweb parameter) and %b to the current
420 # hash base (hb gitweb parameter); %% expands to %.
422 # To enable system wide have in $GITWEB_CONFIG e.g.
423 # $feature{'actions'}{'default'} = [('graphiclog',
424 # '/git-browser/by-commit.html?r=%n', 'summary')];
425 # Project specific override is not supported.
426 'actions' => {
427 'override' => 0,
428 'default' => []},
430 # Allow gitweb scan project content tags described in ctags/
431 # of project repository, and display the popular Web 2.0-ish
432 # "tag cloud" near the project list. Note that this is something
433 # COMPLETELY different from the normal Git tags.
435 # gitweb by itself can show existing tags, but it does not handle
436 # tagging itself; you need an external application for that.
437 # For an example script, check Girocco's cgi/tagproj.cgi.
438 # You may want to install the HTML::TagCloud Perl module to get
439 # a pretty tag cloud instead of just a list of tags.
441 # To enable system wide have in $GITWEB_CONFIG
442 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
443 # Project specific override is not supported.
444 'ctags' => {
445 'override' => 0,
446 'default' => [0]},
448 # The maximum number of patches in a patchset generated in patch
449 # view. Set this to 0 or undef to disable patch view, or to a
450 # negative number to remove any limit.
452 # To disable system wide have in $GITWEB_CONFIG
453 # $feature{'patches'}{'default'} = [0];
454 # To have project specific config enable override in $GITWEB_CONFIG
455 # $feature{'patches'}{'override'} = 1;
456 # and in project config gitweb.patches = 0|n;
457 # where n is the maximum number of patches allowed in a patchset.
458 'patches' => {
459 'sub' => \&feature_patches,
460 'override' => 0,
461 'default' => [16]},
463 # Avatar support. When this feature is enabled, views such as
464 # shortlog or commit will display an avatar associated with
465 # the email of the committer(s) and/or author(s).
467 # Currently available providers are gravatar and picon.
468 # If an unknown provider is specified, the feature is disabled.
470 # Gravatar depends on Digest::MD5.
471 # Picon currently relies on the indiana.edu database.
473 # To enable system wide have in $GITWEB_CONFIG
474 # $feature{'avatar'}{'default'} = ['<provider>'];
475 # where <provider> is either gravatar or picon.
476 # To have project specific config enable override in $GITWEB_CONFIG
477 # $feature{'avatar'}{'override'} = 1;
478 # and in project config gitweb.avatar = <provider>;
479 'avatar' => {
480 'sub' => \&feature_avatar,
481 'override' => 0,
482 'default' => ['']},
484 # Syntax highlighting support. This is based on Daniel Svensson's
485 # and Sham Chukoury's work in gitweb-xmms2.git.
486 # It requires the 'highlight' program present in $PATH,
487 # and therefore is disabled by default.
489 # To enable system wide have in $GITWEB_CONFIG
490 # $feature{'highlight'}{'default'} = [1];
492 'highlight' => {
493 'sub' => sub { feature_bool('highlight', @_) },
494 'override' => 0,
495 'default' => [0]},
498 sub gitweb_get_feature {
499 my ($name) = @_;
500 return unless exists $feature{$name};
501 my ($sub, $override, @defaults) = (
502 $feature{$name}{'sub'},
503 $feature{$name}{'override'},
504 @{$feature{$name}{'default'}});
505 # project specific override is possible only if we have project
506 our $git_dir; # global variable, declared later
507 if (!$override || !defined $git_dir) {
508 return @defaults;
510 if (!defined $sub) {
511 warn "feature $name is not overridable";
512 return @defaults;
514 return $sub->(@defaults);
517 # A wrapper to check if a given feature is enabled.
518 # With this, you can say
520 # my $bool_feat = gitweb_check_feature('bool_feat');
521 # gitweb_check_feature('bool_feat') or somecode;
523 # instead of
525 # my ($bool_feat) = gitweb_get_feature('bool_feat');
526 # (gitweb_get_feature('bool_feat'))[0] or somecode;
528 sub gitweb_check_feature {
529 return (gitweb_get_feature(@_))[0];
533 sub feature_bool {
534 my $key = shift;
535 my ($val) = git_get_project_config($key, '--bool');
537 if (!defined $val) {
538 return ($_[0]);
539 } elsif ($val eq 'true') {
540 return (1);
541 } elsif ($val eq 'false') {
542 return (0);
546 sub feature_snapshot {
547 my (@fmts) = @_;
549 my ($val) = git_get_project_config('snapshot');
551 if ($val) {
552 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
555 return @fmts;
558 sub feature_patches {
559 my @val = (git_get_project_config('patches', '--int'));
561 if (@val) {
562 return @val;
565 return ($_[0]);
568 sub feature_avatar {
569 my @val = (git_get_project_config('avatar'));
571 return @val ? @val : @_;
574 # checking HEAD file with -e is fragile if the repository was
575 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
576 # and then pruned.
577 sub check_head_link {
578 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
579 my ($dir) = @_;
580 my $headfile = "$dir/HEAD";
581 return ((-e $headfile) ||
582 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
585 sub check_export_ok {
586 my ($dir) = @_;
587 return (check_head_link($dir) &&
588 (!$export_ok || -e "$dir/$export_ok") &&
589 (!$export_auth_hook || $export_auth_hook->($dir)));
592 # process alternate names for backward compatibility
593 # filter out unsupported (unknown) snapshot formats
594 sub filter_snapshot_fmts {
595 my @fmts = @_;
597 @fmts = map {
598 exists $known_snapshot_format_aliases{$_} ?
599 $known_snapshot_format_aliases{$_} : $_} @fmts;
600 @fmts = grep {
601 exists $known_snapshot_formats{$_} &&
602 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
605 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
606 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
607 # die if there are errors parsing config file
608 if (-e $GITWEB_CONFIG) {
609 do $GITWEB_CONFIG;
610 die $@ if $@;
611 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
612 do $GITWEB_CONFIG_SYSTEM;
613 die $@ if $@;
616 # version of the core git binary
617 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
619 # email obfuscation
620 our $email;
621 if (eval { require HTML::Email::Obfuscate; 1 }) {
622 $email = HTML::Email::Obfuscate->new(lite => 1);
625 $projects_list ||= $projectroot;
627 # ======================================================================
628 # input validation and dispatch
630 # input parameters can be collected from a variety of sources (presently, CGI
631 # and PATH_INFO), so we define an %input_params hash that collects them all
632 # together during validation: this allows subsequent uses (e.g. href()) to be
633 # agnostic of the parameter origin
635 our %input_params = ();
637 # input parameters are stored with the long parameter name as key. This will
638 # also be used in the href subroutine to convert parameters to their CGI
639 # equivalent, and since the href() usage is the most frequent one, we store
640 # the name -> CGI key mapping here, instead of the reverse.
642 # XXX: Warning: If you touch this, check the search form for updating,
643 # too.
645 our @cgi_param_mapping = (
646 project => "p",
647 action => "a",
648 file_name => "f",
649 file_parent => "fp",
650 hash => "h",
651 hash_parent => "hp",
652 hash_base => "hb",
653 hash_parent_base => "hpb",
654 page => "pg",
655 order => "o",
656 searchtext => "s",
657 searchtype => "st",
658 snapshot_format => "sf",
659 ctag_filter => 't',
660 extra_options => "opt",
661 search_use_regexp => "sr",
663 our %cgi_param_mapping = @cgi_param_mapping;
665 # we will also need to know the possible actions, for validation
666 our %actions = (
667 "blame" => \&git_blame,
668 "blame_incremental" => \&git_blame_incremental,
669 "blame_data" => \&git_blame_data,
670 "blobdiff" => \&git_blobdiff,
671 "blobdiff_plain" => \&git_blobdiff_plain,
672 "blob" => \&git_blob,
673 "blob_plain" => \&git_blob_plain,
674 "commitdiff" => \&git_commitdiff,
675 "commitdiff_plain" => \&git_commitdiff_plain,
676 "commit" => \&git_commit,
677 "forks" => \&git_forks,
678 "heads" => \&git_heads,
679 "history" => \&git_history,
680 "log" => \&git_log,
681 "patch" => \&git_patch,
682 "patches" => \&git_patches,
683 "refs" => \&git_refs,
684 "rss" => \&git_rss,
685 "atom" => \&git_atom,
686 "search" => \&git_search,
687 "search_help" => \&git_search_help,
688 "shortlog" => \&git_shortlog,
689 "summary" => \&git_summary,
690 "tag" => \&git_tag,
691 "tags" => \&git_tags,
692 "tree" => \&git_tree,
693 "snapshot" => \&git_snapshot,
694 "object" => \&git_object,
695 # those below don't need $project
696 "opml" => \&git_opml,
697 "frontpage" => \&git_frontpage,
698 "project_list" => \&git_project_list,
699 "project_index" => \&git_project_index,
702 # finally, we have the hash of allowed extra_options for the commands that
703 # allow them
704 our %allowed_options = (
705 "--no-merges" => [ qw(rss atom log shortlog history) ],
708 # fill %input_params with the CGI parameters. All values except for 'opt'
709 # should be single values, but opt can be an array. We should probably
710 # build an array of parameters that can be multi-valued, but since for the time
711 # being it's only this one, we just single it out
712 while (my ($name, $symbol) = each %cgi_param_mapping) {
713 if ($symbol eq 'opt') {
714 $input_params{$name} = [ $cgi->param($symbol) ];
715 } else {
716 $input_params{$name} = $cgi->param($symbol);
720 # Backwards compatibility - by_tag= <=> t=
721 if ($cgi->param('by_tag')) {
722 $input_params{'ctag_filter'} = $cgi->param('by_tag');
725 # now read PATH_INFO and update the parameter list for missing parameters
726 sub evaluate_path_info {
727 return if defined $input_params{'project'};
728 return if !$path_info;
729 $path_info =~ s,^/+,,;
730 return if !$path_info;
732 # find which part of PATH_INFO is project
733 my $project = $path_info;
734 $project =~ s,/+$,,;
735 while ($project && !check_head_link("$projectroot/$project")) {
736 $project =~ s,/*[^/]*$,,;
738 return unless $project;
739 $input_params{'project'} = $project;
741 # do not change any parameters if an action is given using the query string
742 return if $input_params{'action'};
743 $path_info =~ s,^\Q$project\E/*,,;
745 # next, check if we have an action
746 my $action = $path_info;
747 $action =~ s,/.*$,,;
748 if (exists $actions{$action}) {
749 $path_info =~ s,^$action/*,,;
750 $input_params{'action'} = $action;
753 # list of actions that want hash_base instead of hash, but can have no
754 # pathname (f) parameter
755 my @wants_base = (
756 'tree',
757 'history',
760 # we want to catch
761 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
762 my ($parentrefname, $parentpathname, $refname, $pathname) =
763 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
765 # first, analyze the 'current' part
766 if (defined $pathname) {
767 # we got "branch:filename" or "branch:dir/"
768 # we could use git_get_type(branch:pathname), but:
769 # - it needs $git_dir
770 # - it does a git() call
771 # - the convention of terminating directories with a slash
772 # makes it superfluous
773 # - embedding the action in the PATH_INFO would make it even
774 # more superfluous
775 $pathname =~ s,^/+,,;
776 if (!$pathname || substr($pathname, -1) eq "/") {
777 $input_params{'action'} ||= "tree";
778 $pathname =~ s,/$,,;
779 } else {
780 # the default action depends on whether we had parent info
781 # or not
782 if ($parentrefname) {
783 $input_params{'action'} ||= "blobdiff_plain";
784 } else {
785 $input_params{'action'} ||= "blob_plain";
788 $input_params{'hash_base'} ||= $refname;
789 $input_params{'file_name'} ||= $pathname;
790 } elsif (defined $refname) {
791 # we got "branch". In this case we have to choose if we have to
792 # set hash or hash_base.
794 # Most of the actions without a pathname only want hash to be
795 # set, except for the ones specified in @wants_base that want
796 # hash_base instead. It should also be noted that hand-crafted
797 # links having 'history' as an action and no pathname or hash
798 # set will fail, but that happens regardless of PATH_INFO.
799 $input_params{'action'} ||= "shortlog";
800 if (grep { $_ eq $input_params{'action'} } @wants_base) {
801 $input_params{'hash_base'} ||= $refname;
802 } else {
803 $input_params{'hash'} ||= $refname;
807 # next, handle the 'parent' part, if present
808 if (defined $parentrefname) {
809 # a missing pathspec defaults to the 'current' filename, allowing e.g.
810 # someproject/blobdiff/oldrev..newrev:/filename
811 if ($parentpathname) {
812 $parentpathname =~ s,^/+,,;
813 $parentpathname =~ s,/$,,;
814 $input_params{'file_parent'} ||= $parentpathname;
815 } else {
816 $input_params{'file_parent'} ||= $input_params{'file_name'};
818 # we assume that hash_parent_base is wanted if a path was specified,
819 # or if the action wants hash_base instead of hash
820 if (defined $input_params{'file_parent'} ||
821 grep { $_ eq $input_params{'action'} } @wants_base) {
822 $input_params{'hash_parent_base'} ||= $parentrefname;
823 } else {
824 $input_params{'hash_parent'} ||= $parentrefname;
828 # for the snapshot action, we allow URLs in the form
829 # $project/snapshot/$hash.ext
830 # where .ext determines the snapshot and gets removed from the
831 # passed $refname to provide the $hash.
833 # To be able to tell that $refname includes the format extension, we
834 # require the following two conditions to be satisfied:
835 # - the hash input parameter MUST have been set from the $refname part
836 # of the URL (i.e. they must be equal)
837 # - the snapshot format MUST NOT have been defined already (e.g. from
838 # CGI parameter sf)
839 # It's also useless to try any matching unless $refname has a dot,
840 # so we check for that too
841 if (defined $input_params{'action'} &&
842 $input_params{'action'} eq 'snapshot' &&
843 defined $refname && index($refname, '.') != -1 &&
844 $refname eq $input_params{'hash'} &&
845 !defined $input_params{'snapshot_format'}) {
846 # We loop over the known snapshot formats, checking for
847 # extensions. Allowed extensions are both the defined suffix
848 # (which includes the initial dot already) and the snapshot
849 # format key itself, with a prepended dot
850 while (my ($fmt, $opt) = each %known_snapshot_formats) {
851 my $hash = $refname;
852 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
853 next;
855 my $sfx = $1;
856 # a valid suffix was found, so set the snapshot format
857 # and reset the hash parameter
858 $input_params{'snapshot_format'} = $fmt;
859 $input_params{'hash'} = $hash;
860 # we also set the format suffix to the one requested
861 # in the URL: this way a request for e.g. .tgz returns
862 # a .tgz instead of a .tar.gz
863 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
864 last;
868 evaluate_path_info();
870 our $action = $input_params{'action'};
871 if (defined $action) {
872 if (!validate_action($action)) {
873 die_error(400, "Invalid action parameter");
877 # parameters which are pathnames
878 our $project = $input_params{'project'};
879 if (defined $project) {
880 if (!validate_project($project)) {
881 undef $project;
882 die_error(404, "No such project");
886 our $file_name = $input_params{'file_name'};
887 if (defined $file_name) {
888 if (!validate_pathname($file_name)) {
889 die_error(400, "Invalid file parameter");
893 our $file_parent = $input_params{'file_parent'};
894 if (defined $file_parent) {
895 if (!validate_pathname($file_parent)) {
896 die_error(400, "Invalid file parent parameter");
900 # parameters which are refnames
901 our $hash = $input_params{'hash'};
902 if (defined $hash) {
903 if (!validate_refname($hash)) {
904 die_error(400, "Invalid hash parameter");
908 our $hash_parent = $input_params{'hash_parent'};
909 if (defined $hash_parent) {
910 if (!validate_refname($hash_parent)) {
911 die_error(400, "Invalid hash parent parameter");
915 our $hash_base = $input_params{'hash_base'};
916 if (defined $hash_base) {
917 if (!validate_refname($hash_base)) {
918 die_error(400, "Invalid hash base parameter");
922 our @extra_options = @{$input_params{'extra_options'}};
923 # @extra_options is always defined, since it can only be (currently) set from
924 # CGI, and $cgi->param() returns the empty array in array context if the param
925 # is not set
926 foreach my $opt (@extra_options) {
927 if (not exists $allowed_options{$opt}) {
928 die_error(400, "Invalid option parameter");
930 if (not $action or not grep(/^$action$/, @{$allowed_options{$opt}})) {
931 die_error(400, "Invalid option parameter for this action");
935 our $hash_parent_base = $input_params{'hash_parent_base'};
936 if (defined $hash_parent_base) {
937 if (!validate_refname($hash_parent_base)) {
938 die_error(400, "Invalid hash parent base parameter");
942 # other parameters
943 our $page = $input_params{'page'} || 0;
944 if ($page =~ m/[^0-9]/) {
945 die_error(400, "Invalid page parameter");
948 our $searchtype = $input_params{'searchtype'};
949 if (defined $searchtype) {
950 if ($searchtype =~ m/[^a-z]/) {
951 die_error(400, "Invalid searchtype parameter");
955 our $search_use_regexp = $input_params{'search_use_regexp'};
957 our $searchtext = $input_params{'searchtext'};
958 our $search_regexp;
959 if (defined $searchtext) {
960 if (length($searchtext) < 2) {
961 die_error(403, "At least two characters are required for search parameter");
963 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
966 # path to the current git repository
967 our $git_dir;
968 $git_dir = "$projectroot/$project" if $project;
970 # list of supported snapshot formats
971 our @snapshot_fmts = gitweb_get_feature('snapshot');
972 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
974 # check that the avatar feature is set to a known provider name,
975 # and for each provider check if the dependencies are satisfied.
976 # if the provider name is invalid or the dependencies are not met,
977 # reset $git_avatar to the empty string.
978 our ($git_avatar) = gitweb_get_feature('avatar');
979 if ($git_avatar eq 'gravatar') {
980 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
981 } elsif ($git_avatar eq 'picon') {
982 # no dependencies
983 } else {
984 $git_avatar = '';
987 # custom error handler: 'die <message>' is Internal Server Error
988 sub handle_errors_html {
989 my $msg = shift; # it is already HTML escaped
991 # to avoid infinite loop where error occurs in die_error,
992 # change handler to default handler, disabling handle_errors_html
993 set_message("Error occured when inside die_error:\n$msg");
995 # you cannot jump out of die_error when called as error handler;
996 # the subroutine set via CGI::Carp::set_message is called _after_
997 # HTTP headers are already written, so it cannot write them itself
998 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1000 set_message(\&handle_errors_html);
1002 # dispatch
1003 if (!defined $action) {
1004 if (defined $hash) {
1005 $action = git_get_type($hash);
1006 } elsif (defined $hash_base && defined $file_name) {
1007 $action = git_get_type("$hash_base:$file_name");
1008 } elsif (defined $project) {
1009 $action = 'summary';
1010 } else {
1011 $action = 'frontpage';
1014 if (!defined($action) || !defined($actions{$action})) {
1015 die_error(400, "Unknown action");
1017 if ($action !~ m/^(?:opml|frontpage|project_list|project_index)$/ &&
1018 !$project) {
1019 die_error(400, "Project needed");
1021 $actions{$action}->();
1023 DONE_GITWEB:
1024 if (defined caller) {
1025 # wrapped in a subroutine processing requests,
1026 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1027 return;
1028 } else {
1029 # pure CGI script, serving single request
1030 exit;
1033 ## ======================================================================
1034 ## action links
1036 # possible values of extra options
1037 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1038 # -replay => 1 - start from a current view (replay with modifications)
1039 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1040 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1041 sub href {
1042 my %params = @_;
1043 # default is to use -absolute url() i.e. $my_uri
1044 my $href = $params{-full} ? $my_url : $my_uri;
1046 # implicit -replay, must be first of implicit params
1047 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1049 $params{'project'} = $project unless exists $params{'project'};
1051 if ($params{-replay}) {
1052 while (my ($name, $symbol) = each %cgi_param_mapping) {
1053 if (!exists $params{$name}) {
1054 $params{$name} = $input_params{$name};
1059 my $use_pathinfo = gitweb_check_feature('pathinfo');
1060 if (defined $params{'project'} &&
1061 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1062 # try to put as many parameters as possible in PATH_INFO:
1063 # - project name
1064 # - action
1065 # - hash_parent or hash_parent_base:/file_parent
1066 # - hash or hash_base:/filename
1067 # - the snapshot_format as an appropriate suffix
1069 # When the script is the root DirectoryIndex for the domain,
1070 # $href here would be something like http://gitweb.example.com/
1071 # Thus, we strip any trailing / from $href, to spare us double
1072 # slashes in the final URL
1073 $href =~ s,/$,,;
1075 # Then add the project name, if present
1076 $href .= "/".esc_url($params{'project'});
1077 delete $params{'project'};
1079 # since we destructively absorb parameters, we keep this
1080 # boolean that remembers if we're handling a snapshot
1081 my $is_snapshot = ($params{'action'}||'') eq 'snapshot';
1083 # Summary just uses the project path URL, any other action is
1084 # added to the URL
1085 if (defined $params{'action'}) {
1086 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1087 delete $params{'action'};
1090 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1091 # stripping nonexistent or useless pieces
1092 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1093 || $params{'hash_parent'} || $params{'hash'});
1094 if (defined $params{'hash_base'}) {
1095 if (defined $params{'hash_parent_base'}) {
1096 $href .= esc_url($params{'hash_parent_base'});
1097 # skip the file_parent if it's the same as the file_name
1098 if (defined $params{'file_parent'}) {
1099 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1100 delete $params{'file_parent'};
1101 } elsif ($params{'file_parent'} !~ /\.\./) {
1102 $href .= ":/".esc_url($params{'file_parent'});
1103 delete $params{'file_parent'};
1106 $href .= "..";
1107 delete $params{'hash_parent'};
1108 delete $params{'hash_parent_base'};
1109 } elsif (defined $params{'hash_parent'}) {
1110 $href .= esc_url($params{'hash_parent'}). "..";
1111 delete $params{'hash_parent'};
1114 $href .= esc_url($params{'hash_base'});
1115 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1116 $href .= ":/".esc_url($params{'file_name'});
1117 delete $params{'file_name'};
1119 delete $params{'hash'};
1120 delete $params{'hash_base'};
1121 } elsif (defined $params{'hash'}) {
1122 $href .= esc_url($params{'hash'});
1123 delete $params{'hash'};
1126 # If the action was a snapshot, we can absorb the
1127 # snapshot_format parameter too
1128 if ($is_snapshot) {
1129 my $fmt = $params{'snapshot_format'};
1130 # snapshot_format should always be defined when href()
1131 # is called, but just in case some code forgets, we
1132 # fall back to the default
1133 $fmt ||= $snapshot_fmts[0];
1134 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1135 delete $params{'snapshot_format'};
1139 # now encode the parameters explicitly
1140 my @result = ();
1141 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1142 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1143 if (defined $params{$name}) {
1144 if (ref($params{$name}) eq "ARRAY") {
1145 foreach my $par (@{$params{$name}}) {
1146 push @result, $symbol . "=" . esc_param($par);
1148 } else {
1149 push @result, $symbol . "=" . esc_param($params{$name});
1153 $href .= "?" . join(';', @result) if $params{-partial_query} or scalar @result;
1155 if ($params{-anchor}) {
1156 $href .= "#".esc_param($params{-anchor});
1159 return $href;
1163 ## ======================================================================
1164 ## validation, quoting/unquoting and escaping
1166 sub validate_action {
1167 my $input = shift || return undef;
1168 return undef unless exists $actions{$input};
1169 return $input;
1172 sub validate_project {
1173 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1174 my $input = shift || return undef;
1175 if (!validate_pathname($input) ||
1176 !(-d "$projectroot/$input") ||
1177 !check_export_ok("$projectroot/$input") ||
1178 ($strict_export && !project_in_list($input))) {
1179 return undef;
1180 } else {
1181 return $input;
1185 sub validate_pathname {
1186 my $input = shift || return undef;
1188 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1189 # at the beginning, at the end, and between slashes.
1190 # also this catches doubled slashes
1191 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1192 return undef;
1194 # no null characters
1195 if ($input =~ m!\0!) {
1196 return undef;
1198 return $input;
1201 sub validate_refname {
1202 my $input = shift || return undef;
1204 # textual hashes are O.K.
1205 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1206 return $input;
1208 # it must be correct pathname
1209 $input = validate_pathname($input)
1210 or return undef;
1211 # restrictions on ref name according to git-check-ref-format
1212 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1213 return undef;
1215 return $input;
1218 # decode sequences of octets in utf8 into Perl's internal form,
1219 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1220 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1221 sub to_utf8 {
1222 my $str = shift || '';
1223 if (utf8::valid($str)) {
1224 utf8::decode($str);
1225 return $str;
1226 } else {
1227 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1231 # quote unsafe chars, but keep the slash, even when it's not
1232 # correct, but quoted slashes look too horrible in bookmarks
1233 sub esc_param {
1234 my $str = shift ||'';
1235 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1236 $str =~ s/ /\+/g;
1237 return $str;
1240 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1241 sub esc_url {
1242 my $str = shift || '';
1243 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1244 $str =~ s/\+/%2B/g;
1245 $str =~ s/ /\+/g;
1246 return $str;
1249 # quote unsafe characters in HTML attributes
1250 sub esc_attr {
1252 # for XHTML conformance escaping '"' to '&quot;' is not enough
1253 return esc_html(@_);
1256 # replace invalid utf8 character with SUBSTITUTION sequence
1257 sub esc_html {
1258 my $str = shift || '';
1259 my %opts = @_;
1261 $str = to_utf8($str);
1262 $str = $cgi->escapeHTML($str);
1263 if ($opts{'-nbsp'}) {
1264 $str =~ s/ /&nbsp;/g;
1266 use bytes;
1267 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1268 return $str;
1271 # quote control characters and escape filename to HTML
1272 sub esc_path {
1273 my $str = shift || '';
1274 my %opts = @_;
1276 $str = to_utf8($str);
1277 $str = $cgi->escapeHTML($str);
1278 if ($opts{'-nbsp'}) {
1279 $str =~ s/ /&nbsp;/g;
1281 use bytes;
1282 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1283 return $str;
1286 # Make control characters "printable", using character escape codes (CEC)
1287 sub quot_cec {
1288 my $cntrl = shift;
1289 my %opts = @_;
1290 my %es = ( # character escape codes, aka escape sequences
1291 "\t" => '\t', # tab (HT)
1292 "\n" => '\n', # line feed (LF)
1293 "\r" => '\r', # carrige return (CR)
1294 "\f" => '\f', # form feed (FF)
1295 "\b" => '\b', # backspace (BS)
1296 "\a" => '\a', # alarm (bell) (BEL)
1297 "\e" => '\e', # escape (ESC)
1298 "\013" => '\v', # vertical tab (VT)
1299 "\000" => '\0', # nul character (NUL)
1301 my $chr = ( (exists $es{$cntrl})
1302 ? $es{$cntrl}
1303 : sprintf('\x%02x', ord($cntrl)) );
1304 if ($opts{-nohtml}) {
1305 return $chr;
1306 } else {
1307 return "<span class=\"cntrl\">$chr</span>";
1311 # Alternatively use unicode control pictures codepoints,
1312 # Unicode "printable representation" (PR)
1313 sub quot_upr {
1314 my $cntrl = shift;
1315 my %opts = @_;
1317 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1318 if ($opts{-nohtml}) {
1319 return $chr;
1320 } else {
1321 return "<span class=\"cntrl\">$chr</span>";
1325 # git may return quoted and escaped filenames
1326 sub unquote {
1327 my $str = shift;
1329 sub unq {
1330 my $seq = shift;
1331 my %es = ( # character escape codes, aka escape sequences
1332 't' => "\t", # tab (HT, TAB)
1333 'n' => "\n", # newline (NL)
1334 'r' => "\r", # return (CR)
1335 'f' => "\f", # form feed (FF)
1336 'b' => "\b", # backspace (BS)
1337 'a' => "\a", # alarm (bell) (BEL)
1338 'e' => "\e", # escape (ESC)
1339 'v' => "\013", # vertical tab (VT)
1342 if ($seq =~ m/^[0-7]{1,3}$/) {
1343 # octal char sequence
1344 return chr(oct($seq));
1345 } elsif (exists $es{$seq}) {
1346 # C escape sequence, aka character escape code
1347 return $es{$seq};
1349 # quoted ordinary character
1350 return $seq;
1353 if ($str =~ m/^"(.*)"$/) {
1354 # needs unquoting
1355 $str = $1;
1356 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1358 return $str;
1361 # escape tabs (convert tabs to spaces)
1362 sub untabify {
1363 my $line = shift;
1365 while ((my $pos = index($line, "\t")) != -1) {
1366 if (my $count = (8 - ($pos % 8))) {
1367 my $spaces = ' ' x $count;
1368 $line =~ s/\t/$spaces/;
1372 return $line;
1375 sub project_in_list {
1376 my $project = shift;
1377 my @list = git_get_projects_list();
1378 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1381 ## ----------------------------------------------------------------------
1382 ## HTML aware string manipulation
1384 # Try to chop given string on a word boundary between position
1385 # $len and $len+$add_len. If there is no word boundary there,
1386 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1387 # (marking chopped part) would be longer than given string.
1388 sub chop_str {
1389 my $str = shift;
1390 my $len = shift;
1391 my $add_len = shift || 10;
1392 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1394 # Make sure perl knows it is utf8 encoded so we don't
1395 # cut in the middle of a utf8 multibyte char.
1396 $str = to_utf8($str);
1398 # allow only $len chars, but don't cut a word if it would fit in $add_len
1399 # if it doesn't fit, cut it if it's still longer than the dots we would add
1400 # remove chopped character entities entirely
1402 # when chopping in the middle, distribute $len into left and right part
1403 # return early if chopping wouldn't make string shorter
1404 if ($where eq 'center') {
1405 return $str if ($len + 5 >= length($str)); # filler is length 5
1406 $len = int($len/2);
1407 } else {
1408 return $str if ($len + 4 >= length($str)); # filler is length 4
1411 # regexps: ending and beginning with word part up to $add_len
1412 my $endre = qr/.{$len}\w{0,$add_len}/;
1413 my $begre = qr/\w{0,$add_len}.{$len}/;
1415 if ($where eq 'left') {
1416 $str =~ m/^(.*?)($begre)$/;
1417 my ($lead, $body) = ($1, $2);
1418 if (length($lead) > 4) {
1419 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1420 $lead = " ...";
1422 return "$lead$body";
1424 } elsif ($where eq 'center') {
1425 $str =~ m/^($endre)(.*)$/;
1426 my ($left, $str) = ($1, $2);
1427 $str =~ m/^(.*?)($begre)$/;
1428 my ($mid, $right) = ($1, $2);
1429 if (length($mid) > 5) {
1430 $left =~ s/&[^;]*$//;
1431 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1432 $mid = " ... ";
1434 return "$left$mid$right";
1436 } else {
1437 $str =~ m/^($endre)(.*)$/;
1438 my $body = $1;
1439 my $tail = $2;
1440 if (length($tail) > 4) {
1441 $body =~ s/&[^;]*$//;
1442 $tail = "... ";
1444 return "$body$tail";
1448 # pass-through email filter, obfuscating it when possible
1449 sub email_obfuscate {
1450 my ($str) = @_;
1451 if ($email) {
1452 $str = $email->escape_html($str);
1453 # Stock HTML::Email::Obfuscate version likes to produce
1454 # invalid XHTML...
1455 $str =~ s#<(/?)B>#<$1b>#g;
1456 return $str;
1457 } else {
1458 $str = esc_html($str);
1459 $str =~ s/@/&#x40;/;
1460 return $str;
1464 # takes the same arguments as chop_str, but also wraps a <span> around the
1465 # result with a title attribute if it does get chopped. Additionally, the
1466 # string is HTML-escaped.
1467 sub chop_and_escape_str {
1468 my ($str) = @_;
1470 my $chopped = chop_str(@_);
1471 if ($chopped eq $str) {
1472 return email_obfuscate($chopped);
1473 } else {
1474 use bytes;
1475 $str =~ s/[[:cntrl:]]/?/g;
1476 return $cgi->span({-title=>$str}, email_obfuscate($chopped));
1480 ## ----------------------------------------------------------------------
1481 ## functions returning short strings
1483 # CSS class for given age value (in seconds)
1484 sub age_class {
1485 my $age = shift;
1487 if (!defined $age) {
1488 return "noage";
1489 } elsif ($age < 60*60*2) {
1490 return "age0";
1491 } elsif ($age < 60*60*24*2) {
1492 return "age1";
1493 } else {
1494 return "age2";
1498 # convert age in seconds to "nn units ago" string
1499 sub age_string {
1500 my $age = shift;
1501 my $age_str;
1503 if ($age > 60*60*24*365*2) {
1504 $age_str = (int $age/60/60/24/365);
1505 $age_str .= " years ago";
1506 } elsif ($age > 60*60*24*(365/12)*2) {
1507 $age_str = int $age/60/60/24/(365/12);
1508 $age_str .= " months ago";
1509 } elsif ($age > 60*60*24*7*2) {
1510 $age_str = int $age/60/60/24/7;
1511 $age_str .= " weeks ago";
1512 } elsif ($age > 60*60*24*2) {
1513 $age_str = int $age/60/60/24;
1514 $age_str .= " days ago";
1515 } elsif ($age > 60*60*2) {
1516 $age_str = int $age/60/60;
1517 $age_str .= " hours ago";
1518 } elsif ($age > 60*2) {
1519 $age_str = int $age/60;
1520 $age_str .= " min ago";
1521 } elsif ($age > 2) {
1522 $age_str = int $age;
1523 $age_str .= " sec ago";
1524 } else {
1525 $age_str .= " right now";
1527 return $age_str;
1530 use constant {
1531 S_IFINVALID => 0030000,
1532 S_IFGITLINK => 0160000,
1535 # submodule/subproject, a commit object reference
1536 sub S_ISGITLINK {
1537 my $mode = shift;
1539 return (($mode & S_IFMT) == S_IFGITLINK)
1542 # convert file mode in octal to symbolic file mode string
1543 sub mode_str {
1544 my $mode = oct shift;
1546 if (S_ISGITLINK($mode)) {
1547 return 'm---------';
1548 } elsif (S_ISDIR($mode & S_IFMT)) {
1549 return 'drwxr-xr-x';
1550 } elsif (S_ISLNK($mode)) {
1551 return 'lrwxrwxrwx';
1552 } elsif (S_ISREG($mode)) {
1553 # git cares only about the executable bit
1554 if ($mode & S_IXUSR) {
1555 return '-rwxr-xr-x';
1556 } else {
1557 return '-rw-r--r--';
1559 } else {
1560 return '----------';
1564 # convert file mode in octal to file type string
1565 sub file_type {
1566 my $mode = shift;
1568 if ($mode !~ m/^[0-7]+$/) {
1569 return $mode;
1570 } else {
1571 $mode = oct $mode;
1574 if (S_ISGITLINK($mode)) {
1575 return "submodule";
1576 } elsif (S_ISDIR($mode & S_IFMT)) {
1577 return "directory";
1578 } elsif (S_ISLNK($mode)) {
1579 return "symlink";
1580 } elsif (S_ISREG($mode)) {
1581 return "file";
1582 } else {
1583 return "unknown";
1587 # convert file mode in octal to file type description string
1588 sub file_type_long {
1589 my $mode = shift;
1591 if ($mode !~ m/^[0-7]+$/) {
1592 return $mode;
1593 } else {
1594 $mode = oct $mode;
1597 if (S_ISGITLINK($mode)) {
1598 return "submodule";
1599 } elsif (S_ISDIR($mode & S_IFMT)) {
1600 return "directory";
1601 } elsif (S_ISLNK($mode)) {
1602 return "symlink";
1603 } elsif (S_ISREG($mode)) {
1604 if ($mode & S_IXUSR) {
1605 return "executable";
1606 } else {
1607 return "file";
1609 } else {
1610 return "unknown";
1615 ## ----------------------------------------------------------------------
1616 ## functions returning short HTML fragments, or transforming HTML fragments
1617 ## which don't belong to other sections
1619 # format line of commit message.
1620 sub format_log_line_html {
1621 my $line = shift;
1623 $line = esc_html($line, -nbsp=>1);
1624 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1625 $cgi->a({-href => href(action=>"object", hash=>$1),
1626 -class => "text"}, $1);
1627 }eg unless $line =~ /^\s*git-svn-id:/;
1629 return $line;
1632 # format marker of refs pointing to given object
1634 # the destination action is chosen based on object type and current context:
1635 # - for annotated tags, we choose the tag view unless it's the current view
1636 # already, in which case we go to shortlog view
1637 # - for other refs, we keep the current view if we're in history, shortlog or
1638 # log view, and select shortlog otherwise
1639 sub format_ref_marker {
1640 my ($refs, $id) = @_;
1641 my $markers = '';
1643 if (defined $refs->{$id}) {
1644 foreach my $ref (@{$refs->{$id}}) {
1645 # this code exploits the fact that non-lightweight tags are the
1646 # only indirect objects, and that they are the only objects for which
1647 # we want to use tag instead of shortlog as action
1648 my ($type, $name) = qw();
1649 my $indirect = ($ref =~ s/\^\{\}$//);
1650 # e.g. tags/v2.6.11 or heads/next
1651 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1652 $type = $1;
1653 $name = $2;
1654 } else {
1655 $type = "ref";
1656 $name = $ref;
1659 my $class = $type;
1660 $class .= " indirect" if $indirect;
1662 my $dest_action = "shortlog";
1664 if ($indirect) {
1665 $dest_action = "tag" unless $action eq "tag";
1666 } elsif ($action =~ /^(history|(short)?log)$/) {
1667 $dest_action = $action;
1670 my $dest = "";
1671 $dest .= "refs/" unless $ref =~ m!^refs/!;
1672 $dest .= $ref;
1674 my $link = $cgi->a({
1675 -href => href(
1676 action=>$dest_action,
1677 hash=>$dest
1678 )}, $name);
1680 $markers .= "<span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
1681 $link . "</span>";
1685 if ($markers) {
1686 return '<span class="refs">'. $markers . '</span>';
1687 } else {
1688 return "";
1692 # format, perhaps shortened and with markers, title line
1693 sub format_subject_html {
1694 my ($long, $short, $href, $extra) = @_;
1695 $extra = '' unless defined($extra);
1697 if (length($short) < length($long)) {
1698 use bytes;
1699 $long =~ s/[[:cntrl:]]/?/g;
1700 return $cgi->a({-href => $href, -class => "list subject",
1701 -title => to_utf8($long)},
1702 esc_html($short)) . $extra;
1703 } else {
1704 return $cgi->a({-href => $href, -class => "list subject"},
1705 esc_html($long)) . $extra;
1709 # Rather than recomputing the url for an email multiple times, we cache it
1710 # after the first hit. This gives a visible benefit in views where the avatar
1711 # for the same email is used repeatedly (e.g. shortlog).
1712 # The cache is shared by all avatar engines (currently gravatar only), which
1713 # are free to use it as preferred. Since only one avatar engine is used for any
1714 # given page, there's no risk for cache conflicts.
1715 our %avatar_cache = ();
1717 # Compute the picon url for a given email, by using the picon search service over at
1718 # http://www.cs.indiana.edu/picons/search.html
1719 sub picon_url {
1720 my $email = lc shift;
1721 if (!$avatar_cache{$email}) {
1722 my ($user, $domain) = split('@', $email);
1723 $avatar_cache{$email} =
1724 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1725 "$domain/$user/" .
1726 "users+domains+unknown/up/single";
1728 return $avatar_cache{$email};
1731 # Compute the gravatar url for a given email, if it's not in the cache already.
1732 # Gravatar stores only the part of the URL before the size, since that's the
1733 # one computationally more expensive. This also allows reuse of the cache for
1734 # different sizes (for this particular engine).
1735 sub gravatar_url {
1736 my $email = lc shift;
1737 my $size = shift;
1738 $avatar_cache{$email} ||=
1739 "http://www.gravatar.com/avatar/" .
1740 Digest::MD5::md5_hex($email) . "?s=";
1741 return $avatar_cache{$email} . $size;
1744 # Insert an avatar for the given $email at the given $size if the feature
1745 # is enabled.
1746 sub git_get_avatar {
1747 my $email = shift || '';
1748 my %opts = @_;
1749 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1750 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1751 $opts{-size} ||= 'default';
1752 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1753 my $url = "";
1754 if ($git_avatar eq 'gravatar') {
1755 $url = gravatar_url($email, $size);
1756 } elsif ($git_avatar eq 'picon') {
1757 $url = picon_url($email);
1759 # Other providers can be added by extending the if chain, defining $url
1760 # as needed. If no variant puts something in $url, we assume avatars
1761 # are completely disabled/unavailable.
1762 if ($url) {
1763 return $pre_white .
1764 "<img width=\"$size\" " .
1765 "class=\"avatar\" " .
1766 "src=\"".esc_url($url)."\" " .
1767 "alt=\"\" " .
1768 "/>" . $post_white;
1769 } else {
1770 return "";
1774 sub format_search_author {
1775 my $author = shift || '';
1776 my $searchtype = shift || '';
1777 my $displaytext = shift || '';
1778 my $have_search = gitweb_check_feature('search');
1780 if ($have_search) {
1781 my $performed = "";
1782 if ($searchtype eq 'author') {
1783 $performed = "authored";
1784 } elsif ($searchtype eq 'committer') {
1785 $performed = "committed";
1788 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1789 searchtext=>$author,
1790 searchtype=>$searchtype), class=>"list",
1791 title=>"Search for commits $performed by $author"},
1792 $displaytext);
1794 } else {
1795 return $displaytext;
1799 # format the author name of the given commit with the given tag
1800 # the author name is chopped and escaped according to the other
1801 # optional parameters (see chop_str).
1802 sub format_author_html {
1803 my $tag = shift;
1804 my $co = shift;
1805 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1806 return "<$tag class=\"author\">" .
1807 format_search_author($co->{'author_name'}, "author",
1808 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1809 $author) .
1810 "</$tag>";
1813 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1814 sub format_git_diff_header_line {
1815 my $line = shift;
1816 my $diffinfo = shift;
1817 my ($from, $to) = @_;
1819 if ($diffinfo->{'nparents'}) {
1820 # combined diff
1821 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1822 if ($to->{'href'}) {
1823 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1824 esc_path($to->{'file'}));
1825 } else { # file was deleted (no href)
1826 $line .= esc_path($to->{'file'});
1828 } else {
1829 # "ordinary" diff
1830 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1831 if ($from->{'href'}) {
1832 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1833 'a/' . esc_path($from->{'file'}));
1834 } else { # file was added (no href)
1835 $line .= 'a/' . esc_path($from->{'file'});
1837 $line .= ' ';
1838 if ($to->{'href'}) {
1839 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1840 'b/' . esc_path($to->{'file'}));
1841 } else { # file was deleted
1842 $line .= 'b/' . esc_path($to->{'file'});
1846 return "<div class=\"diff header\">$line</div>\n";
1849 # format extended diff header line, before patch itself
1850 sub format_extended_diff_header_line {
1851 my $line = shift;
1852 my $diffinfo = shift;
1853 my ($from, $to) = @_;
1855 # match <path>
1856 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1857 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1858 esc_path($from->{'file'}));
1860 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1861 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1862 esc_path($to->{'file'}));
1864 # match single <mode>
1865 if ($line =~ m/\s(\d{6})$/) {
1866 $line .= '<span class="info"> (' .
1867 file_type_long($1) .
1868 ')</span>';
1870 # match <hash>
1871 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1872 # can match only for combined diff
1873 $line = 'index ';
1874 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1875 if ($from->{'href'}[$i]) {
1876 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1877 -class=>"hash"},
1878 substr($diffinfo->{'from_id'}[$i],0,7));
1879 } else {
1880 $line .= '0' x 7;
1882 # separator
1883 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1885 $line .= '..';
1886 if ($to->{'href'}) {
1887 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1888 substr($diffinfo->{'to_id'},0,7));
1889 } else {
1890 $line .= '0' x 7;
1893 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1894 # can match only for ordinary diff
1895 my ($from_link, $to_link);
1896 if ($from->{'href'}) {
1897 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1898 substr($diffinfo->{'from_id'},0,7));
1899 } else {
1900 $from_link = '0' x 7;
1902 if ($to->{'href'}) {
1903 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1904 substr($diffinfo->{'to_id'},0,7));
1905 } else {
1906 $to_link = '0' x 7;
1908 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1909 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1912 return $line . "<br/>\n";
1915 # format from-file/to-file diff header
1916 sub format_diff_from_to_header {
1917 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1918 my $line;
1919 my $result = '';
1921 $line = $from_line;
1922 #assert($line =~ m/^---/) if DEBUG;
1923 # no extra formatting for "^--- /dev/null"
1924 if (! $diffinfo->{'nparents'}) {
1925 # ordinary (single parent) diff
1926 if ($line =~ m!^--- "?a/!) {
1927 if ($from->{'href'}) {
1928 $line = '--- a/' .
1929 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1930 esc_path($from->{'file'}));
1931 } else {
1932 $line = '--- a/' .
1933 esc_path($from->{'file'});
1936 $result .= qq!<div class="diff from_file">$line</div>\n!;
1938 } else {
1939 # combined diff (merge commit)
1940 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1941 if ($from->{'href'}[$i]) {
1942 $line = '--- ' .
1943 $cgi->a({-href=>href(action=>"blobdiff",
1944 hash_parent=>$diffinfo->{'from_id'}[$i],
1945 hash_parent_base=>$parents[$i],
1946 file_parent=>$from->{'file'}[$i],
1947 hash=>$diffinfo->{'to_id'},
1948 hash_base=>$hash,
1949 file_name=>$to->{'file'}),
1950 -class=>"path",
1951 -title=>"diff" . ($i+1)},
1952 $i+1) .
1953 '/' .
1954 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1955 esc_path($from->{'file'}[$i]));
1956 } else {
1957 $line = '--- /dev/null';
1959 $result .= qq!<div class="diff from_file">$line</div>\n!;
1963 $line = $to_line;
1964 #assert($line =~ m/^\+\+\+/) if DEBUG;
1965 # no extra formatting for "^+++ /dev/null"
1966 if ($line =~ m!^\+\+\+ "?b/!) {
1967 if ($to->{'href'}) {
1968 $line = '+++ b/' .
1969 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1970 esc_path($to->{'file'}));
1971 } else {
1972 $line = '+++ b/' .
1973 esc_path($to->{'file'});
1976 $result .= qq!<div class="diff to_file">$line</div>\n!;
1978 return $result;
1981 # create note for patch simplified by combined diff
1982 sub format_diff_cc_simplified {
1983 my ($diffinfo, @parents) = @_;
1984 my $result = '';
1986 $result .= "<div class=\"diff header\">" .
1987 "diff --cc ";
1988 if (!is_deleted($diffinfo)) {
1989 $result .= $cgi->a({-href => href(action=>"blob",
1990 hash_base=>$hash,
1991 hash=>$diffinfo->{'to_id'},
1992 file_name=>$diffinfo->{'to_file'}),
1993 -class => "path"},
1994 esc_path($diffinfo->{'to_file'}));
1995 } else {
1996 $result .= esc_path($diffinfo->{'to_file'});
1998 $result .= "</div>\n" . # class="diff header"
1999 "<div class=\"diff nodifferences\">" .
2000 "Simple merge" .
2001 "</div>\n"; # class="diff nodifferences"
2003 return $result;
2006 # format patch (diff) line (not to be used for diff headers)
2007 sub format_diff_line {
2008 my $line = shift;
2009 my ($from, $to) = @_;
2010 my $diff_class = "";
2012 chomp $line;
2014 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2015 # combined diff
2016 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2017 if ($line =~ m/^\@{3}/) {
2018 $diff_class = " chunk_header";
2019 } elsif ($line =~ m/^\\/) {
2020 $diff_class = " incomplete";
2021 } elsif ($prefix =~ tr/+/+/) {
2022 $diff_class = " add";
2023 } elsif ($prefix =~ tr/-/-/) {
2024 $diff_class = " rem";
2026 } else {
2027 # assume ordinary diff
2028 my $char = substr($line, 0, 1);
2029 if ($char eq '+') {
2030 $diff_class = " add";
2031 } elsif ($char eq '-') {
2032 $diff_class = " rem";
2033 } elsif ($char eq '@') {
2034 $diff_class = " chunk_header";
2035 } elsif ($char eq "\\") {
2036 $diff_class = " incomplete";
2039 $line = untabify($line);
2040 if ($from && $to && $line =~ m/^\@{2} /) {
2041 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2042 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2044 $from_lines = 0 unless defined $from_lines;
2045 $to_lines = 0 unless defined $to_lines;
2047 if ($from->{'href'}) {
2048 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2049 -class=>"list"}, $from_text);
2051 if ($to->{'href'}) {
2052 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2053 -class=>"list"}, $to_text);
2055 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2056 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2057 return "<div class=\"diff$diff_class\">$line</div>\n";
2058 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2059 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2060 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2062 @from_text = split(' ', $ranges);
2063 for (my $i = 0; $i < @from_text; ++$i) {
2064 ($from_start[$i], $from_nlines[$i]) =
2065 (split(',', substr($from_text[$i], 1)), 0);
2068 $to_text = pop @from_text;
2069 $to_start = pop @from_start;
2070 $to_nlines = pop @from_nlines;
2072 $line = "<span class=\"chunk_info\">$prefix ";
2073 for (my $i = 0; $i < @from_text; ++$i) {
2074 if ($from->{'href'}[$i]) {
2075 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2076 -class=>"list"}, $from_text[$i]);
2077 } else {
2078 $line .= $from_text[$i];
2080 $line .= " ";
2082 if ($to->{'href'}) {
2083 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2084 -class=>"list"}, $to_text);
2085 } else {
2086 $line .= $to_text;
2088 $line .= " $prefix</span>" .
2089 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2090 return "<div class=\"diff$diff_class\">$line</div>\n";
2092 return "<div class=\"diff diff_body$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2095 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2096 # linked. Pass the hash of the tree/commit to snapshot.
2097 sub format_snapshot_links {
2098 my ($hash) = @_;
2099 my $num_fmts = @snapshot_fmts;
2100 if ($num_fmts > 1) {
2101 # A parenthesized list of links bearing format names.
2102 # e.g. "snapshot (_tar.gz_ _zip_)"
2103 return "snapshot (" . join(' ', map
2104 $cgi->a({
2105 -href => href(
2106 action=>"snapshot",
2107 hash=>$hash,
2108 snapshot_format=>$_
2110 }, $known_snapshot_formats{$_}{'display'})
2111 , @snapshot_fmts) . ")";
2112 } elsif ($num_fmts == 1) {
2113 # A single "snapshot" link whose tooltip bears the format name.
2114 # i.e. "_snapshot_"
2115 my ($fmt) = @snapshot_fmts;
2116 return
2117 $cgi->a({
2118 -href => href(
2119 action=>"snapshot",
2120 hash=>$hash,
2121 snapshot_format=>$fmt
2123 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2124 }, "snapshot");
2125 } else { # $num_fmts == 0
2126 return undef;
2130 ## ......................................................................
2131 ## functions returning values to be passed, perhaps after some
2132 ## transformation, to other functions; e.g. returning arguments to href()
2134 # returns hash to be passed to href to generate gitweb URL
2135 # in -title key it returns description of link
2136 sub get_feed_info {
2137 my $format = shift || 'Atom';
2138 my %res = (action => lc($format));
2140 # feed links are possible only for project views
2141 return unless (defined $project);
2142 # some views should link to OPML, or to generic project feed,
2143 # or don't have specific feed yet (so they should use generic)
2144 return if ($action && $action =~ /^(?:tags|heads|refs|forks|tag|search)$/x);
2146 my $branch;
2147 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2148 # from tag links; this also makes possible to detect branch links
2149 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2150 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2151 $branch = $1;
2153 # find log type for feed description (title)
2154 my $type = 'log';
2155 if (defined $file_name) {
2156 $type = "history of $file_name";
2157 $type .= "/" if ($action && $action eq 'tree');
2158 $type .= " on '$branch'" if (defined $branch);
2159 } else {
2160 $type = "log of $branch" if (defined $branch);
2163 $res{-title} = $type;
2164 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2165 $res{'file_name'} = $file_name;
2167 return %res;
2170 ## ----------------------------------------------------------------------
2171 ## git utility subroutines, invoking git commands
2173 # returns path to the core git executable and the --git-dir parameter as list
2174 sub git_cmd {
2175 return $GIT, '--git-dir='.$git_dir;
2178 # opens a "-|" cmd pipe handle with 2>/dev/null and returns it
2179 sub cmd_pipe {
2180 open(NULL, ">", File::Spec->devnull) or die "Cannot open devnull: $!";
2181 open(SAVEERR, ">&STDERR") || die "couldn't dup STDERR: $!";
2182 open(STDERR, ">&NULL") || die "couldn't dup NULL to STDERR: $!";
2183 my $result = open(my $fd, "-|", @_);
2184 open(STDERR, ">&SAVEERR") || die "couldn't dup SAVERR to STDERR: $!";
2185 close(SAVEERR) or die "couldn't close SAVEERR: $!";
2186 close(NULL) or die "couldn't close NULL: $!";
2187 return $result ? $fd : undef;
2190 # opens a "-|" git_cmd pipe handle with 2>/dev/null and returns it
2191 sub git_cmd_pipe {
2192 return cmd_pipe git_cmd(), @_;
2195 # quote the given arguments for passing them to the shell
2196 # quote_command("command", "arg 1", "arg with ' and ! characters")
2197 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2198 # Try to avoid using this function wherever possible.
2199 sub quote_command {
2200 return join(' ',
2201 map { my $a = $_||''; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2204 # get HEAD ref of given project as hash
2205 sub git_get_head_hash {
2206 my $project = shift;
2207 my $o_git_dir = $git_dir;
2208 my $retval = undef;
2209 $git_dir = "$projectroot/$project";
2210 if (defined(my $fd = git_cmd_pipe "rev-parse", "--verify", "HEAD")) {
2211 my $head = <$fd>;
2212 close $fd;
2213 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
2214 $retval = $1;
2217 if (defined $o_git_dir) {
2218 $git_dir = $o_git_dir;
2220 return $retval;
2223 # get type of given object
2224 sub git_get_type {
2225 my $hash = shift;
2227 defined(my $fd = git_cmd_pipe "cat-file", '-t', $hash) or return;
2228 my $type = <$fd>;
2229 close $fd or return;
2230 chomp $type if $type;
2231 return $type;
2234 # repository configuration
2235 our $config_file = '';
2236 our %config;
2238 # store multiple values for single key as anonymous array reference
2239 # single values stored directly in the hash, not as [ <value> ]
2240 sub hash_set_multi {
2241 my ($hash, $key, $value) = @_;
2243 if (!exists $hash->{$key}) {
2244 $hash->{$key} = $value;
2245 } elsif (!ref $hash->{$key}) {
2246 $hash->{$key} = [ $hash->{$key}, $value ];
2247 } else {
2248 push @{$hash->{$key}}, $value;
2252 # return hash of git project configuration
2253 # optionally limited to some section, e.g. 'gitweb'
2254 sub git_parse_project_config {
2255 my $section_regexp = shift;
2256 my %config;
2258 local $/ = "\0";
2260 defined(my $fh = git_cmd_pipe "config", '-z', '-l')
2261 or return;
2263 while (my $keyval = <$fh>) {
2264 chomp $keyval;
2265 my ($key, $value) = split(/\n/, $keyval, 2);
2267 hash_set_multi(\%config, $key, $value)
2268 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2270 close $fh;
2272 return %config;
2275 # convert config value to boolean: 'true' or 'false'
2276 # no value, number > 0, 'true' and 'yes' values are true
2277 # rest of values are treated as false (never as error)
2278 sub config_to_bool {
2279 my $val = shift;
2281 return 1 if !defined $val; # section.key
2283 # strip leading and trailing whitespace
2284 $val =~ s/^\s+//;
2285 $val =~ s/\s+$//;
2287 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2288 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2291 # convert config value to simple decimal number
2292 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2293 # to be multiplied by 1024, 1048576, or 1073741824
2294 sub config_to_int {
2295 my $val = shift;
2297 # strip leading and trailing whitespace
2298 $val =~ s/^\s+//;
2299 $val =~ s/\s+$//;
2301 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2302 $unit = lc($unit);
2303 # unknown unit is treated as 1
2304 return $num * ($unit eq 'g' ? 1073741824 :
2305 $unit eq 'm' ? 1048576 :
2306 $unit eq 'k' ? 1024 : 1);
2308 return $val;
2311 # convert config value to array reference, if needed
2312 sub config_to_multi {
2313 my $val = shift;
2315 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2318 sub git_get_project_config {
2319 my ($key, $type) = @_;
2321 # do we have project
2322 return unless (defined $project && defined $git_dir);
2324 # key sanity check
2325 return unless ($key);
2326 $key =~ s/^gitweb\.//;
2327 return if ($key =~ m/\W/);
2329 # type sanity check
2330 if (defined $type) {
2331 $type =~ s/^--//;
2332 $type = undef
2333 unless ($type eq 'bool' || $type eq 'int');
2336 # get config
2337 if (!defined $config_file ||
2338 $config_file ne "$git_dir/config") {
2339 %config = git_parse_project_config('gitweb');
2340 $config_file = "$git_dir/config";
2343 # check if config variable (key) exists
2344 return unless exists $config{"gitweb.$key"};
2346 # ensure given type
2347 if (!defined $type) {
2348 return $config{"gitweb.$key"};
2349 } elsif ($type eq 'bool') {
2350 # backward compatibility: 'git config --bool' returns true/false
2351 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2352 } elsif ($type eq 'int') {
2353 return config_to_int($config{"gitweb.$key"});
2355 return $config{"gitweb.$key"};
2358 # get hash of given path at given ref
2359 sub git_get_hash_by_path {
2360 my $base = shift;
2361 my $path = shift || return undef;
2362 my $type = shift;
2364 $path =~ s,/+$,,;
2366 defined(my $fd = git_cmd_pipe "ls-tree", $base, "--", $path)
2367 or die_error(500, "Open git-ls-tree failed");
2368 my $line = <$fd>;
2369 close $fd or return undef;
2371 if (!defined $line) {
2372 # there is no tree or hash given by $path at $base
2373 return undef;
2376 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2377 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2378 if (defined $type && $type ne $2) {
2379 # type doesn't match
2380 return undef;
2382 return $3;
2385 # get path of entry with given hash at given tree-ish (ref)
2386 # used to get 'from' filename for combined diff (merge commit) for renames
2387 sub git_get_path_by_hash {
2388 my $base = shift || return;
2389 my $hash = shift || return;
2391 local $/ = "\0";
2393 defined(my $fd = git_cmd_pipe "ls-tree", '-r', '-t', '-z', $base)
2394 or return undef;
2395 while (my $line = <$fd>) {
2396 chomp $line;
2398 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2399 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2400 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2401 close $fd;
2402 return $1;
2405 close $fd;
2406 return undef;
2409 ## ......................................................................
2410 ## git utility functions, directly accessing git repository
2412 sub git_get_project_description {
2413 my $path = shift;
2415 $git_dir = "$projectroot/$path";
2416 open my $fd, '<', "$git_dir/description"
2417 or return git_get_project_config('description');
2418 my $descr = <$fd>;
2419 close $fd;
2420 if (defined $descr) {
2421 chomp $descr;
2423 return $descr;
2426 sub git_get_project_ctags {
2427 my $path = shift;
2428 my $ctags = {};
2430 $git_dir = "$projectroot/$path";
2431 opendir my $dh, "$git_dir/ctags"
2432 or return $ctags;
2433 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2434 open my $ct, '<', $_ or next;
2435 my $val = <$ct>;
2436 chomp $val;
2437 close $ct;
2438 my $ctag = $_; $ctag =~ s#.*/##;
2439 $ctags->{$ctag} = $val;
2441 closedir $dh;
2442 $ctags;
2445 sub git_populate_project_tagcloud {
2446 my ($ctags, $action) = @_;
2448 # First, merge different-cased tags; tags vote on casing
2449 my %ctags_lc;
2450 foreach (keys %$ctags) {
2451 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2452 if (not $ctags_lc{lc $_}->{topcount}
2453 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2454 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2455 $ctags_lc{lc $_}->{topname} = $_;
2459 my $cloud;
2460 if (eval { require HTML::TagCloud; 1; }) {
2461 $cloud = HTML::TagCloud->new;
2462 foreach (sort keys %ctags_lc) {
2463 # Pad the title with spaces so that the cloud looks
2464 # less crammed.
2465 my $title = $ctags_lc{$_}->{topname};
2466 $title =~ s/ /&nbsp;/g;
2467 $title =~ s/^/&nbsp;/g;
2468 $title =~ s/$/&nbsp;/g;
2469 $cloud->add($title, href(-replay=>1, action=>$action, ctag_filter=>$_),
2470 $ctags_lc{$_}->{count});
2472 } else {
2473 $cloud = \%ctags_lc;
2475 $cloud;
2478 sub git_show_project_tagcloud {
2479 my ($cloud, $count, $action) = @_;
2480 if (ref $cloud eq 'HTML::TagCloud') {
2481 return $cloud->html_and_css($count);
2482 } else {
2483 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2484 return '<p align="center">' . join (', ', map {
2485 $cgi->a({-href => href(-replay=>1, action=>$action, ctag_filter=>$_)},
2486 $cloud->{$_}->{topname});
2487 } splice(@tags, 0, $count)) . '</p>';
2491 sub git_get_project_url_list {
2492 my $path = shift;
2494 $git_dir = "$projectroot/$path";
2495 open my $fd, '<', "$git_dir/cloneurl"
2496 or return wantarray ?
2497 @{ config_to_multi(git_get_project_config('url')) } :
2498 config_to_multi(git_get_project_config('url'));
2499 my @git_project_url_list = map { chomp; $_ } <$fd>;
2500 close $fd;
2502 return wantarray ? @git_project_url_list : \@git_project_url_list;
2505 sub git_get_projects_list {
2506 my ($filter) = @_;
2507 my @list;
2509 $filter ||= '';
2510 $filter =~ s/\.git$//;
2512 my $check_forks = gitweb_check_feature('forks');
2514 if (-d $projects_list) {
2515 # search in directory
2516 my $dir = $projects_list . ($filter ? "/$filter" : '');
2517 # remove the trailing "/"
2518 $dir =~ s!/+$!!;
2519 my $pfxlen = length("$dir");
2520 my $pfxdepth = ($dir =~ tr!/!!);
2522 File::Find::find({
2523 follow_fast => 1, # follow symbolic links
2524 follow_skip => 2, # ignore duplicates
2525 dangling_symlinks => 0, # ignore dangling symlinks, silently
2526 wanted => sub {
2527 # global variables
2528 our $project_maxdepth;
2529 our $projectroot;
2530 # skip project-list toplevel, if we get it.
2531 return if (m!^[/.]$!);
2532 # only directories can be git repositories
2533 return unless (-d $_);
2534 # don't traverse too deep (Find is super slow on os x)
2535 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2536 $File::Find::prune = 1;
2537 return;
2540 my $subdir = substr($File::Find::name, $pfxlen + 1);
2541 # we check related file in $projectroot
2542 my $path = ($filter ? "$filter/" : '') . $subdir;
2543 if (check_export_ok("$projectroot/$path")) {
2544 push @list, { path => $path };
2545 $File::Find::prune = 1;
2548 }, "$dir");
2550 } elsif (-f $projects_list) {
2551 # read from file(url-encoded):
2552 # 'git%2Fgit.git Linus+Torvalds'
2553 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2554 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2555 my %paths;
2556 open my $fd, '<', $projects_list or return;
2557 PROJECT:
2558 while (my $line = <$fd>) {
2559 chomp $line;
2560 my ($path, $owner) = split ' ', $line;
2561 $path = unescape($path);
2562 $owner = unescape($owner);
2563 if (!defined $path) {
2564 next;
2566 if ($filter ne '') {
2567 # looking for forks;
2568 my $pfx = substr($path, 0, length($filter));
2569 if ($pfx ne $filter) {
2570 next PROJECT;
2572 my $sfx = substr($path, length($filter));
2573 if ($sfx !~ /^\/.*\.git$/) {
2574 next PROJECT;
2576 } elsif ($check_forks) {
2577 PATH:
2578 foreach my $filter (keys %paths) {
2579 # looking for forks;
2580 my $pfx = substr($path, 0, length($filter));
2581 if ($pfx ne $filter) {
2582 next PATH;
2584 my $sfx = substr($path, length($filter));
2585 if ($sfx !~ /^\/.*\.git$/) {
2586 next PATH;
2588 # is a fork, don't include it in
2589 # the list
2590 next PROJECT;
2593 if (check_export_ok("$projectroot/$path")) {
2594 my $pr = {
2595 path => $path,
2596 owner => to_utf8($owner),
2598 push @list, $pr;
2599 (my $forks_path = $path) =~ s/\.git$//;
2600 $paths{$forks_path}++;
2603 close $fd;
2605 return @list;
2608 our $gitweb_project_owner = undef;
2609 sub git_get_project_list_from_file {
2611 return if (defined $gitweb_project_owner);
2613 $gitweb_project_owner = {};
2614 # read from file (url-encoded):
2615 # 'git%2Fgit.git Linus+Torvalds'
2616 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2617 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2618 if (-f $projects_list) {
2619 open(my $fd, '<', $projects_list);
2620 while (my $line = <$fd>) {
2621 chomp $line;
2622 my ($pr, $ow) = split ' ', $line;
2623 $pr = unescape($pr);
2624 $ow = unescape($ow);
2625 $gitweb_project_owner->{$pr} = to_utf8($ow);
2627 close $fd;
2631 sub git_get_project_owner {
2632 my $project = shift;
2633 my $owner;
2635 return undef unless $project;
2636 $git_dir = "$projectroot/$project";
2638 if (!defined $gitweb_project_owner) {
2639 git_get_project_list_from_file();
2642 if (exists $gitweb_project_owner->{$project}) {
2643 $owner = $gitweb_project_owner->{$project};
2645 if (!defined $owner){
2646 $owner = git_get_project_config('owner');
2648 if (!defined $owner) {
2649 $owner = get_file_owner("$git_dir");
2652 return $owner;
2655 sub git_get_last_activity {
2656 my ($path) = @_;
2657 my $fd;
2659 $git_dir = "$projectroot/$path";
2660 defined($fd = git_cmd_pipe 'for-each-ref',
2661 '--format=%(committer)',
2662 '--sort=-committerdate',
2663 '--count=1',
2664 'refs/heads') or return;
2665 my $most_recent = <$fd>;
2666 close $fd or return;
2667 if (defined $most_recent &&
2668 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2669 my $timestamp = $1;
2670 my $age = time - $timestamp;
2671 return ($age, age_string($age));
2673 return (undef, undef);
2676 sub git_get_references {
2677 my $type = shift || "";
2678 my %refs;
2679 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2680 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2681 defined(my $fd = git_cmd_pipe "show-ref", "--dereference",
2682 ($type ? ("--", "refs/$type") : ())) # use -- <pattern> if $type
2683 or return;
2685 while (my $line = <$fd>) {
2686 chomp $line;
2687 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2688 if (defined $refs{$1}) {
2689 push @{$refs{$1}}, $2;
2690 } else {
2691 $refs{$1} = [ $2 ];
2695 close $fd or return;
2696 return \%refs;
2699 sub git_get_rev_name_tags {
2700 my $hash = shift || return undef;
2702 defined(my $fd = git_cmd_pipe "name-rev", "--tags", $hash)
2703 or return;
2704 my $name_rev = <$fd>;
2705 close $fd;
2707 if ($name_rev && $name_rev =~ m|^$hash tags/(.*)$|) {
2708 return $1;
2709 } else {
2710 # catches also '$hash undefined' output
2711 return undef;
2715 ## ----------------------------------------------------------------------
2716 ## parse to hash functions
2718 sub parse_date {
2719 my $epoch = shift;
2720 my $tz = shift || "-0000";
2722 my %date;
2723 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2724 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2725 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2726 $date{'hour'} = $hour;
2727 $date{'minute'} = $min;
2728 $date{'mday'} = $mday;
2729 $date{'day'} = $days[$wday];
2730 $date{'month'} = $months[$mon];
2731 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2732 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2733 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2734 $mday, $months[$mon], $hour ,$min;
2735 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2736 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2738 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2739 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2740 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2741 $date{'hour_local'} = $hour;
2742 $date{'minute_local'} = $min;
2743 $date{'tz_local'} = $tz;
2744 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2745 1900+$year, $mon+1, $mday,
2746 $hour, $min, $sec, $tz);
2747 return %date;
2750 sub parse_tag {
2751 my $tag_id = shift;
2752 my %tag;
2753 my @comment;
2755 defined(my $fd = git_cmd_pipe "cat-file", "tag", $tag_id) or return;
2756 $tag{'id'} = $tag_id;
2757 while (my $line = <$fd>) {
2758 chomp $line;
2759 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2760 $tag{'object'} = $1;
2761 } elsif ($line =~ m/^type (.+)$/) {
2762 $tag{'type'} = $1;
2763 } elsif ($line =~ m/^tag (.+)$/) {
2764 $tag{'name'} = $1;
2765 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2766 $tag{'author'} = $1;
2767 $tag{'author_epoch'} = $2;
2768 $tag{'author_tz'} = $3;
2769 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2770 $tag{'author_name'} = $1;
2771 $tag{'author_email'} = $2;
2772 } else {
2773 $tag{'author_name'} = $tag{'author'};
2775 } elsif ($line =~ m/--BEGIN/) {
2776 push @comment, $line;
2777 last;
2778 } elsif ($line eq "") {
2779 last;
2782 push @comment, <$fd>;
2783 $tag{'comment'} = \@comment;
2784 close $fd or return;
2785 if (!defined $tag{'name'}) {
2786 return
2788 return %tag
2791 sub parse_commit_text {
2792 my ($commit_text, $withparents) = @_;
2793 my @commit_lines = split '\n', $commit_text;
2794 my %co;
2796 pop @commit_lines; # Remove '\0'
2798 if (! @commit_lines) {
2799 return;
2802 my $header = shift @commit_lines;
2803 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2804 return;
2806 ($co{'id'}, my @parents) = split ' ', $header;
2807 while (my $line = shift @commit_lines) {
2808 last if $line eq "\n";
2809 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2810 $co{'tree'} = $1;
2811 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2812 push @parents, $1;
2813 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2814 $co{'author'} = to_utf8($1);
2815 $co{'author_epoch'} = $2;
2816 $co{'author_tz'} = $3;
2817 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2818 $co{'author_name'} = $1;
2819 $co{'author_email'} = $2;
2820 } else {
2821 $co{'author_name'} = $co{'author'};
2823 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2824 $co{'committer'} = to_utf8($1);
2825 $co{'committer_epoch'} = $2;
2826 $co{'committer_tz'} = $3;
2827 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2828 $co{'committer_name'} = $1;
2829 $co{'committer_email'} = $2;
2830 } else {
2831 $co{'committer_name'} = $co{'committer'};
2835 if (!defined $co{'tree'}) {
2836 return;
2838 $co{'parents'} = \@parents;
2839 $co{'parent'} = $parents[0];
2841 foreach my $title (@commit_lines) {
2842 $title =~ s/^ //;
2843 if ($title ne "") {
2844 $co{'title'} = chop_str($title, 80, 5);
2845 # remove leading stuff of merges to make the interesting part visible
2846 if (length($title) > 50) {
2847 $title =~ s/^Automatic //;
2848 $title =~ s/^merge (of|with) /Merge ... /i;
2849 if (length($title) > 50) {
2850 $title =~ s/(http|rsync):\/\///;
2852 if (length($title) > 50) {
2853 $title =~ s/(master|www|rsync)\.//;
2855 if (length($title) > 50) {
2856 $title =~ s/kernel.org:?//;
2858 if (length($title) > 50) {
2859 $title =~ s/\/pub\/scm//;
2862 $co{'title_short'} = chop_str($title, 50, 5);
2863 last;
2866 if (! defined $co{'title'} || $co{'title'} eq "") {
2867 $co{'title'} = $co{'title_short'} = '(no commit message)';
2869 # remove added spaces
2870 foreach my $line (@commit_lines) {
2871 $line =~ s/^ //;
2873 $co{'comment'} = \@commit_lines;
2875 my $age = time - $co{'committer_epoch'};
2876 $co{'age'} = $age;
2877 $co{'age_string'} = age_string($age);
2878 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2879 if ($age > 60*60*24*7*2) {
2880 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2881 $co{'age_string_age'} = $co{'age_string'};
2882 } else {
2883 $co{'age_string_date'} = $co{'age_string'};
2884 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2886 return %co;
2889 sub parse_commit {
2890 my ($commit_id) = @_;
2891 my %co;
2893 local $/ = "\0";
2895 defined(my $fd = git_cmd_pipe "rev-list",
2896 "--parents",
2897 "--header",
2898 "--max-count=1",
2899 $commit_id,
2900 "--")
2901 or die_error(500, "Open git-rev-list failed");
2902 %co = parse_commit_text(<$fd>, 1);
2903 close $fd;
2905 return %co;
2908 sub parse_commits {
2909 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2910 my @cos = ();
2912 return wantarray ? @cos : \@cos unless $commit_id;
2914 $maxcount ||= 1;
2915 $skip ||= 0;
2917 local $/ = "\0";
2919 defined(my $fd = git_cmd_pipe "rev-list",
2920 "--header",
2921 @args,
2922 ("--max-count=" . $maxcount),
2923 ("--skip=" . $skip),
2924 @extra_options,
2925 $commit_id,
2926 "--",
2927 ($filename ? ($filename) : ()))
2928 or die_error(500, "Open git-rev-list failed");
2929 while (my $line = <$fd>) {
2930 my %co = parse_commit_text($line);
2931 push @cos, \%co;
2933 close $fd;
2935 return wantarray ? @cos : \@cos;
2938 # parse line of git-diff-tree "raw" output
2939 sub parse_difftree_raw_line {
2940 my $line = shift;
2941 my %res;
2943 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2944 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2945 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2946 $res{'from_mode'} = $1;
2947 $res{'to_mode'} = $2;
2948 $res{'from_id'} = $3;
2949 $res{'to_id'} = $4;
2950 $res{'status'} = $5;
2951 $res{'similarity'} = $6;
2952 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2953 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2954 } else {
2955 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2958 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2959 # combined diff (for merge commit)
2960 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2961 $res{'nparents'} = length($1);
2962 $res{'from_mode'} = [ split(' ', $2) ];
2963 $res{'to_mode'} = pop @{$res{'from_mode'}};
2964 $res{'from_id'} = [ split(' ', $3) ];
2965 $res{'to_id'} = pop @{$res{'from_id'}};
2966 $res{'status'} = [ split('', $4) ];
2967 $res{'to_file'} = unquote($5);
2969 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2970 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2971 $res{'commit'} = $1;
2974 return wantarray ? %res : \%res;
2977 # wrapper: return parsed line of git-diff-tree "raw" output
2978 # (the argument might be raw line, or parsed info)
2979 sub parsed_difftree_line {
2980 my $line_or_ref = shift;
2982 if (ref($line_or_ref) eq "HASH") {
2983 # pre-parsed (or generated by hand)
2984 return $line_or_ref;
2985 } else {
2986 return parse_difftree_raw_line($line_or_ref);
2990 # parse line of git-ls-tree output
2991 sub parse_ls_tree_line {
2992 my $line = shift;
2993 my %opts = @_;
2994 my %res;
2996 if ($opts{'-l'}) {
2997 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
2998 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3000 $res{'mode'} = $1;
3001 $res{'type'} = $2;
3002 $res{'hash'} = $3;
3003 $res{'size'} = $4;
3004 if ($opts{'-z'}) {
3005 $res{'name'} = $5;
3006 } else {
3007 $res{'name'} = unquote($5);
3009 } else {
3010 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3011 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3013 $res{'mode'} = $1;
3014 $res{'type'} = $2;
3015 $res{'hash'} = $3;
3016 if ($opts{'-z'}) {
3017 $res{'name'} = $4;
3018 } else {
3019 $res{'name'} = unquote($4);
3023 return wantarray ? %res : \%res;
3026 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3027 sub parse_from_to_diffinfo {
3028 my ($diffinfo, $from, $to, @parents) = @_;
3030 if ($diffinfo->{'nparents'}) {
3031 # combined diff
3032 $from->{'file'} = [];
3033 $from->{'href'} = [];
3034 fill_from_file_info($diffinfo, @parents)
3035 unless exists $diffinfo->{'from_file'};
3036 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3037 $from->{'file'}[$i] =
3038 defined $diffinfo->{'from_file'}[$i] ?
3039 $diffinfo->{'from_file'}[$i] :
3040 $diffinfo->{'to_file'};
3041 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3042 $from->{'href'}[$i] = href(action=>"blob",
3043 hash_base=>$parents[$i],
3044 hash=>$diffinfo->{'from_id'}[$i],
3045 file_name=>$from->{'file'}[$i]);
3046 } else {
3047 $from->{'href'}[$i] = undef;
3050 } else {
3051 # ordinary (not combined) diff
3052 $from->{'file'} = $diffinfo->{'from_file'};
3053 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3054 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3055 hash=>$diffinfo->{'from_id'},
3056 file_name=>$from->{'file'});
3057 } else {
3058 delete $from->{'href'};
3062 $to->{'file'} = $diffinfo->{'to_file'};
3063 if (!is_deleted($diffinfo)) { # file exists in result
3064 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3065 hash=>$diffinfo->{'to_id'},
3066 file_name=>$to->{'file'});
3067 } else {
3068 delete $to->{'href'};
3072 ## ......................................................................
3073 ## parse to array of hashes functions
3075 sub git_get_heads_list {
3076 my $limit = shift;
3077 my @headslist;
3079 defined(my $fd = git_cmd_pipe 'for-each-ref',
3080 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3081 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3082 'refs/heads')
3083 or return;
3084 while (my $line = <$fd>) {
3085 my %ref_item;
3087 chomp $line;
3088 my ($refinfo, $committerinfo) = split(/\0/, $line);
3089 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3090 my ($committer, $epoch, $tz) =
3091 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3092 $ref_item{'fullname'} = $name;
3093 $name =~ s!^refs/heads/!!;
3095 $ref_item{'name'} = $name;
3096 $ref_item{'id'} = $hash;
3097 $ref_item{'title'} = $title || '(no commit message)';
3098 $ref_item{'epoch'} = $epoch;
3099 if ($epoch) {
3100 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3101 } else {
3102 $ref_item{'age'} = "unknown";
3105 push @headslist, \%ref_item;
3107 close $fd;
3109 return wantarray ? @headslist : \@headslist;
3112 sub git_get_tags_list {
3113 my $limit = shift;
3114 my $all = shift || 0;
3115 my @tagslist;
3117 defined(my $fd = git_cmd_pipe 'for-each-ref',
3118 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3119 '--format=%(objectname) %(objecttype) %(refname) '.
3120 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3121 ($all ? 'refs' : 'refs/tags'))
3122 or return;
3123 while (my $line = <$fd>) {
3124 my %ref_item;
3126 chomp $line;
3127 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3128 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3129 my ($creator, $epoch, $tz) =
3130 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3131 $ref_item{'fullname'} = $name;
3132 $name =~ s!^refs/!! if $all;
3133 $name =~ s!^refs/tags/!! unless $all;
3135 $ref_item{'type'} = $type;
3136 $ref_item{'id'} = $id;
3137 $ref_item{'name'} = $name;
3138 if ($type eq "tag") {
3139 $ref_item{'subject'} = $title;
3140 $ref_item{'reftype'} = $reftype;
3141 $ref_item{'refid'} = $refid;
3142 } else {
3143 $ref_item{'reftype'} = $type;
3144 $ref_item{'refid'} = $id;
3147 if ($type eq "tag" || $type eq "commit") {
3148 $ref_item{'epoch'} = $epoch;
3149 if ($epoch) {
3150 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3151 } else {
3152 $ref_item{'age'} = "unknown";
3156 push @tagslist, \%ref_item;
3158 close $fd;
3160 return wantarray ? @tagslist : \@tagslist;
3163 ## ----------------------------------------------------------------------
3164 ## filesystem-related functions
3166 sub get_file_owner {
3167 my $path = shift;
3169 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3170 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3171 if (!defined $gcos) {
3172 return undef;
3174 my $owner = $gcos;
3175 $owner =~ s/[,;].*$//;
3176 return to_utf8($owner);
3179 # assume that file exists
3180 sub insert_file {
3181 my $filename = shift;
3183 open my $fd, '<', $filename;
3184 print map { to_utf8($_) } <$fd>;
3185 close $fd;
3188 ## ......................................................................
3189 ## mimetype related functions
3191 sub mimetype_guess_file {
3192 my $filename = shift;
3193 my $mimemap = shift;
3194 -r $mimemap or return undef;
3196 my %mimemap;
3197 open(my $mh, '<', $mimemap) or return undef;
3198 while (<$mh>) {
3199 next if m/^#/; # skip comments
3200 my ($mimetype, $exts) = split(/\t+/);
3201 if (defined $exts) {
3202 my @exts = split(/\s+/, $exts);
3203 foreach my $ext (@exts) {
3204 $mimemap{$ext} = $mimetype;
3208 close($mh);
3210 $filename =~ /\.([^.]*)$/;
3211 return $mimemap{$1};
3214 sub mimetype_guess {
3215 my $filename = shift;
3216 my $mime;
3217 $filename =~ /\./ or return undef;
3219 if ($mimetypes_file) {
3220 my $file = $mimetypes_file;
3221 if ($file !~ m!^/!) { # if it is relative path
3222 # it is relative to project
3223 $file = "$projectroot/$project/$file";
3225 $mime = mimetype_guess_file($filename, $file);
3227 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3228 return $mime;
3231 sub blob_mimetype {
3232 my $fd = shift;
3233 my $filename = shift;
3235 if ($filename) {
3236 my $mime = mimetype_guess($filename);
3237 $mime and return $mime;
3240 # just in case
3241 return $default_blob_plain_mimetype unless $fd;
3243 if (-T $fd) {
3244 return 'text/plain';
3245 } elsif (! $filename) {
3246 return 'application/octet-stream';
3247 } elsif ($filename =~ m/\.png$/i) {
3248 return 'image/png';
3249 } elsif ($filename =~ m/\.gif$/i) {
3250 return 'image/gif';
3251 } elsif ($filename =~ m/\.jpe?g$/i) {
3252 return 'image/jpeg';
3253 } else {
3254 return 'application/octet-stream';
3258 sub blob_contenttype {
3259 my ($fd, $file_name, $type) = @_;
3261 $type ||= blob_mimetype($fd, $file_name);
3262 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3263 $type .= "; charset=$default_text_plain_charset";
3266 return $type;
3269 # guess file syntax for syntax highlighting; return undef if no highlighting
3270 # the name of syntax can (in the future) depend on syntax highlighter used
3271 sub guess_file_syntax {
3272 my ($highlight, $mimetype, $file_name) = @_;
3273 return undef unless ($highlight && defined $file_name);
3275 # configuration for 'highlight' (http://www.andre-simon.de/)
3276 # match by basename
3277 my %highlight_basename = (
3278 #'Program' => 'py',
3279 #'Library' => 'py',
3280 'SConstruct' => 'py', # SCons equivalent of Makefile
3281 'Makefile' => 'make',
3282 'makefile' => 'make',
3283 'GNUmakefile' => 'make',
3285 # match by extension
3286 my %highlight_ext = (
3287 # main extensions, defining name of syntax;
3288 # see files in /usr/share/highlight/langDefs/ directory
3289 map { $_ => $_ }
3290 qw(py c cpp rb java css php sh pl js lua tex bib xml awk bat ini spec sql tcl),
3291 # alternate extensions, see /etc/highlight/filetypes.conf
3292 'h' => 'c',
3293 map { $_ => 'objc' } qw(m mm M),
3294 map { $_ => 'cpp' } qw(cxx c++ cc cpp hh hpp hxx),
3295 map { $_ => 'php' } qw(php3 php4),
3296 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
3297 'mak' => 'make',
3298 map { $_ => 'xml' } qw(xhtml html htm),
3301 my $basename = basename($file_name, '.in');
3302 return $highlight_basename{$basename}
3303 if exists $highlight_basename{$basename};
3305 $basename =~ /\.([^.]*)$/;
3306 my $ext = $1 or return undef;
3307 return $highlight_ext{$ext}
3308 if exists $highlight_ext{$ext};
3310 return undef;
3313 # run highlighter and return FD of its output,
3314 # or return original FD if no highlighting
3315 sub run_highlighter {
3316 my ($fd, $highlight, $syntax) = @_;
3317 return $fd unless ($highlight && defined $syntax);
3319 close $fd
3320 or die_error(404, "Reading blob failed");
3321 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3322 "highlight --xhtml --fragment --syntax $syntax |"
3323 or die_error(500, "Couldn't open file or run syntax highlighter");
3324 return $fd;
3327 ## ======================================================================
3328 ## functions printing HTML: header, footer, error page
3330 sub git_header_html {
3331 my $status = shift || "200 OK";
3332 my $expires = shift;
3333 my %opts = @_;
3335 my $title = "$site_name";
3336 if (defined $project) {
3337 $title .= " - " . to_utf8($project);
3338 if (defined $action) {
3339 $title .= "/$action";
3340 if (defined $file_name) {
3341 $title .= " - " . esc_path($file_name);
3342 if ($action eq "tree" && $file_name !~ m|/$|) {
3343 $title .= "/";
3348 # We do not ever emit application/xhtml+xml since that gives us
3349 # no benefits and it makes many browsers (e.g. Firefox) exceedingly
3350 # strict, which is troublesome for example when showing user-supplied
3351 # README.html files.
3352 my $content_type = 'text/html';
3353 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3354 -status=> $status, -expires => $expires)
3355 unless ($opts{'-no_http_header'});
3356 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3357 print <<EOF;
3358 <?xml version="1.0" encoding="utf-8"?>
3359 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3360 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3361 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3362 <!-- git core binaries version $git_version -->
3363 <head>
3364 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3365 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3366 <meta name="robots" content="index, nofollow"/>
3367 <title>$title</title>
3368 <script type="text/javascript">/* <![CDATA[ */
3369 function fixBlameLinks() {
3370 var allLinks = document.getElementsByTagName("a");
3371 for (var i = 0; i < allLinks.length; i++) {
3372 var link = allLinks.item(i);
3373 if (link.className == 'blamelink')
3374 link.href = link.href.replace("/blame/", "/blame_incremental/");
3377 /* ]]> */</script>
3379 # the stylesheet, favicon etc urls won't work correctly with path_info
3380 # unless we set the appropriate base URL
3381 if ($ENV{'PATH_INFO'}) {
3382 print "<base href=\"".esc_url($base_url)."\" />\n";
3384 # print out each stylesheet that exist, providing backwards capability
3385 # for those people who defined $stylesheet in a config file
3386 if (defined $stylesheet) {
3387 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3388 } else {
3389 foreach my $stylesheet (@stylesheets) {
3390 next unless $stylesheet;
3391 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3394 if (defined $project) {
3395 my %href_params = get_feed_info();
3396 if (!exists $href_params{'-title'}) {
3397 $href_params{'-title'} = 'log';
3400 foreach my $format qw(RSS Atom) {
3401 my $type = lc($format);
3402 my %link_attr = (
3403 '-rel' => 'alternate',
3404 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
3405 '-type' => "application/$type+xml"
3408 $href_params{'action'} = $type;
3409 $link_attr{'-href'} = href(%href_params);
3410 print "<link ".
3411 "rel=\"$link_attr{'-rel'}\" ".
3412 "title=\"$link_attr{'-title'}\" ".
3413 "href=\"$link_attr{'-href'}\" ".
3414 "type=\"$link_attr{'-type'}\" ".
3415 "/>\n";
3417 $href_params{'extra_options'} = '--no-merges';
3418 $link_attr{'-href'} = href(%href_params);
3419 $link_attr{'-title'} .= ' (no merges)';
3420 print "<link ".
3421 "rel=\"$link_attr{'-rel'}\" ".
3422 "title=\"$link_attr{'-title'}\" ".
3423 "href=\"$link_attr{'-href'}\" ".
3424 "type=\"$link_attr{'-type'}\" ".
3425 "/>\n";
3428 } else {
3429 printf('<link rel="alternate" title="%s projects list" '.
3430 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3431 esc_attr($site_name), href(project=>undef, action=>"project_index"));
3432 printf('<link rel="alternate" title="%s projects feeds" '.
3433 'href="%s" type="text/x-opml" />'."\n",
3434 esc_attr($site_name), href(project=>undef, action=>"opml"));
3436 if (defined $favicon) {
3437 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
3440 if (defined $gitwebjs) {
3441 print qq(<script src="$gitwebjs" type="text/javascript"></script>\n);
3444 print "</head>\n";
3445 if (gitweb_check_feature('blame_incremental')) {
3446 print "<body onload=\"fixBlameLinks();\">\n";
3447 } else {
3448 print "<body>\n";
3451 if (-f $site_header) {
3452 insert_file($site_header);
3455 print "<div class=\"page_header\">\n" .
3456 $cgi->a({-href => esc_url($logo_url),
3457 -title => $logo_label},
3458 qq(<img src=").esc_url($logo).qq(" width="72" height="27" alt="git" class="logo"/>));
3459 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3460 if (defined $project) {
3461 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3462 if (defined $action) {
3463 print " / $action";
3465 print "\n";
3467 print "</div>\n";
3469 my $have_search = gitweb_check_feature('search');
3470 if (defined $project && $have_search) {
3471 if (!defined $searchtext) {
3472 $searchtext = "";
3474 my $search_hash;
3475 if (defined $hash_base) {
3476 $search_hash = $hash_base;
3477 } elsif (defined $hash) {
3478 $search_hash = $hash;
3479 } else {
3480 $search_hash = "HEAD";
3482 my $action = $my_uri;
3483 my $use_pathinfo = gitweb_check_feature('pathinfo');
3484 if ($use_pathinfo) {
3485 $action .= "/".esc_url($project);
3487 print $cgi->startform(-method => "get", -action => $action) .
3488 "<div class=\"search\">\n" .
3489 (!$use_pathinfo &&
3490 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3491 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3492 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3493 $cgi->popup_menu(-name => 'st', -default => 'commit',
3494 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3495 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3496 " search:\n",
3497 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3498 "<span title=\"Extended regular expression\">" .
3499 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3500 -checked => $search_use_regexp) .
3501 "</span>" .
3502 "</div>" .
3503 $cgi->end_form() . "\n";
3507 sub git_footer_html {
3508 my $feed_class = 'rss_logo';
3510 print "<div class=\"page_footer\">\n";
3511 if (defined $project) {
3512 my $descr = git_get_project_description($project);
3513 if (defined $descr) {
3514 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3517 my %href_params = get_feed_info();
3518 if (!%href_params) {
3519 $feed_class .= ' generic';
3521 $href_params{'-title'} ||= 'log';
3523 foreach my $format qw(RSS Atom) {
3524 $href_params{'action'} = lc($format);
3525 print $cgi->a({-href => href(%href_params),
3526 -title => "$href_params{'-title'} $format feed",
3527 -class => $feed_class}, $format)."\n";
3530 } else {
3531 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3532 -class => $feed_class}, "OPML") . " ";
3533 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3534 -class => $feed_class}, "TXT") . "\n";
3536 print "</div>\n"; # class="page_footer"
3538 if (-f $site_footer) {
3539 insert_file($site_footer);
3542 print "</body>\n" .
3543 "</html>";
3546 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3547 # Example: die_error(404, 'Hash not found')
3548 # By convention, use the following status codes (as defined in RFC 2616):
3549 # 400: Invalid or missing CGI parameters, or
3550 # requested object exists but has wrong type.
3551 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3552 # this server or project.
3553 # 404: Requested object/revision/project doesn't exist.
3554 # 500: The server isn't configured properly, or
3555 # an internal error occurred (e.g. failed assertions caused by bugs), or
3556 # an unknown error occurred (e.g. the git binary died unexpectedly).
3557 # 503: The server is currently unavailable (because it is overloaded,
3558 # or down for maintenance). Generally, this is a temporary state.
3559 sub die_error {
3560 my $status = shift || 500;
3561 my $error = esc_html(shift) || "Internal Server Error";
3562 my $extra = shift;
3563 my %opts = @_;
3565 my %http_responses = (
3566 400 => '400 Bad Request',
3567 403 => '403 Forbidden',
3568 404 => '404 Not Found',
3569 500 => '500 Internal Server Error',
3570 503 => '503 Service Unavailable',
3572 git_header_html($http_responses{$status}, undef, %opts);
3573 print <<EOF;
3574 <div class="page_body">
3575 <br /><br />
3576 $status - $error
3577 <br />
3579 if (defined $extra) {
3580 print "<hr />\n" .
3581 "$extra\n";
3583 print "</div>\n";
3585 git_footer_html();
3586 goto DONE_GITWEB
3587 unless ($opts{'-error_handler'});
3590 ## ----------------------------------------------------------------------
3591 ## functions printing or outputting HTML: navigation
3593 sub git_print_page_nav {
3594 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3595 $extra = '' if !defined $extra; # pager or formats
3597 my @navs = qw(summary log commit commitdiff tree refs);
3598 if ($suppress) {
3599 @navs = grep { $_ ne $suppress } @navs;
3602 my %arg = map { $_ => {action=>$_} } @navs;
3603 if (defined $head) {
3604 for (qw(commit commitdiff)) {
3605 $arg{$_}{'hash'} = $head;
3607 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3608 $arg{'log'}{'hash'} = $head;
3612 $arg{'log'}{'action'} = 'shortlog';
3613 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3614 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3616 my @actions = gitweb_get_feature('actions');
3617 my %repl = (
3618 '%' => '%',
3619 'n' => $project, # project name
3620 'f' => $git_dir, # project path within filesystem
3621 'h' => $treehead || '', # current hash ('h' parameter)
3622 'b' => $treebase || '', # hash base ('hb' parameter)
3624 while (@actions) {
3625 my ($label, $link, $pos) = splice(@actions,0,3);
3626 # insert
3627 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3628 # munch munch
3629 $link =~ s/%([%nfhb])/$repl{$1}/g;
3630 $arg{$label}{'_href'} = $link;
3633 print "<div class=\"page_nav\">\n" .
3634 (join " | ",
3635 map { $_ eq $current ?
3636 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3637 } @navs);
3638 print "<br/>\n$extra<br/>\n" .
3639 "</div>\n";
3642 sub format_paging_nav {
3643 my ($action, $hash, $head, $page, $has_next_link) = @_;
3644 my $paging_nav;
3647 if ((($hash||'') ne ($head||'')) || $page) {
3648 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3649 } else {
3650 $paging_nav .= "HEAD";
3653 if ($page > 0) {
3654 $paging_nav .= " &sdot; " .
3655 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3656 -accesskey => "p", -title => "Alt-p"}, "prev");
3657 } else {
3658 $paging_nav .= " &sdot; prev";
3661 if ($has_next_link) {
3662 $paging_nav .= " &sdot; " .
3663 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3664 -accesskey => "n", -title => "Alt-n"}, "next");
3665 } else {
3666 $paging_nav .= " &sdot; next";
3669 return $paging_nav;
3672 sub format_log_nav {
3673 my ($action, $hash, $head, $page, $has_next_link) = @_;
3674 my $paging_nav;
3676 if ($action eq 'shortlog') {
3677 $paging_nav .= 'shortlog';
3678 } else {
3679 $paging_nav .= $cgi->a({-href => href(action=>'shortlog', -replay=>1)}, 'shortlog');
3681 $paging_nav .= ' | ';
3682 if ($action eq 'log') {
3683 $paging_nav .= 'fulllog';
3684 } else {
3685 $paging_nav .= $cgi->a({-href => href(action=>'log', -replay=>1)}, 'fulllog');
3688 $paging_nav .= " | " . format_paging_nav($action, $hash, $head, $page, $has_next_link);
3689 return $paging_nav;
3692 ## ......................................................................
3693 ## functions printing or outputting HTML: div
3695 sub git_print_header_div {
3696 my ($action, $title, $hash, $hash_base, $extra) = @_;
3697 my %args = ();
3699 $args{'action'} = $action;
3700 $args{'hash'} = $hash if $hash;
3701 $args{'hash_base'} = $hash_base if $hash_base;
3703 my $link1 = $cgi->a({-href => href(%args), -class => "title"},
3704 $title ? $title : $action);
3705 my $link2 = $cgi->a({-href => href(%args), -class => "cover"}, "");
3706 print "<div class=\"header\">\n" . '<span class="title">' .
3707 $link1 . ($extra ? $extra : '') . $link2 .
3708 '</span>' . "\n</div>\n";
3711 sub print_local_time {
3712 my %date = @_;
3713 if ($date{'hour_local'} < 6) {
3714 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3715 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3716 } else {
3717 printf(" (%02d:%02d %s)",
3718 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3722 # Outputs the author name and date in long form
3723 sub git_print_authorship {
3724 my $co = shift;
3725 my %opts = @_;
3726 my $tag = $opts{-tag} || 'div';
3727 my $author = $co->{'author_name'};
3729 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3730 print "<$tag class=\"author_date\">" .
3731 format_search_author($author, "author", esc_html($author)) .
3732 " [$ad{'rfc2822'}";
3733 print_local_time(%ad) if ($opts{-localtime});
3734 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3735 . "</$tag>\n";
3738 # Outputs table rows containing the full author or committer information,
3739 # in the format expected for 'commit' view (& similia).
3740 # Parameters are a commit hash reference, followed by the list of people
3741 # to output information for. If the list is empty it defalts to both
3742 # author and committer.
3743 sub git_print_authorship_rows {
3744 my $co = shift;
3745 # too bad we can't use @people = @_ || ('author', 'committer')
3746 my @people = @_;
3747 @people = ('author', 'committer') unless @people;
3748 foreach my $who (@people) {
3749 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3750 print "<tr><td>$who</td><td>" .
3751 format_search_author($co->{"${who}_name"}, $who,
3752 esc_html($co->{"${who}_name"}||'')) . " " .
3753 format_search_author($co->{"${who}_email"}, $who,
3754 esc_html("<" . ($co->{"${who}_email"}||'') . ">")) .
3755 "</td><td rowspan=\"2\">" .
3756 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3757 "</td></tr>\n" .
3758 "<tr>" .
3759 "<td></td><td> $wd{'rfc2822'}";
3760 print_local_time(%wd);
3761 print "</td>" .
3762 "</tr>\n";
3766 sub git_print_page_path {
3767 my $name = shift;
3768 my $type = shift;
3769 my $hb = shift;
3772 print "<div class=\"page_path\">";
3773 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3774 -title => 'tree root'}, to_utf8("[$project]"));
3775 print " / ";
3776 if (defined $name) {
3777 my @dirname = split '/', $name;
3778 my $basename = pop @dirname;
3779 my $fullname = '';
3781 foreach my $dir (@dirname) {
3782 $fullname .= ($fullname ? '/' : '') . $dir;
3783 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3784 hash_base=>$hb),
3785 -title => $fullname}, esc_path($dir));
3786 print " / ";
3788 if (defined $type && $type eq 'blob') {
3789 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3790 hash_base=>$hb),
3791 -title => $name}, esc_path($basename));
3792 } elsif (defined $type && $type eq 'tree') {
3793 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3794 hash_base=>$hb),
3795 -title => $name}, esc_path($basename));
3796 print " / ";
3797 } else {
3798 print esc_path($basename);
3801 print "<br/></div>\n";
3804 sub git_print_log {
3805 my $log = shift;
3806 my %opts = @_;
3808 if ($opts{'-remove_title'}) {
3809 # remove title, i.e. first line of log
3810 shift @$log;
3812 # remove leading empty lines
3813 while (defined $log->[0] && $log->[0] eq "") {
3814 shift @$log;
3817 # print log
3818 my $signoff = 0;
3819 my $empty = 0;
3820 foreach my $line (@$log) {
3821 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3822 $signoff = 1;
3823 $empty = 0;
3824 if (! $opts{'-remove_signoff'}) {
3825 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3826 next;
3827 } else {
3828 # remove signoff lines
3829 next;
3831 } else {
3832 $signoff = 0;
3835 # print only one empty line
3836 # do not print empty line after signoff
3837 if ($line eq "") {
3838 next if ($empty || $signoff);
3839 $empty = 1;
3840 } else {
3841 $empty = 0;
3844 print format_log_line_html($line) . "<br/>\n";
3847 if ($opts{'-final_empty_line'}) {
3848 # end with single empty line
3849 print "<br/>\n" unless $empty;
3853 # return link target (what link points to)
3854 sub git_get_link_target {
3855 my $hash = shift;
3856 my $link_target;
3858 # read link
3859 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
3860 or return;
3862 local $/ = undef;
3863 $link_target = <$fd>;
3865 close $fd
3866 or return;
3868 return $link_target;
3871 # given link target, and the directory (basedir) the link is in,
3872 # return target of link relative to top directory (top tree);
3873 # return undef if it is not possible (including absolute links).
3874 sub normalize_link_target {
3875 my ($link_target, $basedir) = @_;
3877 # absolute symlinks (beginning with '/') cannot be normalized
3878 return if (substr($link_target, 0, 1) eq '/');
3880 # normalize link target to path from top (root) tree (dir)
3881 my $path;
3882 if ($basedir) {
3883 $path = $basedir . '/' . $link_target;
3884 } else {
3885 # we are in top (root) tree (dir)
3886 $path = $link_target;
3889 # remove //, /./, and /../
3890 my @path_parts;
3891 foreach my $part (split('/', $path)) {
3892 # discard '.' and ''
3893 next if (!$part || $part eq '.');
3894 # handle '..'
3895 if ($part eq '..') {
3896 if (@path_parts) {
3897 pop @path_parts;
3898 } else {
3899 # link leads outside repository (outside top dir)
3900 return;
3902 } else {
3903 push @path_parts, $part;
3906 $path = join('/', @path_parts);
3908 return $path;
3911 # print tree entry (row of git_tree), but without encompassing <tr> element
3912 sub git_print_tree_entry {
3913 my ($t, $basedir, $hash_base, $have_blame) = @_;
3915 my %base_key = ();
3916 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3918 # The format of a table row is: mode list link. Where mode is
3919 # the mode of the entry, list is the name of the entry, an href,
3920 # and link is the action links of the entry.
3922 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3923 if (exists $t->{'size'}) {
3924 print "<td class=\"size\">$t->{'size'}</td>\n";
3926 if ($t->{'type'} eq "blob") {
3927 print "<td class=\"list\">" .
3928 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3929 file_name=>"$basedir$t->{'name'}", %base_key),
3930 -class => "list"}, esc_path($t->{'name'}));
3931 if (S_ISLNK(oct $t->{'mode'})) {
3932 my $link_target = git_get_link_target($t->{'hash'});
3933 if ($link_target) {
3934 my $norm_target = normalize_link_target($link_target, $basedir);
3935 if (defined $norm_target) {
3936 print " -> " .
3937 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3938 file_name=>$norm_target),
3939 -title => $norm_target}, esc_path($link_target));
3940 } else {
3941 print " -> " . esc_path($link_target);
3945 print "</td>\n";
3946 print "<td class=\"link\">";
3947 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3948 file_name=>"$basedir$t->{'name'}", %base_key)},
3949 "blob");
3950 if ($have_blame) {
3951 print " | " .
3952 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3953 file_name=>"$basedir$t->{'name'}", %base_key), -class => "blamelink"},
3954 "blame");
3956 if (defined $hash_base) {
3957 print " | " .
3958 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3959 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3960 "history");
3962 print " | " .
3963 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3964 file_name=>"$basedir$t->{'name'}")},
3965 "raw");
3966 print "</td>\n";
3968 } elsif ($t->{'type'} eq "tree") {
3969 print "<td class=\"list\">";
3970 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3971 file_name=>"$basedir$t->{'name'}",
3972 %base_key)},
3973 esc_path($t->{'name'}));
3974 print "</td>\n";
3975 print "<td class=\"link\">";
3976 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3977 file_name=>"$basedir$t->{'name'}",
3978 %base_key)},
3979 "tree");
3980 if (defined $hash_base) {
3981 print " | " .
3982 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3983 file_name=>"$basedir$t->{'name'}")},
3984 "history");
3986 print "</td>\n";
3987 } else {
3988 # unknown object: we can only present history for it
3989 # (this includes 'commit' object, i.e. submodule support)
3990 print "<td class=\"list\">" .
3991 esc_path($t->{'name'}) .
3992 "</td>\n";
3993 print "<td class=\"link\">";
3994 if (defined $hash_base) {
3995 print $cgi->a({-href => href(action=>"history",
3996 hash_base=>$hash_base,
3997 file_name=>"$basedir$t->{'name'}")},
3998 "history");
4000 print "</td>\n";
4004 ## ......................................................................
4005 ## functions printing large fragments of HTML
4007 # get pre-image filenames for merge (combined) diff
4008 sub fill_from_file_info {
4009 my ($diff, @parents) = @_;
4011 $diff->{'from_file'} = [ ];
4012 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4013 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4014 if ($diff->{'status'}[$i] eq 'R' ||
4015 $diff->{'status'}[$i] eq 'C') {
4016 $diff->{'from_file'}[$i] =
4017 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4021 return $diff;
4024 # is current raw difftree line of file deletion
4025 sub is_deleted {
4026 my $diffinfo = shift;
4028 return $diffinfo->{'to_id'} eq ('0' x 40);
4031 # does patch correspond to [previous] difftree raw line
4032 # $diffinfo - hashref of parsed raw diff format
4033 # $patchinfo - hashref of parsed patch diff format
4034 # (the same keys as in $diffinfo)
4035 sub is_patch_split {
4036 my ($diffinfo, $patchinfo) = @_;
4038 return defined $diffinfo && defined $patchinfo
4039 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4043 sub git_difftree_body {
4044 my ($difftree, $hash, @parents) = @_;
4045 my ($parent) = $parents[0];
4046 my $have_blame = gitweb_check_feature('blame');
4047 print "<div class=\"list_head\">\n";
4048 if ($#{$difftree} > 10) {
4049 print(($#{$difftree} + 1) . " files changed:\n");
4051 print "</div>\n";
4053 print "<table class=\"" .
4054 (@parents > 1 ? "combined " : "") .
4055 "diff_tree\">\n";
4057 # header only for combined diff in 'commitdiff' view
4058 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4059 if ($has_header) {
4060 # table header
4061 print "<thead><tr>\n" .
4062 "<th></th><th></th>\n"; # filename, patchN link
4063 for (my $i = 0; $i < @parents; $i++) {
4064 my $par = $parents[$i];
4065 print "<th>" .
4066 $cgi->a({-href => href(action=>"commitdiff",
4067 hash=>$hash, hash_parent=>$par),
4068 -title => 'commitdiff to parent number ' .
4069 ($i+1) . ': ' . substr($par,0,7)},
4070 $i+1) .
4071 "&nbsp;</th>\n";
4073 print "</tr></thead>\n<tbody>\n";
4076 my $alternate = 1;
4077 my $patchno = 0;
4078 foreach my $line (@{$difftree}) {
4079 my $diff = parsed_difftree_line($line);
4081 if ($alternate) {
4082 print "<tr class=\"dark\">\n";
4083 } else {
4084 print "<tr class=\"light\">\n";
4086 $alternate ^= 1;
4088 if (exists $diff->{'nparents'}) { # combined diff
4090 fill_from_file_info($diff, @parents)
4091 unless exists $diff->{'from_file'};
4093 if (!is_deleted($diff)) {
4094 # file exists in the result (child) commit
4095 print "<td>" .
4096 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4097 file_name=>$diff->{'to_file'},
4098 hash_base=>$hash),
4099 -class => "list"}, esc_path($diff->{'to_file'})) .
4100 "</td>\n";
4101 } else {
4102 print "<td>" .
4103 esc_path($diff->{'to_file'}) .
4104 "</td>\n";
4107 if ($action eq 'commitdiff') {
4108 # link to patch
4109 $patchno++;
4110 print "<td class=\"link\">" .
4111 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4112 "patch") .
4113 " | " .
4114 "</td>\n";
4117 my $has_history = 0;
4118 my $not_deleted = 0;
4119 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4120 my $hash_parent = $parents[$i];
4121 my $from_hash = $diff->{'from_id'}[$i];
4122 my $from_path = $diff->{'from_file'}[$i];
4123 my $status = $diff->{'status'}[$i];
4125 $has_history ||= ($status ne 'A');
4126 $not_deleted ||= ($status ne 'D');
4128 if ($status eq 'A') {
4129 print "<td class=\"link\" align=\"right\"> | </td>\n";
4130 } elsif ($status eq 'D') {
4131 print "<td class=\"link\">" .
4132 $cgi->a({-href => href(action=>"blob",
4133 hash_base=>$hash,
4134 hash=>$from_hash,
4135 file_name=>$from_path)},
4136 "blob" . ($i+1)) .
4137 " | </td>\n";
4138 } else {
4139 if ($diff->{'to_id'} eq $from_hash) {
4140 print "<td class=\"link nochange\">";
4141 } else {
4142 print "<td class=\"link\">";
4144 print $cgi->a({-href => href(action=>"blobdiff",
4145 hash=>$diff->{'to_id'},
4146 hash_parent=>$from_hash,
4147 hash_base=>$hash,
4148 hash_parent_base=>$hash_parent,
4149 file_name=>$diff->{'to_file'},
4150 file_parent=>$from_path)},
4151 "diff" . ($i+1)) .
4152 " | </td>\n";
4156 print "<td class=\"link\">";
4157 if ($not_deleted) {
4158 print $cgi->a({-href => href(action=>"blob",
4159 hash=>$diff->{'to_id'},
4160 file_name=>$diff->{'to_file'},
4161 hash_base=>$hash)},
4162 "blob");
4163 print " | " if ($has_history);
4165 if ($has_history) {
4166 print $cgi->a({-href => href(action=>"history",
4167 file_name=>$diff->{'to_file'},
4168 hash_base=>$hash)},
4169 "history");
4171 print "</td>\n";
4173 print "</tr>\n";
4174 next; # instead of 'else' clause, to avoid extra indent
4176 # else ordinary diff
4178 my ($to_mode_oct, $to_mode_str, $to_file_type);
4179 my ($from_mode_oct, $from_mode_str, $from_file_type);
4180 if ($diff->{'to_mode'} ne ('0' x 6)) {
4181 $to_mode_oct = oct $diff->{'to_mode'};
4182 if (S_ISREG($to_mode_oct)) { # only for regular file
4183 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4185 $to_file_type = file_type($diff->{'to_mode'});
4187 if ($diff->{'from_mode'} ne ('0' x 6)) {
4188 $from_mode_oct = oct $diff->{'from_mode'};
4189 if (S_ISREG($to_mode_oct)) { # only for regular file
4190 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4192 $from_file_type = file_type($diff->{'from_mode'});
4195 if ($diff->{'status'} eq "A") { # created
4196 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4197 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4198 $mode_chng .= "]</span>";
4199 print "<td>";
4200 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4201 hash_base=>$hash, file_name=>$diff->{'file'}),
4202 -class => "list"}, esc_path($diff->{'file'}));
4203 print "</td>\n";
4204 print "<td>$mode_chng</td>\n";
4205 print "<td class=\"link\">";
4206 if ($action eq 'commitdiff') {
4207 # link to patch
4208 $patchno++;
4209 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4210 "patch") .
4211 " | ";
4213 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4214 hash_base=>$hash, file_name=>$diff->{'file'})},
4215 "blob");
4216 print "</td>\n";
4218 } elsif ($diff->{'status'} eq "D") { # deleted
4219 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4220 print "<td>";
4221 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4222 hash_base=>$parent, file_name=>$diff->{'file'}),
4223 -class => "list"}, esc_path($diff->{'file'}));
4224 print "</td>\n";
4225 print "<td>$mode_chng</td>\n";
4226 print "<td class=\"link\">";
4227 if ($action eq 'commitdiff') {
4228 # link to patch
4229 $patchno++;
4230 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4231 "patch") .
4232 " | ";
4234 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4235 hash_base=>$parent, file_name=>$diff->{'file'})},
4236 "blob") . " | ";
4237 if ($have_blame) {
4238 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4239 file_name=>$diff->{'file'})},
4240 "blame") . " | ";
4242 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4243 file_name=>$diff->{'file'})},
4244 "history");
4245 print "</td>\n";
4247 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4248 my $mode_chnge = "";
4249 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4250 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4251 if ($from_file_type ne $to_file_type) {
4252 $mode_chnge .= " from $from_file_type to $to_file_type";
4254 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4255 if ($from_mode_str && $to_mode_str) {
4256 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4257 } elsif ($to_mode_str) {
4258 $mode_chnge .= " mode: $to_mode_str";
4261 $mode_chnge .= "]</span>\n";
4263 print "<td>";
4264 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4265 hash_base=>$hash, file_name=>$diff->{'file'}),
4266 -class => "list"}, esc_path($diff->{'file'}));
4267 print "</td>\n";
4268 print "<td>$mode_chnge</td>\n";
4269 print "<td class=\"link\">";
4270 if ($action eq 'commitdiff') {
4271 # link to patch
4272 $patchno++;
4273 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4274 "patch") .
4275 " | ";
4276 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4277 # "commit" view and modified file (not onlu mode changed)
4278 print $cgi->a({-href => href(action=>"blobdiff",
4279 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4280 hash_base=>$hash, hash_parent_base=>$parent,
4281 file_name=>$diff->{'file'})},
4282 "diff") .
4283 " | ";
4285 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4286 hash_base=>$hash, file_name=>$diff->{'file'})},
4287 "blob") . " | ";
4288 if ($have_blame) {
4289 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4290 file_name=>$diff->{'file'})},
4291 "blame") . " | ";
4293 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4294 file_name=>$diff->{'file'})},
4295 "history");
4296 print "</td>\n";
4298 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4299 my %status_name = ('R' => 'moved', 'C' => 'copied');
4300 my $nstatus = $status_name{$diff->{'status'}};
4301 my $mode_chng = "";
4302 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4303 # mode also for directories, so we cannot use $to_mode_str
4304 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4306 print "<td>" .
4307 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4308 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4309 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4310 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4311 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4312 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4313 -class => "list"}, esc_path($diff->{'from_file'})) .
4314 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4315 "<td class=\"link\">";
4316 if ($action eq 'commitdiff') {
4317 # link to patch
4318 $patchno++;
4319 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4320 "patch") .
4321 " | ";
4322 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4323 # "commit" view and modified file (not only pure rename or copy)
4324 print $cgi->a({-href => href(action=>"blobdiff",
4325 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4326 hash_base=>$hash, hash_parent_base=>$parent,
4327 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4328 "diff") .
4329 " | ";
4331 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4332 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4333 "blob") . " | ";
4334 if ($have_blame) {
4335 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4336 file_name=>$diff->{'to_file'})},
4337 "blame") . " | ";
4339 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4340 file_name=>$diff->{'to_file'})},
4341 "history");
4342 print "</td>\n";
4344 } # we should not encounter Unmerged (U) or Unknown (X) status
4345 print "</tr>\n";
4347 print "</tbody>" if $has_header;
4348 print "</table>\n";
4351 sub git_patchset_body {
4352 my ($fd, $difftree, $hash, @hash_parents) = @_;
4353 my ($hash_parent) = $hash_parents[0];
4355 my $is_combined = (@hash_parents > 1);
4356 my $patch_idx = 0;
4357 my $patch_number = 0;
4358 my $patch_line;
4359 my $diffinfo;
4360 my $to_name;
4361 my (%from, %to);
4363 print "<div class=\"patchset\">\n";
4365 # skip to first patch
4366 while ($patch_line = <$fd>) {
4367 chomp $patch_line;
4369 last if ($patch_line =~ m/^diff /);
4372 PATCH:
4373 while ($patch_line) {
4375 # parse "git diff" header line
4376 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4377 # $1 is from_name, which we do not use
4378 $to_name = unquote($2);
4379 $to_name =~ s!^b/!!;
4380 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4381 # $1 is 'cc' or 'combined', which we do not use
4382 $to_name = unquote($2);
4383 } else {
4384 $to_name = undef;
4387 # check if current patch belong to current raw line
4388 # and parse raw git-diff line if needed
4389 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4390 # this is continuation of a split patch
4391 print "<div class=\"patch cont\">\n";
4392 } else {
4393 # advance raw git-diff output if needed
4394 $patch_idx++ if defined $diffinfo;
4396 # read and prepare patch information
4397 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4399 # compact combined diff output can have some patches skipped
4400 # find which patch (using pathname of result) we are at now;
4401 if ($is_combined) {
4402 while ($to_name ne $diffinfo->{'to_file'}) {
4403 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4404 format_diff_cc_simplified($diffinfo, @hash_parents) .
4405 "</div>\n"; # class="patch"
4407 $patch_idx++;
4408 $patch_number++;
4410 last if $patch_idx > $#$difftree;
4411 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4415 # modifies %from, %to hashes
4416 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4418 # this is first patch for raw difftree line with $patch_idx index
4419 # we index @$difftree array from 0, but number patches from 1
4420 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4423 # git diff header
4424 #assert($patch_line =~ m/^diff /) if DEBUG;
4425 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4426 $patch_number++;
4427 # print "git diff" header
4428 print format_git_diff_header_line($patch_line, $diffinfo,
4429 \%from, \%to);
4431 # print extended diff header
4432 print "<div class=\"diff extended_header\">\n";
4433 EXTENDED_HEADER:
4434 while ($patch_line = <$fd>) {
4435 chomp $patch_line;
4437 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4439 print format_extended_diff_header_line($patch_line, $diffinfo,
4440 \%from, \%to);
4442 print "</div>\n"; # class="diff extended_header"
4444 # from-file/to-file diff header
4445 if (! $patch_line) {
4446 print "</div>\n"; # class="patch"
4447 last PATCH;
4449 next PATCH if ($patch_line =~ m/^diff /);
4450 #assert($patch_line =~ m/^---/) if DEBUG;
4452 my $last_patch_line = $patch_line;
4453 $patch_line = <$fd>;
4454 chomp $patch_line;
4455 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4457 print format_diff_from_to_header($last_patch_line, $patch_line,
4458 $diffinfo, \%from, \%to,
4459 @hash_parents);
4461 # the patch itself
4462 LINE:
4463 while ($patch_line = <$fd>) {
4464 chomp $patch_line;
4466 next PATCH if ($patch_line =~ m/^diff /);
4468 print format_diff_line($patch_line, \%from, \%to);
4471 } continue {
4472 print "</div>\n"; # class="patch"
4475 # for compact combined (--cc) format, with chunk and patch simpliciaction
4476 # patchset might be empty, but there might be unprocessed raw lines
4477 for (++$patch_idx if $patch_number > 0;
4478 $patch_idx < @$difftree;
4479 ++$patch_idx) {
4480 # read and prepare patch information
4481 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4483 # generate anchor for "patch" links in difftree / whatchanged part
4484 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4485 format_diff_cc_simplified($diffinfo, @hash_parents) .
4486 "</div>\n"; # class="patch"
4488 $patch_number++;
4491 if ($patch_number == 0) {
4492 if (@hash_parents > 1) {
4493 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4494 } else {
4495 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4499 print "</div>\n"; # class="patchset"
4502 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4504 # fills project list info (age, description, owner, forks) for each
4505 # project in the list, removing invalid projects from returned list
4506 # NOTE: modifies $projlist, but does not remove entries from it
4507 sub fill_project_list_info {
4508 my ($projlist, $check_forks, $show_ctags) = @_;
4509 my @projects;
4511 PROJECT:
4512 foreach my $pr (@$projlist) {
4513 my (@activity) = git_get_last_activity($pr->{'path'});
4514 unless (@activity) {
4515 next PROJECT;
4517 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4518 if (!defined $pr->{'descr'}) {
4519 my $descr = git_get_project_description($pr->{'path'}) || "";
4520 $descr = to_utf8($descr);
4521 $pr->{'descr_long'} = $descr;
4522 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4524 if (!defined $pr->{'owner'}) {
4525 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4527 if ($check_forks) {
4528 my $pname = $pr->{'path'};
4529 if (($pname =~ s/\.git$//) &&
4530 ($pname !~ /\/$/) &&
4531 (-d "$projectroot/$pname")) {
4532 $pr->{'forks'} = "-d $projectroot/$pname";
4533 } else {
4534 $pr->{'forks'} = 0;
4537 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4538 push @projects, $pr;
4541 return @projects;
4544 sub cached_project_list_info {
4545 my ($projlist, $check_forks, $show_ctags, $cache_lifetime) = @_;
4547 use File::stat;
4548 use POSIX qw(:fcntl_h);
4549 use Storable qw(store_fd retrieve);
4551 my $cache_file = "$cache_dir/$projlist_cache_name";
4553 my @projects;
4554 my $stale = 0;
4555 my $now = time();
4556 my $cache_mtime;
4557 if ($cache_lifetime && -f $cache_file) {
4558 $cache_mtime = stat($cache_file)->mtime;
4560 if (defined $cache_mtime && # caching is on and $cache_file exists
4561 $cache_mtime + $cache_lifetime*60 > $now &&
4562 (my $dump = retrieve($cache_file))) {
4563 # Cache hit.
4564 $stale = $now - $cache_mtime;
4565 @projects = @$dump;
4567 } else { # Cache miss.
4568 if (defined $cache_mtime) {
4569 # Postpone timeout by two minutes so that we get
4570 # enough time to do our job, or to be more exact
4571 # make cache expire after two minutes from now.
4572 my $time = $now - $cache_lifetime*60 + 120;
4573 utime $time, $time, $cache_file;
4575 @projects = fill_project_list_info($projlist, $check_forks, $show_ctags);
4576 if ($cache_lifetime &&
4577 (-d $cache_dir || mkdir($cache_dir, $cache_grpshared ? 0770 : 0700)) &&
4578 sysopen(my $fd, "$cache_file.lock", O_WRONLY|O_CREAT|O_EXCL, $cache_grpshared ? 0660 : 0600)) {
4579 store_fd(\@projects, $fd);
4580 close $fd;
4581 rename "$cache_file.lock", $cache_file;
4585 if ($cache_lifetime && $stale > 0) {
4586 print "<div class=\"stale_info\">Cached version (${stale}s old)</div>\n";
4589 return @projects;
4592 # print 'sort by' <th> element, generating 'sort by $name' replay link
4593 # if that order is not selected
4594 sub print_sort_th {
4595 my ($name, $order, $header) = @_;
4596 $header ||= ucfirst($name);
4598 if ($order eq $name) {
4599 print "<th>$header</th>\n";
4600 } else {
4601 print "<th>" .
4602 $cgi->a({-href => href(-replay=>1, order=>$name),
4603 -class => "header"}, $header) .
4604 "</th>\n";
4608 sub git_project_list_ctags {
4609 my ($projects, $action) = @_;
4610 $action ||= 'project_list';
4612 my %ctags;
4613 foreach my $p (@$projects) {
4614 foreach my $ct (keys %{$p->{'ctags'}}) {
4615 $ctags{$ct} += $p->{'ctags'}->{$ct};
4618 my $cloud = git_populate_project_tagcloud(\%ctags, $action);
4619 print git_show_project_tagcloud($cloud, 64, $action);
4622 sub git_project_list_body {
4623 # actually uses global variable $project
4624 my ($projlist, $order, $from, $to, $extra, $no_header, $ctags_action, $cache_lifetime) = @_;
4626 my $check_forks = gitweb_check_feature('forks');
4627 my $show_ctags = gitweb_check_feature('ctags');
4628 my @projects = cached_project_list_info($projlist, $check_forks, $show_ctags, $cache_lifetime);
4630 $order ||= $default_projects_order;
4631 $from = 0 unless defined $from;
4632 $to = $#projects if (!defined $to || $#projects < $to);
4634 my %order_info = (
4635 project => { key => 'path', type => 'str' },
4636 descr => { key => 'descr_long', type => 'str' },
4637 owner => { key => 'owner', type => 'str' },
4638 age => { key => 'age', type => 'num' }
4640 my $oi = $order_info{$order};
4641 if (($oi->{'type'}||'') eq 'str') {
4642 @projects = sort {lc($a->{$oi->{'key'}||''}||'') cmp lc($b->{$oi->{'key'}||''}||'')} @projects;
4643 } else {
4644 @projects = sort {($a->{$oi->{'key'}||''}||0) <=> ($b->{$oi->{'key'}||''}||0)} @projects;
4647 if ($show_ctags) {
4648 git_project_list_ctags(\@projects, $ctags_action);
4651 print "<table class=\"project_list\">\n";
4652 unless ($no_header) {
4653 print "<tr>\n";
4654 if ($check_forks) {
4655 print "<th></th>\n";
4657 print_sort_th('project', $order, 'Project');
4658 print_sort_th('descr', $order, 'Description');
4659 print_sort_th('owner', $order, 'Owner');
4660 print_sort_th('age', $order, 'Last Change');
4661 print "<th></th>\n" . # for links
4662 "</tr>\n";
4664 my $alternate = 1;
4665 my $tagfilter = $input_params{'ctag_filter'};
4666 for (my $i = $from; $i <= $to; $i++) {
4667 my $pr = $projects[$i];
4669 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4670 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4671 and not $pr->{'descr_long'} =~ /$searchtext/;
4672 # Weed out forks or non-matching entries of search
4673 if ($check_forks) {
4674 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4675 $forkbase="^$forkbase" if $forkbase;
4676 next if not $searchtext and not $tagfilter and $show_ctags
4677 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4680 if ($alternate) {
4681 print "<tr class=\"dark\">\n";
4682 } else {
4683 print "<tr class=\"light\">\n";
4685 $alternate ^= 1;
4686 if ($check_forks) {
4687 print "<td>";
4688 if ($pr->{'forks'}) {
4689 print "<!-- $pr->{'forks'} -->\n";
4690 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4692 print "</td>\n";
4694 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4695 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4696 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4697 -class => "list", -title => $pr->{'descr_long'}},
4698 esc_html($pr->{'descr'})) . "</td>\n";
4699 print "<td><i>" . ($owner_link_hook
4700 ? $cgi->a({-href => $owner_link_hook->($pr->{'owner'}), -class => "list"},
4701 chop_and_escape_str($pr->{'owner'}, 15))
4702 : chop_and_escape_str($pr->{'owner'}, 15)) . "</i></td>\n";
4703 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4704 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4705 "<td class=\"link\">" .
4706 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4707 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "log") . " | " .
4708 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4709 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4710 "</td>\n" .
4711 "</tr>\n";
4713 if (defined $extra) {
4714 print "<tr>\n";
4715 if ($check_forks) {
4716 print "<td></td>\n";
4718 print "<td colspan=\"5\">$extra</td>\n" .
4719 "</tr>\n";
4721 print "</table>\n";
4724 sub git_project_search_form {
4725 print $cgi->startform(-method => "get") .
4726 $cgi->hidden({-name=>"a", -value=>"project_list"}) . "\n" .
4727 "<p class=\"projsearch\">Search:\n" .
4728 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4729 "</p>" .
4730 $cgi->end_form() . "\n";
4733 sub git_project_list_all {
4734 my $order = $input_params{'order'};
4735 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4736 die_error(400, "Unknown order parameter");
4739 my @list = git_get_projects_list();
4740 if (!@list) {
4741 die_error(404, "No projects found");
4744 git_project_list_body(\@list, $order, undef, undef, undef, undef, undef, $projlist_cache_lifetime);
4747 sub git_shortlog_body {
4748 # uses global variable $project
4749 my ($commitlist, $from, $to, $refs, $extra) = @_;
4751 $from = 0 unless defined $from;
4752 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4754 print "<table class=\"shortlog\">\n";
4755 my $alternate = 1;
4756 for (my $i = $from; $i <= $to; $i++) {
4757 my %co = %{$commitlist->[$i]};
4758 my $commit = $co{'id'};
4759 my $ref = format_ref_marker($refs, $commit);
4760 if ($alternate) {
4761 print "<tr class=\"dark\">\n";
4762 } else {
4763 print "<tr class=\"light\">\n";
4765 $alternate ^= 1;
4766 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4767 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4768 format_author_html('td', \%co, 10) . "<td>";
4769 print format_subject_html($co{'title'}, $co{'title_short'},
4770 href(action=>"commit", hash=>$commit), $ref);
4771 print "</td>\n" .
4772 "<td class=\"link\">" .
4773 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4774 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4775 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4776 my $snapshot_links = format_snapshot_links($commit);
4777 if (defined $snapshot_links) {
4778 print " | " . $snapshot_links;
4780 print "</td>\n" .
4781 "</tr>\n";
4783 if (defined $extra) {
4784 print "<tr>\n" .
4785 "<td colspan=\"4\">$extra</td>\n" .
4786 "</tr>\n";
4788 print "</table>\n";
4791 sub git_history_body {
4792 # Warning: assumes constant type (blob or tree) during history
4793 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4795 $from = 0 unless defined $from;
4796 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4798 print "<table class=\"history\">\n";
4799 my $alternate = 1;
4800 for (my $i = $from; $i <= $to; $i++) {
4801 my %co = %{$commitlist->[$i]};
4802 if (!%co) {
4803 next;
4805 my $commit = $co{'id'};
4807 my $ref = format_ref_marker($refs, $commit);
4809 if ($alternate) {
4810 print "<tr class=\"dark\">\n";
4811 } else {
4812 print "<tr class=\"light\">\n";
4814 $alternate ^= 1;
4815 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4816 # shortlog: format_author_html('td', \%co, 10)
4817 format_author_html('td', \%co, 15, 3) . "<td>";
4818 # originally git_history used chop_str($co{'title'}, 50)
4819 print format_subject_html($co{'title'}, $co{'title_short'},
4820 href(action=>"commit", hash=>$commit), $ref);
4821 print "</td>\n" .
4822 "<td class=\"link\">" .
4823 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4824 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4826 if ($ftype eq 'blob') {
4827 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4828 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4829 if (defined $blob_current && defined $blob_parent &&
4830 $blob_current ne $blob_parent) {
4831 print " | " .
4832 $cgi->a({-href => href(action=>"blobdiff",
4833 hash=>$blob_current, hash_parent=>$blob_parent,
4834 hash_base=>$hash_base, hash_parent_base=>$commit,
4835 file_name=>$file_name)},
4836 "diff to current");
4839 print "</td>\n" .
4840 "</tr>\n";
4842 if (defined $extra) {
4843 print "<tr>\n" .
4844 "<td colspan=\"4\">$extra</td>\n" .
4845 "</tr>\n";
4847 print "</table>\n";
4850 sub git_tags_body {
4851 # uses global variable $project
4852 my ($taglist, $from, $to, $extra, $head) = @_;
4853 $from = 0 unless defined $from;
4854 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4856 print "<table class=\"tags\">\n";
4857 my $alternate = 1;
4858 for (my $i = $from; $i <= $to; $i++) {
4859 my $entry = $taglist->[$i];
4860 my %tag = %$entry;
4861 my $comment = $tag{'subject'};
4862 my $comment_short;
4863 if (defined $comment) {
4864 $comment_short = chop_str($comment, 30, 5);
4866 my $curr = $tag{'id'} eq ($head||'');
4867 if ($alternate) {
4868 print "<tr class=\"dark\">\n";
4869 } else {
4870 print "<tr class=\"light\">\n";
4872 $alternate ^= 1;
4873 if (defined $tag{'age'}) {
4874 print "<td><i>$tag{'age'}</i></td>\n";
4875 } else {
4876 print "<td></td>\n";
4878 print(($curr ? "<td class=\"current_head\">" : "<td>") .
4879 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4880 -class => "list name"}, esc_html($tag{'name'})) .
4881 "</td>\n" .
4882 "<td>");
4883 if (defined $comment) {
4884 print format_subject_html($comment, $comment_short,
4885 href(action=>"tag", hash=>$tag{'id'}));
4887 print "</td>\n" .
4888 "<td class=\"selflink\">";
4889 if ($tag{'type'} eq "tag") {
4890 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4891 } else {
4892 print "&nbsp;";
4894 print "</td>\n" .
4895 "<td class=\"link\">" . " | " .
4896 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4897 if ($tag{'reftype'} eq "commit") {
4898 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "log");
4899 } elsif ($tag{'reftype'} eq "blob") {
4900 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4902 print "</td>\n" .
4903 "</tr>";
4905 if (defined $extra) {
4906 print "<tr>\n" .
4907 "<td colspan=\"5\">$extra</td>\n" .
4908 "</tr>\n";
4910 print "</table>\n";
4913 sub git_heads_body {
4914 # uses global variable $project
4915 my ($headlist, $head, $from, $to, $extra) = @_;
4916 $from = 0 unless defined $from;
4917 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4919 print "<table class=\"heads\">\n";
4920 my $alternate = 1;
4921 for (my $i = $from; $i <= $to; $i++) {
4922 my $entry = $headlist->[$i];
4923 my %ref = %$entry;
4924 my $curr = $ref{'id'} eq ($head||'');
4925 if ($alternate) {
4926 print "<tr class=\"dark\">\n";
4927 } else {
4928 print "<tr class=\"light\">\n";
4930 $alternate ^= 1;
4931 print "<td><i>$ref{'age'}</i></td>\n" .
4932 ($curr ? "<td class=\"current_head\">" : "<td>") .
4933 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4934 -class => "list name"},esc_html($ref{'name'})) .
4935 "</td>\n" .
4936 "<td class=\"link\">" .
4937 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "log") . " | " .
4938 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4939 "</td>\n" .
4940 "</tr>";
4942 if (defined $extra) {
4943 print "<tr>\n" .
4944 "<td colspan=\"3\">$extra</td>\n" .
4945 "</tr>\n";
4947 print "</table>\n";
4950 sub git_search_grep_body {
4951 my ($commitlist, $from, $to, $extra) = @_;
4952 $from = 0 unless defined $from;
4953 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4955 print "<table class=\"commit_search\">\n";
4956 my $alternate = 1;
4957 for (my $i = $from; $i <= $to; $i++) {
4958 my %co = %{$commitlist->[$i]};
4959 if (!%co) {
4960 next;
4962 my $commit = $co{'id'};
4963 if ($alternate) {
4964 print "<tr class=\"dark\">\n";
4965 } else {
4966 print "<tr class=\"light\">\n";
4968 $alternate ^= 1;
4969 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4970 format_author_html('td', \%co, 15, 5) .
4971 "<td>" .
4972 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4973 -class => "list subject"},
4974 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4975 my $comment = $co{'comment'};
4976 foreach my $line (@$comment) {
4977 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4978 my ($lead, $match, $trail) = ($1, $2, $3);
4979 $match = chop_str($match, 70, 5, 'center');
4980 my $contextlen = int((80 - length($match))/2);
4981 $contextlen = 30 if ($contextlen > 30);
4982 $lead = chop_str($lead, $contextlen, 10, 'left');
4983 $trail = chop_str($trail, $contextlen, 10, 'right');
4985 $lead = esc_html($lead);
4986 $match = esc_html($match);
4987 $trail = esc_html($trail);
4989 print "$lead<span class=\"match\">$match</span>$trail<br />";
4992 print "</td>\n" .
4993 "<td class=\"link\">" .
4994 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4995 " | " .
4996 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4997 " | " .
4998 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4999 print "</td>\n" .
5000 "</tr>\n";
5002 if (defined $extra) {
5003 print "<tr>\n" .
5004 "<td colspan=\"3\">$extra</td>\n" .
5005 "</tr>\n";
5007 print "</table>\n";
5010 ## ======================================================================
5011 ## ======================================================================
5012 ## actions
5014 sub git_frontpage {
5015 git_header_html();
5016 if (-f $home_text) {
5017 print "<div class=\"index_include\">\n";
5018 insert_file($home_text);
5019 print "</div>\n";
5021 git_project_search_form();
5022 if (not $frontpage_no_project_list) {
5023 git_project_list_all();
5024 } else {
5025 my $show_ctags = gitweb_check_feature('ctags');
5026 if ($frontpage_no_project_list == 1 and $show_ctags) {
5027 my @list = git_get_projects_list();
5028 my @projects = cached_project_list_info(\@list,
5029 gitweb_check_feature('forks'),
5030 $show_ctags, $projlist_cache_lifetime);
5031 git_project_list_ctags(\@projects);
5033 print "<p class=\"projectlist_link\">" .
5034 $cgi->a({-href => href(action=>'project_list')}, "Browse all projects") .
5035 "</p>\n";
5037 git_footer_html();
5040 sub git_project_list {
5041 git_header_html();
5042 git_project_search_form();
5043 git_project_list_all();
5044 git_footer_html();
5047 sub git_forks {
5048 my $order = $input_params{'order'};
5049 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5050 die_error(400, "Unknown order parameter");
5053 my @list = git_get_projects_list($project);
5054 if (!@list) {
5055 die_error(404, "No forks found");
5058 git_header_html();
5059 git_print_page_nav('','');
5060 git_print_header_div('summary', "$project forks");
5061 git_project_list_body(\@list, $order, undef, undef, undef, undef, 'forks');
5062 git_footer_html();
5065 sub git_project_index {
5066 my @projects = git_get_projects_list($project);
5068 print $cgi->header(
5069 -type => 'text/plain',
5070 -charset => 'utf-8',
5071 -content_disposition => 'inline; filename="index.aux"');
5073 foreach my $pr (@projects) {
5074 if (!exists $pr->{'owner'}) {
5075 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5078 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5079 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5080 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5081 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5082 $path =~ s/ /\+/g;
5083 $owner =~ s/ /\+/g;
5085 print "$path $owner\n";
5089 sub git_summary {
5090 my $descr = git_get_project_description($project) || "none";
5091 my %co = parse_commit("HEAD");
5092 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5093 my $head = $co{'id'};
5095 my $owner = git_get_project_owner($project);
5096 my $homepage = git_get_project_config('homepage');
5097 my $base_url = git_get_project_config('baseurl');
5098 my $last_refresh = git_get_project_config("lastrefresh");
5100 my $refs = git_get_references();
5101 # These get_*_list functions return one more to allow us to see if
5102 # there are more ...
5103 my @taglist = git_get_tags_list(16);
5104 my @headlist = git_get_heads_list(16);
5105 my @forklist;
5106 my $check_forks = gitweb_check_feature('forks');
5108 if ($check_forks) {
5109 @forklist = git_get_projects_list($project);
5112 git_header_html();
5113 git_print_page_nav('summary','', $head);
5115 if ($check_forks and $project =~ m#/#) {
5116 my $xproject = $project; $xproject =~ s#/[^/]+$#.git#; #
5117 my $r = $cgi->a({-href=> href(project => $xproject, action => 'summary')}, $xproject);
5118 print <<EOT;
5119 <div class="forkinfo">
5120 This project is a fork of the $r project. If you have that one
5121 already cloned locally, you can use
5122 <pre>git clone --reference /path/to/your/$xproject/incarnation mirror_URL</pre>
5123 to save bandwidth during cloning.
5124 </div>
5128 print "<div class=\"title\">&nbsp;</div>\n";
5129 print "<table class=\"projects_list\">\n";
5130 print "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
5131 $homepage and print "<tr id=\"metadata_homepage\"><td>homepage URL</td><td>" . $cgi->a({-href => $homepage}, $homepage) . "</td></tr>\n";
5132 $base_url and print "<tr id=\"metadata_baseurl\"><td>repository URL</td><td>" . esc_html($base_url) . "</td></tr>\n";
5133 print "<tr id=\"metadata_owner\"><td>owner</td><td>" .
5134 ($owner_link_hook ? $cgi->a({-href => $owner_link_hook->($owner)}, email_obfuscate($owner)) : email_obfuscate($owner)) . "</td></tr>\n";
5135 if (defined $cd{'rfc2822'}) {
5136 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5138 $last_refresh and print "<tr id=\"metadata_lrefresh\"><td>last refresh</td><td>$last_refresh</td></tr>\n";
5140 # use per project git URL list in $projectroot/$project/cloneurl
5141 # or make project git URL from git base URL and project name
5142 my $url_tag = $base_url ? "mirror URL" : "URL";
5143 my @url_list = git_get_project_url_list($project);
5144 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5145 foreach my $git_url (@url_list) {
5146 next unless $git_url;
5147 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5148 $url_tag = "";
5150 @url_list = map { "$_/$project" } @git_base_push_urls;
5151 if (-f "$projectroot/$project/.nofetch") {
5152 $url_tag = "Push URL";
5153 foreach my $git_push_url (@url_list) {
5154 next unless $git_push_url;
5155 my $hint = $https_hint_html && $git_push_url =~ /^https:/i ?
5156 " $https_hint_html" : '';
5157 print "<tr class=\"metadata_pushurl\"><td>$url_tag</td><td>$git_push_url$hint</td></tr>\n";
5158 $url_tag = "";
5162 # Tag cloud
5163 my $show_ctags = gitweb_check_feature('ctags');
5164 if ($show_ctags) {
5165 my $ctags = git_get_project_ctags($project);
5166 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
5167 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5168 print "</td>\n<td>" unless %$ctags;
5169 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5170 print "</td>\n<td>" if %$ctags;
5171 print git_show_project_tagcloud($cloud, 48, 'project_list');
5172 print "</td></tr>";
5175 print "</table>\n";
5177 # If XSS prevention is on, we don't include README.html.
5178 # TODO: Allow a readme in some safe format.
5179 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5180 print "<div class=\"title\">readme</div>\n" .
5181 "<div class=\"readme\">\n";
5182 insert_file("$projectroot/$project/README.html");
5183 print "\n</div>\n"; # class="readme"
5186 # we need to request one more than 16 (0..15) to check if
5187 # those 16 are all
5188 my @commitlist = $head ? parse_commits($head, 17) : ();
5189 if (@commitlist) {
5190 git_print_header_div('shortlog');
5191 git_shortlog_body(\@commitlist, 0, 15, $refs,
5192 $#commitlist <= 15 ? undef :
5193 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5196 if (@taglist) {
5197 git_print_header_div('tags');
5198 git_tags_body(\@taglist, 0, 15,
5199 $#taglist <= 15 ? undef :
5200 $cgi->a({-href => href(action=>"tags")}, "..."));
5203 if (@headlist) {
5204 git_print_header_div('heads');
5205 git_heads_body(\@headlist, $head, 0, 15,
5206 $#headlist <= 15 ? undef :
5207 $cgi->a({-href => href(action=>"heads")}, "..."));
5210 if (@forklist) {
5211 git_print_header_div('forks');
5212 git_project_list_body(\@forklist, 'age', 0, 15,
5213 $#forklist <= 15 ? undef :
5214 $cgi->a({-href => href(action=>"forks")}, "..."),
5215 'no_header', 'forks');
5218 git_footer_html();
5221 sub git_tag {
5222 my $head = git_get_head_hash($project);
5223 git_header_html();
5224 git_print_page_nav('','', $head,undef,$head);
5225 my %tag = parse_tag($hash);
5227 if (! %tag) {
5228 die_error(404, "Unknown tag object");
5231 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5232 print "<div class=\"title_text\">\n" .
5233 "<table class=\"object_header\">\n" .
5234 "<tr>\n" .
5235 "<td>object</td>\n" .
5236 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5237 $tag{'object'}) . "</td>\n" .
5238 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5239 $tag{'type'}) . "</td>\n" .
5240 "</tr>\n";
5241 if (defined($tag{'author'})) {
5242 git_print_authorship_rows(\%tag, 'author');
5244 print "</table>\n\n" .
5245 "</div>\n";
5246 print "<div class=\"page_body\">";
5247 my $comment = $tag{'comment'};
5248 foreach my $line (@$comment) {
5249 chomp $line;
5250 print esc_html($line, -nbsp=>1) . "<br/>\n";
5252 print "</div>\n";
5253 git_footer_html();
5256 sub git_blame_data {
5257 my $ftype;
5259 my ($have_blame) = gitweb_check_feature('blame');
5260 if (!$have_blame) {
5261 die_error('403 Permission denied', "Permission denied");
5263 die_error('404 Not Found', "File name not defined") if (!$file_name);
5264 $hash_base ||= git_get_head_hash($project);
5265 die_error(undef, "Couldn't find base commit") unless ($hash_base);
5266 my %co = parse_commit($hash_base)
5267 or die_error(undef, "Reading commit failed");
5268 if (!defined $hash) {
5269 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5270 or die_error(undef, "Error looking up file");
5272 $ftype = git_get_type($hash);
5273 if ($ftype !~ "blob") {
5274 die_error("400 Bad Request", "Object is not a blob");
5276 defined(my $fd = git_cmd_pipe "blame", '--incremental',
5277 $hash_base, '--', $file_name)
5278 or die_error(undef, "Open git-blame --incremental failed");
5280 print $cgi->header(-type=>"text/plain", -charset => 'utf-8',
5281 -status=> "200 OK");
5283 while(<$fd>) {
5284 if (/^([0-9a-f]{40}) ([0-9]+) ([0-9]+) ([0-9]+)/ or
5285 /^author-time |^author |^filename /) {
5286 print;
5290 close $fd or print "Reading blame data failed\n";
5293 sub git_blame_common {
5294 my ($type) = @_;
5296 # permissions
5297 gitweb_check_feature('blame')
5298 or die_error(403, "Blame view not allowed");
5300 # error checking
5301 die_error(400, "No file name given") unless $file_name;
5302 $hash_base ||= git_get_head_hash($project);
5303 die_error(404, "Couldn't find base commit") unless $hash_base;
5304 my %co = parse_commit($hash_base)
5305 or die_error(404, "Commit not found");
5306 my $ftype = "blob";
5307 if (!defined $hash) {
5308 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5309 or die_error(404, "Error looking up file");
5310 } else {
5311 $ftype = git_get_type($hash);
5312 if ($ftype !~ "blob") {
5313 die_error(400, "Object is not a blob");
5316 $ftype = git_get_type($hash);
5317 if ($ftype !~ "blob") {
5318 die_error(400, "Object is not a blob");
5320 my $fd;
5321 if ($type eq 'incremental') {
5322 defined($fd = git_cmd_pipe 'cat-file', 'blob', $hash)
5323 or die_error(undef, "Open git-cat-file failed");
5324 } else {
5325 # run git-blame --porcelain
5326 defined($fd = git_cmd_pipe "blame", '-p',
5327 $hash_base, '--', $file_name)
5328 or die_error(500, "Open git-blame failed");
5331 # page header
5332 git_header_html();
5333 my $formats_nav =
5334 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5335 "blob") .
5336 " | " .
5337 $cgi->a({-href => href(action=>"history", -replay=>1)},
5338 "history") .
5339 " | " .
5340 $cgi->a({-href => href(action=>"blame", file_name=>$file_name), -class => "blamelink"},
5341 "HEAD");
5342 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5343 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5344 git_print_page_path($file_name, $ftype, $hash_base);
5346 # page body
5347 my @rev_color = qw(light dark);
5348 my $num_colors = scalar(@rev_color);
5349 my $current_color = 0;
5350 my %metainfo = ();
5352 print <<HTML;
5354 <div class="page_body">
5355 <table class="blame">
5356 <tr><th>Commit&nbsp;<a href="javascript:extra_blame_columns()" id="columns_expander">[+]</a></th>
5357 <th class="extra_column">Author</th>
5358 <th class="extra_column">Date</th>
5359 <th>Line</th>
5360 <th>Data</th></tr>
5361 HTML
5362 LINE:
5363 my $linenr = 0;
5364 while (my $line = <$fd>) {
5365 chomp $line;
5366 if ($type eq 'incremental') {
5367 # Empty stage with just the file contents
5368 $linenr += 1;
5369 print "<tr id=\"l$linenr\" class=\"light2\">";
5370 print '<td class="sha1"><a href=""></a></td>';
5371 print "<td class=\"extra_column\"></td>";
5372 print "<td class=\"extra_column\"></td>";
5373 print "<td class=\"linenr\"><a class=\"linenr\" href=\"\">$linenr</a></td><td class=\"pre\">" . esc_html($line) . "</td>\n";
5374 print "</tr>\n";
5375 next;
5378 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5379 # no <lines in group> for subsequent lines in group of lines
5380 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5381 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5382 if (!exists $metainfo{$full_rev}) {
5383 $metainfo{$full_rev} = { 'nprevious' => 0 };
5385 my $meta = $metainfo{$full_rev};
5386 my $data;
5387 while ($data = <$fd>) {
5388 chomp $data;
5389 last if ($data =~ s/^\t//); # contents of line
5390 if ($data =~ /^(\S+)(?: (.*))?$/) {
5391 $meta->{$1} = $2 unless exists $meta->{$1};
5393 if ($data =~ /^previous /) {
5394 $meta->{'nprevious'}++;
5397 my $short_rev = substr($full_rev, 0, 8);
5398 my $author = $meta->{'author'};
5399 my %date =
5400 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5401 my $date = $date{'iso-tz'};
5402 if ($group_size) {
5403 $current_color = ($current_color + 1) % $num_colors;
5405 my $tr_class = $rev_color[$current_color];
5406 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5407 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5408 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5409 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5410 if ($group_size) {
5411 my $rowspan = $group_size > 1 ? " rowspan=\"$group_size\"" : "";
5412 print "<td class=\"sha1\"";
5413 print " title=\"". esc_html($author) . ", $date\"";
5414 print "$rowspan>";
5415 print $cgi->a({-href => href(action=>"commit",
5416 hash=>$full_rev,
5417 file_name=>$file_name)},
5418 esc_html($short_rev));
5419 if ($group_size >= 2) {
5420 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5421 if (@author_initials) {
5422 print "<br />" .
5423 esc_html(join('', @author_initials));
5424 # or join('.', ...)
5427 print "</td>\n";
5428 print "<td class=\"extra_column\" $rowspan>". esc_html($author) . "</td>";
5429 print "<td class=\"extra_column\" $rowspan>". $date . "</td>";
5431 # 'previous' <sha1 of parent commit> <filename at commit>
5432 if (exists $meta->{'previous'} &&
5433 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5434 $meta->{'parent'} = $1;
5435 $meta->{'file_parent'} = unquote($2);
5437 my $linenr_commit =
5438 exists($meta->{'parent'}) ?
5439 $meta->{'parent'} : $full_rev;
5440 my $linenr_filename =
5441 exists($meta->{'file_parent'}) ?
5442 $meta->{'file_parent'} : unquote($meta->{'filename'});
5443 my $blamed = href(action => 'blame',
5444 file_name => $linenr_filename,
5445 hash_base => $linenr_commit);
5446 print "<td class=\"linenr\">";
5447 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5448 -class => "linenr" },
5449 esc_html($lineno));
5450 print "</td>";
5451 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5452 print "</tr>\n";
5455 print "</table>\n";
5456 print "</div>";
5457 close $fd
5458 or print "Reading blob failed\n";
5460 if ($type eq 'incremental') {
5461 print "<script type=\"text/javascript\">\n";
5462 print "startBlame(\"" . href(action=>"blame_data", hash_base=>$hash_base, file_name=>$file_name) . "\", \"" .
5463 href(-partial_query=>1) . "\");\n";
5464 print "</script>\n";
5467 # page footer
5468 git_footer_html();
5471 sub git_blame_incremental {
5472 git_blame_common('incremental');
5475 sub git_blame {
5476 git_blame_common('oneshot');
5479 sub git_tags {
5480 my $head = git_get_head_hash($project);
5481 git_header_html();
5482 git_print_page_nav('','', $head,undef,$head);
5483 git_print_header_div('summary', $project);
5485 my @tagslist = git_get_tags_list();
5486 if (@tagslist) {
5487 git_tags_body(\@tagslist);
5489 git_footer_html();
5492 sub git_refs {
5493 my $head = git_get_head_hash($project);
5494 git_header_html();
5495 git_print_page_nav('refs','', $head,undef,$head);
5496 git_print_header_div('summary', $project);
5498 my @refslist = git_get_tags_list(0, 1);
5499 if (@refslist) {
5500 git_tags_body(\@refslist, undef, undef, undef, $head);
5502 git_footer_html();
5505 sub git_heads {
5506 my $head = git_get_head_hash($project);
5507 git_header_html();
5508 git_print_page_nav('','', $head,undef,$head);
5509 git_print_header_div('summary', $project);
5511 my @headslist = git_get_heads_list();
5512 if (@headslist) {
5513 git_heads_body(\@headslist, $head);
5515 git_footer_html();
5518 sub git_blob_plain {
5519 my $type = shift;
5520 my $expires;
5522 if (!defined $hash) {
5523 if (defined $file_name) {
5524 my $base = $hash_base || git_get_head_hash($project);
5525 $hash = git_get_hash_by_path($base, $file_name, "blob")
5526 or die_error(404, "Cannot find file");
5527 } else {
5528 die_error(400, "No file name defined");
5530 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5531 # blobs defined by non-textual hash id's can be cached
5532 $expires = "+1d";
5535 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
5536 or die_error(500, "Open git-cat-file blob '$hash' failed");
5538 # content-type (can include charset)
5539 $type = blob_contenttype($fd, $file_name, $type);
5541 # "save as" filename, even when no $file_name is given
5542 my $save_as = "$hash";
5543 if (defined $file_name) {
5544 $save_as = $file_name;
5545 } elsif ($type =~ m/^text\//) {
5546 $save_as .= '.txt';
5549 # With XSS prevention on, blobs of all types except a few known safe
5550 # ones are served with "Content-Disposition: attachment" to make sure
5551 # they don't run in our security domain. For certain image types,
5552 # blob view writes an <img> tag referring to blob_plain view, and we
5553 # want to be sure not to break that by serving the image as an
5554 # attachment (though Firefox 3 doesn't seem to care).
5555 my $sandbox = $prevent_xss &&
5556 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5558 print $cgi->header(
5559 -type => $type,
5560 -expires => $expires,
5561 -content_disposition =>
5562 ($sandbox ? 'attachment' : 'inline')
5563 . '; filename="' . $save_as . '"');
5564 local $/ = undef;
5565 binmode STDOUT, ':raw';
5566 print <$fd>;
5567 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5568 close $fd;
5571 sub git_blob {
5572 my $expires;
5574 if (!defined $hash) {
5575 if (defined $file_name) {
5576 my $base = $hash_base || git_get_head_hash($project);
5577 $hash = git_get_hash_by_path($base, $file_name, "blob")
5578 or die_error(404, "Cannot find file");
5579 } else {
5580 die_error(400, "No file name defined");
5582 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5583 # blobs defined by non-textual hash id's can be cached
5584 $expires = "+1d";
5587 my $have_blame = gitweb_check_feature('blame');
5588 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
5589 or die_error(500, "Couldn't cat $file_name, $hash");
5590 my $mimetype = blob_mimetype($fd, $file_name);
5591 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5592 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5593 close $fd;
5594 return git_blob_plain($mimetype);
5596 # we can have blame only for text/* mimetype
5597 $have_blame &&= ($mimetype =~ m!^text/!);
5599 my $highlight = gitweb_check_feature('highlight');
5600 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5601 $fd = run_highlighter($fd, $highlight, $syntax)
5602 if $syntax;
5604 git_header_html(undef, $expires);
5605 my $formats_nav = '';
5606 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5607 if (defined $file_name) {
5608 if ($have_blame) {
5609 $formats_nav .=
5610 $cgi->a({-href => href(action=>"blame", -replay=>1,
5611 -class => "blamelink")},
5612 "blame") .
5613 " | ";
5615 $formats_nav .=
5616 $cgi->a({-href => href(action=>"history", -replay=>1)},
5617 "history") .
5618 " | " .
5619 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5620 "raw") .
5621 " | " .
5622 $cgi->a({-href => href(action=>"blob",
5623 hash_base=>"HEAD", file_name=>$file_name)},
5624 "HEAD");
5625 } else {
5626 $formats_nav .=
5627 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5628 "raw");
5630 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5631 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5632 } else {
5633 print "<div class=\"page_nav\">\n" .
5634 "<br/><br/></div>\n" .
5635 "<div class=\"title\">".esc_html($hash)."</div>\n";
5637 git_print_page_path($file_name, "blob", $hash_base);
5638 print "<div class=\"page_body\">\n";
5639 if ($mimetype =~ m!^image/!) {
5640 print qq!<img type="!.esc_attr($mimetype).qq!"!;
5641 if ($file_name) {
5642 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
5644 print qq! src="! .
5645 href(action=>"blob_plain", hash=>$hash,
5646 hash_base=>$hash_base, file_name=>$file_name) .
5647 qq!" />\n!;
5648 } else {
5649 my $nr=0;
5650 while (my $line = <$fd>) {
5651 chomp $line;
5652 $nr++;
5653 $line = untabify($line);
5654 printf "<div class=\"pre\"><a id=\"l%i\" href=\"%s"
5655 . "#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5656 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
5657 $syntax ? $line : esc_html($line, -nbsp=>1);
5660 close $fd
5661 or print "Reading blob failed.\n";
5662 print "</div>";
5663 git_footer_html();
5666 sub git_tree {
5667 if (!defined $hash_base) {
5668 $hash_base = "HEAD";
5670 if (!defined $hash) {
5671 if (defined $file_name) {
5672 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5673 } else {
5674 $hash = $hash_base;
5677 die_error(404, "No such tree") unless defined($hash);
5679 my $show_sizes = gitweb_check_feature('show-sizes');
5680 my $have_blame = gitweb_check_feature('blame');
5682 my @entries = ();
5684 local $/ = "\0";
5685 defined(my $fd = git_cmd_pipe "ls-tree", '-z',
5686 ($show_sizes ? '-l' : ()), @extra_options, $hash)
5687 or die_error(500, "Open git-ls-tree failed");
5688 @entries = map { chomp; $_ } <$fd>;
5689 close $fd
5690 or die_error(404, "Reading tree failed");
5693 git_header_html();
5694 my $basedir = '';
5695 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5696 my $refs = git_get_references();
5697 my $ref = format_ref_marker($refs, $co{'id'});
5698 my @views_nav = ();
5699 if (defined $file_name) {
5700 push @views_nav,
5701 $cgi->a({-href => href(action=>"history", -replay=>1)},
5702 "history"),
5703 $cgi->a({-href => href(action=>"tree",
5704 hash_base=>"HEAD", file_name=>$file_name)},
5705 "HEAD"),
5707 my $snapshot_links = format_snapshot_links($hash);
5708 if (defined $snapshot_links) {
5709 # FIXME: Should be available when we have no hash base as well.
5710 push @views_nav, $snapshot_links;
5712 git_print_page_nav('tree','', $hash_base, undef, undef,
5713 join(' | ', @views_nav));
5714 git_print_header_div('commit', esc_html($co{'title'}), $hash_base, undef, $ref);
5715 } else {
5716 undef $hash_base;
5717 print "<div class=\"page_nav\">\n";
5718 print "<br/><br/></div>\n";
5719 print "<div class=\"title\">".esc_html($hash)."</div>\n";
5721 if (defined $file_name) {
5722 $basedir = $file_name;
5723 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5724 $basedir .= '/';
5726 git_print_page_path($file_name, 'tree', $hash_base);
5728 print "<div class=\"page_body\">\n";
5729 print "<table class=\"tree\">\n";
5730 my $alternate = 1;
5731 # '..' (top directory) link if possible
5732 if (defined $hash_base &&
5733 defined $file_name && $file_name =~ m![^/]+$!) {
5734 if ($alternate) {
5735 print "<tr class=\"dark\">\n";
5736 } else {
5737 print "<tr class=\"light\">\n";
5739 $alternate ^= 1;
5741 my $up = $file_name;
5742 $up =~ s!/?[^/]+$!!;
5743 undef $up unless $up;
5744 # based on git_print_tree_entry
5745 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5746 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5747 print '<td class="list">';
5748 print $cgi->a({-href => href(action=>"tree",
5749 hash_base=>$hash_base,
5750 file_name=>$up)},
5751 "..");
5752 print "</td>\n";
5753 print "<td class=\"link\"></td>\n";
5755 print "</tr>\n";
5757 foreach my $line (@entries) {
5758 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5760 if ($alternate) {
5761 print "<tr class=\"dark\">\n";
5762 } else {
5763 print "<tr class=\"light\">\n";
5765 $alternate ^= 1;
5767 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5769 print "</tr>\n";
5771 print "</table>\n" .
5772 "</div>";
5773 git_footer_html();
5776 sub git_snapshot {
5777 my $format = $input_params{'snapshot_format'};
5778 if (!@snapshot_fmts) {
5779 die_error(403, "Snapshots not allowed");
5781 # default to first supported snapshot format
5782 $format ||= $snapshot_fmts[0];
5783 if ($format !~ m/^[a-z0-9]+$/) {
5784 die_error(400, "Invalid snapshot format parameter");
5785 } elsif (!exists($known_snapshot_formats{$format})) {
5786 die_error(400, "Unknown snapshot format");
5787 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5788 die_error(403, "Snapshot format not allowed");
5789 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5790 die_error(403, "Unsupported snapshot format");
5793 if (!defined $hash) {
5794 $hash = git_get_head_hash($project);
5795 $hash or die_error(404, "Unknown commit object");
5798 my $name = $project;
5799 $name =~ s,([^/])/*\.git$,$1,;
5800 $name = basename($name);
5801 my $filename = to_utf8($name);
5802 $name =~ s/\047/\047\\\047\047/g;
5803 my $cmd;
5804 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5805 $cmd = quote_command(
5806 git_cmd(), 'archive',
5807 "--format=$known_snapshot_formats{$format}{'format'}",
5808 "--prefix=$name/", $hash);
5809 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5810 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5813 print $cgi->header(
5814 -type => $known_snapshot_formats{$format}{'type'},
5815 -content_disposition => 'inline; filename="' . "$filename" . '"',
5816 -status => '200 OK');
5818 defined(my $fd = cmd_pipe $cmd)
5819 or die_error(500, "Execute git-archive failed");
5820 binmode STDOUT, ':raw';
5821 print <$fd>;
5822 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5823 close $fd;
5826 sub git_log {
5827 my $head = git_get_head_hash($project);
5828 if (!defined $hash) {
5829 $hash = $head;
5831 my $refs = git_get_references();
5833 my @commitlist = parse_commits($hash, 101, (100 * $page));
5835 my $paging_nav = format_log_nav('log', $hash, $head, $page, $#commitlist >= 100);
5837 my ($patch_max) = gitweb_get_feature('patches');
5838 if ($patch_max) {
5839 if ($patch_max < 0 || @commitlist <= $patch_max) {
5840 $paging_nav .= " &sdot; " .
5841 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5842 "patches");
5847 local $action = 'fulllog';
5848 git_header_html();
5850 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5852 if (!@commitlist) {
5853 my %co = parse_commit($hash);
5855 git_print_header_div('summary', $project);
5856 my $age = $co{'age_string'} || 'not found';
5857 print "<div class=\"page_body\"> Last change $age.<br/><br/></div>\n";
5859 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5860 for (my $i = 0; $i <= $to; $i++) {
5861 my %co = %{$commitlist[$i]};
5862 next if !%co;
5863 my $commit = $co{'id'};
5864 my $ref = format_ref_marker($refs, $commit);
5865 my %ad = parse_date($co{'author_epoch'});
5866 git_print_header_div('commit',
5867 "<span class=\"age\">$co{'age_string'}</span>" .
5868 esc_html($co{'title'}),
5869 $commit, undef, $ref);
5870 print "<div class=\"title_text\">\n" .
5871 "<div class=\"log_link\">\n" .
5872 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5873 " | " .
5874 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5875 " | " .
5876 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5877 "<br/>\n" .
5878 "</div>\n";
5879 git_print_authorship(\%co, -tag => 'span');
5880 print "<br/>\n</div>\n";
5882 print "<div class=\"log_body\">\n";
5883 git_print_log($co{'comment'}, -final_empty_line=> 1);
5884 print "</div>\n";
5886 if ($#commitlist >= 100) {
5887 print "<div class=\"page_nav\">\n";
5888 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5889 -accesskey => "n", -title => "Alt-n"}, "next");
5890 print "</div>\n";
5892 git_footer_html();
5895 sub git_commit {
5896 $hash ||= $hash_base || "HEAD";
5897 my %co = parse_commit($hash)
5898 or die_error(404, "Unknown commit object");
5900 my $parent = $co{'parent'};
5901 my $parents = $co{'parents'}; # listref
5903 # we need to prepare $formats_nav before any parameter munging
5904 my $formats_nav;
5905 if (!defined $parent) {
5906 # --root commitdiff
5907 $formats_nav .= '(initial)';
5908 } elsif (@$parents == 1) {
5909 # single parent commit
5910 $formats_nav .=
5911 '(parent: ' .
5912 $cgi->a({-href => href(action=>"commit",
5913 hash=>$parent)},
5914 esc_html(substr($parent, 0, 7))) .
5915 ')';
5916 } else {
5917 # merge commit
5918 $formats_nav .=
5919 '(merge: ' .
5920 join(' ', map {
5921 $cgi->a({-href => href(action=>"commit",
5922 hash=>$_)},
5923 esc_html(substr($_, 0, 7)));
5924 } @$parents ) .
5925 ')';
5927 if (gitweb_check_feature('patches') && @$parents <= 1) {
5928 $formats_nav .= " | " .
5929 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5930 "patch");
5933 if (!defined $parent) {
5934 $parent = "--root";
5936 my @difftree;
5937 defined(my $fd = git_cmd_pipe "diff-tree", '-r', "--no-commit-id",
5938 @diff_opts,
5939 (@$parents <= 1 ? $parent : '-c'),
5940 $hash, "--")
5941 or die_error(500, "Open git-diff-tree failed");
5942 @difftree = map { chomp; $_ } <$fd>;
5943 close $fd or die_error(404, "Reading git-diff-tree failed");
5945 # non-textual hash id's can be cached
5946 my $expires;
5947 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5948 $expires = "+1d";
5950 my $refs = git_get_references();
5951 my $ref = format_ref_marker($refs, $co{'id'});
5953 git_header_html(undef, $expires);
5954 git_print_page_nav('commit', '',
5955 $hash, $co{'tree'}, $hash,
5956 $formats_nav);
5958 if (defined $co{'parent'}) {
5959 git_print_header_div('commitdiff', esc_html($co{'title'}), $hash, undef, $ref);
5960 } else {
5961 git_print_header_div('tree', esc_html($co{'title'}), $co{'tree'}, $hash, $ref);
5963 print "<div class=\"title_text\">\n" .
5964 "<table class=\"object_header\">\n";
5965 git_print_authorship_rows(\%co);
5966 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5967 print "<tr>" .
5968 "<td>tree</td>" .
5969 "<td class=\"sha1\">" .
5970 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5971 class => "list"}, $co{'tree'}) .
5972 "</td>" .
5973 "<td class=\"link\">" .
5974 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5975 "tree");
5976 my $snapshot_links = format_snapshot_links($hash);
5977 if (defined $snapshot_links) {
5978 print " | " . $snapshot_links;
5980 print "</td>" .
5981 "</tr>\n";
5983 foreach my $par (@$parents) {
5984 print "<tr>" .
5985 "<td>parent</td>" .
5986 "<td class=\"sha1\">" .
5987 $cgi->a({-href => href(action=>"commit", hash=>$par),
5988 class => "list"}, $par) .
5989 "</td>" .
5990 "<td class=\"link\">" .
5991 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5992 " | " .
5993 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5994 "</td>" .
5995 "</tr>\n";
5997 print "</table>".
5998 "</div>\n";
6000 print "<div class=\"page_body\">\n";
6001 git_print_log($co{'comment'});
6002 print "</div>\n";
6004 git_difftree_body(\@difftree, $hash, @$parents);
6006 git_footer_html();
6009 sub git_object {
6010 # object is defined by:
6011 # - hash or hash_base alone
6012 # - hash_base and file_name
6013 my $type;
6015 # - hash or hash_base alone
6016 if ($hash || ($hash_base && !defined $file_name)) {
6017 my $object_id = $hash || $hash_base;
6019 defined(my $fd = git_cmd_pipe 'cat-file', '-t', $object_id)
6020 or die_error(404, "Object does not exist");
6021 $type = <$fd>;
6022 chomp $type if $type;
6023 close $fd
6024 or die_error(404, "Object does not exist");
6026 # - hash_base and file_name
6027 } elsif ($hash_base && defined $file_name) {
6028 $file_name =~ s,/+$,,;
6030 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6031 or die_error(404, "Base object does not exist");
6033 # here errors should not hapen
6034 defined(my $fd = git_cmd_pipe "ls-tree", $hash_base, "--", $file_name)
6035 or die_error(500, "Open git-ls-tree failed");
6036 my $line = <$fd>;
6037 close $fd;
6039 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6040 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6041 die_error(404, "File or directory for given base does not exist");
6043 $type = $2;
6044 $hash = $3;
6045 } else {
6046 die_error(400, "Not enough information to find object");
6049 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6050 hash=>$hash, hash_base=>$hash_base,
6051 file_name=>$file_name),
6052 -status => '302 Found');
6055 sub git_blobdiff {
6056 my $format = shift || 'html';
6058 my $fd;
6059 my @difftree;
6060 my %diffinfo;
6061 my $expires;
6063 # preparing $fd and %diffinfo for git_patchset_body
6064 # new style URI
6065 if (defined $hash_base && defined $hash_parent_base) {
6066 if (defined $file_name) {
6067 # read raw output
6068 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
6069 $hash_parent_base, $hash_base,
6070 "--", (defined $file_parent ? $file_parent : ()), $file_name)
6071 or die_error(500, "Open git-diff-tree failed");
6072 @difftree = map { chomp; $_ } <$fd>;
6073 close $fd
6074 or die_error(404, "Reading git-diff-tree failed");
6075 @difftree
6076 or die_error(404, "Blob diff not found");
6078 } elsif (defined $hash &&
6079 $hash =~ /[0-9a-fA-F]{40}/) {
6080 # try to find filename from $hash
6082 # read filtered raw output
6083 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
6084 $hash_parent_base, $hash_base, "--")
6085 or die_error(500, "Open git-diff-tree failed");
6086 @difftree =
6087 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6088 # $hash == to_id
6089 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6090 map { chomp; $_ } <$fd>;
6091 close $fd
6092 or die_error(404, "Reading git-diff-tree failed");
6093 @difftree
6094 or die_error(404, "Blob diff not found");
6096 } else {
6097 die_error(400, "Missing one of the blob diff parameters");
6100 if (@difftree > 1) {
6101 die_error(400, "Ambiguous blob diff specification");
6104 %diffinfo = parse_difftree_raw_line($difftree[0]);
6105 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6106 $file_name ||= $diffinfo{'to_file'};
6108 $hash_parent ||= $diffinfo{'from_id'};
6109 $hash ||= $diffinfo{'to_id'};
6111 # non-textual hash id's can be cached
6112 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6113 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6114 $expires = '+1d';
6117 # open patch output
6118 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
6119 '-p', ($format eq 'html' ? "--full-index" : ()),
6120 $hash_parent_base, $hash_base,
6121 "--", (defined $file_parent ? $file_parent : ()), $file_name)
6122 or die_error(500, "Open git-diff-tree failed");
6125 # old/legacy style URI -- not generated anymore since 1.4.3.
6126 if (!%diffinfo) {
6127 die_error('404 Not Found', "Missing one of the blob diff parameters")
6130 # header
6131 if ($format eq 'html') {
6132 my $formats_nav =
6133 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6134 "raw");
6135 git_header_html(undef, $expires);
6136 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6137 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6138 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6139 } else {
6140 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6141 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
6143 if (defined $file_name) {
6144 git_print_page_path($file_name, "blob", $hash_base);
6145 } else {
6146 print "<div class=\"page_path\"></div>\n";
6149 } elsif ($format eq 'plain') {
6150 print $cgi->header(
6151 -type => 'text/plain',
6152 -charset => 'utf-8',
6153 -expires => $expires,
6154 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6156 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6158 } else {
6159 die_error(400, "Unknown blobdiff format");
6162 # patch
6163 if ($format eq 'html') {
6164 print "<div class=\"page_body\">\n";
6166 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6167 close $fd;
6169 print "</div>\n"; # class="page_body"
6170 git_footer_html();
6172 } else {
6173 while (my $line = <$fd>) {
6174 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6175 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6177 print $line;
6179 last if $line =~ m!^\+\+\+!;
6181 local $/ = undef;
6182 print <$fd>;
6183 close $fd;
6187 sub git_blobdiff_plain {
6188 git_blobdiff('plain');
6191 sub git_commitdiff {
6192 my %params = @_;
6193 my $format = $params{-format} || 'html';
6195 my ($patch_max) = gitweb_get_feature('patches');
6196 if ($format eq 'patch') {
6197 die_error(403, "Patch view not allowed") unless $patch_max;
6200 $hash ||= $hash_base || "HEAD";
6201 my %co = parse_commit($hash)
6202 or die_error(404, "Unknown commit object");
6204 # choose format for commitdiff for merge
6205 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6206 $hash_parent = '--cc';
6208 # we need to prepare $formats_nav before almost any parameter munging
6209 my $formats_nav;
6210 if ($format eq 'html') {
6211 $formats_nav =
6212 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6213 "raw");
6214 if ($patch_max && @{$co{'parents'}} <= 1) {
6215 $formats_nav .= " | " .
6216 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6217 "patch");
6220 if (defined $hash_parent &&
6221 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6222 # commitdiff with two commits given
6223 my $hash_parent_short = $hash_parent;
6224 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6225 $hash_parent_short = substr($hash_parent, 0, 7);
6227 $formats_nav .=
6228 ' (from';
6229 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6230 if ($co{'parents'}[$i] eq $hash_parent) {
6231 $formats_nav .= ' parent ' . ($i+1);
6232 last;
6235 $formats_nav .= ': ' .
6236 $cgi->a({-href => href(action=>"commitdiff",
6237 hash=>$hash_parent)},
6238 esc_html($hash_parent_short)) .
6239 ')';
6240 } elsif (!$co{'parent'}) {
6241 # --root commitdiff
6242 $formats_nav .= ' (initial)';
6243 } elsif (scalar @{$co{'parents'}} == 1) {
6244 # single parent commit
6245 $formats_nav .=
6246 ' (parent: ' .
6247 $cgi->a({-href => href(action=>"commitdiff",
6248 hash=>$co{'parent'})},
6249 esc_html(substr($co{'parent'}, 0, 7))) .
6250 ')';
6251 } else {
6252 # merge commit
6253 if ($hash_parent eq '--cc') {
6254 $formats_nav .= ' | ' .
6255 $cgi->a({-href => href(action=>"commitdiff",
6256 hash=>$hash, hash_parent=>'-c')},
6257 'combined');
6258 } else { # $hash_parent eq '-c'
6259 $formats_nav .= ' | ' .
6260 $cgi->a({-href => href(action=>"commitdiff",
6261 hash=>$hash, hash_parent=>'--cc')},
6262 'compact');
6264 $formats_nav .=
6265 ' (merge: ' .
6266 join(' ', map {
6267 $cgi->a({-href => href(action=>"commitdiff",
6268 hash=>$_)},
6269 esc_html(substr($_, 0, 7)));
6270 } @{$co{'parents'}} ) .
6271 ')';
6275 my $hash_parent_param = $hash_parent;
6276 if (!defined $hash_parent_param) {
6277 # --cc for multiple parents, --root for parentless
6278 $hash_parent_param =
6279 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6282 # read commitdiff
6283 my $fd;
6284 my @difftree;
6285 if ($format eq 'html') {
6286 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
6287 "--no-commit-id", "--patch-with-raw", "--full-index",
6288 $hash_parent_param, $hash, "--")
6289 or die_error(500, "Open git-diff-tree failed");
6291 while (my $line = <$fd>) {
6292 chomp $line;
6293 # empty line ends raw part of diff-tree output
6294 last unless $line;
6295 push @difftree, scalar parse_difftree_raw_line($line);
6298 } elsif ($format eq 'plain') {
6299 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
6300 '-p', $hash_parent_param, $hash, "--")
6301 or die_error(500, "Open git-diff-tree failed");
6302 } elsif ($format eq 'patch') {
6303 # For commit ranges, we limit the output to the number of
6304 # patches specified in the 'patches' feature.
6305 # For single commits, we limit the output to a single patch,
6306 # diverging from the git-format-patch default.
6307 my @commit_spec = ();
6308 if ($hash_parent) {
6309 if ($patch_max > 0) {
6310 push @commit_spec, "-$patch_max";
6312 push @commit_spec, '-n', "$hash_parent..$hash";
6313 } else {
6314 if ($params{-single}) {
6315 push @commit_spec, '-1';
6316 } else {
6317 if ($patch_max > 0) {
6318 push @commit_spec, "-$patch_max";
6320 push @commit_spec, "-n";
6322 push @commit_spec, '--root', $hash;
6324 defined($fd = git_cmd_pipe "format-patch", @diff_opts,
6325 '--encoding=utf8', '--stdout', @commit_spec)
6326 or die_error(500, "Open git-format-patch failed");
6327 } else {
6328 die_error(400, "Unknown commitdiff format");
6331 # non-textual hash id's can be cached
6332 my $expires;
6333 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6334 $expires = "+1d";
6337 # write commit message
6338 if ($format eq 'html') {
6339 my $refs = git_get_references();
6340 my $ref = format_ref_marker($refs, $co{'id'});
6342 git_header_html(undef, $expires);
6343 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6344 git_print_header_div('commit', esc_html($co{'title'}), $hash, undef, $ref);
6345 print "<div class=\"title_text\">\n" .
6346 "<table class=\"object_header\">\n";
6347 git_print_authorship_rows(\%co);
6348 print "</table>".
6349 "</div>\n";
6350 print "<div class=\"page_body\">\n";
6351 if (@{$co{'comment'}} > 1) {
6352 print "<div class=\"log\">\n";
6353 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6354 print "</div>\n"; # class="log"
6357 } elsif ($format eq 'plain') {
6358 my $refs = git_get_references("tags");
6359 my $tagname = git_get_rev_name_tags($hash);
6360 my $filename = basename($project) . "-$hash.patch";
6362 print $cgi->header(
6363 -type => 'text/plain',
6364 -charset => 'utf-8',
6365 -expires => $expires,
6366 -content_disposition => 'inline; filename="' . "$filename" . '"');
6367 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6368 print "From: " . to_utf8($co{'author'}) . "\n";
6369 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6370 print "Subject: " . to_utf8($co{'title'}) . "\n";
6372 print "X-Git-Tag: $tagname\n" if $tagname;
6373 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6375 foreach my $line (@{$co{'comment'}}) {
6376 print to_utf8($line) . "\n";
6378 print "---\n\n";
6379 } elsif ($format eq 'patch') {
6380 my $filename = basename($project) . "-$hash.patch";
6382 print $cgi->header(
6383 -type => 'text/plain',
6384 -charset => 'utf-8',
6385 -expires => $expires,
6386 -content_disposition => 'inline; filename="' . "$filename" . '"');
6389 # write patch
6390 if ($format eq 'html') {
6391 my $use_parents = !defined $hash_parent ||
6392 $hash_parent eq '-c' || $hash_parent eq '--cc';
6393 git_difftree_body(\@difftree, $hash,
6394 $use_parents ? @{$co{'parents'}} : $hash_parent);
6395 print "<br/>\n";
6397 git_patchset_body($fd, \@difftree, $hash,
6398 $use_parents ? @{$co{'parents'}} : $hash_parent);
6399 close $fd;
6400 print "</div>\n"; # class="page_body"
6401 git_footer_html();
6403 } elsif ($format eq 'plain') {
6404 local $/ = undef;
6405 print <$fd>;
6406 close $fd
6407 or print "Reading git-diff-tree failed\n";
6408 } elsif ($format eq 'patch') {
6409 local $/ = undef;
6410 print <$fd>;
6411 close $fd
6412 or print "Reading git-format-patch failed\n";
6416 sub git_commitdiff_plain {
6417 git_commitdiff(-format => 'plain');
6420 # format-patch-style patches
6421 sub git_patch {
6422 git_commitdiff(-format => 'patch', -single => 1);
6425 sub git_patches {
6426 git_commitdiff(-format => 'patch');
6429 sub git_history {
6430 if (!defined $hash_base) {
6431 $hash_base = git_get_head_hash($project);
6433 my $ftype;
6434 my %co = parse_commit($hash_base)
6435 or die_error(404, "Unknown commit object");
6437 my $refs = git_get_references();
6438 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
6440 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
6441 $file_name, "--full-history")
6442 or die_error(404, "No such file or directory on given branch");
6444 if (!defined $hash && defined $file_name) {
6445 # some commits could have deleted file in question,
6446 # and not have it in tree, but one of them has to have it
6447 for (my $i = 0; $i <= @commitlist; $i++) {
6448 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6449 last if defined $hash;
6452 if (defined $hash) {
6453 $ftype = git_get_type($hash);
6455 if (!defined $ftype) {
6456 die_error(500, "Unknown type of object");
6459 my $paging_nav = '';
6460 if ($page > 0) {
6461 $paging_nav .=
6462 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
6463 file_name=>$file_name)},
6464 "first");
6465 $paging_nav .= " &sdot; " .
6466 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6467 -accesskey => "p", -title => "Alt-p"}, "prev");
6468 } else {
6469 $paging_nav .= "first";
6470 $paging_nav .= " &sdot; prev";
6472 my $next_link = '';
6473 if ($#commitlist >= 100) {
6474 $next_link =
6475 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6476 -accesskey => "n", -title => "Alt-n"}, "next");
6477 $paging_nav .= " &sdot; $next_link";
6478 } else {
6479 $paging_nav .= " &sdot; next";
6482 git_header_html();
6483 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
6484 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6485 git_print_page_path($file_name, $ftype, $hash_base);
6487 git_history_body(\@commitlist, 0, 99,
6488 $refs, $hash_base, $ftype, $next_link);
6490 git_footer_html();
6493 sub git_search {
6494 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6495 if (!defined $searchtext) {
6496 die_error(400, "Text field is empty");
6498 if (!defined $hash) {
6499 $hash = git_get_head_hash($project);
6501 my %co = parse_commit($hash);
6502 if (!%co) {
6503 die_error(404, "Unknown commit object");
6506 $searchtype ||= 'commit';
6507 if ($searchtype eq 'pickaxe') {
6508 # pickaxe may take all resources of your box and run for several minutes
6509 # with every query - so decide by yourself how public you make this feature
6510 gitweb_check_feature('pickaxe')
6511 or die_error(403, "Pickaxe is disabled");
6513 if ($searchtype eq 'grep') {
6514 gitweb_check_feature('grep')
6515 or die_error(403, "Grep is disabled");
6518 git_header_html();
6520 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6521 my $greptype;
6522 if ($searchtype eq 'commit') {
6523 $greptype = "--grep=";
6524 } elsif ($searchtype eq 'author') {
6525 $greptype = "--author=";
6526 } elsif ($searchtype eq 'committer') {
6527 $greptype = "--committer=";
6529 $greptype .= $searchtext;
6530 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6531 $greptype, '--regexp-ignore-case',
6532 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6534 my $paging_nav = '';
6535 if ($page > 0) {
6536 $paging_nav .=
6537 $cgi->a({-href => href(action=>"search", hash=>$hash,
6538 searchtext=>$searchtext,
6539 searchtype=>$searchtype)},
6540 "first");
6541 $paging_nav .= " &sdot; " .
6542 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6543 -accesskey => "p", -title => "Alt-p"}, "prev");
6544 } else {
6545 $paging_nav .= "first";
6546 $paging_nav .= " &sdot; prev";
6548 my $next_link = '';
6549 if ($#commitlist >= 100) {
6550 $next_link =
6551 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6552 -accesskey => "n", -title => "Alt-n"}, "next");
6553 $paging_nav .= " &sdot; $next_link";
6554 } else {
6555 $paging_nav .= " &sdot; next";
6558 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6559 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6560 if ($page == 0 && !@commitlist) {
6561 print "<p>No match.</p>\n";
6562 } else {
6563 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6567 if ($searchtype eq 'pickaxe') {
6568 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6569 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6571 print "<table class=\"pickaxe search\">\n";
6572 my $alternate = 1;
6573 local $/ = "\n";
6574 my $fd = git_cmd_pipe '--no-pager', 'log', @diff_opts,
6575 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6576 ($search_use_regexp ? '--pickaxe-regex' : ());
6577 undef %co;
6578 my @files;
6579 while (my $line = <$fd>) {
6580 chomp $line;
6581 next unless $line;
6583 my %set = parse_difftree_raw_line($line);
6584 if (defined $set{'commit'}) {
6585 # finish previous commit
6586 if (%co) {
6587 print "</td>\n" .
6588 "<td class=\"link\">" .
6589 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6590 " | " .
6591 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6592 print "</td>\n" .
6593 "</tr>\n";
6596 if ($alternate) {
6597 print "<tr class=\"dark\">\n";
6598 } else {
6599 print "<tr class=\"light\">\n";
6601 $alternate ^= 1;
6602 %co = parse_commit($set{'commit'});
6603 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6604 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6605 "<td><i>$author</i></td>\n" .
6606 "<td>" .
6607 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6608 -class => "list subject"},
6609 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6610 } elsif (defined $set{'to_id'}) {
6611 next if ($set{'to_id'} =~ m/^0{40}$/);
6613 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6614 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6615 -class => "list"},
6616 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6617 "<br/>\n";
6620 close $fd;
6622 # finish last commit (warning: repetition!)
6623 if (%co) {
6624 print "</td>\n" .
6625 "<td class=\"link\">" .
6626 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6627 " | " .
6628 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6629 print "</td>\n" .
6630 "</tr>\n";
6633 print "</table>\n";
6636 if ($searchtype eq 'grep') {
6637 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6638 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6640 print "<table class=\"grep_search\">\n";
6641 my $alternate = 1;
6642 my $matches = 0;
6643 local $/ = "\n";
6644 my $fd = git_cmd_pipe 'grep', '-n',
6645 $search_use_regexp ? ('-E', '-i') : '-F',
6646 $searchtext, $co{'tree'};
6647 my $lastfile = '';
6648 while (my $line = <$fd>) {
6649 chomp $line;
6650 my ($file, $lno, $ltext, $binary);
6651 last if ($matches++ > 1000);
6652 if ($line =~ /^Binary file (.+) matches$/) {
6653 $file = $1;
6654 $binary = 1;
6655 } else {
6656 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6658 if ($file ne $lastfile) {
6659 $lastfile and print "</td></tr>\n";
6660 if ($alternate++) {
6661 print "<tr class=\"dark\">\n";
6662 } else {
6663 print "<tr class=\"light\">\n";
6665 print "<td class=\"list\">".
6666 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6667 file_name=>"$file"),
6668 -class => "list"}, esc_path($file));
6669 print "</td><td>\n";
6670 $lastfile = $file;
6672 if ($binary) {
6673 print "<div class=\"binary\">Binary file</div>\n";
6674 } else {
6675 $ltext = untabify($ltext);
6676 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6677 $ltext = esc_html($1, -nbsp=>1);
6678 $ltext .= '<span class="match">';
6679 $ltext .= esc_html($2, -nbsp=>1);
6680 $ltext .= '</span>';
6681 $ltext .= esc_html($3, -nbsp=>1);
6682 } else {
6683 $ltext = esc_html($ltext, -nbsp=>1);
6685 print "<div class=\"pre\">" .
6686 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6687 file_name=>"$file").'#l'.$lno,
6688 -class => "linenr"}, sprintf('%4i', $lno))
6689 . ' ' . $ltext . "</div>\n";
6692 if ($lastfile) {
6693 print "</td></tr>\n";
6694 if ($matches > 1000) {
6695 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6697 } else {
6698 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6700 close $fd;
6702 print "</table>\n";
6704 git_footer_html();
6707 sub git_search_help {
6708 git_header_html();
6709 git_print_page_nav('','', $hash,$hash,$hash);
6710 print <<EOT;
6711 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6712 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6713 the pattern entered is recognized as the POSIX extended
6714 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6715 insensitive).</p>
6716 <dl>
6717 <dt><b>commit</b></dt>
6718 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6720 my $have_grep = gitweb_check_feature('grep');
6721 if ($have_grep) {
6722 print <<EOT;
6723 <dt><b>grep</b></dt>
6724 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6725 a different one) are searched for the given pattern. On large trees, this search can take
6726 a while and put some strain on the server, so please use it with some consideration. Note that
6727 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6728 case-sensitive.</dd>
6731 print <<EOT;
6732 <dt><b>author</b></dt>
6733 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6734 <dt><b>committer</b></dt>
6735 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6737 my $have_pickaxe = gitweb_check_feature('pickaxe');
6738 if ($have_pickaxe) {
6739 print <<EOT;
6740 <dt><b>pickaxe</b></dt>
6741 <dd>All commits that caused the string to appear or disappear from any file (changes that
6742 added, removed or "modified" the string) will be listed. This search can take a while and
6743 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6744 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6747 print "</dl>\n";
6748 git_footer_html();
6751 sub git_shortlog {
6752 my $head = git_get_head_hash($project);
6753 if (!defined $hash) {
6754 $hash = $head;
6756 my $refs = git_get_references();
6758 my $commit_hash = $hash;
6759 if (defined $hash_parent) {
6760 $commit_hash = "$hash_parent..$hash";
6762 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6764 my $paging_nav = format_log_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6766 my $next_link = '';
6767 if ($#commitlist >= 100) {
6768 $next_link =
6769 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6770 -accesskey => "n", -title => "Alt-n"}, "next");
6772 my $patch_max = gitweb_check_feature('patches');
6773 if ($patch_max) {
6774 if ($patch_max < 0 || @commitlist <= $patch_max) {
6775 $paging_nav .= " &sdot; " .
6776 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6777 "patches");
6781 git_header_html();
6782 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6783 git_print_header_div('summary', $project);
6785 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6787 git_footer_html();
6790 ## ......................................................................
6791 ## feeds (RSS, Atom; OPML)
6793 sub git_feed {
6794 my $format = shift || 'atom';
6795 my $have_blame = gitweb_check_feature('blame');
6797 # Atom: http://www.atomenabled.org/developers/syndication/
6798 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6799 if ($format ne 'rss' && $format ne 'atom') {
6800 die_error(400, "Unknown web feed format");
6803 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6804 my $head = $hash || 'HEAD';
6805 my @commitlist = parse_commits($head, 150, 0, $file_name);
6807 my %latest_commit;
6808 my %latest_date;
6809 my $content_type = "application/$format+xml";
6810 if (defined $cgi->http('HTTP_ACCEPT') &&
6811 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6812 # browser (feed reader) prefers text/xml
6813 $content_type = 'text/xml';
6815 if (defined($commitlist[0])) {
6816 %latest_commit = %{$commitlist[0]};
6817 my $latest_epoch = $latest_commit{'committer_epoch'};
6818 %latest_date = parse_date($latest_epoch);
6819 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6820 if (defined $if_modified) {
6821 my $since;
6822 if (eval { require HTTP::Date; 1; }) {
6823 $since = HTTP::Date::str2time($if_modified);
6824 } elsif (eval { require Time::ParseDate; 1; }) {
6825 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6827 if (defined $since && $latest_epoch <= $since) {
6828 print $cgi->header(
6829 -type => $content_type,
6830 -charset => 'utf-8',
6831 -last_modified => $latest_date{'rfc2822'},
6832 -status => '304 Not Modified');
6833 return;
6836 print $cgi->header(
6837 -type => $content_type,
6838 -charset => 'utf-8',
6839 -last_modified => $latest_date{'rfc2822'});
6840 } else {
6841 print $cgi->header(
6842 -type => $content_type,
6843 -charset => 'utf-8');
6846 # Optimization: skip generating the body if client asks only
6847 # for Last-Modified date.
6848 return if ($cgi->request_method() eq 'HEAD');
6850 # header variables
6851 my $title = "$site_name - $project/$action";
6852 my $feed_type = 'log';
6853 if (defined $hash) {
6854 $title .= " - '$hash'";
6855 $feed_type = 'branch log';
6856 if (defined $file_name) {
6857 $title .= " :: $file_name";
6858 $feed_type = 'history';
6860 } elsif (defined $file_name) {
6861 $title .= " - $file_name";
6862 $feed_type = 'history';
6864 $title .= " $feed_type";
6865 my $descr = git_get_project_description($project);
6866 if (defined $descr) {
6867 $descr = esc_html($descr);
6868 } else {
6869 $descr = "$project " .
6870 ($format eq 'rss' ? 'RSS' : 'Atom') .
6871 " feed";
6873 my $owner = git_get_project_owner($project);
6874 $owner = esc_html($owner);
6876 #header
6877 my $alt_url;
6878 if (defined $file_name) {
6879 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6880 } elsif (defined $hash) {
6881 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6882 } else {
6883 $alt_url = href(-full=>1, action=>"summary");
6885 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6886 if ($format eq 'rss') {
6887 print <<XML;
6888 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6889 <channel>
6891 print "<title>$title</title>\n" .
6892 "<link>$alt_url</link>\n" .
6893 "<description>$descr</description>\n" .
6894 "<language>en</language>\n" .
6895 # project owner is responsible for 'editorial' content
6896 "<managingEditor>$owner</managingEditor>\n";
6897 if (defined $logo || defined $favicon) {
6898 # prefer the logo to the favicon, since RSS
6899 # doesn't allow both
6900 my $img = esc_url($logo || $favicon);
6901 print "<image>\n" .
6902 "<url>$img</url>\n" .
6903 "<title>$title</title>\n" .
6904 "<link>$alt_url</link>\n" .
6905 "</image>\n";
6907 if (%latest_date) {
6908 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6909 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6911 print "<generator>gitweb v.$version/$git_version</generator>\n";
6912 } elsif ($format eq 'atom') {
6913 print <<XML;
6914 <feed xmlns="http://www.w3.org/2005/Atom">
6916 print "<title>$title</title>\n" .
6917 "<subtitle>$descr</subtitle>\n" .
6918 '<link rel="alternate" type="text/html" href="' .
6919 $alt_url . '" />' . "\n" .
6920 '<link rel="self" type="' . $content_type . '" href="' .
6921 $cgi->self_url() . '" />' . "\n" .
6922 "<id>" . href(-full=>1) . "</id>\n" .
6923 # use project owner for feed author
6924 '<author><name>'. email_obfuscate($owner) . '</name></author>\n';
6925 if (defined $favicon) {
6926 print "<icon>" . esc_url($favicon) . "</icon>\n";
6928 if (defined $logo_url) {
6929 # not twice as wide as tall: 72 x 27 pixels
6930 print "<logo>" . esc_url($logo) . "</logo>\n";
6932 if (! %latest_date) {
6933 # dummy date to keep the feed valid until commits trickle in:
6934 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6935 } else {
6936 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6938 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6941 # contents
6942 for (my $i = 0; $i <= $#commitlist; $i++) {
6943 my %co = %{$commitlist[$i]};
6944 my $commit = $co{'id'};
6945 # we read 150, we always show 30 and the ones more recent than 48 hours
6946 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6947 last;
6949 my %cd = parse_date($co{'author_epoch'});
6951 # get list of changed files
6952 defined(my $fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
6953 $co{'parent'} || "--root",
6954 $co{'id'}, "--", (defined $file_name ? $file_name : ()))
6955 or next;
6956 my @difftree = map { chomp; $_ } <$fd>;
6957 close $fd
6958 or next;
6960 # print element (entry, item)
6961 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6962 if ($format eq 'rss') {
6963 print "<item>\n" .
6964 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6965 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6966 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6967 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6968 "<link>$co_url</link>\n" .
6969 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6970 "<content:encoded>" .
6971 "<![CDATA[\n";
6972 } elsif ($format eq 'atom') {
6973 print "<entry>\n" .
6974 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6975 "<updated>$cd{'iso-8601'}</updated>\n" .
6976 "<author>\n" .
6977 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6978 if ($co{'author_email'}) {
6979 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6981 print "</author>\n" .
6982 # use committer for contributor
6983 "<contributor>\n" .
6984 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6985 if ($co{'committer_email'}) {
6986 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6988 print "</contributor>\n" .
6989 "<published>$cd{'iso-8601'}</published>\n" .
6990 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6991 "<id>$co_url</id>\n" .
6992 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6993 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6995 my $comment = $co{'comment'};
6996 print "<pre>\n";
6997 foreach my $line (@$comment) {
6998 $line = esc_html($line);
6999 print "$line\n";
7001 print "</pre><ul>\n";
7002 foreach my $difftree_line (@difftree) {
7003 my %difftree = parse_difftree_raw_line($difftree_line);
7004 next if !$difftree{'from_id'};
7006 my $file = $difftree{'file'} || $difftree{'to_file'};
7008 print "<li>" .
7009 "[" .
7010 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7011 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7012 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7013 file_name=>$file, file_parent=>$difftree{'from_file'}),
7014 -title => "diff"}, 'D');
7015 if ($have_blame) {
7016 print $cgi->a({-href => href(-full=>1, action=>"blame",
7017 file_name=>$file, hash_base=>$commit), -class => "blamelink",
7018 -title => "blame"}, 'B');
7020 # if this is not a feed of a file history
7021 if (!defined $file_name || $file_name ne $file) {
7022 print $cgi->a({-href => href(-full=>1, action=>"history",
7023 file_name=>$file, hash=>$commit),
7024 -title => "history"}, 'H');
7026 $file = esc_path($file);
7027 print "] ".
7028 "$file</li>\n";
7030 if ($format eq 'rss') {
7031 print "</ul>]]>\n" .
7032 "</content:encoded>\n" .
7033 "</item>\n";
7034 } elsif ($format eq 'atom') {
7035 print "</ul>\n</div>\n" .
7036 "</content>\n" .
7037 "</entry>\n";
7041 # end of feed
7042 if ($format eq 'rss') {
7043 print "</channel>\n</rss>\n";
7044 } elsif ($format eq 'atom') {
7045 print "</feed>\n";
7049 sub git_rss {
7050 git_feed('rss');
7053 sub git_atom {
7054 git_feed('atom');
7057 sub git_opml {
7058 my @list = git_get_projects_list();
7060 print $cgi->header(
7061 -type => 'text/xml',
7062 -charset => 'utf-8',
7063 -content_disposition => 'inline; filename="opml.xml"');
7065 print <<XML;
7066 <?xml version="1.0" encoding="utf-8"?>
7067 <opml version="1.0">
7068 <head>
7069 <title>$site_name OPML Export</title>
7070 </head>
7071 <body>
7072 <outline text="git RSS feeds">
7075 foreach my $pr (@list) {
7076 my %proj = %$pr;
7077 my $head = git_get_head_hash($proj{'path'});
7078 if (!defined $head) {
7079 next;
7081 $git_dir = "$projectroot/$proj{'path'}";
7082 my %co = parse_commit($head);
7083 if (!%co) {
7084 next;
7087 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7088 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7089 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7090 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7092 print <<XML;
7093 </outline>
7094 </body>
7095 </opml>