Merge branch 'jn/gitweb-fastcgi' into next
[git/dscho.git] / gitweb / gitweb.perl
blob1ce3ed6da1bd6d980a440fed0101ae8bf5c39be0
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use strict;
11 use warnings;
12 use CGI qw(:standard :escapeHTML -nosticky);
13 use CGI::Util qw(unescape);
14 use CGI::Carp qw(fatalsToBrowser set_message);
15 use Encode;
16 use Fcntl ':mode';
17 use File::Find qw();
18 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
21 our $t0;
22 if (eval { require Time::HiRes; 1; }) {
23 $t0 = [Time::HiRes::gettimeofday()];
25 our $number_of_git_cmds = 0;
27 BEGIN {
28 CGI->compile() if $ENV{'MOD_PERL'};
31 our $version = "++GIT_VERSION++";
33 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
34 sub evaluate_uri {
35 our $cgi;
37 our $my_url = $cgi->url();
38 our $my_uri = $cgi->url(-absolute => 1);
40 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
41 # needed and used only for URLs with nonempty PATH_INFO
42 our $base_url = $my_url;
44 # When the script is used as DirectoryIndex, the URL does not contain the name
45 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
46 # have to do it ourselves. We make $path_info global because it's also used
47 # later on.
49 # Another issue with the script being the DirectoryIndex is that the resulting
50 # $my_url data is not the full script URL: this is good, because we want
51 # generated links to keep implying the script name if it wasn't explicitly
52 # indicated in the URL we're handling, but it means that $my_url cannot be used
53 # as base URL.
54 # Therefore, if we needed to strip PATH_INFO, then we know that we have
55 # to build the base URL ourselves:
56 our $path_info = $ENV{"PATH_INFO"};
57 if ($path_info) {
58 if ($my_url =~ s,\Q$path_info\E$,, &&
59 $my_uri =~ s,\Q$path_info\E$,, &&
60 defined $ENV{'SCRIPT_NAME'}) {
61 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
65 # target of the home link on top of all pages
66 our $home_link = $my_uri || "/";
69 # core git executable to use
70 # this can just be "git" if your webserver has a sensible PATH
71 our $GIT = "++GIT_BINDIR++/git";
73 # absolute fs-path which will be prepended to the project path
74 #our $projectroot = "/pub/scm";
75 our $projectroot = "++GITWEB_PROJECTROOT++";
77 # fs traversing limit for getting project list
78 # the number is relative to the projectroot
79 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
81 # string of the home link on top of all pages
82 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
84 # name of your site or organization to appear in page titles
85 # replace this with something more descriptive for clearer bookmarks
86 our $site_name = "++GITWEB_SITENAME++"
87 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
89 # filename of html text to include at top of each page
90 our $site_header = "++GITWEB_SITE_HEADER++";
91 # html text to include at home page
92 our $home_text = "++GITWEB_HOMETEXT++";
93 # filename of html text to include at bottom of each page
94 our $site_footer = "++GITWEB_SITE_FOOTER++";
96 # URI of stylesheets
97 our @stylesheets = ("++GITWEB_CSS++");
98 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
99 our $stylesheet = undef;
100 # URI of GIT logo (72x27 size)
101 our $logo = "++GITWEB_LOGO++";
102 # URI of GIT favicon, assumed to be image/png type
103 our $favicon = "++GITWEB_FAVICON++";
104 # URI of gitweb.js (JavaScript code for gitweb)
105 our $javascript = "++GITWEB_JS++";
107 # URI and label (title) of GIT logo link
108 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
109 #our $logo_label = "git documentation";
110 our $logo_url = "http://git-scm.com/";
111 our $logo_label = "git homepage";
113 # source of projects list
114 our $projects_list = "++GITWEB_LIST++";
116 # the width (in characters) of the projects list "Description" column
117 our $projects_list_description_width = 25;
119 # default order of projects list
120 # valid values are none, project, descr, owner, and age
121 our $default_projects_order = "project";
123 # show repository only if this file exists
124 # (only effective if this variable evaluates to true)
125 our $export_ok = "++GITWEB_EXPORT_OK++";
127 # show repository only if this subroutine returns true
128 # when given the path to the project, for example:
129 # sub { return -e "$_[0]/git-daemon-export-ok"; }
130 our $export_auth_hook = undef;
132 # only allow viewing of repositories also shown on the overview page
133 our $strict_export = "++GITWEB_STRICT_EXPORT++";
135 # list of git base URLs used for URL to where fetch project from,
136 # i.e. full URL is "$git_base_url/$project"
137 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
139 # default blob_plain mimetype and default charset for text/plain blob
140 our $default_blob_plain_mimetype = 'text/plain';
141 our $default_text_plain_charset = undef;
143 # file to use for guessing MIME types before trying /etc/mime.types
144 # (relative to the current git repository)
145 our $mimetypes_file = undef;
147 # assume this charset if line contains non-UTF-8 characters;
148 # it should be valid encoding (see Encoding::Supported(3pm) for list),
149 # for which encoding all byte sequences are valid, for example
150 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
151 # could be even 'utf-8' for the old behavior)
152 our $fallback_encoding = 'latin1';
154 # rename detection options for git-diff and git-diff-tree
155 # - default is '-M', with the cost proportional to
156 # (number of removed files) * (number of new files).
157 # - more costly is '-C' (which implies '-M'), with the cost proportional to
158 # (number of changed files + number of removed files) * (number of new files)
159 # - even more costly is '-C', '--find-copies-harder' with cost
160 # (number of files in the original tree) * (number of new files)
161 # - one might want to include '-B' option, e.g. '-B', '-M'
162 our @diff_opts = ('-M'); # taken from git_commit
164 # Disables features that would allow repository owners to inject script into
165 # the gitweb domain.
166 our $prevent_xss = 0;
168 # information about snapshot formats that gitweb is capable of serving
169 our %known_snapshot_formats = (
170 # name => {
171 # 'display' => display name,
172 # 'type' => mime type,
173 # 'suffix' => filename suffix,
174 # 'format' => --format for git-archive,
175 # 'compressor' => [compressor command and arguments]
176 # (array reference, optional)
177 # 'disabled' => boolean (optional)}
179 'tgz' => {
180 'display' => 'tar.gz',
181 'type' => 'application/x-gzip',
182 'suffix' => '.tar.gz',
183 'format' => 'tar',
184 'compressor' => ['gzip']},
186 'tbz2' => {
187 'display' => 'tar.bz2',
188 'type' => 'application/x-bzip2',
189 'suffix' => '.tar.bz2',
190 'format' => 'tar',
191 'compressor' => ['bzip2']},
193 'txz' => {
194 'display' => 'tar.xz',
195 'type' => 'application/x-xz',
196 'suffix' => '.tar.xz',
197 'format' => 'tar',
198 'compressor' => ['xz'],
199 'disabled' => 1},
201 'zip' => {
202 'display' => 'zip',
203 'type' => 'application/x-zip',
204 'suffix' => '.zip',
205 'format' => 'zip'},
208 # Aliases so we understand old gitweb.snapshot values in repository
209 # configuration.
210 our %known_snapshot_format_aliases = (
211 'gzip' => 'tgz',
212 'bzip2' => 'tbz2',
213 'xz' => 'txz',
215 # backward compatibility: legacy gitweb config support
216 'x-gzip' => undef, 'gz' => undef,
217 'x-bzip2' => undef, 'bz2' => undef,
218 'x-zip' => undef, '' => undef,
221 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
222 # are changed, it may be appropriate to change these values too via
223 # $GITWEB_CONFIG.
224 our %avatar_size = (
225 'default' => 16,
226 'double' => 32
229 # Used to set the maximum load that we will still respond to gitweb queries.
230 # If server load exceed this value then return "503 server busy" error.
231 # If gitweb cannot determined server load, it is taken to be 0.
232 # Leave it undefined (or set to 'undef') to turn off load checking.
233 our $maxload = 300;
235 # You define site-wide feature defaults here; override them with
236 # $GITWEB_CONFIG as necessary.
237 our %feature = (
238 # feature => {
239 # 'sub' => feature-sub (subroutine),
240 # 'override' => allow-override (boolean),
241 # 'default' => [ default options...] (array reference)}
243 # if feature is overridable (it means that allow-override has true value),
244 # then feature-sub will be called with default options as parameters;
245 # return value of feature-sub indicates if to enable specified feature
247 # if there is no 'sub' key (no feature-sub), then feature cannot be
248 # overriden
250 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
251 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
252 # is enabled
254 # Enable the 'blame' blob view, showing the last commit that modified
255 # each line in the file. This can be very CPU-intensive.
257 # To enable system wide have in $GITWEB_CONFIG
258 # $feature{'blame'}{'default'} = [1];
259 # To have project specific config enable override in $GITWEB_CONFIG
260 # $feature{'blame'}{'override'} = 1;
261 # and in project config gitweb.blame = 0|1;
262 'blame' => {
263 'sub' => sub { feature_bool('blame', @_) },
264 'override' => 0,
265 'default' => [0]},
267 # Enable the 'snapshot' link, providing a compressed archive of any
268 # tree. This can potentially generate high traffic if you have large
269 # project.
271 # Value is a list of formats defined in %known_snapshot_formats that
272 # you wish to offer.
273 # To disable system wide have in $GITWEB_CONFIG
274 # $feature{'snapshot'}{'default'} = [];
275 # To have project specific config enable override in $GITWEB_CONFIG
276 # $feature{'snapshot'}{'override'} = 1;
277 # and in project config, a comma-separated list of formats or "none"
278 # to disable. Example: gitweb.snapshot = tbz2,zip;
279 'snapshot' => {
280 'sub' => \&feature_snapshot,
281 'override' => 0,
282 'default' => ['tgz']},
284 # Enable text search, which will list the commits which match author,
285 # committer or commit text to a given string. Enabled by default.
286 # Project specific override is not supported.
287 'search' => {
288 'override' => 0,
289 'default' => [1]},
291 # Enable grep search, which will list the files in currently selected
292 # tree containing the given string. Enabled by default. This can be
293 # potentially CPU-intensive, of course.
295 # To enable system wide have in $GITWEB_CONFIG
296 # $feature{'grep'}{'default'} = [1];
297 # To have project specific config enable override in $GITWEB_CONFIG
298 # $feature{'grep'}{'override'} = 1;
299 # and in project config gitweb.grep = 0|1;
300 'grep' => {
301 'sub' => sub { feature_bool('grep', @_) },
302 'override' => 0,
303 'default' => [1]},
305 # Enable the pickaxe search, which will list the commits that modified
306 # a given string in a file. This can be practical and quite faster
307 # alternative to 'blame', but still potentially CPU-intensive.
309 # To enable system wide have in $GITWEB_CONFIG
310 # $feature{'pickaxe'}{'default'} = [1];
311 # To have project specific config enable override in $GITWEB_CONFIG
312 # $feature{'pickaxe'}{'override'} = 1;
313 # and in project config gitweb.pickaxe = 0|1;
314 'pickaxe' => {
315 'sub' => sub { feature_bool('pickaxe', @_) },
316 'override' => 0,
317 'default' => [1]},
319 # Enable showing size of blobs in a 'tree' view, in a separate
320 # column, similar to what 'ls -l' does. This cost a bit of IO.
322 # To disable system wide have in $GITWEB_CONFIG
323 # $feature{'show-sizes'}{'default'} = [0];
324 # To have project specific config enable override in $GITWEB_CONFIG
325 # $feature{'show-sizes'}{'override'} = 1;
326 # and in project config gitweb.showsizes = 0|1;
327 'show-sizes' => {
328 'sub' => sub { feature_bool('showsizes', @_) },
329 'override' => 0,
330 'default' => [1]},
332 # Make gitweb use an alternative format of the URLs which can be
333 # more readable and natural-looking: project name is embedded
334 # directly in the path and the query string contains other
335 # auxiliary information. All gitweb installations recognize
336 # URL in either format; this configures in which formats gitweb
337 # generates links.
339 # To enable system wide have in $GITWEB_CONFIG
340 # $feature{'pathinfo'}{'default'} = [1];
341 # Project specific override is not supported.
343 # Note that you will need to change the default location of CSS,
344 # favicon, logo and possibly other files to an absolute URL. Also,
345 # if gitweb.cgi serves as your indexfile, you will need to force
346 # $my_uri to contain the script name in your $GITWEB_CONFIG.
347 'pathinfo' => {
348 'override' => 0,
349 'default' => [0]},
351 # Make gitweb consider projects in project root subdirectories
352 # to be forks of existing projects. Given project $projname.git,
353 # projects matching $projname/*.git will not be shown in the main
354 # projects list, instead a '+' mark will be added to $projname
355 # there and a 'forks' view will be enabled for the project, listing
356 # all the forks. If project list is taken from a file, forks have
357 # to be listed after the main project.
359 # To enable system wide have in $GITWEB_CONFIG
360 # $feature{'forks'}{'default'} = [1];
361 # Project specific override is not supported.
362 'forks' => {
363 'override' => 0,
364 'default' => [0]},
366 # Insert custom links to the action bar of all project pages.
367 # This enables you mainly to link to third-party scripts integrating
368 # into gitweb; e.g. git-browser for graphical history representation
369 # or custom web-based repository administration interface.
371 # The 'default' value consists of a list of triplets in the form
372 # (label, link, position) where position is the label after which
373 # to insert the link and link is a format string where %n expands
374 # to the project name, %f to the project path within the filesystem,
375 # %h to the current hash (h gitweb parameter) and %b to the current
376 # hash base (hb gitweb parameter); %% expands to %.
378 # To enable system wide have in $GITWEB_CONFIG e.g.
379 # $feature{'actions'}{'default'} = [('graphiclog',
380 # '/git-browser/by-commit.html?r=%n', 'summary')];
381 # Project specific override is not supported.
382 'actions' => {
383 'override' => 0,
384 'default' => []},
386 # Allow gitweb scan project content tags described in ctags/
387 # of project repository, and display the popular Web 2.0-ish
388 # "tag cloud" near the project list. Note that this is something
389 # COMPLETELY different from the normal Git tags.
391 # gitweb by itself can show existing tags, but it does not handle
392 # tagging itself; you need an external application for that.
393 # For an example script, check Girocco's cgi/tagproj.cgi.
394 # You may want to install the HTML::TagCloud Perl module to get
395 # a pretty tag cloud instead of just a list of tags.
397 # To enable system wide have in $GITWEB_CONFIG
398 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
399 # Project specific override is not supported.
400 'ctags' => {
401 'override' => 0,
402 'default' => [0]},
404 # The maximum number of patches in a patchset generated in patch
405 # view. Set this to 0 or undef to disable patch view, or to a
406 # negative number to remove any limit.
408 # To disable system wide have in $GITWEB_CONFIG
409 # $feature{'patches'}{'default'} = [0];
410 # To have project specific config enable override in $GITWEB_CONFIG
411 # $feature{'patches'}{'override'} = 1;
412 # and in project config gitweb.patches = 0|n;
413 # where n is the maximum number of patches allowed in a patchset.
414 'patches' => {
415 'sub' => \&feature_patches,
416 'override' => 0,
417 'default' => [16]},
419 # Avatar support. When this feature is enabled, views such as
420 # shortlog or commit will display an avatar associated with
421 # the email of the committer(s) and/or author(s).
423 # Currently available providers are gravatar and picon.
424 # If an unknown provider is specified, the feature is disabled.
426 # Gravatar depends on Digest::MD5.
427 # Picon currently relies on the indiana.edu database.
429 # To enable system wide have in $GITWEB_CONFIG
430 # $feature{'avatar'}{'default'} = ['<provider>'];
431 # where <provider> is either gravatar or picon.
432 # To have project specific config enable override in $GITWEB_CONFIG
433 # $feature{'avatar'}{'override'} = 1;
434 # and in project config gitweb.avatar = <provider>;
435 'avatar' => {
436 'sub' => \&feature_avatar,
437 'override' => 0,
438 'default' => ['']},
440 # Enable displaying how much time and how many git commands
441 # it took to generate and display page. Disabled by default.
442 # Project specific override is not supported.
443 'timed' => {
444 'override' => 0,
445 'default' => [0]},
447 # Enable turning some links into links to actions which require
448 # JavaScript to run (like 'blame_incremental'). Not enabled by
449 # default. Project specific override is currently not supported.
450 'javascript-actions' => {
451 'override' => 0,
452 'default' => [0]},
455 sub gitweb_get_feature {
456 my ($name) = @_;
457 return unless exists $feature{$name};
458 my ($sub, $override, @defaults) = (
459 $feature{$name}{'sub'},
460 $feature{$name}{'override'},
461 @{$feature{$name}{'default'}});
462 # project specific override is possible only if we have project
463 our $git_dir; # global variable, declared later
464 if (!$override || !defined $git_dir) {
465 return @defaults;
467 if (!defined $sub) {
468 warn "feature $name is not overridable";
469 return @defaults;
471 return $sub->(@defaults);
474 # A wrapper to check if a given feature is enabled.
475 # With this, you can say
477 # my $bool_feat = gitweb_check_feature('bool_feat');
478 # gitweb_check_feature('bool_feat') or somecode;
480 # instead of
482 # my ($bool_feat) = gitweb_get_feature('bool_feat');
483 # (gitweb_get_feature('bool_feat'))[0] or somecode;
485 sub gitweb_check_feature {
486 return (gitweb_get_feature(@_))[0];
490 sub feature_bool {
491 my $key = shift;
492 my ($val) = git_get_project_config($key, '--bool');
494 if (!defined $val) {
495 return ($_[0]);
496 } elsif ($val eq 'true') {
497 return (1);
498 } elsif ($val eq 'false') {
499 return (0);
503 sub feature_snapshot {
504 my (@fmts) = @_;
506 my ($val) = git_get_project_config('snapshot');
508 if ($val) {
509 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
512 return @fmts;
515 sub feature_patches {
516 my @val = (git_get_project_config('patches', '--int'));
518 if (@val) {
519 return @val;
522 return ($_[0]);
525 sub feature_avatar {
526 my @val = (git_get_project_config('avatar'));
528 return @val ? @val : @_;
531 # checking HEAD file with -e is fragile if the repository was
532 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
533 # and then pruned.
534 sub check_head_link {
535 my ($dir) = @_;
536 my $headfile = "$dir/HEAD";
537 return ((-e $headfile) ||
538 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
541 sub check_export_ok {
542 my ($dir) = @_;
543 return (check_head_link($dir) &&
544 (!$export_ok || -e "$dir/$export_ok") &&
545 (!$export_auth_hook || $export_auth_hook->($dir)));
548 # process alternate names for backward compatibility
549 # filter out unsupported (unknown) snapshot formats
550 sub filter_snapshot_fmts {
551 my @fmts = @_;
553 @fmts = map {
554 exists $known_snapshot_format_aliases{$_} ?
555 $known_snapshot_format_aliases{$_} : $_} @fmts;
556 @fmts = grep {
557 exists $known_snapshot_formats{$_} &&
558 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
561 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
562 sub evaluate_gitweb_config {
563 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
564 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
565 # die if there are errors parsing config file
566 if (-e $GITWEB_CONFIG) {
567 do $GITWEB_CONFIG;
568 die $@ if $@;
569 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
570 do $GITWEB_CONFIG_SYSTEM;
571 die $@ if $@;
575 # Get loadavg of system, to compare against $maxload.
576 # Currently it requires '/proc/loadavg' present to get loadavg;
577 # if it is not present it returns 0, which means no load checking.
578 sub get_loadavg {
579 if( -e '/proc/loadavg' ){
580 open my $fd, '<', '/proc/loadavg'
581 or return 0;
582 my @load = split(/\s+/, scalar <$fd>);
583 close $fd;
585 # The first three columns measure CPU and IO utilization of the last one,
586 # five, and 10 minute periods. The fourth column shows the number of
587 # currently running processes and the total number of processes in the m/n
588 # format. The last column displays the last process ID used.
589 return $load[0] || 0;
591 # additional checks for load average should go here for things that don't export
592 # /proc/loadavg
594 return 0;
597 # version of the core git binary
598 our $git_version;
599 sub evaluate_git_version {
600 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
601 $number_of_git_cmds++;
604 sub check_loadavg {
605 if (defined $maxload && get_loadavg() > $maxload) {
606 die_error(503, "The load average on the server is too high");
610 # ======================================================================
611 # input validation and dispatch
613 # input parameters can be collected from a variety of sources (presently, CGI
614 # and PATH_INFO), so we define an %input_params hash that collects them all
615 # together during validation: this allows subsequent uses (e.g. href()) to be
616 # agnostic of the parameter origin
618 our %input_params = ();
620 # input parameters are stored with the long parameter name as key. This will
621 # also be used in the href subroutine to convert parameters to their CGI
622 # equivalent, and since the href() usage is the most frequent one, we store
623 # the name -> CGI key mapping here, instead of the reverse.
625 # XXX: Warning: If you touch this, check the search form for updating,
626 # too.
628 our @cgi_param_mapping = (
629 project => "p",
630 action => "a",
631 file_name => "f",
632 file_parent => "fp",
633 hash => "h",
634 hash_parent => "hp",
635 hash_base => "hb",
636 hash_parent_base => "hpb",
637 page => "pg",
638 order => "o",
639 searchtext => "s",
640 searchtype => "st",
641 snapshot_format => "sf",
642 extra_options => "opt",
643 search_use_regexp => "sr",
644 # this must be last entry (for manipulation from JavaScript)
645 javascript => "js"
647 our %cgi_param_mapping = @cgi_param_mapping;
649 # we will also need to know the possible actions, for validation
650 our %actions = (
651 "blame" => \&git_blame,
652 "blame_incremental" => \&git_blame_incremental,
653 "blame_data" => \&git_blame_data,
654 "blobdiff" => \&git_blobdiff,
655 "blobdiff_plain" => \&git_blobdiff_plain,
656 "blob" => \&git_blob,
657 "blob_plain" => \&git_blob_plain,
658 "commitdiff" => \&git_commitdiff,
659 "commitdiff_plain" => \&git_commitdiff_plain,
660 "commit" => \&git_commit,
661 "forks" => \&git_forks,
662 "heads" => \&git_heads,
663 "history" => \&git_history,
664 "log" => \&git_log,
665 "patch" => \&git_patch,
666 "patches" => \&git_patches,
667 "rss" => \&git_rss,
668 "atom" => \&git_atom,
669 "search" => \&git_search,
670 "search_help" => \&git_search_help,
671 "shortlog" => \&git_shortlog,
672 "summary" => \&git_summary,
673 "tag" => \&git_tag,
674 "tags" => \&git_tags,
675 "tree" => \&git_tree,
676 "snapshot" => \&git_snapshot,
677 "object" => \&git_object,
678 # those below don't need $project
679 "opml" => \&git_opml,
680 "project_list" => \&git_project_list,
681 "project_index" => \&git_project_index,
684 # finally, we have the hash of allowed extra_options for the commands that
685 # allow them
686 our %allowed_options = (
687 "--no-merges" => [ qw(rss atom log shortlog history) ],
690 # fill %input_params with the CGI parameters. All values except for 'opt'
691 # should be single values, but opt can be an array. We should probably
692 # build an array of parameters that can be multi-valued, but since for the time
693 # being it's only this one, we just single it out
694 sub evaluate_query_params {
695 our $cgi;
697 while (my ($name, $symbol) = each %cgi_param_mapping) {
698 if ($symbol eq 'opt') {
699 $input_params{$name} = [ $cgi->param($symbol) ];
700 } else {
701 $input_params{$name} = $cgi->param($symbol);
706 # now read PATH_INFO and update the parameter list for missing parameters
707 sub evaluate_path_info {
708 return if defined $input_params{'project'};
709 return if !$path_info;
710 $path_info =~ s,^/+,,;
711 return if !$path_info;
713 # find which part of PATH_INFO is project
714 my $project = $path_info;
715 $project =~ s,/+$,,;
716 while ($project && !check_head_link("$projectroot/$project")) {
717 $project =~ s,/*[^/]*$,,;
719 return unless $project;
720 $input_params{'project'} = $project;
722 # do not change any parameters if an action is given using the query string
723 return if $input_params{'action'};
724 $path_info =~ s,^\Q$project\E/*,,;
726 # next, check if we have an action
727 my $action = $path_info;
728 $action =~ s,/.*$,,;
729 if (exists $actions{$action}) {
730 $path_info =~ s,^$action/*,,;
731 $input_params{'action'} = $action;
734 # list of actions that want hash_base instead of hash, but can have no
735 # pathname (f) parameter
736 my @wants_base = (
737 'tree',
738 'history',
741 # we want to catch
742 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
743 my ($parentrefname, $parentpathname, $refname, $pathname) =
744 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
746 # first, analyze the 'current' part
747 if (defined $pathname) {
748 # we got "branch:filename" or "branch:dir/"
749 # we could use git_get_type(branch:pathname), but:
750 # - it needs $git_dir
751 # - it does a git() call
752 # - the convention of terminating directories with a slash
753 # makes it superfluous
754 # - embedding the action in the PATH_INFO would make it even
755 # more superfluous
756 $pathname =~ s,^/+,,;
757 if (!$pathname || substr($pathname, -1) eq "/") {
758 $input_params{'action'} ||= "tree";
759 $pathname =~ s,/$,,;
760 } else {
761 # the default action depends on whether we had parent info
762 # or not
763 if ($parentrefname) {
764 $input_params{'action'} ||= "blobdiff_plain";
765 } else {
766 $input_params{'action'} ||= "blob_plain";
769 $input_params{'hash_base'} ||= $refname;
770 $input_params{'file_name'} ||= $pathname;
771 } elsif (defined $refname) {
772 # we got "branch". In this case we have to choose if we have to
773 # set hash or hash_base.
775 # Most of the actions without a pathname only want hash to be
776 # set, except for the ones specified in @wants_base that want
777 # hash_base instead. It should also be noted that hand-crafted
778 # links having 'history' as an action and no pathname or hash
779 # set will fail, but that happens regardless of PATH_INFO.
780 $input_params{'action'} ||= "shortlog";
781 if (grep { $_ eq $input_params{'action'} } @wants_base) {
782 $input_params{'hash_base'} ||= $refname;
783 } else {
784 $input_params{'hash'} ||= $refname;
788 # next, handle the 'parent' part, if present
789 if (defined $parentrefname) {
790 # a missing pathspec defaults to the 'current' filename, allowing e.g.
791 # someproject/blobdiff/oldrev..newrev:/filename
792 if ($parentpathname) {
793 $parentpathname =~ s,^/+,,;
794 $parentpathname =~ s,/$,,;
795 $input_params{'file_parent'} ||= $parentpathname;
796 } else {
797 $input_params{'file_parent'} ||= $input_params{'file_name'};
799 # we assume that hash_parent_base is wanted if a path was specified,
800 # or if the action wants hash_base instead of hash
801 if (defined $input_params{'file_parent'} ||
802 grep { $_ eq $input_params{'action'} } @wants_base) {
803 $input_params{'hash_parent_base'} ||= $parentrefname;
804 } else {
805 $input_params{'hash_parent'} ||= $parentrefname;
809 # for the snapshot action, we allow URLs in the form
810 # $project/snapshot/$hash.ext
811 # where .ext determines the snapshot and gets removed from the
812 # passed $refname to provide the $hash.
814 # To be able to tell that $refname includes the format extension, we
815 # require the following two conditions to be satisfied:
816 # - the hash input parameter MUST have been set from the $refname part
817 # of the URL (i.e. they must be equal)
818 # - the snapshot format MUST NOT have been defined already (e.g. from
819 # CGI parameter sf)
820 # It's also useless to try any matching unless $refname has a dot,
821 # so we check for that too
822 if (defined $input_params{'action'} &&
823 $input_params{'action'} eq 'snapshot' &&
824 defined $refname && index($refname, '.') != -1 &&
825 $refname eq $input_params{'hash'} &&
826 !defined $input_params{'snapshot_format'}) {
827 # We loop over the known snapshot formats, checking for
828 # extensions. Allowed extensions are both the defined suffix
829 # (which includes the initial dot already) and the snapshot
830 # format key itself, with a prepended dot
831 while (my ($fmt, $opt) = each %known_snapshot_formats) {
832 my $hash = $refname;
833 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
834 next;
836 my $sfx = $1;
837 # a valid suffix was found, so set the snapshot format
838 # and reset the hash parameter
839 $input_params{'snapshot_format'} = $fmt;
840 $input_params{'hash'} = $hash;
841 # we also set the format suffix to the one requested
842 # in the URL: this way a request for e.g. .tgz returns
843 # a .tgz instead of a .tar.gz
844 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
845 last;
850 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
851 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
852 $searchtext, $search_regexp);
853 sub evaluate_and_validate_params {
854 our $action = $input_params{'action'};
855 if (defined $action) {
856 if (!validate_action($action)) {
857 die_error(400, "Invalid action parameter");
861 # parameters which are pathnames
862 our $project = $input_params{'project'};
863 if (defined $project) {
864 if (!validate_project($project)) {
865 undef $project;
866 die_error(404, "No such project");
870 our $file_name = $input_params{'file_name'};
871 if (defined $file_name) {
872 if (!validate_pathname($file_name)) {
873 die_error(400, "Invalid file parameter");
877 our $file_parent = $input_params{'file_parent'};
878 if (defined $file_parent) {
879 if (!validate_pathname($file_parent)) {
880 die_error(400, "Invalid file parent parameter");
884 # parameters which are refnames
885 our $hash = $input_params{'hash'};
886 if (defined $hash) {
887 if (!validate_refname($hash)) {
888 die_error(400, "Invalid hash parameter");
892 our $hash_parent = $input_params{'hash_parent'};
893 if (defined $hash_parent) {
894 if (!validate_refname($hash_parent)) {
895 die_error(400, "Invalid hash parent parameter");
899 our $hash_base = $input_params{'hash_base'};
900 if (defined $hash_base) {
901 if (!validate_refname($hash_base)) {
902 die_error(400, "Invalid hash base parameter");
906 our @extra_options = @{$input_params{'extra_options'}};
907 # @extra_options is always defined, since it can only be (currently) set from
908 # CGI, and $cgi->param() returns the empty array in array context if the param
909 # is not set
910 foreach my $opt (@extra_options) {
911 if (not exists $allowed_options{$opt}) {
912 die_error(400, "Invalid option parameter");
914 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
915 die_error(400, "Invalid option parameter for this action");
919 our $hash_parent_base = $input_params{'hash_parent_base'};
920 if (defined $hash_parent_base) {
921 if (!validate_refname($hash_parent_base)) {
922 die_error(400, "Invalid hash parent base parameter");
926 # other parameters
927 our $page = $input_params{'page'};
928 if (defined $page) {
929 if ($page =~ m/[^0-9]/) {
930 die_error(400, "Invalid page parameter");
934 our $searchtype = $input_params{'searchtype'};
935 if (defined $searchtype) {
936 if ($searchtype =~ m/[^a-z]/) {
937 die_error(400, "Invalid searchtype parameter");
941 our $search_use_regexp = $input_params{'search_use_regexp'};
943 our $searchtext = $input_params{'searchtext'};
944 our $search_regexp;
945 if (defined $searchtext) {
946 if (length($searchtext) < 2) {
947 die_error(403, "At least two characters are required for search parameter");
949 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
953 # path to the current git repository
954 our $git_dir;
955 sub evaluate_git_dir {
956 our $git_dir = "$projectroot/$project" if $project;
959 our (@snapshot_fmts, $git_avatar);
960 sub configure_gitweb_features {
961 # list of supported snapshot formats
962 our @snapshot_fmts = gitweb_get_feature('snapshot');
963 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
965 # check that the avatar feature is set to a known provider name,
966 # and for each provider check if the dependencies are satisfied.
967 # if the provider name is invalid or the dependencies are not met,
968 # reset $git_avatar to the empty string.
969 our ($git_avatar) = gitweb_get_feature('avatar');
970 if ($git_avatar eq 'gravatar') {
971 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
972 } elsif ($git_avatar eq 'picon') {
973 # no dependencies
974 } else {
975 $git_avatar = '';
979 # custom error handler: 'die <message>' is Internal Server Error
980 sub handle_errors_html {
981 my $msg = shift; # it is already HTML escaped
983 # to avoid infinite loop where error occurs in die_error,
984 # change handler to default handler, disabling handle_errors_html
985 set_message("Error occured when inside die_error:\n$msg");
987 # you cannot jump out of die_error when called as error handler;
988 # the subroutine set via CGI::Carp::set_message is called _after_
989 # HTTP headers are already written, so it cannot write them itself
990 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
992 set_message(\&handle_errors_html);
994 # dispatch
995 sub dispatch {
996 if (!defined $action) {
997 if (defined $hash) {
998 $action = git_get_type($hash);
999 } elsif (defined $hash_base && defined $file_name) {
1000 $action = git_get_type("$hash_base:$file_name");
1001 } elsif (defined $project) {
1002 $action = 'summary';
1003 } else {
1004 $action = 'project_list';
1007 if (!defined($actions{$action})) {
1008 die_error(400, "Unknown action");
1010 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1011 !$project) {
1012 die_error(400, "Project needed");
1014 $actions{$action}->();
1017 sub run_request {
1018 our $t0 = [Time::HiRes::gettimeofday()]
1019 if defined $t0;
1021 evaluate_uri();
1022 evaluate_gitweb_config();
1023 evaluate_git_version();
1024 check_loadavg();
1026 # $projectroot and $projects_list might be set in gitweb config file
1027 $projects_list ||= $projectroot;
1029 evaluate_query_params();
1030 evaluate_path_info();
1031 evaluate_and_validate_params();
1032 evaluate_git_dir();
1034 configure_gitweb_features();
1036 dispatch();
1039 our $is_last_request = sub { 1 };
1040 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1041 our $CGI = 'CGI';
1042 our $cgi;
1043 sub evaluate_argv {
1044 return unless (@ARGV);
1046 require Getopt::Long;
1047 Getopt::Long::GetOptions(
1048 'fastcgi|fcgi|f' => sub {
1049 require CGI::Fast;
1050 our $CGI = 'CGI::Fast';
1052 my $request_number = 0;
1053 # let each child service 100 requests
1054 our $is_last_request = sub { ++$request_number > 100 };
1056 'nproc|n=i' => sub {
1057 my ($arg, $val) = @_;
1058 return unless eval { require FCGI::ProcManager; 1; };
1059 my $proc_manager = FCGI::ProcManager->new({
1060 n_processes => $val,
1062 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1063 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1064 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1069 sub run {
1070 evaluate_argv();
1072 $pre_listen_hook->()
1073 if $pre_listen_hook;
1075 REQUEST:
1076 while ($cgi = $CGI->new()) {
1077 $pre_dispatch_hook->()
1078 if $pre_dispatch_hook;
1080 run_request();
1082 $pre_dispatch_hook->()
1083 if $post_dispatch_hook;
1085 last REQUEST if ($is_last_request->());
1088 DONE_GITWEB:
1092 run();
1094 ## ======================================================================
1095 ## action links
1097 # possible values of extra options
1098 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1099 # -replay => 1 - start from a current view (replay with modifications)
1100 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1101 sub href {
1102 my %params = @_;
1103 # default is to use -absolute url() i.e. $my_uri
1104 my $href = $params{-full} ? $my_url : $my_uri;
1106 $params{'project'} = $project unless exists $params{'project'};
1108 if ($params{-replay}) {
1109 while (my ($name, $symbol) = each %cgi_param_mapping) {
1110 if (!exists $params{$name}) {
1111 $params{$name} = $input_params{$name};
1116 my $use_pathinfo = gitweb_check_feature('pathinfo');
1117 if (defined $params{'project'} &&
1118 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1119 # try to put as many parameters as possible in PATH_INFO:
1120 # - project name
1121 # - action
1122 # - hash_parent or hash_parent_base:/file_parent
1123 # - hash or hash_base:/filename
1124 # - the snapshot_format as an appropriate suffix
1126 # When the script is the root DirectoryIndex for the domain,
1127 # $href here would be something like http://gitweb.example.com/
1128 # Thus, we strip any trailing / from $href, to spare us double
1129 # slashes in the final URL
1130 $href =~ s,/$,,;
1132 # Then add the project name, if present
1133 $href .= "/".esc_url($params{'project'});
1134 delete $params{'project'};
1136 # since we destructively absorb parameters, we keep this
1137 # boolean that remembers if we're handling a snapshot
1138 my $is_snapshot = $params{'action'} eq 'snapshot';
1140 # Summary just uses the project path URL, any other action is
1141 # added to the URL
1142 if (defined $params{'action'}) {
1143 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1144 delete $params{'action'};
1147 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1148 # stripping nonexistent or useless pieces
1149 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1150 || $params{'hash_parent'} || $params{'hash'});
1151 if (defined $params{'hash_base'}) {
1152 if (defined $params{'hash_parent_base'}) {
1153 $href .= esc_url($params{'hash_parent_base'});
1154 # skip the file_parent if it's the same as the file_name
1155 if (defined $params{'file_parent'}) {
1156 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1157 delete $params{'file_parent'};
1158 } elsif ($params{'file_parent'} !~ /\.\./) {
1159 $href .= ":/".esc_url($params{'file_parent'});
1160 delete $params{'file_parent'};
1163 $href .= "..";
1164 delete $params{'hash_parent'};
1165 delete $params{'hash_parent_base'};
1166 } elsif (defined $params{'hash_parent'}) {
1167 $href .= esc_url($params{'hash_parent'}). "..";
1168 delete $params{'hash_parent'};
1171 $href .= esc_url($params{'hash_base'});
1172 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1173 $href .= ":/".esc_url($params{'file_name'});
1174 delete $params{'file_name'};
1176 delete $params{'hash'};
1177 delete $params{'hash_base'};
1178 } elsif (defined $params{'hash'}) {
1179 $href .= esc_url($params{'hash'});
1180 delete $params{'hash'};
1183 # If the action was a snapshot, we can absorb the
1184 # snapshot_format parameter too
1185 if ($is_snapshot) {
1186 my $fmt = $params{'snapshot_format'};
1187 # snapshot_format should always be defined when href()
1188 # is called, but just in case some code forgets, we
1189 # fall back to the default
1190 $fmt ||= $snapshot_fmts[0];
1191 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1192 delete $params{'snapshot_format'};
1196 # now encode the parameters explicitly
1197 my @result = ();
1198 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1199 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1200 if (defined $params{$name}) {
1201 if (ref($params{$name}) eq "ARRAY") {
1202 foreach my $par (@{$params{$name}}) {
1203 push @result, $symbol . "=" . esc_param($par);
1205 } else {
1206 push @result, $symbol . "=" . esc_param($params{$name});
1210 $href .= "?" . join(';', @result) if scalar @result;
1212 return $href;
1216 ## ======================================================================
1217 ## validation, quoting/unquoting and escaping
1219 sub validate_action {
1220 my $input = shift || return undef;
1221 return undef unless exists $actions{$input};
1222 return $input;
1225 sub validate_project {
1226 my $input = shift || return undef;
1227 if (!validate_pathname($input) ||
1228 !(-d "$projectroot/$input") ||
1229 !check_export_ok("$projectroot/$input") ||
1230 ($strict_export && !project_in_list($input))) {
1231 return undef;
1232 } else {
1233 return $input;
1237 sub validate_pathname {
1238 my $input = shift || return undef;
1240 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1241 # at the beginning, at the end, and between slashes.
1242 # also this catches doubled slashes
1243 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1244 return undef;
1246 # no null characters
1247 if ($input =~ m!\0!) {
1248 return undef;
1250 return $input;
1253 sub validate_refname {
1254 my $input = shift || return undef;
1256 # textual hashes are O.K.
1257 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1258 return $input;
1260 # it must be correct pathname
1261 $input = validate_pathname($input)
1262 or return undef;
1263 # restrictions on ref name according to git-check-ref-format
1264 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1265 return undef;
1267 return $input;
1270 # decode sequences of octets in utf8 into Perl's internal form,
1271 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1272 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1273 sub to_utf8 {
1274 my $str = shift;
1275 return undef unless defined $str;
1276 if (utf8::valid($str)) {
1277 utf8::decode($str);
1278 return $str;
1279 } else {
1280 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1284 # quote unsafe chars, but keep the slash, even when it's not
1285 # correct, but quoted slashes look too horrible in bookmarks
1286 sub esc_param {
1287 my $str = shift;
1288 return undef unless defined $str;
1289 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1290 $str =~ s/ /\+/g;
1291 return $str;
1294 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1295 sub esc_url {
1296 my $str = shift;
1297 return undef unless defined $str;
1298 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1299 $str =~ s/\+/%2B/g;
1300 $str =~ s/ /\+/g;
1301 return $str;
1304 # replace invalid utf8 character with SUBSTITUTION sequence
1305 sub esc_html {
1306 my $str = shift;
1307 my %opts = @_;
1309 return undef unless defined $str;
1311 $str = to_utf8($str);
1312 $str = $cgi->escapeHTML($str);
1313 if ($opts{'-nbsp'}) {
1314 $str =~ s/ /&nbsp;/g;
1316 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1317 return $str;
1320 # quote control characters and escape filename to HTML
1321 sub esc_path {
1322 my $str = shift;
1323 my %opts = @_;
1325 return undef unless defined $str;
1327 $str = to_utf8($str);
1328 $str = $cgi->escapeHTML($str);
1329 if ($opts{'-nbsp'}) {
1330 $str =~ s/ /&nbsp;/g;
1332 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1333 return $str;
1336 # Make control characters "printable", using character escape codes (CEC)
1337 sub quot_cec {
1338 my $cntrl = shift;
1339 my %opts = @_;
1340 my %es = ( # character escape codes, aka escape sequences
1341 "\t" => '\t', # tab (HT)
1342 "\n" => '\n', # line feed (LF)
1343 "\r" => '\r', # carrige return (CR)
1344 "\f" => '\f', # form feed (FF)
1345 "\b" => '\b', # backspace (BS)
1346 "\a" => '\a', # alarm (bell) (BEL)
1347 "\e" => '\e', # escape (ESC)
1348 "\013" => '\v', # vertical tab (VT)
1349 "\000" => '\0', # nul character (NUL)
1351 my $chr = ( (exists $es{$cntrl})
1352 ? $es{$cntrl}
1353 : sprintf('\%2x', ord($cntrl)) );
1354 if ($opts{-nohtml}) {
1355 return $chr;
1356 } else {
1357 return "<span class=\"cntrl\">$chr</span>";
1361 # Alternatively use unicode control pictures codepoints,
1362 # Unicode "printable representation" (PR)
1363 sub quot_upr {
1364 my $cntrl = shift;
1365 my %opts = @_;
1367 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1368 if ($opts{-nohtml}) {
1369 return $chr;
1370 } else {
1371 return "<span class=\"cntrl\">$chr</span>";
1375 # git may return quoted and escaped filenames
1376 sub unquote {
1377 my $str = shift;
1379 sub unq {
1380 my $seq = shift;
1381 my %es = ( # character escape codes, aka escape sequences
1382 't' => "\t", # tab (HT, TAB)
1383 'n' => "\n", # newline (NL)
1384 'r' => "\r", # return (CR)
1385 'f' => "\f", # form feed (FF)
1386 'b' => "\b", # backspace (BS)
1387 'a' => "\a", # alarm (bell) (BEL)
1388 'e' => "\e", # escape (ESC)
1389 'v' => "\013", # vertical tab (VT)
1392 if ($seq =~ m/^[0-7]{1,3}$/) {
1393 # octal char sequence
1394 return chr(oct($seq));
1395 } elsif (exists $es{$seq}) {
1396 # C escape sequence, aka character escape code
1397 return $es{$seq};
1399 # quoted ordinary character
1400 return $seq;
1403 if ($str =~ m/^"(.*)"$/) {
1404 # needs unquoting
1405 $str = $1;
1406 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1408 return $str;
1411 # escape tabs (convert tabs to spaces)
1412 sub untabify {
1413 my $line = shift;
1415 while ((my $pos = index($line, "\t")) != -1) {
1416 if (my $count = (8 - ($pos % 8))) {
1417 my $spaces = ' ' x $count;
1418 $line =~ s/\t/$spaces/;
1422 return $line;
1425 sub project_in_list {
1426 my $project = shift;
1427 my @list = git_get_projects_list();
1428 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1431 ## ----------------------------------------------------------------------
1432 ## HTML aware string manipulation
1434 # Try to chop given string on a word boundary between position
1435 # $len and $len+$add_len. If there is no word boundary there,
1436 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1437 # (marking chopped part) would be longer than given string.
1438 sub chop_str {
1439 my $str = shift;
1440 my $len = shift;
1441 my $add_len = shift || 10;
1442 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1444 # Make sure perl knows it is utf8 encoded so we don't
1445 # cut in the middle of a utf8 multibyte char.
1446 $str = to_utf8($str);
1448 # allow only $len chars, but don't cut a word if it would fit in $add_len
1449 # if it doesn't fit, cut it if it's still longer than the dots we would add
1450 # remove chopped character entities entirely
1452 # when chopping in the middle, distribute $len into left and right part
1453 # return early if chopping wouldn't make string shorter
1454 if ($where eq 'center') {
1455 return $str if ($len + 5 >= length($str)); # filler is length 5
1456 $len = int($len/2);
1457 } else {
1458 return $str if ($len + 4 >= length($str)); # filler is length 4
1461 # regexps: ending and beginning with word part up to $add_len
1462 my $endre = qr/.{$len}\w{0,$add_len}/;
1463 my $begre = qr/\w{0,$add_len}.{$len}/;
1465 if ($where eq 'left') {
1466 $str =~ m/^(.*?)($begre)$/;
1467 my ($lead, $body) = ($1, $2);
1468 if (length($lead) > 4) {
1469 $lead = " ...";
1471 return "$lead$body";
1473 } elsif ($where eq 'center') {
1474 $str =~ m/^($endre)(.*)$/;
1475 my ($left, $str) = ($1, $2);
1476 $str =~ m/^(.*?)($begre)$/;
1477 my ($mid, $right) = ($1, $2);
1478 if (length($mid) > 5) {
1479 $mid = " ... ";
1481 return "$left$mid$right";
1483 } else {
1484 $str =~ m/^($endre)(.*)$/;
1485 my $body = $1;
1486 my $tail = $2;
1487 if (length($tail) > 4) {
1488 $tail = "... ";
1490 return "$body$tail";
1494 # takes the same arguments as chop_str, but also wraps a <span> around the
1495 # result with a title attribute if it does get chopped. Additionally, the
1496 # string is HTML-escaped.
1497 sub chop_and_escape_str {
1498 my ($str) = @_;
1500 my $chopped = chop_str(@_);
1501 if ($chopped eq $str) {
1502 return esc_html($chopped);
1503 } else {
1504 $str =~ s/[[:cntrl:]]/?/g;
1505 return $cgi->span({-title=>$str}, esc_html($chopped));
1509 ## ----------------------------------------------------------------------
1510 ## functions returning short strings
1512 # CSS class for given age value (in seconds)
1513 sub age_class {
1514 my $age = shift;
1516 if (!defined $age) {
1517 return "noage";
1518 } elsif ($age < 60*60*2) {
1519 return "age0";
1520 } elsif ($age < 60*60*24*2) {
1521 return "age1";
1522 } else {
1523 return "age2";
1527 # convert age in seconds to "nn units ago" string
1528 sub age_string {
1529 my $age = shift;
1530 my $age_str;
1532 if ($age > 60*60*24*365*2) {
1533 $age_str = (int $age/60/60/24/365);
1534 $age_str .= " years ago";
1535 } elsif ($age > 60*60*24*(365/12)*2) {
1536 $age_str = int $age/60/60/24/(365/12);
1537 $age_str .= " months ago";
1538 } elsif ($age > 60*60*24*7*2) {
1539 $age_str = int $age/60/60/24/7;
1540 $age_str .= " weeks ago";
1541 } elsif ($age > 60*60*24*2) {
1542 $age_str = int $age/60/60/24;
1543 $age_str .= " days ago";
1544 } elsif ($age > 60*60*2) {
1545 $age_str = int $age/60/60;
1546 $age_str .= " hours ago";
1547 } elsif ($age > 60*2) {
1548 $age_str = int $age/60;
1549 $age_str .= " min ago";
1550 } elsif ($age > 2) {
1551 $age_str = int $age;
1552 $age_str .= " sec ago";
1553 } else {
1554 $age_str .= " right now";
1556 return $age_str;
1559 use constant {
1560 S_IFINVALID => 0030000,
1561 S_IFGITLINK => 0160000,
1564 # submodule/subproject, a commit object reference
1565 sub S_ISGITLINK {
1566 my $mode = shift;
1568 return (($mode & S_IFMT) == S_IFGITLINK)
1571 # convert file mode in octal to symbolic file mode string
1572 sub mode_str {
1573 my $mode = oct shift;
1575 if (S_ISGITLINK($mode)) {
1576 return 'm---------';
1577 } elsif (S_ISDIR($mode & S_IFMT)) {
1578 return 'drwxr-xr-x';
1579 } elsif (S_ISLNK($mode)) {
1580 return 'lrwxrwxrwx';
1581 } elsif (S_ISREG($mode)) {
1582 # git cares only about the executable bit
1583 if ($mode & S_IXUSR) {
1584 return '-rwxr-xr-x';
1585 } else {
1586 return '-rw-r--r--';
1588 } else {
1589 return '----------';
1593 # convert file mode in octal to file type string
1594 sub file_type {
1595 my $mode = shift;
1597 if ($mode !~ m/^[0-7]+$/) {
1598 return $mode;
1599 } else {
1600 $mode = oct $mode;
1603 if (S_ISGITLINK($mode)) {
1604 return "submodule";
1605 } elsif (S_ISDIR($mode & S_IFMT)) {
1606 return "directory";
1607 } elsif (S_ISLNK($mode)) {
1608 return "symlink";
1609 } elsif (S_ISREG($mode)) {
1610 return "file";
1611 } else {
1612 return "unknown";
1616 # convert file mode in octal to file type description string
1617 sub file_type_long {
1618 my $mode = shift;
1620 if ($mode !~ m/^[0-7]+$/) {
1621 return $mode;
1622 } else {
1623 $mode = oct $mode;
1626 if (S_ISGITLINK($mode)) {
1627 return "submodule";
1628 } elsif (S_ISDIR($mode & S_IFMT)) {
1629 return "directory";
1630 } elsif (S_ISLNK($mode)) {
1631 return "symlink";
1632 } elsif (S_ISREG($mode)) {
1633 if ($mode & S_IXUSR) {
1634 return "executable";
1635 } else {
1636 return "file";
1638 } else {
1639 return "unknown";
1644 ## ----------------------------------------------------------------------
1645 ## functions returning short HTML fragments, or transforming HTML fragments
1646 ## which don't belong to other sections
1648 # format line of commit message.
1649 sub format_log_line_html {
1650 my $line = shift;
1652 $line = esc_html($line, -nbsp=>1);
1653 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1654 $cgi->a({-href => href(action=>"object", hash=>$1),
1655 -class => "text"}, $1);
1656 }eg;
1658 return $line;
1661 # format marker of refs pointing to given object
1663 # the destination action is chosen based on object type and current context:
1664 # - for annotated tags, we choose the tag view unless it's the current view
1665 # already, in which case we go to shortlog view
1666 # - for other refs, we keep the current view if we're in history, shortlog or
1667 # log view, and select shortlog otherwise
1668 sub format_ref_marker {
1669 my ($refs, $id) = @_;
1670 my $markers = '';
1672 if (defined $refs->{$id}) {
1673 foreach my $ref (@{$refs->{$id}}) {
1674 # this code exploits the fact that non-lightweight tags are the
1675 # only indirect objects, and that they are the only objects for which
1676 # we want to use tag instead of shortlog as action
1677 my ($type, $name) = qw();
1678 my $indirect = ($ref =~ s/\^\{\}$//);
1679 # e.g. tags/v2.6.11 or heads/next
1680 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1681 $type = $1;
1682 $name = $2;
1683 } else {
1684 $type = "ref";
1685 $name = $ref;
1688 my $class = $type;
1689 $class .= " indirect" if $indirect;
1691 my $dest_action = "shortlog";
1693 if ($indirect) {
1694 $dest_action = "tag" unless $action eq "tag";
1695 } elsif ($action =~ /^(history|(short)?log)$/) {
1696 $dest_action = $action;
1699 my $dest = "";
1700 $dest .= "refs/" unless $ref =~ m!^refs/!;
1701 $dest .= $ref;
1703 my $link = $cgi->a({
1704 -href => href(
1705 action=>$dest_action,
1706 hash=>$dest
1707 )}, $name);
1709 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1710 $link . "</span>";
1714 if ($markers) {
1715 return ' <span class="refs">'. $markers . '</span>';
1716 } else {
1717 return "";
1721 # format, perhaps shortened and with markers, title line
1722 sub format_subject_html {
1723 my ($long, $short, $href, $extra) = @_;
1724 $extra = '' unless defined($extra);
1726 if (length($short) < length($long)) {
1727 $long =~ s/[[:cntrl:]]/?/g;
1728 return $cgi->a({-href => $href, -class => "list subject",
1729 -title => to_utf8($long)},
1730 esc_html($short)) . $extra;
1731 } else {
1732 return $cgi->a({-href => $href, -class => "list subject"},
1733 esc_html($long)) . $extra;
1737 # Rather than recomputing the url for an email multiple times, we cache it
1738 # after the first hit. This gives a visible benefit in views where the avatar
1739 # for the same email is used repeatedly (e.g. shortlog).
1740 # The cache is shared by all avatar engines (currently gravatar only), which
1741 # are free to use it as preferred. Since only one avatar engine is used for any
1742 # given page, there's no risk for cache conflicts.
1743 our %avatar_cache = ();
1745 # Compute the picon url for a given email, by using the picon search service over at
1746 # http://www.cs.indiana.edu/picons/search.html
1747 sub picon_url {
1748 my $email = lc shift;
1749 if (!$avatar_cache{$email}) {
1750 my ($user, $domain) = split('@', $email);
1751 $avatar_cache{$email} =
1752 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1753 "$domain/$user/" .
1754 "users+domains+unknown/up/single";
1756 return $avatar_cache{$email};
1759 # Compute the gravatar url for a given email, if it's not in the cache already.
1760 # Gravatar stores only the part of the URL before the size, since that's the
1761 # one computationally more expensive. This also allows reuse of the cache for
1762 # different sizes (for this particular engine).
1763 sub gravatar_url {
1764 my $email = lc shift;
1765 my $size = shift;
1766 $avatar_cache{$email} ||=
1767 "http://www.gravatar.com/avatar/" .
1768 Digest::MD5::md5_hex($email) . "?s=";
1769 return $avatar_cache{$email} . $size;
1772 # Insert an avatar for the given $email at the given $size if the feature
1773 # is enabled.
1774 sub git_get_avatar {
1775 my ($email, %opts) = @_;
1776 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1777 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1778 $opts{-size} ||= 'default';
1779 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1780 my $url = "";
1781 if ($git_avatar eq 'gravatar') {
1782 $url = gravatar_url($email, $size);
1783 } elsif ($git_avatar eq 'picon') {
1784 $url = picon_url($email);
1786 # Other providers can be added by extending the if chain, defining $url
1787 # as needed. If no variant puts something in $url, we assume avatars
1788 # are completely disabled/unavailable.
1789 if ($url) {
1790 return $pre_white .
1791 "<img width=\"$size\" " .
1792 "class=\"avatar\" " .
1793 "src=\"$url\" " .
1794 "alt=\"\" " .
1795 "/>" . $post_white;
1796 } else {
1797 return "";
1801 sub format_search_author {
1802 my ($author, $searchtype, $displaytext) = @_;
1803 my $have_search = gitweb_check_feature('search');
1805 if ($have_search) {
1806 my $performed = "";
1807 if ($searchtype eq 'author') {
1808 $performed = "authored";
1809 } elsif ($searchtype eq 'committer') {
1810 $performed = "committed";
1813 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1814 searchtext=>$author,
1815 searchtype=>$searchtype), class=>"list",
1816 title=>"Search for commits $performed by $author"},
1817 $displaytext);
1819 } else {
1820 return $displaytext;
1824 # format the author name of the given commit with the given tag
1825 # the author name is chopped and escaped according to the other
1826 # optional parameters (see chop_str).
1827 sub format_author_html {
1828 my $tag = shift;
1829 my $co = shift;
1830 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1831 return "<$tag class=\"author\">" .
1832 format_search_author($co->{'author_name'}, "author",
1833 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1834 $author) .
1835 "</$tag>";
1838 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1839 sub format_git_diff_header_line {
1840 my $line = shift;
1841 my $diffinfo = shift;
1842 my ($from, $to) = @_;
1844 if ($diffinfo->{'nparents'}) {
1845 # combined diff
1846 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1847 if ($to->{'href'}) {
1848 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1849 esc_path($to->{'file'}));
1850 } else { # file was deleted (no href)
1851 $line .= esc_path($to->{'file'});
1853 } else {
1854 # "ordinary" diff
1855 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1856 if ($from->{'href'}) {
1857 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1858 'a/' . esc_path($from->{'file'}));
1859 } else { # file was added (no href)
1860 $line .= 'a/' . esc_path($from->{'file'});
1862 $line .= ' ';
1863 if ($to->{'href'}) {
1864 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1865 'b/' . esc_path($to->{'file'}));
1866 } else { # file was deleted
1867 $line .= 'b/' . esc_path($to->{'file'});
1871 return "<div class=\"diff header\">$line</div>\n";
1874 # format extended diff header line, before patch itself
1875 sub format_extended_diff_header_line {
1876 my $line = shift;
1877 my $diffinfo = shift;
1878 my ($from, $to) = @_;
1880 # match <path>
1881 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1882 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1883 esc_path($from->{'file'}));
1885 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1886 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1887 esc_path($to->{'file'}));
1889 # match single <mode>
1890 if ($line =~ m/\s(\d{6})$/) {
1891 $line .= '<span class="info"> (' .
1892 file_type_long($1) .
1893 ')</span>';
1895 # match <hash>
1896 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1897 # can match only for combined diff
1898 $line = 'index ';
1899 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1900 if ($from->{'href'}[$i]) {
1901 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1902 -class=>"hash"},
1903 substr($diffinfo->{'from_id'}[$i],0,7));
1904 } else {
1905 $line .= '0' x 7;
1907 # separator
1908 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1910 $line .= '..';
1911 if ($to->{'href'}) {
1912 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1913 substr($diffinfo->{'to_id'},0,7));
1914 } else {
1915 $line .= '0' x 7;
1918 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1919 # can match only for ordinary diff
1920 my ($from_link, $to_link);
1921 if ($from->{'href'}) {
1922 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1923 substr($diffinfo->{'from_id'},0,7));
1924 } else {
1925 $from_link = '0' x 7;
1927 if ($to->{'href'}) {
1928 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1929 substr($diffinfo->{'to_id'},0,7));
1930 } else {
1931 $to_link = '0' x 7;
1933 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1934 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1937 return $line . "<br/>\n";
1940 # format from-file/to-file diff header
1941 sub format_diff_from_to_header {
1942 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1943 my $line;
1944 my $result = '';
1946 $line = $from_line;
1947 #assert($line =~ m/^---/) if DEBUG;
1948 # no extra formatting for "^--- /dev/null"
1949 if (! $diffinfo->{'nparents'}) {
1950 # ordinary (single parent) diff
1951 if ($line =~ m!^--- "?a/!) {
1952 if ($from->{'href'}) {
1953 $line = '--- a/' .
1954 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1955 esc_path($from->{'file'}));
1956 } else {
1957 $line = '--- a/' .
1958 esc_path($from->{'file'});
1961 $result .= qq!<div class="diff from_file">$line</div>\n!;
1963 } else {
1964 # combined diff (merge commit)
1965 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1966 if ($from->{'href'}[$i]) {
1967 $line = '--- ' .
1968 $cgi->a({-href=>href(action=>"blobdiff",
1969 hash_parent=>$diffinfo->{'from_id'}[$i],
1970 hash_parent_base=>$parents[$i],
1971 file_parent=>$from->{'file'}[$i],
1972 hash=>$diffinfo->{'to_id'},
1973 hash_base=>$hash,
1974 file_name=>$to->{'file'}),
1975 -class=>"path",
1976 -title=>"diff" . ($i+1)},
1977 $i+1) .
1978 '/' .
1979 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1980 esc_path($from->{'file'}[$i]));
1981 } else {
1982 $line = '--- /dev/null';
1984 $result .= qq!<div class="diff from_file">$line</div>\n!;
1988 $line = $to_line;
1989 #assert($line =~ m/^\+\+\+/) if DEBUG;
1990 # no extra formatting for "^+++ /dev/null"
1991 if ($line =~ m!^\+\+\+ "?b/!) {
1992 if ($to->{'href'}) {
1993 $line = '+++ b/' .
1994 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1995 esc_path($to->{'file'}));
1996 } else {
1997 $line = '+++ b/' .
1998 esc_path($to->{'file'});
2001 $result .= qq!<div class="diff to_file">$line</div>\n!;
2003 return $result;
2006 # create note for patch simplified by combined diff
2007 sub format_diff_cc_simplified {
2008 my ($diffinfo, @parents) = @_;
2009 my $result = '';
2011 $result .= "<div class=\"diff header\">" .
2012 "diff --cc ";
2013 if (!is_deleted($diffinfo)) {
2014 $result .= $cgi->a({-href => href(action=>"blob",
2015 hash_base=>$hash,
2016 hash=>$diffinfo->{'to_id'},
2017 file_name=>$diffinfo->{'to_file'}),
2018 -class => "path"},
2019 esc_path($diffinfo->{'to_file'}));
2020 } else {
2021 $result .= esc_path($diffinfo->{'to_file'});
2023 $result .= "</div>\n" . # class="diff header"
2024 "<div class=\"diff nodifferences\">" .
2025 "Simple merge" .
2026 "</div>\n"; # class="diff nodifferences"
2028 return $result;
2031 # format patch (diff) line (not to be used for diff headers)
2032 sub format_diff_line {
2033 my $line = shift;
2034 my ($from, $to) = @_;
2035 my $diff_class = "";
2037 chomp $line;
2039 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2040 # combined diff
2041 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2042 if ($line =~ m/^\@{3}/) {
2043 $diff_class = " chunk_header";
2044 } elsif ($line =~ m/^\\/) {
2045 $diff_class = " incomplete";
2046 } elsif ($prefix =~ tr/+/+/) {
2047 $diff_class = " add";
2048 } elsif ($prefix =~ tr/-/-/) {
2049 $diff_class = " rem";
2051 } else {
2052 # assume ordinary diff
2053 my $char = substr($line, 0, 1);
2054 if ($char eq '+') {
2055 $diff_class = " add";
2056 } elsif ($char eq '-') {
2057 $diff_class = " rem";
2058 } elsif ($char eq '@') {
2059 $diff_class = " chunk_header";
2060 } elsif ($char eq "\\") {
2061 $diff_class = " incomplete";
2064 $line = untabify($line);
2065 if ($from && $to && $line =~ m/^\@{2} /) {
2066 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2067 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2069 $from_lines = 0 unless defined $from_lines;
2070 $to_lines = 0 unless defined $to_lines;
2072 if ($from->{'href'}) {
2073 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2074 -class=>"list"}, $from_text);
2076 if ($to->{'href'}) {
2077 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2078 -class=>"list"}, $to_text);
2080 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2081 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2082 return "<div class=\"diff$diff_class\">$line</div>\n";
2083 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2084 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2085 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2087 @from_text = split(' ', $ranges);
2088 for (my $i = 0; $i < @from_text; ++$i) {
2089 ($from_start[$i], $from_nlines[$i]) =
2090 (split(',', substr($from_text[$i], 1)), 0);
2093 $to_text = pop @from_text;
2094 $to_start = pop @from_start;
2095 $to_nlines = pop @from_nlines;
2097 $line = "<span class=\"chunk_info\">$prefix ";
2098 for (my $i = 0; $i < @from_text; ++$i) {
2099 if ($from->{'href'}[$i]) {
2100 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2101 -class=>"list"}, $from_text[$i]);
2102 } else {
2103 $line .= $from_text[$i];
2105 $line .= " ";
2107 if ($to->{'href'}) {
2108 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2109 -class=>"list"}, $to_text);
2110 } else {
2111 $line .= $to_text;
2113 $line .= " $prefix</span>" .
2114 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2115 return "<div class=\"diff$diff_class\">$line</div>\n";
2117 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2120 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2121 # linked. Pass the hash of the tree/commit to snapshot.
2122 sub format_snapshot_links {
2123 my ($hash) = @_;
2124 my $num_fmts = @snapshot_fmts;
2125 if ($num_fmts > 1) {
2126 # A parenthesized list of links bearing format names.
2127 # e.g. "snapshot (_tar.gz_ _zip_)"
2128 return "snapshot (" . join(' ', map
2129 $cgi->a({
2130 -href => href(
2131 action=>"snapshot",
2132 hash=>$hash,
2133 snapshot_format=>$_
2135 }, $known_snapshot_formats{$_}{'display'})
2136 , @snapshot_fmts) . ")";
2137 } elsif ($num_fmts == 1) {
2138 # A single "snapshot" link whose tooltip bears the format name.
2139 # i.e. "_snapshot_"
2140 my ($fmt) = @snapshot_fmts;
2141 return
2142 $cgi->a({
2143 -href => href(
2144 action=>"snapshot",
2145 hash=>$hash,
2146 snapshot_format=>$fmt
2148 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2149 }, "snapshot");
2150 } else { # $num_fmts == 0
2151 return undef;
2155 ## ......................................................................
2156 ## functions returning values to be passed, perhaps after some
2157 ## transformation, to other functions; e.g. returning arguments to href()
2159 # returns hash to be passed to href to generate gitweb URL
2160 # in -title key it returns description of link
2161 sub get_feed_info {
2162 my $format = shift || 'Atom';
2163 my %res = (action => lc($format));
2165 # feed links are possible only for project views
2166 return unless (defined $project);
2167 # some views should link to OPML, or to generic project feed,
2168 # or don't have specific feed yet (so they should use generic)
2169 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2171 my $branch;
2172 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2173 # from tag links; this also makes possible to detect branch links
2174 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2175 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2176 $branch = $1;
2178 # find log type for feed description (title)
2179 my $type = 'log';
2180 if (defined $file_name) {
2181 $type = "history of $file_name";
2182 $type .= "/" if ($action eq 'tree');
2183 $type .= " on '$branch'" if (defined $branch);
2184 } else {
2185 $type = "log of $branch" if (defined $branch);
2188 $res{-title} = $type;
2189 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2190 $res{'file_name'} = $file_name;
2192 return %res;
2195 ## ----------------------------------------------------------------------
2196 ## git utility subroutines, invoking git commands
2198 # returns path to the core git executable and the --git-dir parameter as list
2199 sub git_cmd {
2200 $number_of_git_cmds++;
2201 return $GIT, '--git-dir='.$git_dir;
2204 # quote the given arguments for passing them to the shell
2205 # quote_command("command", "arg 1", "arg with ' and ! characters")
2206 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2207 # Try to avoid using this function wherever possible.
2208 sub quote_command {
2209 return join(' ',
2210 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2213 # get HEAD ref of given project as hash
2214 sub git_get_head_hash {
2215 return git_get_full_hash(shift, 'HEAD');
2218 sub git_get_full_hash {
2219 return git_get_hash(@_);
2222 sub git_get_short_hash {
2223 return git_get_hash(@_, '--short=7');
2226 sub git_get_hash {
2227 my ($project, $hash, @options) = @_;
2228 my $o_git_dir = $git_dir;
2229 my $retval = undef;
2230 $git_dir = "$projectroot/$project";
2231 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2232 '--verify', '-q', @options, $hash) {
2233 $retval = <$fd>;
2234 chomp $retval if defined $retval;
2235 close $fd;
2237 if (defined $o_git_dir) {
2238 $git_dir = $o_git_dir;
2240 return $retval;
2243 # get type of given object
2244 sub git_get_type {
2245 my $hash = shift;
2247 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2248 my $type = <$fd>;
2249 close $fd or return;
2250 chomp $type;
2251 return $type;
2254 # repository configuration
2255 our $config_file = '';
2256 our %config;
2258 # store multiple values for single key as anonymous array reference
2259 # single values stored directly in the hash, not as [ <value> ]
2260 sub hash_set_multi {
2261 my ($hash, $key, $value) = @_;
2263 if (!exists $hash->{$key}) {
2264 $hash->{$key} = $value;
2265 } elsif (!ref $hash->{$key}) {
2266 $hash->{$key} = [ $hash->{$key}, $value ];
2267 } else {
2268 push @{$hash->{$key}}, $value;
2272 # return hash of git project configuration
2273 # optionally limited to some section, e.g. 'gitweb'
2274 sub git_parse_project_config {
2275 my $section_regexp = shift;
2276 my %config;
2278 local $/ = "\0";
2280 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2281 or return;
2283 while (my $keyval = <$fh>) {
2284 chomp $keyval;
2285 my ($key, $value) = split(/\n/, $keyval, 2);
2287 hash_set_multi(\%config, $key, $value)
2288 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2290 close $fh;
2292 return %config;
2295 # convert config value to boolean: 'true' or 'false'
2296 # no value, number > 0, 'true' and 'yes' values are true
2297 # rest of values are treated as false (never as error)
2298 sub config_to_bool {
2299 my $val = shift;
2301 return 1 if !defined $val; # section.key
2303 # strip leading and trailing whitespace
2304 $val =~ s/^\s+//;
2305 $val =~ s/\s+$//;
2307 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2308 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2311 # convert config value to simple decimal number
2312 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2313 # to be multiplied by 1024, 1048576, or 1073741824
2314 sub config_to_int {
2315 my $val = shift;
2317 # strip leading and trailing whitespace
2318 $val =~ s/^\s+//;
2319 $val =~ s/\s+$//;
2321 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2322 $unit = lc($unit);
2323 # unknown unit is treated as 1
2324 return $num * ($unit eq 'g' ? 1073741824 :
2325 $unit eq 'm' ? 1048576 :
2326 $unit eq 'k' ? 1024 : 1);
2328 return $val;
2331 # convert config value to array reference, if needed
2332 sub config_to_multi {
2333 my $val = shift;
2335 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2338 sub git_get_project_config {
2339 my ($key, $type) = @_;
2341 return unless defined $git_dir;
2343 # key sanity check
2344 return unless ($key);
2345 $key =~ s/^gitweb\.//;
2346 return if ($key =~ m/\W/);
2348 # type sanity check
2349 if (defined $type) {
2350 $type =~ s/^--//;
2351 $type = undef
2352 unless ($type eq 'bool' || $type eq 'int');
2355 # get config
2356 if (!defined $config_file ||
2357 $config_file ne "$git_dir/config") {
2358 %config = git_parse_project_config('gitweb');
2359 $config_file = "$git_dir/config";
2362 # check if config variable (key) exists
2363 return unless exists $config{"gitweb.$key"};
2365 # ensure given type
2366 if (!defined $type) {
2367 return $config{"gitweb.$key"};
2368 } elsif ($type eq 'bool') {
2369 # backward compatibility: 'git config --bool' returns true/false
2370 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2371 } elsif ($type eq 'int') {
2372 return config_to_int($config{"gitweb.$key"});
2374 return $config{"gitweb.$key"};
2377 # get hash of given path at given ref
2378 sub git_get_hash_by_path {
2379 my $base = shift;
2380 my $path = shift || return undef;
2381 my $type = shift;
2383 $path =~ s,/+$,,;
2385 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2386 or die_error(500, "Open git-ls-tree failed");
2387 my $line = <$fd>;
2388 close $fd or return undef;
2390 if (!defined $line) {
2391 # there is no tree or hash given by $path at $base
2392 return undef;
2395 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2396 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2397 if (defined $type && $type ne $2) {
2398 # type doesn't match
2399 return undef;
2401 return $3;
2404 # get path of entry with given hash at given tree-ish (ref)
2405 # used to get 'from' filename for combined diff (merge commit) for renames
2406 sub git_get_path_by_hash {
2407 my $base = shift || return;
2408 my $hash = shift || return;
2410 local $/ = "\0";
2412 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2413 or return undef;
2414 while (my $line = <$fd>) {
2415 chomp $line;
2417 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2418 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2419 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2420 close $fd;
2421 return $1;
2424 close $fd;
2425 return undef;
2428 ## ......................................................................
2429 ## git utility functions, directly accessing git repository
2431 sub git_get_project_description {
2432 my $path = shift;
2434 $git_dir = "$projectroot/$path";
2435 open my $fd, '<', "$git_dir/description"
2436 or return git_get_project_config('description');
2437 my $descr = <$fd>;
2438 close $fd;
2439 if (defined $descr) {
2440 chomp $descr;
2442 return $descr;
2445 sub git_get_project_ctags {
2446 my $path = shift;
2447 my $ctags = {};
2449 $git_dir = "$projectroot/$path";
2450 opendir my $dh, "$git_dir/ctags"
2451 or return $ctags;
2452 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2453 open my $ct, '<', $_ or next;
2454 my $val = <$ct>;
2455 chomp $val;
2456 close $ct;
2457 my $ctag = $_; $ctag =~ s#.*/##;
2458 $ctags->{$ctag} = $val;
2460 closedir $dh;
2461 $ctags;
2464 sub git_populate_project_tagcloud {
2465 my $ctags = shift;
2467 # First, merge different-cased tags; tags vote on casing
2468 my %ctags_lc;
2469 foreach (keys %$ctags) {
2470 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2471 if (not $ctags_lc{lc $_}->{topcount}
2472 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2473 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2474 $ctags_lc{lc $_}->{topname} = $_;
2478 my $cloud;
2479 if (eval { require HTML::TagCloud; 1; }) {
2480 $cloud = HTML::TagCloud->new;
2481 foreach (sort keys %ctags_lc) {
2482 # Pad the title with spaces so that the cloud looks
2483 # less crammed.
2484 my $title = $ctags_lc{$_}->{topname};
2485 $title =~ s/ /&nbsp;/g;
2486 $title =~ s/^/&nbsp;/g;
2487 $title =~ s/$/&nbsp;/g;
2488 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2490 } else {
2491 $cloud = \%ctags_lc;
2493 $cloud;
2496 sub git_show_project_tagcloud {
2497 my ($cloud, $count) = @_;
2498 print STDERR ref($cloud)."..\n";
2499 if (ref $cloud eq 'HTML::TagCloud') {
2500 return $cloud->html_and_css($count);
2501 } else {
2502 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2503 return '<p align="center">' . join (', ', map {
2504 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2505 } splice(@tags, 0, $count)) . '</p>';
2509 sub git_get_project_url_list {
2510 my $path = shift;
2512 $git_dir = "$projectroot/$path";
2513 open my $fd, '<', "$git_dir/cloneurl"
2514 or return wantarray ?
2515 @{ config_to_multi(git_get_project_config('url')) } :
2516 config_to_multi(git_get_project_config('url'));
2517 my @git_project_url_list = map { chomp; $_ } <$fd>;
2518 close $fd;
2520 return wantarray ? @git_project_url_list : \@git_project_url_list;
2523 sub git_get_projects_list {
2524 my ($filter) = @_;
2525 my @list;
2527 $filter ||= '';
2528 $filter =~ s/\.git$//;
2530 my $check_forks = gitweb_check_feature('forks');
2532 if (-d $projects_list) {
2533 # search in directory
2534 my $dir = $projects_list . ($filter ? "/$filter" : '');
2535 # remove the trailing "/"
2536 $dir =~ s!/+$!!;
2537 my $pfxlen = length("$dir");
2538 my $pfxdepth = ($dir =~ tr!/!!);
2540 File::Find::find({
2541 follow_fast => 1, # follow symbolic links
2542 follow_skip => 2, # ignore duplicates
2543 dangling_symlinks => 0, # ignore dangling symlinks, silently
2544 wanted => sub {
2545 # global variables
2546 our $project_maxdepth;
2547 our $projectroot;
2548 # skip project-list toplevel, if we get it.
2549 return if (m!^[/.]$!);
2550 # only directories can be git repositories
2551 return unless (-d $_);
2552 # don't traverse too deep (Find is super slow on os x)
2553 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2554 $File::Find::prune = 1;
2555 return;
2558 my $subdir = substr($File::Find::name, $pfxlen + 1);
2559 # we check related file in $projectroot
2560 my $path = ($filter ? "$filter/" : '') . $subdir;
2561 if (check_export_ok("$projectroot/$path")) {
2562 push @list, { path => $path };
2563 $File::Find::prune = 1;
2566 }, "$dir");
2568 } elsif (-f $projects_list) {
2569 # read from file(url-encoded):
2570 # 'git%2Fgit.git Linus+Torvalds'
2571 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2572 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2573 my %paths;
2574 open my $fd, '<', $projects_list or return;
2575 PROJECT:
2576 while (my $line = <$fd>) {
2577 chomp $line;
2578 my ($path, $owner) = split ' ', $line;
2579 $path = unescape($path);
2580 $owner = unescape($owner);
2581 if (!defined $path) {
2582 next;
2584 if ($filter ne '') {
2585 # looking for forks;
2586 my $pfx = substr($path, 0, length($filter));
2587 if ($pfx ne $filter) {
2588 next PROJECT;
2590 my $sfx = substr($path, length($filter));
2591 if ($sfx !~ /^\/.*\.git$/) {
2592 next PROJECT;
2594 } elsif ($check_forks) {
2595 PATH:
2596 foreach my $filter (keys %paths) {
2597 # looking for forks;
2598 my $pfx = substr($path, 0, length($filter));
2599 if ($pfx ne $filter) {
2600 next PATH;
2602 my $sfx = substr($path, length($filter));
2603 if ($sfx !~ /^\/.*\.git$/) {
2604 next PATH;
2606 # is a fork, don't include it in
2607 # the list
2608 next PROJECT;
2611 if (check_export_ok("$projectroot/$path")) {
2612 my $pr = {
2613 path => $path,
2614 owner => to_utf8($owner),
2616 push @list, $pr;
2617 (my $forks_path = $path) =~ s/\.git$//;
2618 $paths{$forks_path}++;
2621 close $fd;
2623 return @list;
2626 our $gitweb_project_owner = undef;
2627 sub git_get_project_list_from_file {
2629 return if (defined $gitweb_project_owner);
2631 $gitweb_project_owner = {};
2632 # read from file (url-encoded):
2633 # 'git%2Fgit.git Linus+Torvalds'
2634 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2635 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2636 if (-f $projects_list) {
2637 open(my $fd, '<', $projects_list);
2638 while (my $line = <$fd>) {
2639 chomp $line;
2640 my ($pr, $ow) = split ' ', $line;
2641 $pr = unescape($pr);
2642 $ow = unescape($ow);
2643 $gitweb_project_owner->{$pr} = to_utf8($ow);
2645 close $fd;
2649 sub git_get_project_owner {
2650 my $project = shift;
2651 my $owner;
2653 return undef unless $project;
2654 $git_dir = "$projectroot/$project";
2656 if (!defined $gitweb_project_owner) {
2657 git_get_project_list_from_file();
2660 if (exists $gitweb_project_owner->{$project}) {
2661 $owner = $gitweb_project_owner->{$project};
2663 if (!defined $owner){
2664 $owner = git_get_project_config('owner');
2666 if (!defined $owner) {
2667 $owner = get_file_owner("$git_dir");
2670 return $owner;
2673 sub git_get_last_activity {
2674 my ($path) = @_;
2675 my $fd;
2677 $git_dir = "$projectroot/$path";
2678 open($fd, "-|", git_cmd(), 'for-each-ref',
2679 '--format=%(committer)',
2680 '--sort=-committerdate',
2681 '--count=1',
2682 'refs/heads') or return;
2683 my $most_recent = <$fd>;
2684 close $fd or return;
2685 if (defined $most_recent &&
2686 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2687 my $timestamp = $1;
2688 my $age = time - $timestamp;
2689 return ($age, age_string($age));
2691 return (undef, undef);
2694 sub git_get_references {
2695 my $type = shift || "";
2696 my %refs;
2697 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2698 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2699 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2700 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2701 or return;
2703 while (my $line = <$fd>) {
2704 chomp $line;
2705 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2706 if (defined $refs{$1}) {
2707 push @{$refs{$1}}, $2;
2708 } else {
2709 $refs{$1} = [ $2 ];
2713 close $fd or return;
2714 return \%refs;
2717 sub git_get_rev_name_tags {
2718 my $hash = shift || return undef;
2720 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2721 or return;
2722 my $name_rev = <$fd>;
2723 close $fd;
2725 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2726 return $1;
2727 } else {
2728 # catches also '$hash undefined' output
2729 return undef;
2733 ## ----------------------------------------------------------------------
2734 ## parse to hash functions
2736 sub parse_date {
2737 my $epoch = shift;
2738 my $tz = shift || "-0000";
2740 my %date;
2741 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2742 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2743 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2744 $date{'hour'} = $hour;
2745 $date{'minute'} = $min;
2746 $date{'mday'} = $mday;
2747 $date{'day'} = $days[$wday];
2748 $date{'month'} = $months[$mon];
2749 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2750 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2751 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2752 $mday, $months[$mon], $hour ,$min;
2753 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2754 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2756 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2757 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2758 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2759 $date{'hour_local'} = $hour;
2760 $date{'minute_local'} = $min;
2761 $date{'tz_local'} = $tz;
2762 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2763 1900+$year, $mon+1, $mday,
2764 $hour, $min, $sec, $tz);
2765 return %date;
2768 sub parse_tag {
2769 my $tag_id = shift;
2770 my %tag;
2771 my @comment;
2773 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2774 $tag{'id'} = $tag_id;
2775 while (my $line = <$fd>) {
2776 chomp $line;
2777 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2778 $tag{'object'} = $1;
2779 } elsif ($line =~ m/^type (.+)$/) {
2780 $tag{'type'} = $1;
2781 } elsif ($line =~ m/^tag (.+)$/) {
2782 $tag{'name'} = $1;
2783 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2784 $tag{'author'} = $1;
2785 $tag{'author_epoch'} = $2;
2786 $tag{'author_tz'} = $3;
2787 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2788 $tag{'author_name'} = $1;
2789 $tag{'author_email'} = $2;
2790 } else {
2791 $tag{'author_name'} = $tag{'author'};
2793 } elsif ($line =~ m/--BEGIN/) {
2794 push @comment, $line;
2795 last;
2796 } elsif ($line eq "") {
2797 last;
2800 push @comment, <$fd>;
2801 $tag{'comment'} = \@comment;
2802 close $fd or return;
2803 if (!defined $tag{'name'}) {
2804 return
2806 return %tag
2809 sub parse_commit_text {
2810 my ($commit_text, $withparents) = @_;
2811 my @commit_lines = split '\n', $commit_text;
2812 my %co;
2814 pop @commit_lines; # Remove '\0'
2816 if (! @commit_lines) {
2817 return;
2820 my $header = shift @commit_lines;
2821 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2822 return;
2824 ($co{'id'}, my @parents) = split ' ', $header;
2825 while (my $line = shift @commit_lines) {
2826 last if $line eq "\n";
2827 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2828 $co{'tree'} = $1;
2829 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2830 push @parents, $1;
2831 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2832 $co{'author'} = to_utf8($1);
2833 $co{'author_epoch'} = $2;
2834 $co{'author_tz'} = $3;
2835 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2836 $co{'author_name'} = $1;
2837 $co{'author_email'} = $2;
2838 } else {
2839 $co{'author_name'} = $co{'author'};
2841 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2842 $co{'committer'} = to_utf8($1);
2843 $co{'committer_epoch'} = $2;
2844 $co{'committer_tz'} = $3;
2845 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2846 $co{'committer_name'} = $1;
2847 $co{'committer_email'} = $2;
2848 } else {
2849 $co{'committer_name'} = $co{'committer'};
2853 if (!defined $co{'tree'}) {
2854 return;
2856 $co{'parents'} = \@parents;
2857 $co{'parent'} = $parents[0];
2859 foreach my $title (@commit_lines) {
2860 $title =~ s/^ //;
2861 if ($title ne "") {
2862 $co{'title'} = chop_str($title, 80, 5);
2863 # remove leading stuff of merges to make the interesting part visible
2864 if (length($title) > 50) {
2865 $title =~ s/^Automatic //;
2866 $title =~ s/^merge (of|with) /Merge ... /i;
2867 if (length($title) > 50) {
2868 $title =~ s/(http|rsync):\/\///;
2870 if (length($title) > 50) {
2871 $title =~ s/(master|www|rsync)\.//;
2873 if (length($title) > 50) {
2874 $title =~ s/kernel.org:?//;
2876 if (length($title) > 50) {
2877 $title =~ s/\/pub\/scm//;
2880 $co{'title_short'} = chop_str($title, 50, 5);
2881 last;
2884 if (! defined $co{'title'} || $co{'title'} eq "") {
2885 $co{'title'} = $co{'title_short'} = '(no commit message)';
2887 # remove added spaces
2888 foreach my $line (@commit_lines) {
2889 $line =~ s/^ //;
2891 $co{'comment'} = \@commit_lines;
2893 my $age = time - $co{'committer_epoch'};
2894 $co{'age'} = $age;
2895 $co{'age_string'} = age_string($age);
2896 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2897 if ($age > 60*60*24*7*2) {
2898 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2899 $co{'age_string_age'} = $co{'age_string'};
2900 } else {
2901 $co{'age_string_date'} = $co{'age_string'};
2902 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2904 return %co;
2907 sub parse_commit {
2908 my ($commit_id) = @_;
2909 my %co;
2911 local $/ = "\0";
2913 open my $fd, "-|", git_cmd(), "rev-list",
2914 "--parents",
2915 "--header",
2916 "--max-count=1",
2917 $commit_id,
2918 "--",
2919 or die_error(500, "Open git-rev-list failed");
2920 %co = parse_commit_text(<$fd>, 1);
2921 close $fd;
2923 return %co;
2926 sub parse_commits {
2927 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2928 my @cos;
2930 $maxcount ||= 1;
2931 $skip ||= 0;
2933 local $/ = "\0";
2935 open my $fd, "-|", git_cmd(), "rev-list",
2936 "--header",
2937 @args,
2938 ("--max-count=" . $maxcount),
2939 ("--skip=" . $skip),
2940 @extra_options,
2941 $commit_id,
2942 "--",
2943 ($filename ? ($filename) : ())
2944 or die_error(500, "Open git-rev-list failed");
2945 while (my $line = <$fd>) {
2946 my %co = parse_commit_text($line);
2947 push @cos, \%co;
2949 close $fd;
2951 return wantarray ? @cos : \@cos;
2954 # parse line of git-diff-tree "raw" output
2955 sub parse_difftree_raw_line {
2956 my $line = shift;
2957 my %res;
2959 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2960 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2961 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2962 $res{'from_mode'} = $1;
2963 $res{'to_mode'} = $2;
2964 $res{'from_id'} = $3;
2965 $res{'to_id'} = $4;
2966 $res{'status'} = $5;
2967 $res{'similarity'} = $6;
2968 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2969 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2970 } else {
2971 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2974 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2975 # combined diff (for merge commit)
2976 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2977 $res{'nparents'} = length($1);
2978 $res{'from_mode'} = [ split(' ', $2) ];
2979 $res{'to_mode'} = pop @{$res{'from_mode'}};
2980 $res{'from_id'} = [ split(' ', $3) ];
2981 $res{'to_id'} = pop @{$res{'from_id'}};
2982 $res{'status'} = [ split('', $4) ];
2983 $res{'to_file'} = unquote($5);
2985 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2986 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2987 $res{'commit'} = $1;
2990 return wantarray ? %res : \%res;
2993 # wrapper: return parsed line of git-diff-tree "raw" output
2994 # (the argument might be raw line, or parsed info)
2995 sub parsed_difftree_line {
2996 my $line_or_ref = shift;
2998 if (ref($line_or_ref) eq "HASH") {
2999 # pre-parsed (or generated by hand)
3000 return $line_or_ref;
3001 } else {
3002 return parse_difftree_raw_line($line_or_ref);
3006 # parse line of git-ls-tree output
3007 sub parse_ls_tree_line {
3008 my $line = shift;
3009 my %opts = @_;
3010 my %res;
3012 if ($opts{'-l'}) {
3013 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3014 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3016 $res{'mode'} = $1;
3017 $res{'type'} = $2;
3018 $res{'hash'} = $3;
3019 $res{'size'} = $4;
3020 if ($opts{'-z'}) {
3021 $res{'name'} = $5;
3022 } else {
3023 $res{'name'} = unquote($5);
3025 } else {
3026 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3027 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3029 $res{'mode'} = $1;
3030 $res{'type'} = $2;
3031 $res{'hash'} = $3;
3032 if ($opts{'-z'}) {
3033 $res{'name'} = $4;
3034 } else {
3035 $res{'name'} = unquote($4);
3039 return wantarray ? %res : \%res;
3042 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3043 sub parse_from_to_diffinfo {
3044 my ($diffinfo, $from, $to, @parents) = @_;
3046 if ($diffinfo->{'nparents'}) {
3047 # combined diff
3048 $from->{'file'} = [];
3049 $from->{'href'} = [];
3050 fill_from_file_info($diffinfo, @parents)
3051 unless exists $diffinfo->{'from_file'};
3052 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3053 $from->{'file'}[$i] =
3054 defined $diffinfo->{'from_file'}[$i] ?
3055 $diffinfo->{'from_file'}[$i] :
3056 $diffinfo->{'to_file'};
3057 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3058 $from->{'href'}[$i] = href(action=>"blob",
3059 hash_base=>$parents[$i],
3060 hash=>$diffinfo->{'from_id'}[$i],
3061 file_name=>$from->{'file'}[$i]);
3062 } else {
3063 $from->{'href'}[$i] = undef;
3066 } else {
3067 # ordinary (not combined) diff
3068 $from->{'file'} = $diffinfo->{'from_file'};
3069 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3070 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3071 hash=>$diffinfo->{'from_id'},
3072 file_name=>$from->{'file'});
3073 } else {
3074 delete $from->{'href'};
3078 $to->{'file'} = $diffinfo->{'to_file'};
3079 if (!is_deleted($diffinfo)) { # file exists in result
3080 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3081 hash=>$diffinfo->{'to_id'},
3082 file_name=>$to->{'file'});
3083 } else {
3084 delete $to->{'href'};
3088 ## ......................................................................
3089 ## parse to array of hashes functions
3091 sub git_get_heads_list {
3092 my $limit = shift;
3093 my @headslist;
3095 open my $fd, '-|', git_cmd(), 'for-each-ref',
3096 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3097 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3098 'refs/heads'
3099 or return;
3100 while (my $line = <$fd>) {
3101 my %ref_item;
3103 chomp $line;
3104 my ($refinfo, $committerinfo) = split(/\0/, $line);
3105 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3106 my ($committer, $epoch, $tz) =
3107 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3108 $ref_item{'fullname'} = $name;
3109 $name =~ s!^refs/heads/!!;
3111 $ref_item{'name'} = $name;
3112 $ref_item{'id'} = $hash;
3113 $ref_item{'title'} = $title || '(no commit message)';
3114 $ref_item{'epoch'} = $epoch;
3115 if ($epoch) {
3116 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3117 } else {
3118 $ref_item{'age'} = "unknown";
3121 push @headslist, \%ref_item;
3123 close $fd;
3125 return wantarray ? @headslist : \@headslist;
3128 sub git_get_tags_list {
3129 my $limit = shift;
3130 my @tagslist;
3132 open my $fd, '-|', git_cmd(), 'for-each-ref',
3133 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3134 '--format=%(objectname) %(objecttype) %(refname) '.
3135 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3136 'refs/tags'
3137 or return;
3138 while (my $line = <$fd>) {
3139 my %ref_item;
3141 chomp $line;
3142 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3143 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3144 my ($creator, $epoch, $tz) =
3145 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3146 $ref_item{'fullname'} = $name;
3147 $name =~ s!^refs/tags/!!;
3149 $ref_item{'type'} = $type;
3150 $ref_item{'id'} = $id;
3151 $ref_item{'name'} = $name;
3152 if ($type eq "tag") {
3153 $ref_item{'subject'} = $title;
3154 $ref_item{'reftype'} = $reftype;
3155 $ref_item{'refid'} = $refid;
3156 } else {
3157 $ref_item{'reftype'} = $type;
3158 $ref_item{'refid'} = $id;
3161 if ($type eq "tag" || $type eq "commit") {
3162 $ref_item{'epoch'} = $epoch;
3163 if ($epoch) {
3164 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3165 } else {
3166 $ref_item{'age'} = "unknown";
3170 push @tagslist, \%ref_item;
3172 close $fd;
3174 return wantarray ? @tagslist : \@tagslist;
3177 ## ----------------------------------------------------------------------
3178 ## filesystem-related functions
3180 sub get_file_owner {
3181 my $path = shift;
3183 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3184 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3185 if (!defined $gcos) {
3186 return undef;
3188 my $owner = $gcos;
3189 $owner =~ s/[,;].*$//;
3190 return to_utf8($owner);
3193 # assume that file exists
3194 sub insert_file {
3195 my $filename = shift;
3197 open my $fd, '<', $filename;
3198 print map { to_utf8($_) } <$fd>;
3199 close $fd;
3202 ## ......................................................................
3203 ## mimetype related functions
3205 sub mimetype_guess_file {
3206 my $filename = shift;
3207 my $mimemap = shift;
3208 -r $mimemap or return undef;
3210 my %mimemap;
3211 open(my $mh, '<', $mimemap) or return undef;
3212 while (<$mh>) {
3213 next if m/^#/; # skip comments
3214 my ($mimetype, $exts) = split(/\t+/);
3215 if (defined $exts) {
3216 my @exts = split(/\s+/, $exts);
3217 foreach my $ext (@exts) {
3218 $mimemap{$ext} = $mimetype;
3222 close($mh);
3224 $filename =~ /\.([^.]*)$/;
3225 return $mimemap{$1};
3228 sub mimetype_guess {
3229 my $filename = shift;
3230 my $mime;
3231 $filename =~ /\./ or return undef;
3233 if ($mimetypes_file) {
3234 my $file = $mimetypes_file;
3235 if ($file !~ m!^/!) { # if it is relative path
3236 # it is relative to project
3237 $file = "$projectroot/$project/$file";
3239 $mime = mimetype_guess_file($filename, $file);
3241 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3242 return $mime;
3245 sub blob_mimetype {
3246 my $fd = shift;
3247 my $filename = shift;
3249 if ($filename) {
3250 my $mime = mimetype_guess($filename);
3251 $mime and return $mime;
3254 # just in case
3255 return $default_blob_plain_mimetype unless $fd;
3257 if (-T $fd) {
3258 return 'text/plain';
3259 } elsif (! $filename) {
3260 return 'application/octet-stream';
3261 } elsif ($filename =~ m/\.png$/i) {
3262 return 'image/png';
3263 } elsif ($filename =~ m/\.gif$/i) {
3264 return 'image/gif';
3265 } elsif ($filename =~ m/\.jpe?g$/i) {
3266 return 'image/jpeg';
3267 } else {
3268 return 'application/octet-stream';
3272 sub blob_contenttype {
3273 my ($fd, $file_name, $type) = @_;
3275 $type ||= blob_mimetype($fd, $file_name);
3276 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3277 $type .= "; charset=$default_text_plain_charset";
3280 return $type;
3283 ## ======================================================================
3284 ## functions printing HTML: header, footer, error page
3286 sub get_page_title {
3287 my $title = to_utf8($site_name);
3289 return $title unless (defined $project);
3290 $title .= " - " . to_utf8($project);
3292 return $title unless (defined $action);
3293 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3295 return $title unless (defined $file_name);
3296 $title .= " - " . esc_path($file_name);
3297 if ($action eq "tree" && $file_name !~ m|/$|) {
3298 $title .= "/";
3301 return $title;
3304 sub git_header_html {
3305 my $status = shift || "200 OK";
3306 my $expires = shift;
3307 my %opts = @_;
3309 my $title = get_page_title();
3310 my $content_type;
3311 # require explicit support from the UA if we are to send the page as
3312 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3313 # we have to do this because MSIE sometimes globs '*/*', pretending to
3314 # support xhtml+xml but choking when it gets what it asked for.
3315 if (defined $cgi->http('HTTP_ACCEPT') &&
3316 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3317 $cgi->Accept('application/xhtml+xml') != 0) {
3318 $content_type = 'application/xhtml+xml';
3319 } else {
3320 $content_type = 'text/html';
3322 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3323 -status=> $status, -expires => $expires)
3324 unless ($opts{'-no_http_headers'});
3325 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3326 print <<EOF;
3327 <?xml version="1.0" encoding="utf-8"?>
3328 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3329 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3330 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3331 <!-- git core binaries version $git_version -->
3332 <head>
3333 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3334 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3335 <meta name="robots" content="index, nofollow"/>
3336 <title>$title</title>
3338 # the stylesheet, favicon etc urls won't work correctly with path_info
3339 # unless we set the appropriate base URL
3340 if ($ENV{'PATH_INFO'}) {
3341 print "<base href=\"".esc_url($base_url)."\" />\n";
3343 # print out each stylesheet that exist, providing backwards capability
3344 # for those people who defined $stylesheet in a config file
3345 if (defined $stylesheet) {
3346 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3347 } else {
3348 foreach my $stylesheet (@stylesheets) {
3349 next unless $stylesheet;
3350 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3353 if (defined $project) {
3354 my %href_params = get_feed_info();
3355 if (!exists $href_params{'-title'}) {
3356 $href_params{'-title'} = 'log';
3359 foreach my $format qw(RSS Atom) {
3360 my $type = lc($format);
3361 my %link_attr = (
3362 '-rel' => 'alternate',
3363 '-title' => "$project - $href_params{'-title'} - $format feed",
3364 '-type' => "application/$type+xml"
3367 $href_params{'action'} = $type;
3368 $link_attr{'-href'} = href(%href_params);
3369 print "<link ".
3370 "rel=\"$link_attr{'-rel'}\" ".
3371 "title=\"$link_attr{'-title'}\" ".
3372 "href=\"$link_attr{'-href'}\" ".
3373 "type=\"$link_attr{'-type'}\" ".
3374 "/>\n";
3376 $href_params{'extra_options'} = '--no-merges';
3377 $link_attr{'-href'} = href(%href_params);
3378 $link_attr{'-title'} .= ' (no merges)';
3379 print "<link ".
3380 "rel=\"$link_attr{'-rel'}\" ".
3381 "title=\"$link_attr{'-title'}\" ".
3382 "href=\"$link_attr{'-href'}\" ".
3383 "type=\"$link_attr{'-type'}\" ".
3384 "/>\n";
3387 } else {
3388 printf('<link rel="alternate" title="%s projects list" '.
3389 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3390 $site_name, href(project=>undef, action=>"project_index"));
3391 printf('<link rel="alternate" title="%s projects feeds" '.
3392 'href="%s" type="text/x-opml" />'."\n",
3393 $site_name, href(project=>undef, action=>"opml"));
3395 if (defined $favicon) {
3396 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3399 print "</head>\n" .
3400 "<body>\n";
3402 if (defined $site_header && -f $site_header) {
3403 insert_file($site_header);
3406 print "<div class=\"page_header\">\n" .
3407 $cgi->a({-href => esc_url($logo_url),
3408 -title => $logo_label},
3409 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3410 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3411 if (defined $project) {
3412 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3413 if (defined $action) {
3414 print " / $action";
3416 print "\n";
3418 print "</div>\n";
3420 my $have_search = gitweb_check_feature('search');
3421 if (defined $project && $have_search) {
3422 if (!defined $searchtext) {
3423 $searchtext = "";
3425 my $search_hash;
3426 if (defined $hash_base) {
3427 $search_hash = $hash_base;
3428 } elsif (defined $hash) {
3429 $search_hash = $hash;
3430 } else {
3431 $search_hash = "HEAD";
3433 my $action = $my_uri;
3434 my $use_pathinfo = gitweb_check_feature('pathinfo');
3435 if ($use_pathinfo) {
3436 $action .= "/".esc_url($project);
3438 print $cgi->startform(-method => "get", -action => $action) .
3439 "<div class=\"search\">\n" .
3440 (!$use_pathinfo &&
3441 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3442 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3443 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3444 $cgi->popup_menu(-name => 'st', -default => 'commit',
3445 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3446 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3447 " search:\n",
3448 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3449 "<span title=\"Extended regular expression\">" .
3450 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3451 -checked => $search_use_regexp) .
3452 "</span>" .
3453 "</div>" .
3454 $cgi->end_form() . "\n";
3458 sub git_footer_html {
3459 my $feed_class = 'rss_logo';
3461 print "<div class=\"page_footer\">\n";
3462 if (defined $project) {
3463 my $descr = git_get_project_description($project);
3464 if (defined $descr) {
3465 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3468 my %href_params = get_feed_info();
3469 if (!%href_params) {
3470 $feed_class .= ' generic';
3472 $href_params{'-title'} ||= 'log';
3474 foreach my $format qw(RSS Atom) {
3475 $href_params{'action'} = lc($format);
3476 print $cgi->a({-href => href(%href_params),
3477 -title => "$href_params{'-title'} $format feed",
3478 -class => $feed_class}, $format)."\n";
3481 } else {
3482 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3483 -class => $feed_class}, "OPML") . " ";
3484 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3485 -class => $feed_class}, "TXT") . "\n";
3487 print "</div>\n"; # class="page_footer"
3489 if (defined $t0 && gitweb_check_feature('timed')) {
3490 print "<div id=\"generating_info\">\n";
3491 print 'This page took '.
3492 '<span id="generating_time" class="time_span">'.
3493 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3494 ' seconds </span>'.
3495 ' and '.
3496 '<span id="generating_cmd">'.
3497 $number_of_git_cmds.
3498 '</span> git commands '.
3499 " to generate.\n";
3500 print "</div>\n"; # class="page_footer"
3503 if (defined $site_footer && -f $site_footer) {
3504 insert_file($site_footer);
3507 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3508 if (defined $action &&
3509 $action eq 'blame_incremental') {
3510 print qq!<script type="text/javascript">\n!.
3511 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3512 qq! "!. href() .qq!");\n!.
3513 qq!</script>\n!;
3514 } elsif (gitweb_check_feature('javascript-actions')) {
3515 print qq!<script type="text/javascript">\n!.
3516 qq!window.onload = fixLinks;\n!.
3517 qq!</script>\n!;
3520 print "</body>\n" .
3521 "</html>";
3524 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3525 # Example: die_error(404, 'Hash not found')
3526 # By convention, use the following status codes (as defined in RFC 2616):
3527 # 400: Invalid or missing CGI parameters, or
3528 # requested object exists but has wrong type.
3529 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3530 # this server or project.
3531 # 404: Requested object/revision/project doesn't exist.
3532 # 500: The server isn't configured properly, or
3533 # an internal error occurred (e.g. failed assertions caused by bugs), or
3534 # an unknown error occurred (e.g. the git binary died unexpectedly).
3535 # 503: The server is currently unavailable (because it is overloaded,
3536 # or down for maintenance). Generally, this is a temporary state.
3537 sub die_error {
3538 my $status = shift || 500;
3539 my $error = esc_html(shift) || "Internal Server Error";
3540 my $extra = shift;
3541 my %opts = @_;
3543 my %http_responses = (
3544 400 => '400 Bad Request',
3545 403 => '403 Forbidden',
3546 404 => '404 Not Found',
3547 500 => '500 Internal Server Error',
3548 503 => '503 Service Unavailable',
3550 git_header_html($http_responses{$status}, undef, %opts);
3551 print <<EOF;
3552 <div class="page_body">
3553 <br /><br />
3554 $status - $error
3555 <br />
3557 if (defined $extra) {
3558 print "<hr />\n" .
3559 "$extra\n";
3561 print "</div>\n";
3563 git_footer_html();
3564 goto DONE_GITWEB
3565 unless ($opts{'-error_handler'});
3568 ## ----------------------------------------------------------------------
3569 ## functions printing or outputting HTML: navigation
3571 sub git_print_page_nav {
3572 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3573 $extra = '' if !defined $extra; # pager or formats
3575 my @navs = qw(summary shortlog log commit commitdiff tree);
3576 if ($suppress) {
3577 @navs = grep { $_ ne $suppress } @navs;
3580 my %arg = map { $_ => {action=>$_} } @navs;
3581 if (defined $head) {
3582 for (qw(commit commitdiff)) {
3583 $arg{$_}{'hash'} = $head;
3585 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3586 for (qw(shortlog log)) {
3587 $arg{$_}{'hash'} = $head;
3592 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3593 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3595 my @actions = gitweb_get_feature('actions');
3596 my %repl = (
3597 '%' => '%',
3598 'n' => $project, # project name
3599 'f' => $git_dir, # project path within filesystem
3600 'h' => $treehead || '', # current hash ('h' parameter)
3601 'b' => $treebase || '', # hash base ('hb' parameter)
3603 while (@actions) {
3604 my ($label, $link, $pos) = splice(@actions,0,3);
3605 # insert
3606 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3607 # munch munch
3608 $link =~ s/%([%nfhb])/$repl{$1}/g;
3609 $arg{$label}{'_href'} = $link;
3612 print "<div class=\"page_nav\">\n" .
3613 (join " | ",
3614 map { $_ eq $current ?
3615 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3616 } @navs);
3617 print "<br/>\n$extra<br/>\n" .
3618 "</div>\n";
3621 sub format_paging_nav {
3622 my ($action, $page, $has_next_link) = @_;
3623 my $paging_nav;
3626 if ($page > 0) {
3627 $paging_nav .=
3628 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3629 " &sdot; " .
3630 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3631 -accesskey => "p", -title => "Alt-p"}, "prev");
3632 } else {
3633 $paging_nav .= "first &sdot; prev";
3636 if ($has_next_link) {
3637 $paging_nav .= " &sdot; " .
3638 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3639 -accesskey => "n", -title => "Alt-n"}, "next");
3640 } else {
3641 $paging_nav .= " &sdot; next";
3644 return $paging_nav;
3647 ## ......................................................................
3648 ## functions printing or outputting HTML: div
3650 sub git_print_header_div {
3651 my ($action, $title, $hash, $hash_base) = @_;
3652 my %args = ();
3654 $args{'action'} = $action;
3655 $args{'hash'} = $hash if $hash;
3656 $args{'hash_base'} = $hash_base if $hash_base;
3658 print "<div class=\"header\">\n" .
3659 $cgi->a({-href => href(%args), -class => "title"},
3660 $title ? $title : $action) .
3661 "\n</div>\n";
3664 sub print_local_time {
3665 print format_local_time(@_);
3668 sub format_local_time {
3669 my $localtime = '';
3670 my %date = @_;
3671 if ($date{'hour_local'} < 6) {
3672 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3673 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3674 } else {
3675 $localtime .= sprintf(" (%02d:%02d %s)",
3676 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3679 return $localtime;
3682 # Outputs the author name and date in long form
3683 sub git_print_authorship {
3684 my $co = shift;
3685 my %opts = @_;
3686 my $tag = $opts{-tag} || 'div';
3687 my $author = $co->{'author_name'};
3689 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3690 print "<$tag class=\"author_date\">" .
3691 format_search_author($author, "author", esc_html($author)) .
3692 " [$ad{'rfc2822'}";
3693 print_local_time(%ad) if ($opts{-localtime});
3694 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3695 . "</$tag>\n";
3698 # Outputs table rows containing the full author or committer information,
3699 # in the format expected for 'commit' view (& similia).
3700 # Parameters are a commit hash reference, followed by the list of people
3701 # to output information for. If the list is empty it defalts to both
3702 # author and committer.
3703 sub git_print_authorship_rows {
3704 my $co = shift;
3705 # too bad we can't use @people = @_ || ('author', 'committer')
3706 my @people = @_;
3707 @people = ('author', 'committer') unless @people;
3708 foreach my $who (@people) {
3709 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3710 print "<tr><td>$who</td><td>" .
3711 format_search_author($co->{"${who}_name"}, $who,
3712 esc_html($co->{"${who}_name"})) . " " .
3713 format_search_author($co->{"${who}_email"}, $who,
3714 esc_html("<" . $co->{"${who}_email"} . ">")) .
3715 "</td><td rowspan=\"2\">" .
3716 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3717 "</td></tr>\n" .
3718 "<tr>" .
3719 "<td></td><td> $wd{'rfc2822'}";
3720 print_local_time(%wd);
3721 print "</td>" .
3722 "</tr>\n";
3726 sub git_print_page_path {
3727 my $name = shift;
3728 my $type = shift;
3729 my $hb = shift;
3732 print "<div class=\"page_path\">";
3733 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3734 -title => 'tree root'}, to_utf8("[$project]"));
3735 print " / ";
3736 if (defined $name) {
3737 my @dirname = split '/', $name;
3738 my $basename = pop @dirname;
3739 my $fullname = '';
3741 foreach my $dir (@dirname) {
3742 $fullname .= ($fullname ? '/' : '') . $dir;
3743 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3744 hash_base=>$hb),
3745 -title => $fullname}, esc_path($dir));
3746 print " / ";
3748 if (defined $type && $type eq 'blob') {
3749 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3750 hash_base=>$hb),
3751 -title => $name}, esc_path($basename));
3752 } elsif (defined $type && $type eq 'tree') {
3753 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3754 hash_base=>$hb),
3755 -title => $name}, esc_path($basename));
3756 print " / ";
3757 } else {
3758 print esc_path($basename);
3761 print "<br/></div>\n";
3764 sub git_print_log {
3765 my $log = shift;
3766 my %opts = @_;
3768 if ($opts{'-remove_title'}) {
3769 # remove title, i.e. first line of log
3770 shift @$log;
3772 # remove leading empty lines
3773 while (defined $log->[0] && $log->[0] eq "") {
3774 shift @$log;
3777 # print log
3778 my $signoff = 0;
3779 my $empty = 0;
3780 foreach my $line (@$log) {
3781 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3782 $signoff = 1;
3783 $empty = 0;
3784 if (! $opts{'-remove_signoff'}) {
3785 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3786 next;
3787 } else {
3788 # remove signoff lines
3789 next;
3791 } else {
3792 $signoff = 0;
3795 # print only one empty line
3796 # do not print empty line after signoff
3797 if ($line eq "") {
3798 next if ($empty || $signoff);
3799 $empty = 1;
3800 } else {
3801 $empty = 0;
3804 print format_log_line_html($line) . "<br/>\n";
3807 if ($opts{'-final_empty_line'}) {
3808 # end with single empty line
3809 print "<br/>\n" unless $empty;
3813 # return link target (what link points to)
3814 sub git_get_link_target {
3815 my $hash = shift;
3816 my $link_target;
3818 # read link
3819 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3820 or return;
3822 local $/ = undef;
3823 $link_target = <$fd>;
3825 close $fd
3826 or return;
3828 return $link_target;
3831 # given link target, and the directory (basedir) the link is in,
3832 # return target of link relative to top directory (top tree);
3833 # return undef if it is not possible (including absolute links).
3834 sub normalize_link_target {
3835 my ($link_target, $basedir) = @_;
3837 # absolute symlinks (beginning with '/') cannot be normalized
3838 return if (substr($link_target, 0, 1) eq '/');
3840 # normalize link target to path from top (root) tree (dir)
3841 my $path;
3842 if ($basedir) {
3843 $path = $basedir . '/' . $link_target;
3844 } else {
3845 # we are in top (root) tree (dir)
3846 $path = $link_target;
3849 # remove //, /./, and /../
3850 my @path_parts;
3851 foreach my $part (split('/', $path)) {
3852 # discard '.' and ''
3853 next if (!$part || $part eq '.');
3854 # handle '..'
3855 if ($part eq '..') {
3856 if (@path_parts) {
3857 pop @path_parts;
3858 } else {
3859 # link leads outside repository (outside top dir)
3860 return;
3862 } else {
3863 push @path_parts, $part;
3866 $path = join('/', @path_parts);
3868 return $path;
3871 # print tree entry (row of git_tree), but without encompassing <tr> element
3872 sub git_print_tree_entry {
3873 my ($t, $basedir, $hash_base, $have_blame) = @_;
3875 my %base_key = ();
3876 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3878 # The format of a table row is: mode list link. Where mode is
3879 # the mode of the entry, list is the name of the entry, an href,
3880 # and link is the action links of the entry.
3882 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3883 if (exists $t->{'size'}) {
3884 print "<td class=\"size\">$t->{'size'}</td>\n";
3886 if ($t->{'type'} eq "blob") {
3887 print "<td class=\"list\">" .
3888 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3889 file_name=>"$basedir$t->{'name'}", %base_key),
3890 -class => "list"}, esc_path($t->{'name'}));
3891 if (S_ISLNK(oct $t->{'mode'})) {
3892 my $link_target = git_get_link_target($t->{'hash'});
3893 if ($link_target) {
3894 my $norm_target = normalize_link_target($link_target, $basedir);
3895 if (defined $norm_target) {
3896 print " -> " .
3897 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3898 file_name=>$norm_target),
3899 -title => $norm_target}, esc_path($link_target));
3900 } else {
3901 print " -> " . esc_path($link_target);
3905 print "</td>\n";
3906 print "<td class=\"link\">";
3907 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3908 file_name=>"$basedir$t->{'name'}", %base_key)},
3909 "blob");
3910 if ($have_blame) {
3911 print " | " .
3912 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3913 file_name=>"$basedir$t->{'name'}", %base_key)},
3914 "blame");
3916 if (defined $hash_base) {
3917 print " | " .
3918 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3919 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3920 "history");
3922 print " | " .
3923 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3924 file_name=>"$basedir$t->{'name'}")},
3925 "raw");
3926 print "</td>\n";
3928 } elsif ($t->{'type'} eq "tree") {
3929 print "<td class=\"list\">";
3930 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3931 file_name=>"$basedir$t->{'name'}",
3932 %base_key)},
3933 esc_path($t->{'name'}));
3934 print "</td>\n";
3935 print "<td class=\"link\">";
3936 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3937 file_name=>"$basedir$t->{'name'}",
3938 %base_key)},
3939 "tree");
3940 if (defined $hash_base) {
3941 print " | " .
3942 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3943 file_name=>"$basedir$t->{'name'}")},
3944 "history");
3946 print "</td>\n";
3947 } else {
3948 # unknown object: we can only present history for it
3949 # (this includes 'commit' object, i.e. submodule support)
3950 print "<td class=\"list\">" .
3951 esc_path($t->{'name'}) .
3952 "</td>\n";
3953 print "<td class=\"link\">";
3954 if (defined $hash_base) {
3955 print $cgi->a({-href => href(action=>"history",
3956 hash_base=>$hash_base,
3957 file_name=>"$basedir$t->{'name'}")},
3958 "history");
3960 print "</td>\n";
3964 ## ......................................................................
3965 ## functions printing large fragments of HTML
3967 # get pre-image filenames for merge (combined) diff
3968 sub fill_from_file_info {
3969 my ($diff, @parents) = @_;
3971 $diff->{'from_file'} = [ ];
3972 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3973 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3974 if ($diff->{'status'}[$i] eq 'R' ||
3975 $diff->{'status'}[$i] eq 'C') {
3976 $diff->{'from_file'}[$i] =
3977 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3981 return $diff;
3984 # is current raw difftree line of file deletion
3985 sub is_deleted {
3986 my $diffinfo = shift;
3988 return $diffinfo->{'to_id'} eq ('0' x 40);
3991 # does patch correspond to [previous] difftree raw line
3992 # $diffinfo - hashref of parsed raw diff format
3993 # $patchinfo - hashref of parsed patch diff format
3994 # (the same keys as in $diffinfo)
3995 sub is_patch_split {
3996 my ($diffinfo, $patchinfo) = @_;
3998 return defined $diffinfo && defined $patchinfo
3999 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4003 sub git_difftree_body {
4004 my ($difftree, $hash, @parents) = @_;
4005 my ($parent) = $parents[0];
4006 my $have_blame = gitweb_check_feature('blame');
4007 print "<div class=\"list_head\">\n";
4008 if ($#{$difftree} > 10) {
4009 print(($#{$difftree} + 1) . " files changed:\n");
4011 print "</div>\n";
4013 print "<table class=\"" .
4014 (@parents > 1 ? "combined " : "") .
4015 "diff_tree\">\n";
4017 # header only for combined diff in 'commitdiff' view
4018 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4019 if ($has_header) {
4020 # table header
4021 print "<thead><tr>\n" .
4022 "<th></th><th></th>\n"; # filename, patchN link
4023 for (my $i = 0; $i < @parents; $i++) {
4024 my $par = $parents[$i];
4025 print "<th>" .
4026 $cgi->a({-href => href(action=>"commitdiff",
4027 hash=>$hash, hash_parent=>$par),
4028 -title => 'commitdiff to parent number ' .
4029 ($i+1) . ': ' . substr($par,0,7)},
4030 $i+1) .
4031 "&nbsp;</th>\n";
4033 print "</tr></thead>\n<tbody>\n";
4036 my $alternate = 1;
4037 my $patchno = 0;
4038 foreach my $line (@{$difftree}) {
4039 my $diff = parsed_difftree_line($line);
4041 if ($alternate) {
4042 print "<tr class=\"dark\">\n";
4043 } else {
4044 print "<tr class=\"light\">\n";
4046 $alternate ^= 1;
4048 if (exists $diff->{'nparents'}) { # combined diff
4050 fill_from_file_info($diff, @parents)
4051 unless exists $diff->{'from_file'};
4053 if (!is_deleted($diff)) {
4054 # file exists in the result (child) commit
4055 print "<td>" .
4056 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4057 file_name=>$diff->{'to_file'},
4058 hash_base=>$hash),
4059 -class => "list"}, esc_path($diff->{'to_file'})) .
4060 "</td>\n";
4061 } else {
4062 print "<td>" .
4063 esc_path($diff->{'to_file'}) .
4064 "</td>\n";
4067 if ($action eq 'commitdiff') {
4068 # link to patch
4069 $patchno++;
4070 print "<td class=\"link\">" .
4071 $cgi->a({-href => "#patch$patchno"}, "patch") .
4072 " | " .
4073 "</td>\n";
4076 my $has_history = 0;
4077 my $not_deleted = 0;
4078 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4079 my $hash_parent = $parents[$i];
4080 my $from_hash = $diff->{'from_id'}[$i];
4081 my $from_path = $diff->{'from_file'}[$i];
4082 my $status = $diff->{'status'}[$i];
4084 $has_history ||= ($status ne 'A');
4085 $not_deleted ||= ($status ne 'D');
4087 if ($status eq 'A') {
4088 print "<td class=\"link\" align=\"right\"> | </td>\n";
4089 } elsif ($status eq 'D') {
4090 print "<td class=\"link\">" .
4091 $cgi->a({-href => href(action=>"blob",
4092 hash_base=>$hash,
4093 hash=>$from_hash,
4094 file_name=>$from_path)},
4095 "blob" . ($i+1)) .
4096 " | </td>\n";
4097 } else {
4098 if ($diff->{'to_id'} eq $from_hash) {
4099 print "<td class=\"link nochange\">";
4100 } else {
4101 print "<td class=\"link\">";
4103 print $cgi->a({-href => href(action=>"blobdiff",
4104 hash=>$diff->{'to_id'},
4105 hash_parent=>$from_hash,
4106 hash_base=>$hash,
4107 hash_parent_base=>$hash_parent,
4108 file_name=>$diff->{'to_file'},
4109 file_parent=>$from_path)},
4110 "diff" . ($i+1)) .
4111 " | </td>\n";
4115 print "<td class=\"link\">";
4116 if ($not_deleted) {
4117 print $cgi->a({-href => href(action=>"blob",
4118 hash=>$diff->{'to_id'},
4119 file_name=>$diff->{'to_file'},
4120 hash_base=>$hash)},
4121 "blob");
4122 print " | " if ($has_history);
4124 if ($has_history) {
4125 print $cgi->a({-href => href(action=>"history",
4126 file_name=>$diff->{'to_file'},
4127 hash_base=>$hash)},
4128 "history");
4130 print "</td>\n";
4132 print "</tr>\n";
4133 next; # instead of 'else' clause, to avoid extra indent
4135 # else ordinary diff
4137 my ($to_mode_oct, $to_mode_str, $to_file_type);
4138 my ($from_mode_oct, $from_mode_str, $from_file_type);
4139 if ($diff->{'to_mode'} ne ('0' x 6)) {
4140 $to_mode_oct = oct $diff->{'to_mode'};
4141 if (S_ISREG($to_mode_oct)) { # only for regular file
4142 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4144 $to_file_type = file_type($diff->{'to_mode'});
4146 if ($diff->{'from_mode'} ne ('0' x 6)) {
4147 $from_mode_oct = oct $diff->{'from_mode'};
4148 if (S_ISREG($to_mode_oct)) { # only for regular file
4149 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4151 $from_file_type = file_type($diff->{'from_mode'});
4154 if ($diff->{'status'} eq "A") { # created
4155 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4156 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4157 $mode_chng .= "]</span>";
4158 print "<td>";
4159 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4160 hash_base=>$hash, file_name=>$diff->{'file'}),
4161 -class => "list"}, esc_path($diff->{'file'}));
4162 print "</td>\n";
4163 print "<td>$mode_chng</td>\n";
4164 print "<td class=\"link\">";
4165 if ($action eq 'commitdiff') {
4166 # link to patch
4167 $patchno++;
4168 print $cgi->a({-href => "#patch$patchno"}, "patch");
4169 print " | ";
4171 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4172 hash_base=>$hash, file_name=>$diff->{'file'})},
4173 "blob");
4174 print "</td>\n";
4176 } elsif ($diff->{'status'} eq "D") { # deleted
4177 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4178 print "<td>";
4179 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4180 hash_base=>$parent, file_name=>$diff->{'file'}),
4181 -class => "list"}, esc_path($diff->{'file'}));
4182 print "</td>\n";
4183 print "<td>$mode_chng</td>\n";
4184 print "<td class=\"link\">";
4185 if ($action eq 'commitdiff') {
4186 # link to patch
4187 $patchno++;
4188 print $cgi->a({-href => "#patch$patchno"}, "patch");
4189 print " | ";
4191 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4192 hash_base=>$parent, file_name=>$diff->{'file'})},
4193 "blob") . " | ";
4194 if ($have_blame) {
4195 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4196 file_name=>$diff->{'file'})},
4197 "blame") . " | ";
4199 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4200 file_name=>$diff->{'file'})},
4201 "history");
4202 print "</td>\n";
4204 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4205 my $mode_chnge = "";
4206 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4207 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4208 if ($from_file_type ne $to_file_type) {
4209 $mode_chnge .= " from $from_file_type to $to_file_type";
4211 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4212 if ($from_mode_str && $to_mode_str) {
4213 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4214 } elsif ($to_mode_str) {
4215 $mode_chnge .= " mode: $to_mode_str";
4218 $mode_chnge .= "]</span>\n";
4220 print "<td>";
4221 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4222 hash_base=>$hash, file_name=>$diff->{'file'}),
4223 -class => "list"}, esc_path($diff->{'file'}));
4224 print "</td>\n";
4225 print "<td>$mode_chnge</td>\n";
4226 print "<td class=\"link\">";
4227 if ($action eq 'commitdiff') {
4228 # link to patch
4229 $patchno++;
4230 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4231 " | ";
4232 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4233 # "commit" view and modified file (not onlu mode changed)
4234 print $cgi->a({-href => href(action=>"blobdiff",
4235 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4236 hash_base=>$hash, hash_parent_base=>$parent,
4237 file_name=>$diff->{'file'})},
4238 "diff") .
4239 " | ";
4241 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4242 hash_base=>$hash, file_name=>$diff->{'file'})},
4243 "blob") . " | ";
4244 if ($have_blame) {
4245 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4246 file_name=>$diff->{'file'})},
4247 "blame") . " | ";
4249 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4250 file_name=>$diff->{'file'})},
4251 "history");
4252 print "</td>\n";
4254 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4255 my %status_name = ('R' => 'moved', 'C' => 'copied');
4256 my $nstatus = $status_name{$diff->{'status'}};
4257 my $mode_chng = "";
4258 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4259 # mode also for directories, so we cannot use $to_mode_str
4260 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4262 print "<td>" .
4263 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4264 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4265 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4266 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4267 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4268 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4269 -class => "list"}, esc_path($diff->{'from_file'})) .
4270 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4271 "<td class=\"link\">";
4272 if ($action eq 'commitdiff') {
4273 # link to patch
4274 $patchno++;
4275 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4276 " | ";
4277 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4278 # "commit" view and modified file (not only pure rename or copy)
4279 print $cgi->a({-href => href(action=>"blobdiff",
4280 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4281 hash_base=>$hash, hash_parent_base=>$parent,
4282 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4283 "diff") .
4284 " | ";
4286 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4287 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4288 "blob") . " | ";
4289 if ($have_blame) {
4290 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4291 file_name=>$diff->{'to_file'})},
4292 "blame") . " | ";
4294 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4295 file_name=>$diff->{'to_file'})},
4296 "history");
4297 print "</td>\n";
4299 } # we should not encounter Unmerged (U) or Unknown (X) status
4300 print "</tr>\n";
4302 print "</tbody>" if $has_header;
4303 print "</table>\n";
4306 sub git_patchset_body {
4307 my ($fd, $difftree, $hash, @hash_parents) = @_;
4308 my ($hash_parent) = $hash_parents[0];
4310 my $is_combined = (@hash_parents > 1);
4311 my $patch_idx = 0;
4312 my $patch_number = 0;
4313 my $patch_line;
4314 my $diffinfo;
4315 my $to_name;
4316 my (%from, %to);
4318 print "<div class=\"patchset\">\n";
4320 # skip to first patch
4321 while ($patch_line = <$fd>) {
4322 chomp $patch_line;
4324 last if ($patch_line =~ m/^diff /);
4327 PATCH:
4328 while ($patch_line) {
4330 # parse "git diff" header line
4331 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4332 # $1 is from_name, which we do not use
4333 $to_name = unquote($2);
4334 $to_name =~ s!^b/!!;
4335 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4336 # $1 is 'cc' or 'combined', which we do not use
4337 $to_name = unquote($2);
4338 } else {
4339 $to_name = undef;
4342 # check if current patch belong to current raw line
4343 # and parse raw git-diff line if needed
4344 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4345 # this is continuation of a split patch
4346 print "<div class=\"patch cont\">\n";
4347 } else {
4348 # advance raw git-diff output if needed
4349 $patch_idx++ if defined $diffinfo;
4351 # read and prepare patch information
4352 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4354 # compact combined diff output can have some patches skipped
4355 # find which patch (using pathname of result) we are at now;
4356 if ($is_combined) {
4357 while ($to_name ne $diffinfo->{'to_file'}) {
4358 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4359 format_diff_cc_simplified($diffinfo, @hash_parents) .
4360 "</div>\n"; # class="patch"
4362 $patch_idx++;
4363 $patch_number++;
4365 last if $patch_idx > $#$difftree;
4366 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4370 # modifies %from, %to hashes
4371 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4373 # this is first patch for raw difftree line with $patch_idx index
4374 # we index @$difftree array from 0, but number patches from 1
4375 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4378 # git diff header
4379 #assert($patch_line =~ m/^diff /) if DEBUG;
4380 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4381 $patch_number++;
4382 # print "git diff" header
4383 print format_git_diff_header_line($patch_line, $diffinfo,
4384 \%from, \%to);
4386 # print extended diff header
4387 print "<div class=\"diff extended_header\">\n";
4388 EXTENDED_HEADER:
4389 while ($patch_line = <$fd>) {
4390 chomp $patch_line;
4392 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4394 print format_extended_diff_header_line($patch_line, $diffinfo,
4395 \%from, \%to);
4397 print "</div>\n"; # class="diff extended_header"
4399 # from-file/to-file diff header
4400 if (! $patch_line) {
4401 print "</div>\n"; # class="patch"
4402 last PATCH;
4404 next PATCH if ($patch_line =~ m/^diff /);
4405 #assert($patch_line =~ m/^---/) if DEBUG;
4407 my $last_patch_line = $patch_line;
4408 $patch_line = <$fd>;
4409 chomp $patch_line;
4410 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4412 print format_diff_from_to_header($last_patch_line, $patch_line,
4413 $diffinfo, \%from, \%to,
4414 @hash_parents);
4416 # the patch itself
4417 LINE:
4418 while ($patch_line = <$fd>) {
4419 chomp $patch_line;
4421 next PATCH if ($patch_line =~ m/^diff /);
4423 print format_diff_line($patch_line, \%from, \%to);
4426 } continue {
4427 print "</div>\n"; # class="patch"
4430 # for compact combined (--cc) format, with chunk and patch simpliciaction
4431 # patchset might be empty, but there might be unprocessed raw lines
4432 for (++$patch_idx if $patch_number > 0;
4433 $patch_idx < @$difftree;
4434 ++$patch_idx) {
4435 # read and prepare patch information
4436 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4438 # generate anchor for "patch" links in difftree / whatchanged part
4439 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4440 format_diff_cc_simplified($diffinfo, @hash_parents) .
4441 "</div>\n"; # class="patch"
4443 $patch_number++;
4446 if ($patch_number == 0) {
4447 if (@hash_parents > 1) {
4448 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4449 } else {
4450 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4454 print "</div>\n"; # class="patchset"
4457 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4459 # fills project list info (age, description, owner, forks) for each
4460 # project in the list, removing invalid projects from returned list
4461 # NOTE: modifies $projlist, but does not remove entries from it
4462 sub fill_project_list_info {
4463 my ($projlist, $check_forks) = @_;
4464 my @projects;
4466 my $show_ctags = gitweb_check_feature('ctags');
4467 PROJECT:
4468 foreach my $pr (@$projlist) {
4469 my (@activity) = git_get_last_activity($pr->{'path'});
4470 unless (@activity) {
4471 next PROJECT;
4473 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4474 if (!defined $pr->{'descr'}) {
4475 my $descr = git_get_project_description($pr->{'path'}) || "";
4476 $descr = to_utf8($descr);
4477 $pr->{'descr_long'} = $descr;
4478 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4480 if (!defined $pr->{'owner'}) {
4481 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4483 if ($check_forks) {
4484 my $pname = $pr->{'path'};
4485 if (($pname =~ s/\.git$//) &&
4486 ($pname !~ /\/$/) &&
4487 (-d "$projectroot/$pname")) {
4488 $pr->{'forks'} = "-d $projectroot/$pname";
4489 } else {
4490 $pr->{'forks'} = 0;
4493 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4494 push @projects, $pr;
4497 return @projects;
4500 # print 'sort by' <th> element, generating 'sort by $name' replay link
4501 # if that order is not selected
4502 sub print_sort_th {
4503 print format_sort_th(@_);
4506 sub format_sort_th {
4507 my ($name, $order, $header) = @_;
4508 my $sort_th = "";
4509 $header ||= ucfirst($name);
4511 if ($order eq $name) {
4512 $sort_th .= "<th>$header</th>\n";
4513 } else {
4514 $sort_th .= "<th>" .
4515 $cgi->a({-href => href(-replay=>1, order=>$name),
4516 -class => "header"}, $header) .
4517 "</th>\n";
4520 return $sort_th;
4523 sub git_project_list_body {
4524 # actually uses global variable $project
4525 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4527 my $check_forks = gitweb_check_feature('forks');
4528 my @projects = fill_project_list_info($projlist, $check_forks);
4530 $order ||= $default_projects_order;
4531 $from = 0 unless defined $from;
4532 $to = $#projects if (!defined $to || $#projects < $to);
4534 my %order_info = (
4535 project => { key => 'path', type => 'str' },
4536 descr => { key => 'descr_long', type => 'str' },
4537 owner => { key => 'owner', type => 'str' },
4538 age => { key => 'age', type => 'num' }
4540 my $oi = $order_info{$order};
4541 if ($oi->{'type'} eq 'str') {
4542 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4543 } else {
4544 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4547 my $show_ctags = gitweb_check_feature('ctags');
4548 if ($show_ctags) {
4549 my %ctags;
4550 foreach my $p (@projects) {
4551 foreach my $ct (keys %{$p->{'ctags'}}) {
4552 $ctags{$ct} += $p->{'ctags'}->{$ct};
4555 my $cloud = git_populate_project_tagcloud(\%ctags);
4556 print git_show_project_tagcloud($cloud, 64);
4559 print "<table class=\"project_list\">\n";
4560 unless ($no_header) {
4561 print "<tr>\n";
4562 if ($check_forks) {
4563 print "<th></th>\n";
4565 print_sort_th('project', $order, 'Project');
4566 print_sort_th('descr', $order, 'Description');
4567 print_sort_th('owner', $order, 'Owner');
4568 print_sort_th('age', $order, 'Last Change');
4569 print "<th></th>\n" . # for links
4570 "</tr>\n";
4572 my $alternate = 1;
4573 my $tagfilter = $cgi->param('by_tag');
4574 for (my $i = $from; $i <= $to; $i++) {
4575 my $pr = $projects[$i];
4577 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4578 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4579 and not $pr->{'descr_long'} =~ /$searchtext/;
4580 # Weed out forks or non-matching entries of search
4581 if ($check_forks) {
4582 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4583 $forkbase="^$forkbase" if $forkbase;
4584 next if not $searchtext and not $tagfilter and $show_ctags
4585 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4588 if ($alternate) {
4589 print "<tr class=\"dark\">\n";
4590 } else {
4591 print "<tr class=\"light\">\n";
4593 $alternate ^= 1;
4594 if ($check_forks) {
4595 print "<td>";
4596 if ($pr->{'forks'}) {
4597 print "<!-- $pr->{'forks'} -->\n";
4598 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4600 print "</td>\n";
4602 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4603 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4604 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4605 -class => "list", -title => $pr->{'descr_long'}},
4606 esc_html($pr->{'descr'})) . "</td>\n" .
4607 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4608 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4609 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4610 "<td class=\"link\">" .
4611 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4612 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4613 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4614 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4615 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4616 "</td>\n" .
4617 "</tr>\n";
4619 if (defined $extra) {
4620 print "<tr>\n";
4621 if ($check_forks) {
4622 print "<td></td>\n";
4624 print "<td colspan=\"5\">$extra</td>\n" .
4625 "</tr>\n";
4627 print "</table>\n";
4630 sub git_log_body {
4631 # uses global variable $project
4632 my ($commitlist, $from, $to, $refs, $extra) = @_;
4634 $from = 0 unless defined $from;
4635 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4637 for (my $i = 0; $i <= $to; $i++) {
4638 my %co = %{$commitlist->[$i]};
4639 next if !%co;
4640 my $commit = $co{'id'};
4641 my $ref = format_ref_marker($refs, $commit);
4642 my %ad = parse_date($co{'author_epoch'});
4643 git_print_header_div('commit',
4644 "<span class=\"age\">$co{'age_string'}</span>" .
4645 esc_html($co{'title'}) . $ref,
4646 $commit);
4647 print "<div class=\"title_text\">\n" .
4648 "<div class=\"log_link\">\n" .
4649 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4650 " | " .
4651 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4652 " | " .
4653 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4654 "<br/>\n" .
4655 "</div>\n";
4656 git_print_authorship(\%co, -tag => 'span');
4657 print "<br/>\n</div>\n";
4659 print "<div class=\"log_body\">\n";
4660 git_print_log($co{'comment'}, -final_empty_line=> 1);
4661 print "</div>\n";
4663 if ($extra) {
4664 print "<div class=\"page_nav\">\n";
4665 print "$extra\n";
4666 print "</div>\n";
4670 sub git_shortlog_body {
4671 # uses global variable $project
4672 my ($commitlist, $from, $to, $refs, $extra) = @_;
4674 $from = 0 unless defined $from;
4675 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4677 print "<table class=\"shortlog\">\n";
4678 my $alternate = 1;
4679 for (my $i = $from; $i <= $to; $i++) {
4680 my %co = %{$commitlist->[$i]};
4681 my $commit = $co{'id'};
4682 my $ref = format_ref_marker($refs, $commit);
4683 if ($alternate) {
4684 print "<tr class=\"dark\">\n";
4685 } else {
4686 print "<tr class=\"light\">\n";
4688 $alternate ^= 1;
4689 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4690 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4691 format_author_html('td', \%co, 10) . "<td>";
4692 print format_subject_html($co{'title'}, $co{'title_short'},
4693 href(action=>"commit", hash=>$commit), $ref);
4694 print "</td>\n" .
4695 "<td class=\"link\">" .
4696 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4697 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4698 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4699 my $snapshot_links = format_snapshot_links($commit);
4700 if (defined $snapshot_links) {
4701 print " | " . $snapshot_links;
4703 print "</td>\n" .
4704 "</tr>\n";
4706 if (defined $extra) {
4707 print "<tr>\n" .
4708 "<td colspan=\"4\">$extra</td>\n" .
4709 "</tr>\n";
4711 print "</table>\n";
4714 sub git_history_body {
4715 # Warning: assumes constant type (blob or tree) during history
4716 my ($commitlist, $from, $to, $refs, $extra,
4717 $file_name, $file_hash, $ftype) = @_;
4719 $from = 0 unless defined $from;
4720 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4722 print "<table class=\"history\">\n";
4723 my $alternate = 1;
4724 for (my $i = $from; $i <= $to; $i++) {
4725 my %co = %{$commitlist->[$i]};
4726 if (!%co) {
4727 next;
4729 my $commit = $co{'id'};
4731 my $ref = format_ref_marker($refs, $commit);
4733 if ($alternate) {
4734 print "<tr class=\"dark\">\n";
4735 } else {
4736 print "<tr class=\"light\">\n";
4738 $alternate ^= 1;
4739 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4740 # shortlog: format_author_html('td', \%co, 10)
4741 format_author_html('td', \%co, 15, 3) . "<td>";
4742 # originally git_history used chop_str($co{'title'}, 50)
4743 print format_subject_html($co{'title'}, $co{'title_short'},
4744 href(action=>"commit", hash=>$commit), $ref);
4745 print "</td>\n" .
4746 "<td class=\"link\">" .
4747 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4748 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4750 if ($ftype eq 'blob') {
4751 my $blob_current = $file_hash;
4752 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4753 if (defined $blob_current && defined $blob_parent &&
4754 $blob_current ne $blob_parent) {
4755 print " | " .
4756 $cgi->a({-href => href(action=>"blobdiff",
4757 hash=>$blob_current, hash_parent=>$blob_parent,
4758 hash_base=>$hash_base, hash_parent_base=>$commit,
4759 file_name=>$file_name)},
4760 "diff to current");
4763 print "</td>\n" .
4764 "</tr>\n";
4766 if (defined $extra) {
4767 print "<tr>\n" .
4768 "<td colspan=\"4\">$extra</td>\n" .
4769 "</tr>\n";
4771 print "</table>\n";
4774 sub git_tags_body {
4775 # uses global variable $project
4776 my ($taglist, $from, $to, $extra) = @_;
4777 $from = 0 unless defined $from;
4778 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4780 print "<table class=\"tags\">\n";
4781 my $alternate = 1;
4782 for (my $i = $from; $i <= $to; $i++) {
4783 my $entry = $taglist->[$i];
4784 my %tag = %$entry;
4785 my $comment = $tag{'subject'};
4786 my $comment_short;
4787 if (defined $comment) {
4788 $comment_short = chop_str($comment, 30, 5);
4790 if ($alternate) {
4791 print "<tr class=\"dark\">\n";
4792 } else {
4793 print "<tr class=\"light\">\n";
4795 $alternate ^= 1;
4796 if (defined $tag{'age'}) {
4797 print "<td><i>$tag{'age'}</i></td>\n";
4798 } else {
4799 print "<td></td>\n";
4801 print "<td>" .
4802 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4803 -class => "list name"}, esc_html($tag{'name'})) .
4804 "</td>\n" .
4805 "<td>";
4806 if (defined $comment) {
4807 print format_subject_html($comment, $comment_short,
4808 href(action=>"tag", hash=>$tag{'id'}));
4810 print "</td>\n" .
4811 "<td class=\"selflink\">";
4812 if ($tag{'type'} eq "tag") {
4813 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4814 } else {
4815 print "&nbsp;";
4817 print "</td>\n" .
4818 "<td class=\"link\">" . " | " .
4819 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4820 if ($tag{'reftype'} eq "commit") {
4821 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4822 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4823 } elsif ($tag{'reftype'} eq "blob") {
4824 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4826 print "</td>\n" .
4827 "</tr>";
4829 if (defined $extra) {
4830 print "<tr>\n" .
4831 "<td colspan=\"5\">$extra</td>\n" .
4832 "</tr>\n";
4834 print "</table>\n";
4837 sub git_heads_body {
4838 # uses global variable $project
4839 my ($headlist, $head, $from, $to, $extra) = @_;
4840 $from = 0 unless defined $from;
4841 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4843 print "<table class=\"heads\">\n";
4844 my $alternate = 1;
4845 for (my $i = $from; $i <= $to; $i++) {
4846 my $entry = $headlist->[$i];
4847 my %ref = %$entry;
4848 my $curr = $ref{'id'} eq $head;
4849 if ($alternate) {
4850 print "<tr class=\"dark\">\n";
4851 } else {
4852 print "<tr class=\"light\">\n";
4854 $alternate ^= 1;
4855 print "<td><i>$ref{'age'}</i></td>\n" .
4856 ($curr ? "<td class=\"current_head\">" : "<td>") .
4857 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4858 -class => "list name"},esc_html($ref{'name'})) .
4859 "</td>\n" .
4860 "<td class=\"link\">" .
4861 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4862 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4863 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4864 "</td>\n" .
4865 "</tr>";
4867 if (defined $extra) {
4868 print "<tr>\n" .
4869 "<td colspan=\"3\">$extra</td>\n" .
4870 "</tr>\n";
4872 print "</table>\n";
4875 sub git_search_grep_body {
4876 my ($commitlist, $from, $to, $extra) = @_;
4877 $from = 0 unless defined $from;
4878 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4880 print "<table class=\"commit_search\">\n";
4881 my $alternate = 1;
4882 for (my $i = $from; $i <= $to; $i++) {
4883 my %co = %{$commitlist->[$i]};
4884 if (!%co) {
4885 next;
4887 my $commit = $co{'id'};
4888 if ($alternate) {
4889 print "<tr class=\"dark\">\n";
4890 } else {
4891 print "<tr class=\"light\">\n";
4893 $alternate ^= 1;
4894 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4895 format_author_html('td', \%co, 15, 5) .
4896 "<td>" .
4897 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4898 -class => "list subject"},
4899 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4900 my $comment = $co{'comment'};
4901 foreach my $line (@$comment) {
4902 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4903 my ($lead, $match, $trail) = ($1, $2, $3);
4904 $match = chop_str($match, 70, 5, 'center');
4905 my $contextlen = int((80 - length($match))/2);
4906 $contextlen = 30 if ($contextlen > 30);
4907 $lead = chop_str($lead, $contextlen, 10, 'left');
4908 $trail = chop_str($trail, $contextlen, 10, 'right');
4910 $lead = esc_html($lead);
4911 $match = esc_html($match);
4912 $trail = esc_html($trail);
4914 print "$lead<span class=\"match\">$match</span>$trail<br />";
4917 print "</td>\n" .
4918 "<td class=\"link\">" .
4919 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4920 " | " .
4921 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4922 " | " .
4923 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4924 print "</td>\n" .
4925 "</tr>\n";
4927 if (defined $extra) {
4928 print "<tr>\n" .
4929 "<td colspan=\"3\">$extra</td>\n" .
4930 "</tr>\n";
4932 print "</table>\n";
4935 ## ======================================================================
4936 ## ======================================================================
4937 ## actions
4939 sub git_project_list {
4940 my $order = $input_params{'order'};
4941 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4942 die_error(400, "Unknown order parameter");
4945 my @list = git_get_projects_list();
4946 if (!@list) {
4947 die_error(404, "No projects found");
4950 git_header_html();
4951 if (defined $home_text && -f $home_text) {
4952 print "<div class=\"index_include\">\n";
4953 insert_file($home_text);
4954 print "</div>\n";
4956 print $cgi->startform(-method => "get") .
4957 "<p class=\"projsearch\">Search:\n" .
4958 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4959 "</p>" .
4960 $cgi->end_form() . "\n";
4961 git_project_list_body(\@list, $order);
4962 git_footer_html();
4965 sub git_forks {
4966 my $order = $input_params{'order'};
4967 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4968 die_error(400, "Unknown order parameter");
4971 my @list = git_get_projects_list($project);
4972 if (!@list) {
4973 die_error(404, "No forks found");
4976 git_header_html();
4977 git_print_page_nav('','');
4978 git_print_header_div('summary', "$project forks");
4979 git_project_list_body(\@list, $order);
4980 git_footer_html();
4983 sub git_project_index {
4984 my @projects = git_get_projects_list($project);
4986 print $cgi->header(
4987 -type => 'text/plain',
4988 -charset => 'utf-8',
4989 -content_disposition => 'inline; filename="index.aux"');
4991 foreach my $pr (@projects) {
4992 if (!exists $pr->{'owner'}) {
4993 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4996 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4997 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4998 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4999 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5000 $path =~ s/ /\+/g;
5001 $owner =~ s/ /\+/g;
5003 print "$path $owner\n";
5007 sub git_summary {
5008 my $descr = git_get_project_description($project) || "none";
5009 my %co = parse_commit("HEAD");
5010 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5011 my $head = $co{'id'};
5013 my $owner = git_get_project_owner($project);
5015 my $refs = git_get_references();
5016 # These get_*_list functions return one more to allow us to see if
5017 # there are more ...
5018 my @taglist = git_get_tags_list(16);
5019 my @headlist = git_get_heads_list(16);
5020 my @forklist;
5021 my $check_forks = gitweb_check_feature('forks');
5023 if ($check_forks) {
5024 @forklist = git_get_projects_list($project);
5027 git_header_html();
5028 git_print_page_nav('summary','', $head);
5030 print "<div class=\"title\">&nbsp;</div>\n";
5031 print "<table class=\"projects_list\">\n" .
5032 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5033 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5034 if (defined $cd{'rfc2822'}) {
5035 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5038 # use per project git URL list in $projectroot/$project/cloneurl
5039 # or make project git URL from git base URL and project name
5040 my $url_tag = "URL";
5041 my @url_list = git_get_project_url_list($project);
5042 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5043 foreach my $git_url (@url_list) {
5044 next unless $git_url;
5045 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5046 $url_tag = "";
5049 # Tag cloud
5050 my $show_ctags = gitweb_check_feature('ctags');
5051 if ($show_ctags) {
5052 my $ctags = git_get_project_ctags($project);
5053 my $cloud = git_populate_project_tagcloud($ctags);
5054 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5055 print "</td>\n<td>" unless %$ctags;
5056 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5057 print "</td>\n<td>" if %$ctags;
5058 print git_show_project_tagcloud($cloud, 48);
5059 print "</td></tr>";
5062 print "</table>\n";
5064 # If XSS prevention is on, we don't include README.html.
5065 # TODO: Allow a readme in some safe format.
5066 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5067 print "<div class=\"title\">readme</div>\n" .
5068 "<div class=\"readme\">\n";
5069 insert_file("$projectroot/$project/README.html");
5070 print "\n</div>\n"; # class="readme"
5073 # we need to request one more than 16 (0..15) to check if
5074 # those 16 are all
5075 my @commitlist = $head ? parse_commits($head, 17) : ();
5076 if (@commitlist) {
5077 git_print_header_div('shortlog');
5078 git_shortlog_body(\@commitlist, 0, 15, $refs,
5079 $#commitlist <= 15 ? undef :
5080 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5083 if (@taglist) {
5084 git_print_header_div('tags');
5085 git_tags_body(\@taglist, 0, 15,
5086 $#taglist <= 15 ? undef :
5087 $cgi->a({-href => href(action=>"tags")}, "..."));
5090 if (@headlist) {
5091 git_print_header_div('heads');
5092 git_heads_body(\@headlist, $head, 0, 15,
5093 $#headlist <= 15 ? undef :
5094 $cgi->a({-href => href(action=>"heads")}, "..."));
5097 if (@forklist) {
5098 git_print_header_div('forks');
5099 git_project_list_body(\@forklist, 'age', 0, 15,
5100 $#forklist <= 15 ? undef :
5101 $cgi->a({-href => href(action=>"forks")}, "..."),
5102 'no_header');
5105 git_footer_html();
5108 sub git_tag {
5109 my $head = git_get_head_hash($project);
5110 git_header_html();
5111 git_print_page_nav('','', $head,undef,$head);
5112 my %tag = parse_tag($hash);
5114 if (! %tag) {
5115 die_error(404, "Unknown tag object");
5118 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5119 print "<div class=\"title_text\">\n" .
5120 "<table class=\"object_header\">\n" .
5121 "<tr>\n" .
5122 "<td>object</td>\n" .
5123 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5124 $tag{'object'}) . "</td>\n" .
5125 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5126 $tag{'type'}) . "</td>\n" .
5127 "</tr>\n";
5128 if (defined($tag{'author'})) {
5129 git_print_authorship_rows(\%tag, 'author');
5131 print "</table>\n\n" .
5132 "</div>\n";
5133 print "<div class=\"page_body\">";
5134 my $comment = $tag{'comment'};
5135 foreach my $line (@$comment) {
5136 chomp $line;
5137 print esc_html($line, -nbsp=>1) . "<br/>\n";
5139 print "</div>\n";
5140 git_footer_html();
5143 sub git_blame_common {
5144 my $format = shift || 'porcelain';
5145 if ($format eq 'porcelain' && $cgi->param('js')) {
5146 $format = 'incremental';
5147 $action = 'blame_incremental'; # for page title etc
5150 # permissions
5151 gitweb_check_feature('blame')
5152 or die_error(403, "Blame view not allowed");
5154 # error checking
5155 die_error(400, "No file name given") unless $file_name;
5156 $hash_base ||= git_get_head_hash($project);
5157 die_error(404, "Couldn't find base commit") unless $hash_base;
5158 my %co = parse_commit($hash_base)
5159 or die_error(404, "Commit not found");
5160 my $ftype = "blob";
5161 if (!defined $hash) {
5162 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5163 or die_error(404, "Error looking up file");
5164 } else {
5165 $ftype = git_get_type($hash);
5166 if ($ftype !~ "blob") {
5167 die_error(400, "Object is not a blob");
5171 my $fd;
5172 if ($format eq 'incremental') {
5173 # get file contents (as base)
5174 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5175 or die_error(500, "Open git-cat-file failed");
5176 } elsif ($format eq 'data') {
5177 # run git-blame --incremental
5178 open $fd, "-|", git_cmd(), "blame", "--incremental",
5179 $hash_base, "--", $file_name
5180 or die_error(500, "Open git-blame --incremental failed");
5181 } else {
5182 # run git-blame --porcelain
5183 open $fd, "-|", git_cmd(), "blame", '-p',
5184 $hash_base, '--', $file_name
5185 or die_error(500, "Open git-blame --porcelain failed");
5188 # incremental blame data returns early
5189 if ($format eq 'data') {
5190 print $cgi->header(
5191 -type=>"text/plain", -charset => "utf-8",
5192 -status=> "200 OK");
5193 local $| = 1; # output autoflush
5194 print while <$fd>;
5195 close $fd
5196 or print "ERROR $!\n";
5198 print 'END';
5199 if (defined $t0 && gitweb_check_feature('timed')) {
5200 print ' '.
5201 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5202 ' '.$number_of_git_cmds;
5204 print "\n";
5206 return;
5209 # page header
5210 git_header_html();
5211 my $formats_nav =
5212 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5213 "blob") .
5214 " | ";
5215 if ($format eq 'incremental') {
5216 $formats_nav .=
5217 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5218 "blame") . " (non-incremental)";
5219 } else {
5220 $formats_nav .=
5221 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5222 "blame") . " (incremental)";
5224 $formats_nav .=
5225 " | " .
5226 $cgi->a({-href => href(action=>"history", -replay=>1)},
5227 "history") .
5228 " | " .
5229 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5230 "HEAD");
5231 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5232 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5233 git_print_page_path($file_name, $ftype, $hash_base);
5235 # page body
5236 if ($format eq 'incremental') {
5237 print "<noscript>\n<div class=\"error\"><center><b>\n".
5238 "This page requires JavaScript to run.\n Use ".
5239 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5240 'this page').
5241 " instead.\n".
5242 "</b></center></div>\n</noscript>\n";
5244 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5247 print qq!<div class="page_body">\n!;
5248 print qq!<div id="progress_info">... / ...</div>\n!
5249 if ($format eq 'incremental');
5250 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5251 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5252 qq!<thead>\n!.
5253 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5254 qq!</thead>\n!.
5255 qq!<tbody>\n!;
5257 my @rev_color = qw(light dark);
5258 my $num_colors = scalar(@rev_color);
5259 my $current_color = 0;
5261 if ($format eq 'incremental') {
5262 my $color_class = $rev_color[$current_color];
5264 #contents of a file
5265 my $linenr = 0;
5266 LINE:
5267 while (my $line = <$fd>) {
5268 chomp $line;
5269 $linenr++;
5271 print qq!<tr id="l$linenr" class="$color_class">!.
5272 qq!<td class="sha1"><a href=""> </a></td>!.
5273 qq!<td class="linenr">!.
5274 qq!<a class="linenr" href="">$linenr</a></td>!;
5275 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5276 print qq!</tr>\n!;
5279 } else { # porcelain, i.e. ordinary blame
5280 my %metainfo = (); # saves information about commits
5282 # blame data
5283 LINE:
5284 while (my $line = <$fd>) {
5285 chomp $line;
5286 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5287 # no <lines in group> for subsequent lines in group of lines
5288 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5289 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5290 if (!exists $metainfo{$full_rev}) {
5291 $metainfo{$full_rev} = { 'nprevious' => 0 };
5293 my $meta = $metainfo{$full_rev};
5294 my $data;
5295 while ($data = <$fd>) {
5296 chomp $data;
5297 last if ($data =~ s/^\t//); # contents of line
5298 if ($data =~ /^(\S+)(?: (.*))?$/) {
5299 $meta->{$1} = $2 unless exists $meta->{$1};
5301 if ($data =~ /^previous /) {
5302 $meta->{'nprevious'}++;
5305 my $short_rev = substr($full_rev, 0, 8);
5306 my $author = $meta->{'author'};
5307 my %date =
5308 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5309 my $date = $date{'iso-tz'};
5310 if ($group_size) {
5311 $current_color = ($current_color + 1) % $num_colors;
5313 my $tr_class = $rev_color[$current_color];
5314 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5315 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5316 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5317 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5318 if ($group_size) {
5319 print "<td class=\"sha1\"";
5320 print " title=\"". esc_html($author) . ", $date\"";
5321 print " rowspan=\"$group_size\"" if ($group_size > 1);
5322 print ">";
5323 print $cgi->a({-href => href(action=>"commit",
5324 hash=>$full_rev,
5325 file_name=>$file_name)},
5326 esc_html($short_rev));
5327 if ($group_size >= 2) {
5328 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5329 if (@author_initials) {
5330 print "<br />" .
5331 esc_html(join('', @author_initials));
5332 # or join('.', ...)
5335 print "</td>\n";
5337 # 'previous' <sha1 of parent commit> <filename at commit>
5338 if (exists $meta->{'previous'} &&
5339 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5340 $meta->{'parent'} = $1;
5341 $meta->{'file_parent'} = unquote($2);
5343 my $linenr_commit =
5344 exists($meta->{'parent'}) ?
5345 $meta->{'parent'} : $full_rev;
5346 my $linenr_filename =
5347 exists($meta->{'file_parent'}) ?
5348 $meta->{'file_parent'} : unquote($meta->{'filename'});
5349 my $blamed = href(action => 'blame',
5350 file_name => $linenr_filename,
5351 hash_base => $linenr_commit);
5352 print "<td class=\"linenr\">";
5353 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5354 -class => "linenr" },
5355 esc_html($lineno));
5356 print "</td>";
5357 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5358 print "</tr>\n";
5359 } # end while
5363 # footer
5364 print "</tbody>\n".
5365 "</table>\n"; # class="blame"
5366 print "</div>\n"; # class="blame_body"
5367 close $fd
5368 or print "Reading blob failed\n";
5370 git_footer_html();
5373 sub git_blame {
5374 git_blame_common();
5377 sub git_blame_incremental {
5378 git_blame_common('incremental');
5381 sub git_blame_data {
5382 git_blame_common('data');
5385 sub git_tags {
5386 my $head = git_get_head_hash($project);
5387 git_header_html();
5388 git_print_page_nav('','', $head,undef,$head);
5389 git_print_header_div('summary', $project);
5391 my @tagslist = git_get_tags_list();
5392 if (@tagslist) {
5393 git_tags_body(\@tagslist);
5395 git_footer_html();
5398 sub git_heads {
5399 my $head = git_get_head_hash($project);
5400 git_header_html();
5401 git_print_page_nav('','', $head,undef,$head);
5402 git_print_header_div('summary', $project);
5404 my @headslist = git_get_heads_list();
5405 if (@headslist) {
5406 git_heads_body(\@headslist, $head);
5408 git_footer_html();
5411 sub git_blob_plain {
5412 my $type = shift;
5413 my $expires;
5415 if (!defined $hash) {
5416 if (defined $file_name) {
5417 my $base = $hash_base || git_get_head_hash($project);
5418 $hash = git_get_hash_by_path($base, $file_name, "blob")
5419 or die_error(404, "Cannot find file");
5420 } else {
5421 die_error(400, "No file name defined");
5423 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5424 # blobs defined by non-textual hash id's can be cached
5425 $expires = "+1d";
5428 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5429 or die_error(500, "Open git-cat-file blob '$hash' failed");
5431 # content-type (can include charset)
5432 $type = blob_contenttype($fd, $file_name, $type);
5434 # "save as" filename, even when no $file_name is given
5435 my $save_as = "$hash";
5436 if (defined $file_name) {
5437 $save_as = $file_name;
5438 } elsif ($type =~ m/^text\//) {
5439 $save_as .= '.txt';
5442 # With XSS prevention on, blobs of all types except a few known safe
5443 # ones are served with "Content-Disposition: attachment" to make sure
5444 # they don't run in our security domain. For certain image types,
5445 # blob view writes an <img> tag referring to blob_plain view, and we
5446 # want to be sure not to break that by serving the image as an
5447 # attachment (though Firefox 3 doesn't seem to care).
5448 my $sandbox = $prevent_xss &&
5449 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5451 print $cgi->header(
5452 -type => $type,
5453 -expires => $expires,
5454 -content_disposition =>
5455 ($sandbox ? 'attachment' : 'inline')
5456 . '; filename="' . $save_as . '"');
5457 local $/ = undef;
5458 binmode STDOUT, ':raw';
5459 print <$fd>;
5460 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5461 close $fd;
5464 sub git_blob {
5465 my $expires;
5467 if (!defined $hash) {
5468 if (defined $file_name) {
5469 my $base = $hash_base || git_get_head_hash($project);
5470 $hash = git_get_hash_by_path($base, $file_name, "blob")
5471 or die_error(404, "Cannot find file");
5472 } else {
5473 die_error(400, "No file name defined");
5475 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5476 # blobs defined by non-textual hash id's can be cached
5477 $expires = "+1d";
5480 my $have_blame = gitweb_check_feature('blame');
5481 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5482 or die_error(500, "Couldn't cat $file_name, $hash");
5483 my $mimetype = blob_mimetype($fd, $file_name);
5484 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5485 close $fd;
5486 return git_blob_plain($mimetype);
5488 # we can have blame only for text/* mimetype
5489 $have_blame &&= ($mimetype =~ m!^text/!);
5491 git_header_html(undef, $expires);
5492 my $formats_nav = '';
5493 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5494 if (defined $file_name) {
5495 if ($have_blame) {
5496 $formats_nav .=
5497 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5498 "blame") .
5499 " | ";
5501 $formats_nav .=
5502 $cgi->a({-href => href(action=>"history", -replay=>1)},
5503 "history") .
5504 " | " .
5505 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5506 "raw") .
5507 " | " .
5508 $cgi->a({-href => href(action=>"blob",
5509 hash_base=>"HEAD", file_name=>$file_name)},
5510 "HEAD");
5511 } else {
5512 $formats_nav .=
5513 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5514 "raw");
5516 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5517 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5518 } else {
5519 print "<div class=\"page_nav\">\n" .
5520 "<br/><br/></div>\n" .
5521 "<div class=\"title\">$hash</div>\n";
5523 git_print_page_path($file_name, "blob", $hash_base);
5524 print "<div class=\"page_body\">\n";
5525 if ($mimetype =~ m!^image/!) {
5526 print qq!<img type="$mimetype"!;
5527 if ($file_name) {
5528 print qq! alt="$file_name" title="$file_name"!;
5530 print qq! src="! .
5531 href(action=>"blob_plain", hash=>$hash,
5532 hash_base=>$hash_base, file_name=>$file_name) .
5533 qq!" />\n!;
5534 } else {
5535 my $nr;
5536 while (my $line = <$fd>) {
5537 chomp $line;
5538 $nr++;
5539 $line = untabify($line);
5540 printf "<div class=\"pre\"><a id=\"l%i\" href=\"" . href(-replay => 1)
5541 . "#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5542 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5545 close $fd
5546 or print "Reading blob failed.\n";
5547 print "</div>";
5548 git_footer_html();
5551 sub git_tree {
5552 if (!defined $hash_base) {
5553 $hash_base = "HEAD";
5555 if (!defined $hash) {
5556 if (defined $file_name) {
5557 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5558 } else {
5559 $hash = $hash_base;
5562 die_error(404, "No such tree") unless defined($hash);
5564 my $show_sizes = gitweb_check_feature('show-sizes');
5565 my $have_blame = gitweb_check_feature('blame');
5567 my @entries = ();
5569 local $/ = "\0";
5570 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5571 ($show_sizes ? '-l' : ()), @extra_options, $hash
5572 or die_error(500, "Open git-ls-tree failed");
5573 @entries = map { chomp; $_ } <$fd>;
5574 close $fd
5575 or die_error(404, "Reading tree failed");
5578 my $refs = git_get_references();
5579 my $ref = format_ref_marker($refs, $hash_base);
5580 git_header_html();
5581 my $basedir = '';
5582 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5583 my @views_nav = ();
5584 if (defined $file_name) {
5585 push @views_nav,
5586 $cgi->a({-href => href(action=>"history", -replay=>1)},
5587 "history"),
5588 $cgi->a({-href => href(action=>"tree",
5589 hash_base=>"HEAD", file_name=>$file_name)},
5590 "HEAD"),
5592 my $snapshot_links = format_snapshot_links($hash);
5593 if (defined $snapshot_links) {
5594 # FIXME: Should be available when we have no hash base as well.
5595 push @views_nav, $snapshot_links;
5597 git_print_page_nav('tree','', $hash_base, undef, undef,
5598 join(' | ', @views_nav));
5599 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5600 } else {
5601 undef $hash_base;
5602 print "<div class=\"page_nav\">\n";
5603 print "<br/><br/></div>\n";
5604 print "<div class=\"title\">$hash</div>\n";
5606 if (defined $file_name) {
5607 $basedir = $file_name;
5608 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5609 $basedir .= '/';
5611 git_print_page_path($file_name, 'tree', $hash_base);
5613 print "<div class=\"page_body\">\n";
5614 print "<table class=\"tree\">\n";
5615 my $alternate = 1;
5616 # '..' (top directory) link if possible
5617 if (defined $hash_base &&
5618 defined $file_name && $file_name =~ m![^/]+$!) {
5619 if ($alternate) {
5620 print "<tr class=\"dark\">\n";
5621 } else {
5622 print "<tr class=\"light\">\n";
5624 $alternate ^= 1;
5626 my $up = $file_name;
5627 $up =~ s!/?[^/]+$!!;
5628 undef $up unless $up;
5629 # based on git_print_tree_entry
5630 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5631 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5632 print '<td class="list">';
5633 print $cgi->a({-href => href(action=>"tree",
5634 hash_base=>$hash_base,
5635 file_name=>$up)},
5636 "..");
5637 print "</td>\n";
5638 print "<td class=\"link\"></td>\n";
5640 print "</tr>\n";
5642 foreach my $line (@entries) {
5643 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5645 if ($alternate) {
5646 print "<tr class=\"dark\">\n";
5647 } else {
5648 print "<tr class=\"light\">\n";
5650 $alternate ^= 1;
5652 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5654 print "</tr>\n";
5656 print "</table>\n" .
5657 "</div>";
5658 git_footer_html();
5661 sub snapshot_name {
5662 my ($project, $hash) = @_;
5664 # path/to/project.git -> project
5665 # path/to/project/.git -> project
5666 my $name = to_utf8($project);
5667 $name =~ s,([^/])/*\.git$,$1,;
5668 $name = basename($name);
5669 # sanitize name
5670 $name =~ s/[[:cntrl:]]/?/g;
5672 my $ver = $hash;
5673 if ($hash =~ /^[0-9a-fA-F]+$/) {
5674 # shorten SHA-1 hash
5675 my $full_hash = git_get_full_hash($project, $hash);
5676 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5677 $ver = git_get_short_hash($project, $hash);
5679 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5680 # tags don't need shortened SHA-1 hash
5681 $ver = $1;
5682 } else {
5683 # branches and other need shortened SHA-1 hash
5684 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5685 $ver = $1;
5687 $ver .= '-' . git_get_short_hash($project, $hash);
5689 # in case of hierarchical branch names
5690 $ver =~ s!/!.!g;
5692 # name = project-version_string
5693 $name = "$name-$ver";
5695 return wantarray ? ($name, $name) : $name;
5698 sub git_snapshot {
5699 my $format = $input_params{'snapshot_format'};
5700 if (!@snapshot_fmts) {
5701 die_error(403, "Snapshots not allowed");
5703 # default to first supported snapshot format
5704 $format ||= $snapshot_fmts[0];
5705 if ($format !~ m/^[a-z0-9]+$/) {
5706 die_error(400, "Invalid snapshot format parameter");
5707 } elsif (!exists($known_snapshot_formats{$format})) {
5708 die_error(400, "Unknown snapshot format");
5709 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5710 die_error(403, "Snapshot format not allowed");
5711 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5712 die_error(403, "Unsupported snapshot format");
5715 my $type = git_get_type("$hash^{}");
5716 if (!$type) {
5717 die_error(404, 'Object does not exist');
5718 } elsif ($type eq 'blob') {
5719 die_error(400, 'Object is not a tree-ish');
5722 my ($name, $prefix) = snapshot_name($project, $hash);
5723 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
5724 my $cmd = quote_command(
5725 git_cmd(), 'archive',
5726 "--format=$known_snapshot_formats{$format}{'format'}",
5727 "--prefix=$prefix/", $hash);
5728 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5729 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5732 $filename =~ s/(["\\])/\\$1/g;
5733 print $cgi->header(
5734 -type => $known_snapshot_formats{$format}{'type'},
5735 -content_disposition => 'inline; filename="' . $filename . '"',
5736 -status => '200 OK');
5738 open my $fd, "-|", $cmd
5739 or die_error(500, "Execute git-archive failed");
5740 binmode STDOUT, ':raw';
5741 print <$fd>;
5742 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5743 close $fd;
5746 sub git_log_generic {
5747 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
5749 my $head = git_get_head_hash($project);
5750 if (!defined $base) {
5751 $base = $head;
5753 if (!defined $page) {
5754 $page = 0;
5756 my $refs = git_get_references();
5758 my $commit_hash = $base;
5759 if (defined $parent) {
5760 $commit_hash = "$parent..$base";
5762 my @commitlist =
5763 parse_commits($commit_hash, 101, (100 * $page),
5764 defined $file_name ? ($file_name, "--full-history") : ());
5766 my $ftype;
5767 if (!defined $file_hash && defined $file_name) {
5768 # some commits could have deleted file in question,
5769 # and not have it in tree, but one of them has to have it
5770 for (my $i = 0; $i < @commitlist; $i++) {
5771 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5772 last if defined $file_hash;
5775 if (defined $file_hash) {
5776 $ftype = git_get_type($file_hash);
5778 if (defined $file_name && !defined $ftype) {
5779 die_error(500, "Unknown type of object");
5781 my %co;
5782 if (defined $file_name) {
5783 %co = parse_commit($base)
5784 or die_error(404, "Unknown commit object");
5788 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
5789 my $next_link = '';
5790 if ($#commitlist >= 100) {
5791 $next_link =
5792 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5793 -accesskey => "n", -title => "Alt-n"}, "next");
5795 my $patch_max = gitweb_get_feature('patches');
5796 if ($patch_max && !defined $file_name) {
5797 if ($patch_max < 0 || @commitlist <= $patch_max) {
5798 $paging_nav .= " &sdot; " .
5799 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5800 "patches");
5804 git_header_html();
5805 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
5806 if (defined $file_name) {
5807 git_print_header_div('commit', esc_html($co{'title'}), $base);
5808 } else {
5809 git_print_header_div('summary', $project)
5811 git_print_page_path($file_name, $ftype, $hash_base)
5812 if (defined $file_name);
5814 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
5815 $file_name, $file_hash, $ftype);
5817 git_footer_html();
5820 sub git_log {
5821 git_log_generic('log', \&git_log_body,
5822 $hash, $hash_parent);
5825 sub git_commit {
5826 $hash ||= $hash_base || "HEAD";
5827 my %co = parse_commit($hash)
5828 or die_error(404, "Unknown commit object");
5830 my $parent = $co{'parent'};
5831 my $parents = $co{'parents'}; # listref
5833 # we need to prepare $formats_nav before any parameter munging
5834 my $formats_nav;
5835 if (!defined $parent) {
5836 # --root commitdiff
5837 $formats_nav .= '(initial)';
5838 } elsif (@$parents == 1) {
5839 # single parent commit
5840 $formats_nav .=
5841 '(parent: ' .
5842 $cgi->a({-href => href(action=>"commit",
5843 hash=>$parent)},
5844 esc_html(substr($parent, 0, 7))) .
5845 ')';
5846 } else {
5847 # merge commit
5848 $formats_nav .=
5849 '(merge: ' .
5850 join(' ', map {
5851 $cgi->a({-href => href(action=>"commit",
5852 hash=>$_)},
5853 esc_html(substr($_, 0, 7)));
5854 } @$parents ) .
5855 ')';
5857 if (gitweb_check_feature('patches') && @$parents <= 1) {
5858 $formats_nav .= " | " .
5859 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5860 "patch");
5863 if (!defined $parent) {
5864 $parent = "--root";
5866 my @difftree;
5867 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5868 @diff_opts,
5869 (@$parents <= 1 ? $parent : '-c'),
5870 $hash, "--"
5871 or die_error(500, "Open git-diff-tree failed");
5872 @difftree = map { chomp; $_ } <$fd>;
5873 close $fd or die_error(404, "Reading git-diff-tree failed");
5875 # non-textual hash id's can be cached
5876 my $expires;
5877 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5878 $expires = "+1d";
5880 my $refs = git_get_references();
5881 my $ref = format_ref_marker($refs, $co{'id'});
5883 git_header_html(undef, $expires);
5884 git_print_page_nav('commit', '',
5885 $hash, $co{'tree'}, $hash,
5886 $formats_nav);
5888 if (defined $co{'parent'}) {
5889 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5890 } else {
5891 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5893 print "<div class=\"title_text\">\n" .
5894 "<table class=\"object_header\">\n";
5895 git_print_authorship_rows(\%co);
5896 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5897 print "<tr>" .
5898 "<td>tree</td>" .
5899 "<td class=\"sha1\">" .
5900 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5901 class => "list"}, $co{'tree'}) .
5902 "</td>" .
5903 "<td class=\"link\">" .
5904 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5905 "tree");
5906 my $snapshot_links = format_snapshot_links($hash);
5907 if (defined $snapshot_links) {
5908 print " | " . $snapshot_links;
5910 print "</td>" .
5911 "</tr>\n";
5913 foreach my $par (@$parents) {
5914 print "<tr>" .
5915 "<td>parent</td>" .
5916 "<td class=\"sha1\">" .
5917 $cgi->a({-href => href(action=>"commit", hash=>$par),
5918 class => "list"}, $par) .
5919 "</td>" .
5920 "<td class=\"link\">" .
5921 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5922 " | " .
5923 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5924 "</td>" .
5925 "</tr>\n";
5927 print "</table>".
5928 "</div>\n";
5930 print "<div class=\"page_body\">\n";
5931 git_print_log($co{'comment'});
5932 print "</div>\n";
5934 git_difftree_body(\@difftree, $hash, @$parents);
5936 git_footer_html();
5939 sub git_object {
5940 # object is defined by:
5941 # - hash or hash_base alone
5942 # - hash_base and file_name
5943 my $type;
5945 # - hash or hash_base alone
5946 if ($hash || ($hash_base && !defined $file_name)) {
5947 my $object_id = $hash || $hash_base;
5949 open my $fd, "-|", quote_command(
5950 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5951 or die_error(404, "Object does not exist");
5952 $type = <$fd>;
5953 chomp $type;
5954 close $fd
5955 or die_error(404, "Object does not exist");
5957 # - hash_base and file_name
5958 } elsif ($hash_base && defined $file_name) {
5959 $file_name =~ s,/+$,,;
5961 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5962 or die_error(404, "Base object does not exist");
5964 # here errors should not hapen
5965 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5966 or die_error(500, "Open git-ls-tree failed");
5967 my $line = <$fd>;
5968 close $fd;
5970 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5971 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5972 die_error(404, "File or directory for given base does not exist");
5974 $type = $2;
5975 $hash = $3;
5976 } else {
5977 die_error(400, "Not enough information to find object");
5980 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5981 hash=>$hash, hash_base=>$hash_base,
5982 file_name=>$file_name),
5983 -status => '302 Found');
5986 sub git_blobdiff {
5987 my $format = shift || 'html';
5989 my $fd;
5990 my @difftree;
5991 my %diffinfo;
5992 my $expires;
5994 # preparing $fd and %diffinfo for git_patchset_body
5995 # new style URI
5996 if (defined $hash_base && defined $hash_parent_base) {
5997 if (defined $file_name) {
5998 # read raw output
5999 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6000 $hash_parent_base, $hash_base,
6001 "--", (defined $file_parent ? $file_parent : ()), $file_name
6002 or die_error(500, "Open git-diff-tree failed");
6003 @difftree = map { chomp; $_ } <$fd>;
6004 close $fd
6005 or die_error(404, "Reading git-diff-tree failed");
6006 @difftree
6007 or die_error(404, "Blob diff not found");
6009 } elsif (defined $hash &&
6010 $hash =~ /[0-9a-fA-F]{40}/) {
6011 # try to find filename from $hash
6013 # read filtered raw output
6014 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6015 $hash_parent_base, $hash_base, "--"
6016 or die_error(500, "Open git-diff-tree failed");
6017 @difftree =
6018 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6019 # $hash == to_id
6020 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6021 map { chomp; $_ } <$fd>;
6022 close $fd
6023 or die_error(404, "Reading git-diff-tree failed");
6024 @difftree
6025 or die_error(404, "Blob diff not found");
6027 } else {
6028 die_error(400, "Missing one of the blob diff parameters");
6031 if (@difftree > 1) {
6032 die_error(400, "Ambiguous blob diff specification");
6035 %diffinfo = parse_difftree_raw_line($difftree[0]);
6036 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6037 $file_name ||= $diffinfo{'to_file'};
6039 $hash_parent ||= $diffinfo{'from_id'};
6040 $hash ||= $diffinfo{'to_id'};
6042 # non-textual hash id's can be cached
6043 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6044 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6045 $expires = '+1d';
6048 # open patch output
6049 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6050 '-p', ($format eq 'html' ? "--full-index" : ()),
6051 $hash_parent_base, $hash_base,
6052 "--", (defined $file_parent ? $file_parent : ()), $file_name
6053 or die_error(500, "Open git-diff-tree failed");
6056 # old/legacy style URI -- not generated anymore since 1.4.3.
6057 if (!%diffinfo) {
6058 die_error('404 Not Found', "Missing one of the blob diff parameters")
6061 # header
6062 if ($format eq 'html') {
6063 my $formats_nav =
6064 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6065 "raw");
6066 git_header_html(undef, $expires);
6067 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6068 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6069 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6070 } else {
6071 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6072 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6074 if (defined $file_name) {
6075 git_print_page_path($file_name, "blob", $hash_base);
6076 } else {
6077 print "<div class=\"page_path\"></div>\n";
6080 } elsif ($format eq 'plain') {
6081 print $cgi->header(
6082 -type => 'text/plain',
6083 -charset => 'utf-8',
6084 -expires => $expires,
6085 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6087 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6089 } else {
6090 die_error(400, "Unknown blobdiff format");
6093 # patch
6094 if ($format eq 'html') {
6095 print "<div class=\"page_body\">\n";
6097 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6098 close $fd;
6100 print "</div>\n"; # class="page_body"
6101 git_footer_html();
6103 } else {
6104 while (my $line = <$fd>) {
6105 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6106 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6108 print $line;
6110 last if $line =~ m!^\+\+\+!;
6112 local $/ = undef;
6113 print <$fd>;
6114 close $fd;
6118 sub git_blobdiff_plain {
6119 git_blobdiff('plain');
6122 sub git_commitdiff {
6123 my %params = @_;
6124 my $format = $params{-format} || 'html';
6126 my ($patch_max) = gitweb_get_feature('patches');
6127 if ($format eq 'patch') {
6128 die_error(403, "Patch view not allowed") unless $patch_max;
6131 $hash ||= $hash_base || "HEAD";
6132 my %co = parse_commit($hash)
6133 or die_error(404, "Unknown commit object");
6135 # choose format for commitdiff for merge
6136 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6137 $hash_parent = '--cc';
6139 # we need to prepare $formats_nav before almost any parameter munging
6140 my $formats_nav;
6141 if ($format eq 'html') {
6142 $formats_nav =
6143 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6144 "raw");
6145 if ($patch_max && @{$co{'parents'}} <= 1) {
6146 $formats_nav .= " | " .
6147 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6148 "patch");
6151 if (defined $hash_parent &&
6152 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6153 # commitdiff with two commits given
6154 my $hash_parent_short = $hash_parent;
6155 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6156 $hash_parent_short = substr($hash_parent, 0, 7);
6158 $formats_nav .=
6159 ' (from';
6160 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6161 if ($co{'parents'}[$i] eq $hash_parent) {
6162 $formats_nav .= ' parent ' . ($i+1);
6163 last;
6166 $formats_nav .= ': ' .
6167 $cgi->a({-href => href(action=>"commitdiff",
6168 hash=>$hash_parent)},
6169 esc_html($hash_parent_short)) .
6170 ')';
6171 } elsif (!$co{'parent'}) {
6172 # --root commitdiff
6173 $formats_nav .= ' (initial)';
6174 } elsif (scalar @{$co{'parents'}} == 1) {
6175 # single parent commit
6176 $formats_nav .=
6177 ' (parent: ' .
6178 $cgi->a({-href => href(action=>"commitdiff",
6179 hash=>$co{'parent'})},
6180 esc_html(substr($co{'parent'}, 0, 7))) .
6181 ')';
6182 } else {
6183 # merge commit
6184 if ($hash_parent eq '--cc') {
6185 $formats_nav .= ' | ' .
6186 $cgi->a({-href => href(action=>"commitdiff",
6187 hash=>$hash, hash_parent=>'-c')},
6188 'combined');
6189 } else { # $hash_parent eq '-c'
6190 $formats_nav .= ' | ' .
6191 $cgi->a({-href => href(action=>"commitdiff",
6192 hash=>$hash, hash_parent=>'--cc')},
6193 'compact');
6195 $formats_nav .=
6196 ' (merge: ' .
6197 join(' ', map {
6198 $cgi->a({-href => href(action=>"commitdiff",
6199 hash=>$_)},
6200 esc_html(substr($_, 0, 7)));
6201 } @{$co{'parents'}} ) .
6202 ')';
6206 my $hash_parent_param = $hash_parent;
6207 if (!defined $hash_parent_param) {
6208 # --cc for multiple parents, --root for parentless
6209 $hash_parent_param =
6210 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6213 # read commitdiff
6214 my $fd;
6215 my @difftree;
6216 if ($format eq 'html') {
6217 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6218 "--no-commit-id", "--patch-with-raw", "--full-index",
6219 $hash_parent_param, $hash, "--"
6220 or die_error(500, "Open git-diff-tree failed");
6222 while (my $line = <$fd>) {
6223 chomp $line;
6224 # empty line ends raw part of diff-tree output
6225 last unless $line;
6226 push @difftree, scalar parse_difftree_raw_line($line);
6229 } elsif ($format eq 'plain') {
6230 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6231 '-p', $hash_parent_param, $hash, "--"
6232 or die_error(500, "Open git-diff-tree failed");
6233 } elsif ($format eq 'patch') {
6234 # For commit ranges, we limit the output to the number of
6235 # patches specified in the 'patches' feature.
6236 # For single commits, we limit the output to a single patch,
6237 # diverging from the git-format-patch default.
6238 my @commit_spec = ();
6239 if ($hash_parent) {
6240 if ($patch_max > 0) {
6241 push @commit_spec, "-$patch_max";
6243 push @commit_spec, '-n', "$hash_parent..$hash";
6244 } else {
6245 if ($params{-single}) {
6246 push @commit_spec, '-1';
6247 } else {
6248 if ($patch_max > 0) {
6249 push @commit_spec, "-$patch_max";
6251 push @commit_spec, "-n";
6253 push @commit_spec, '--root', $hash;
6255 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6256 '--encoding=utf8', '--stdout', @commit_spec
6257 or die_error(500, "Open git-format-patch failed");
6258 } else {
6259 die_error(400, "Unknown commitdiff format");
6262 # non-textual hash id's can be cached
6263 my $expires;
6264 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6265 $expires = "+1d";
6268 # write commit message
6269 if ($format eq 'html') {
6270 my $refs = git_get_references();
6271 my $ref = format_ref_marker($refs, $co{'id'});
6273 git_header_html(undef, $expires);
6274 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6275 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6276 print "<div class=\"title_text\">\n" .
6277 "<table class=\"object_header\">\n";
6278 git_print_authorship_rows(\%co);
6279 print "</table>".
6280 "</div>\n";
6281 print "<div class=\"page_body\">\n";
6282 if (@{$co{'comment'}} > 1) {
6283 print "<div class=\"log\">\n";
6284 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6285 print "</div>\n"; # class="log"
6288 } elsif ($format eq 'plain') {
6289 my $refs = git_get_references("tags");
6290 my $tagname = git_get_rev_name_tags($hash);
6291 my $filename = basename($project) . "-$hash.patch";
6293 print $cgi->header(
6294 -type => 'text/plain',
6295 -charset => 'utf-8',
6296 -expires => $expires,
6297 -content_disposition => 'inline; filename="' . "$filename" . '"');
6298 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6299 print "From: " . to_utf8($co{'author'}) . "\n";
6300 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6301 print "Subject: " . to_utf8($co{'title'}) . "\n";
6303 print "X-Git-Tag: $tagname\n" if $tagname;
6304 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6306 foreach my $line (@{$co{'comment'}}) {
6307 print to_utf8($line) . "\n";
6309 print "---\n\n";
6310 } elsif ($format eq 'patch') {
6311 my $filename = basename($project) . "-$hash.patch";
6313 print $cgi->header(
6314 -type => 'text/plain',
6315 -charset => 'utf-8',
6316 -expires => $expires,
6317 -content_disposition => 'inline; filename="' . "$filename" . '"');
6320 # write patch
6321 if ($format eq 'html') {
6322 my $use_parents = !defined $hash_parent ||
6323 $hash_parent eq '-c' || $hash_parent eq '--cc';
6324 git_difftree_body(\@difftree, $hash,
6325 $use_parents ? @{$co{'parents'}} : $hash_parent);
6326 print "<br/>\n";
6328 git_patchset_body($fd, \@difftree, $hash,
6329 $use_parents ? @{$co{'parents'}} : $hash_parent);
6330 close $fd;
6331 print "</div>\n"; # class="page_body"
6332 git_footer_html();
6334 } elsif ($format eq 'plain') {
6335 local $/ = undef;
6336 print <$fd>;
6337 close $fd
6338 or print "Reading git-diff-tree failed\n";
6339 } elsif ($format eq 'patch') {
6340 local $/ = undef;
6341 print <$fd>;
6342 close $fd
6343 or print "Reading git-format-patch failed\n";
6347 sub git_commitdiff_plain {
6348 git_commitdiff(-format => 'plain');
6351 # format-patch-style patches
6352 sub git_patch {
6353 git_commitdiff(-format => 'patch', -single => 1);
6356 sub git_patches {
6357 git_commitdiff(-format => 'patch');
6360 sub git_history {
6361 git_log_generic('history', \&git_history_body,
6362 $hash_base, $hash_parent_base,
6363 $file_name, $hash);
6366 sub git_search {
6367 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6368 if (!defined $searchtext) {
6369 die_error(400, "Text field is empty");
6371 if (!defined $hash) {
6372 $hash = git_get_head_hash($project);
6374 my %co = parse_commit($hash);
6375 if (!%co) {
6376 die_error(404, "Unknown commit object");
6378 if (!defined $page) {
6379 $page = 0;
6382 $searchtype ||= 'commit';
6383 if ($searchtype eq 'pickaxe') {
6384 # pickaxe may take all resources of your box and run for several minutes
6385 # with every query - so decide by yourself how public you make this feature
6386 gitweb_check_feature('pickaxe')
6387 or die_error(403, "Pickaxe is disabled");
6389 if ($searchtype eq 'grep') {
6390 gitweb_check_feature('grep')
6391 or die_error(403, "Grep is disabled");
6394 git_header_html();
6396 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6397 my $greptype;
6398 if ($searchtype eq 'commit') {
6399 $greptype = "--grep=";
6400 } elsif ($searchtype eq 'author') {
6401 $greptype = "--author=";
6402 } elsif ($searchtype eq 'committer') {
6403 $greptype = "--committer=";
6405 $greptype .= $searchtext;
6406 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6407 $greptype, '--regexp-ignore-case',
6408 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6410 my $paging_nav = '';
6411 if ($page > 0) {
6412 $paging_nav .=
6413 $cgi->a({-href => href(action=>"search", hash=>$hash,
6414 searchtext=>$searchtext,
6415 searchtype=>$searchtype)},
6416 "first");
6417 $paging_nav .= " &sdot; " .
6418 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6419 -accesskey => "p", -title => "Alt-p"}, "prev");
6420 } else {
6421 $paging_nav .= "first";
6422 $paging_nav .= " &sdot; prev";
6424 my $next_link = '';
6425 if ($#commitlist >= 100) {
6426 $next_link =
6427 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6428 -accesskey => "n", -title => "Alt-n"}, "next");
6429 $paging_nav .= " &sdot; $next_link";
6430 } else {
6431 $paging_nav .= " &sdot; next";
6434 if ($#commitlist >= 100) {
6437 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6438 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6439 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6442 if ($searchtype eq 'pickaxe') {
6443 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6444 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6446 print "<table class=\"pickaxe search\">\n";
6447 my $alternate = 1;
6448 local $/ = "\n";
6449 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6450 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6451 ($search_use_regexp ? '--pickaxe-regex' : ());
6452 undef %co;
6453 my @files;
6454 while (my $line = <$fd>) {
6455 chomp $line;
6456 next unless $line;
6458 my %set = parse_difftree_raw_line($line);
6459 if (defined $set{'commit'}) {
6460 # finish previous commit
6461 if (%co) {
6462 print "</td>\n" .
6463 "<td class=\"link\">" .
6464 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6465 " | " .
6466 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6467 print "</td>\n" .
6468 "</tr>\n";
6471 if ($alternate) {
6472 print "<tr class=\"dark\">\n";
6473 } else {
6474 print "<tr class=\"light\">\n";
6476 $alternate ^= 1;
6477 %co = parse_commit($set{'commit'});
6478 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6479 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6480 "<td><i>$author</i></td>\n" .
6481 "<td>" .
6482 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6483 -class => "list subject"},
6484 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6485 } elsif (defined $set{'to_id'}) {
6486 next if ($set{'to_id'} =~ m/^0{40}$/);
6488 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6489 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6490 -class => "list"},
6491 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6492 "<br/>\n";
6495 close $fd;
6497 # finish last commit (warning: repetition!)
6498 if (%co) {
6499 print "</td>\n" .
6500 "<td class=\"link\">" .
6501 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6502 " | " .
6503 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6504 print "</td>\n" .
6505 "</tr>\n";
6508 print "</table>\n";
6511 if ($searchtype eq 'grep') {
6512 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6513 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6515 print "<table class=\"grep_search\">\n";
6516 my $alternate = 1;
6517 my $matches = 0;
6518 local $/ = "\n";
6519 open my $fd, "-|", git_cmd(), 'grep', '-n',
6520 $search_use_regexp ? ('-E', '-i') : '-F',
6521 $searchtext, $co{'tree'};
6522 my $lastfile = '';
6523 while (my $line = <$fd>) {
6524 chomp $line;
6525 my ($file, $lno, $ltext, $binary);
6526 last if ($matches++ > 1000);
6527 if ($line =~ /^Binary file (.+) matches$/) {
6528 $file = $1;
6529 $binary = 1;
6530 } else {
6531 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6533 if ($file ne $lastfile) {
6534 $lastfile and print "</td></tr>\n";
6535 if ($alternate++) {
6536 print "<tr class=\"dark\">\n";
6537 } else {
6538 print "<tr class=\"light\">\n";
6540 print "<td class=\"list\">".
6541 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6542 file_name=>"$file"),
6543 -class => "list"}, esc_path($file));
6544 print "</td><td>\n";
6545 $lastfile = $file;
6547 if ($binary) {
6548 print "<div class=\"binary\">Binary file</div>\n";
6549 } else {
6550 $ltext = untabify($ltext);
6551 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6552 $ltext = esc_html($1, -nbsp=>1);
6553 $ltext .= '<span class="match">';
6554 $ltext .= esc_html($2, -nbsp=>1);
6555 $ltext .= '</span>';
6556 $ltext .= esc_html($3, -nbsp=>1);
6557 } else {
6558 $ltext = esc_html($ltext, -nbsp=>1);
6560 print "<div class=\"pre\">" .
6561 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6562 file_name=>"$file").'#l'.$lno,
6563 -class => "linenr"}, sprintf('%4i', $lno))
6564 . ' ' . $ltext . "</div>\n";
6567 if ($lastfile) {
6568 print "</td></tr>\n";
6569 if ($matches > 1000) {
6570 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6572 } else {
6573 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6575 close $fd;
6577 print "</table>\n";
6579 git_footer_html();
6582 sub git_search_help {
6583 git_header_html();
6584 git_print_page_nav('','', $hash,$hash,$hash);
6585 print <<EOT;
6586 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6587 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6588 the pattern entered is recognized as the POSIX extended
6589 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6590 insensitive).</p>
6591 <dl>
6592 <dt><b>commit</b></dt>
6593 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6595 my $have_grep = gitweb_check_feature('grep');
6596 if ($have_grep) {
6597 print <<EOT;
6598 <dt><b>grep</b></dt>
6599 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6600 a different one) are searched for the given pattern. On large trees, this search can take
6601 a while and put some strain on the server, so please use it with some consideration. Note that
6602 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6603 case-sensitive.</dd>
6606 print <<EOT;
6607 <dt><b>author</b></dt>
6608 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6609 <dt><b>committer</b></dt>
6610 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6612 my $have_pickaxe = gitweb_check_feature('pickaxe');
6613 if ($have_pickaxe) {
6614 print <<EOT;
6615 <dt><b>pickaxe</b></dt>
6616 <dd>All commits that caused the string to appear or disappear from any file (changes that
6617 added, removed or "modified" the string) will be listed. This search can take a while and
6618 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6619 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6622 print "</dl>\n";
6623 git_footer_html();
6626 sub git_shortlog {
6627 git_log_generic('shortlog', \&git_shortlog_body,
6628 $hash, $hash_parent);
6631 ## ......................................................................
6632 ## feeds (RSS, Atom; OPML)
6634 sub git_feed {
6635 my $format = shift || 'atom';
6636 my $have_blame = gitweb_check_feature('blame');
6638 # Atom: http://www.atomenabled.org/developers/syndication/
6639 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6640 if ($format ne 'rss' && $format ne 'atom') {
6641 die_error(400, "Unknown web feed format");
6644 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6645 my $head = $hash || 'HEAD';
6646 my @commitlist = parse_commits($head, 150, 0, $file_name);
6648 my %latest_commit;
6649 my %latest_date;
6650 my $content_type = "application/$format+xml";
6651 if (defined $cgi->http('HTTP_ACCEPT') &&
6652 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6653 # browser (feed reader) prefers text/xml
6654 $content_type = 'text/xml';
6656 if (defined($commitlist[0])) {
6657 %latest_commit = %{$commitlist[0]};
6658 my $latest_epoch = $latest_commit{'committer_epoch'};
6659 %latest_date = parse_date($latest_epoch);
6660 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6661 if (defined $if_modified) {
6662 my $since;
6663 if (eval { require HTTP::Date; 1; }) {
6664 $since = HTTP::Date::str2time($if_modified);
6665 } elsif (eval { require Time::ParseDate; 1; }) {
6666 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6668 if (defined $since && $latest_epoch <= $since) {
6669 print $cgi->header(
6670 -type => $content_type,
6671 -charset => 'utf-8',
6672 -last_modified => $latest_date{'rfc2822'},
6673 -status => '304 Not Modified');
6674 return;
6677 print $cgi->header(
6678 -type => $content_type,
6679 -charset => 'utf-8',
6680 -last_modified => $latest_date{'rfc2822'});
6681 } else {
6682 print $cgi->header(
6683 -type => $content_type,
6684 -charset => 'utf-8');
6687 # Optimization: skip generating the body if client asks only
6688 # for Last-Modified date.
6689 return if ($cgi->request_method() eq 'HEAD');
6691 # header variables
6692 my $title = "$site_name - $project/$action";
6693 my $feed_type = 'log';
6694 if (defined $hash) {
6695 $title .= " - '$hash'";
6696 $feed_type = 'branch log';
6697 if (defined $file_name) {
6698 $title .= " :: $file_name";
6699 $feed_type = 'history';
6701 } elsif (defined $file_name) {
6702 $title .= " - $file_name";
6703 $feed_type = 'history';
6705 $title .= " $feed_type";
6706 my $descr = git_get_project_description($project);
6707 if (defined $descr) {
6708 $descr = esc_html($descr);
6709 } else {
6710 $descr = "$project " .
6711 ($format eq 'rss' ? 'RSS' : 'Atom') .
6712 " feed";
6714 my $owner = git_get_project_owner($project);
6715 $owner = esc_html($owner);
6717 #header
6718 my $alt_url;
6719 if (defined $file_name) {
6720 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6721 } elsif (defined $hash) {
6722 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6723 } else {
6724 $alt_url = href(-full=>1, action=>"summary");
6726 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6727 if ($format eq 'rss') {
6728 print <<XML;
6729 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6730 <channel>
6732 print "<title>$title</title>\n" .
6733 "<link>$alt_url</link>\n" .
6734 "<description>$descr</description>\n" .
6735 "<language>en</language>\n" .
6736 # project owner is responsible for 'editorial' content
6737 "<managingEditor>$owner</managingEditor>\n";
6738 if (defined $logo || defined $favicon) {
6739 # prefer the logo to the favicon, since RSS
6740 # doesn't allow both
6741 my $img = esc_url($logo || $favicon);
6742 print "<image>\n" .
6743 "<url>$img</url>\n" .
6744 "<title>$title</title>\n" .
6745 "<link>$alt_url</link>\n" .
6746 "</image>\n";
6748 if (%latest_date) {
6749 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6750 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6752 print "<generator>gitweb v.$version/$git_version</generator>\n";
6753 } elsif ($format eq 'atom') {
6754 print <<XML;
6755 <feed xmlns="http://www.w3.org/2005/Atom">
6757 print "<title>$title</title>\n" .
6758 "<subtitle>$descr</subtitle>\n" .
6759 '<link rel="alternate" type="text/html" href="' .
6760 $alt_url . '" />' . "\n" .
6761 '<link rel="self" type="' . $content_type . '" href="' .
6762 $cgi->self_url() . '" />' . "\n" .
6763 "<id>" . href(-full=>1) . "</id>\n" .
6764 # use project owner for feed author
6765 "<author><name>$owner</name></author>\n";
6766 if (defined $favicon) {
6767 print "<icon>" . esc_url($favicon) . "</icon>\n";
6769 if (defined $logo_url) {
6770 # not twice as wide as tall: 72 x 27 pixels
6771 print "<logo>" . esc_url($logo) . "</logo>\n";
6773 if (! %latest_date) {
6774 # dummy date to keep the feed valid until commits trickle in:
6775 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6776 } else {
6777 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6779 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6782 # contents
6783 for (my $i = 0; $i <= $#commitlist; $i++) {
6784 my %co = %{$commitlist[$i]};
6785 my $commit = $co{'id'};
6786 # we read 150, we always show 30 and the ones more recent than 48 hours
6787 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6788 last;
6790 my %cd = parse_date($co{'author_epoch'});
6792 # get list of changed files
6793 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6794 $co{'parent'} || "--root",
6795 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6796 or next;
6797 my @difftree = map { chomp; $_ } <$fd>;
6798 close $fd
6799 or next;
6801 # print element (entry, item)
6802 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6803 if ($format eq 'rss') {
6804 print "<item>\n" .
6805 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6806 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6807 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6808 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6809 "<link>$co_url</link>\n" .
6810 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6811 "<content:encoded>" .
6812 "<![CDATA[\n";
6813 } elsif ($format eq 'atom') {
6814 print "<entry>\n" .
6815 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6816 "<updated>$cd{'iso-8601'}</updated>\n" .
6817 "<author>\n" .
6818 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6819 if ($co{'author_email'}) {
6820 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6822 print "</author>\n" .
6823 # use committer for contributor
6824 "<contributor>\n" .
6825 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6826 if ($co{'committer_email'}) {
6827 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6829 print "</contributor>\n" .
6830 "<published>$cd{'iso-8601'}</published>\n" .
6831 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6832 "<id>$co_url</id>\n" .
6833 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6834 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6836 my $comment = $co{'comment'};
6837 print "<pre>\n";
6838 foreach my $line (@$comment) {
6839 $line = esc_html($line);
6840 print "$line\n";
6842 print "</pre><ul>\n";
6843 foreach my $difftree_line (@difftree) {
6844 my %difftree = parse_difftree_raw_line($difftree_line);
6845 next if !$difftree{'from_id'};
6847 my $file = $difftree{'file'} || $difftree{'to_file'};
6849 print "<li>" .
6850 "[" .
6851 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6852 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6853 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6854 file_name=>$file, file_parent=>$difftree{'from_file'}),
6855 -title => "diff"}, 'D');
6856 if ($have_blame) {
6857 print $cgi->a({-href => href(-full=>1, action=>"blame",
6858 file_name=>$file, hash_base=>$commit),
6859 -title => "blame"}, 'B');
6861 # if this is not a feed of a file history
6862 if (!defined $file_name || $file_name ne $file) {
6863 print $cgi->a({-href => href(-full=>1, action=>"history",
6864 file_name=>$file, hash=>$commit),
6865 -title => "history"}, 'H');
6867 $file = esc_path($file);
6868 print "] ".
6869 "$file</li>\n";
6871 if ($format eq 'rss') {
6872 print "</ul>]]>\n" .
6873 "</content:encoded>\n" .
6874 "</item>\n";
6875 } elsif ($format eq 'atom') {
6876 print "</ul>\n</div>\n" .
6877 "</content>\n" .
6878 "</entry>\n";
6882 # end of feed
6883 if ($format eq 'rss') {
6884 print "</channel>\n</rss>\n";
6885 } elsif ($format eq 'atom') {
6886 print "</feed>\n";
6890 sub git_rss {
6891 git_feed('rss');
6894 sub git_atom {
6895 git_feed('atom');
6898 sub git_opml {
6899 my @list = git_get_projects_list();
6901 print $cgi->header(
6902 -type => 'text/xml',
6903 -charset => 'utf-8',
6904 -content_disposition => 'inline; filename="opml.xml"');
6906 print <<XML;
6907 <?xml version="1.0" encoding="utf-8"?>
6908 <opml version="1.0">
6909 <head>
6910 <title>$site_name OPML Export</title>
6911 </head>
6912 <body>
6913 <outline text="git RSS feeds">
6916 foreach my $pr (@list) {
6917 my %proj = %$pr;
6918 my $head = git_get_head_hash($proj{'path'});
6919 if (!defined $head) {
6920 next;
6922 $git_dir = "$projectroot/$proj{'path'}";
6923 my %co = parse_commit($head);
6924 if (!%co) {
6925 next;
6928 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6929 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6930 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6931 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6933 print <<XML;
6934 </outline>
6935 </body>
6936 </opml>