MinGW: Add missing file mode bit defines
[git/dscho.git] / gitweb / gitweb.perl
blob673e7a338b40d8cf1cb2af9c62fc47be320cb108
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]},
454 # Syntax highlighting support. This is based on Daniel Svensson's
455 # and Sham Chukoury's work in gitweb-xmms2.git.
456 # It requires the 'highlight' program present in $PATH,
457 # and therefore is disabled by default.
459 # To enable system wide have in $GITWEB_CONFIG
460 # $feature{'highlight'}{'default'} = [1];
462 'highlight' => {
463 'sub' => sub { feature_bool('highlight', @_) },
464 'override' => 0,
465 'default' => [0]},
468 sub gitweb_get_feature {
469 my ($name) = @_;
470 return unless exists $feature{$name};
471 my ($sub, $override, @defaults) = (
472 $feature{$name}{'sub'},
473 $feature{$name}{'override'},
474 @{$feature{$name}{'default'}});
475 # project specific override is possible only if we have project
476 our $git_dir; # global variable, declared later
477 if (!$override || !defined $git_dir) {
478 return @defaults;
480 if (!defined $sub) {
481 warn "feature $name is not overridable";
482 return @defaults;
484 return $sub->(@defaults);
487 # A wrapper to check if a given feature is enabled.
488 # With this, you can say
490 # my $bool_feat = gitweb_check_feature('bool_feat');
491 # gitweb_check_feature('bool_feat') or somecode;
493 # instead of
495 # my ($bool_feat) = gitweb_get_feature('bool_feat');
496 # (gitweb_get_feature('bool_feat'))[0] or somecode;
498 sub gitweb_check_feature {
499 return (gitweb_get_feature(@_))[0];
503 sub feature_bool {
504 my $key = shift;
505 my ($val) = git_get_project_config($key, '--bool');
507 if (!defined $val) {
508 return ($_[0]);
509 } elsif ($val eq 'true') {
510 return (1);
511 } elsif ($val eq 'false') {
512 return (0);
516 sub feature_snapshot {
517 my (@fmts) = @_;
519 my ($val) = git_get_project_config('snapshot');
521 if ($val) {
522 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
525 return @fmts;
528 sub feature_patches {
529 my @val = (git_get_project_config('patches', '--int'));
531 if (@val) {
532 return @val;
535 return ($_[0]);
538 sub feature_avatar {
539 my @val = (git_get_project_config('avatar'));
541 return @val ? @val : @_;
544 # checking HEAD file with -e is fragile if the repository was
545 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
546 # and then pruned.
547 sub check_head_link {
548 my ($dir) = @_;
549 my $headfile = "$dir/HEAD";
550 return ((-e $headfile) ||
551 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
554 sub check_export_ok {
555 my ($dir) = @_;
556 return (check_head_link($dir) &&
557 (!$export_ok || -e "$dir/$export_ok") &&
558 (!$export_auth_hook || $export_auth_hook->($dir)));
561 # process alternate names for backward compatibility
562 # filter out unsupported (unknown) snapshot formats
563 sub filter_snapshot_fmts {
564 my @fmts = @_;
566 @fmts = map {
567 exists $known_snapshot_format_aliases{$_} ?
568 $known_snapshot_format_aliases{$_} : $_} @fmts;
569 @fmts = grep {
570 exists $known_snapshot_formats{$_} &&
571 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
574 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
575 sub evaluate_gitweb_config {
576 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
577 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
578 # die if there are errors parsing config file
579 if (-e $GITWEB_CONFIG) {
580 do $GITWEB_CONFIG;
581 die $@ if $@;
582 } elsif (-e $GITWEB_CONFIG_SYSTEM) {
583 do $GITWEB_CONFIG_SYSTEM;
584 die $@ if $@;
588 # Get loadavg of system, to compare against $maxload.
589 # Currently it requires '/proc/loadavg' present to get loadavg;
590 # if it is not present it returns 0, which means no load checking.
591 sub get_loadavg {
592 if( -e '/proc/loadavg' ){
593 open my $fd, '<', '/proc/loadavg'
594 or return 0;
595 my @load = split(/\s+/, scalar <$fd>);
596 close $fd;
598 # The first three columns measure CPU and IO utilization of the last one,
599 # five, and 10 minute periods. The fourth column shows the number of
600 # currently running processes and the total number of processes in the m/n
601 # format. The last column displays the last process ID used.
602 return $load[0] || 0;
604 # additional checks for load average should go here for things that don't export
605 # /proc/loadavg
607 return 0;
610 # version of the core git binary
611 our $git_version;
612 sub evaluate_git_version {
613 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
614 $number_of_git_cmds++;
617 sub check_loadavg {
618 if (defined $maxload && get_loadavg() > $maxload) {
619 die_error(503, "The load average on the server is too high");
623 # ======================================================================
624 # input validation and dispatch
626 # input parameters can be collected from a variety of sources (presently, CGI
627 # and PATH_INFO), so we define an %input_params hash that collects them all
628 # together during validation: this allows subsequent uses (e.g. href()) to be
629 # agnostic of the parameter origin
631 our %input_params = ();
633 # input parameters are stored with the long parameter name as key. This will
634 # also be used in the href subroutine to convert parameters to their CGI
635 # equivalent, and since the href() usage is the most frequent one, we store
636 # the name -> CGI key mapping here, instead of the reverse.
638 # XXX: Warning: If you touch this, check the search form for updating,
639 # too.
641 our @cgi_param_mapping = (
642 project => "p",
643 action => "a",
644 file_name => "f",
645 file_parent => "fp",
646 hash => "h",
647 hash_parent => "hp",
648 hash_base => "hb",
649 hash_parent_base => "hpb",
650 page => "pg",
651 order => "o",
652 searchtext => "s",
653 searchtype => "st",
654 snapshot_format => "sf",
655 extra_options => "opt",
656 search_use_regexp => "sr",
657 # this must be last entry (for manipulation from JavaScript)
658 javascript => "js"
660 our %cgi_param_mapping = @cgi_param_mapping;
662 # we will also need to know the possible actions, for validation
663 our %actions = (
664 "blame" => \&git_blame,
665 "blame_incremental" => \&git_blame_incremental,
666 "blame_data" => \&git_blame_data,
667 "blobdiff" => \&git_blobdiff,
668 "blobdiff_plain" => \&git_blobdiff_plain,
669 "blob" => \&git_blob,
670 "blob_plain" => \&git_blob_plain,
671 "commitdiff" => \&git_commitdiff,
672 "commitdiff_plain" => \&git_commitdiff_plain,
673 "commit" => \&git_commit,
674 "forks" => \&git_forks,
675 "heads" => \&git_heads,
676 "history" => \&git_history,
677 "log" => \&git_log,
678 "patch" => \&git_patch,
679 "patches" => \&git_patches,
680 "rss" => \&git_rss,
681 "atom" => \&git_atom,
682 "search" => \&git_search,
683 "search_help" => \&git_search_help,
684 "shortlog" => \&git_shortlog,
685 "summary" => \&git_summary,
686 "tag" => \&git_tag,
687 "tags" => \&git_tags,
688 "tree" => \&git_tree,
689 "snapshot" => \&git_snapshot,
690 "object" => \&git_object,
691 # those below don't need $project
692 "opml" => \&git_opml,
693 "project_list" => \&git_project_list,
694 "project_index" => \&git_project_index,
697 # finally, we have the hash of allowed extra_options for the commands that
698 # allow them
699 our %allowed_options = (
700 "--no-merges" => [ qw(rss atom log shortlog history) ],
703 # fill %input_params with the CGI parameters. All values except for 'opt'
704 # should be single values, but opt can be an array. We should probably
705 # build an array of parameters that can be multi-valued, but since for the time
706 # being it's only this one, we just single it out
707 sub evaluate_query_params {
708 our $cgi;
710 while (my ($name, $symbol) = each %cgi_param_mapping) {
711 if ($symbol eq 'opt') {
712 $input_params{$name} = [ $cgi->param($symbol) ];
713 } else {
714 $input_params{$name} = $cgi->param($symbol);
719 # now read PATH_INFO and update the parameter list for missing parameters
720 sub evaluate_path_info {
721 return if defined $input_params{'project'};
722 return if !$path_info;
723 $path_info =~ s,^/+,,;
724 return if !$path_info;
726 # find which part of PATH_INFO is project
727 my $project = $path_info;
728 $project =~ s,/+$,,;
729 while ($project && !check_head_link("$projectroot/$project")) {
730 $project =~ s,/*[^/]*$,,;
732 return unless $project;
733 $input_params{'project'} = $project;
735 # do not change any parameters if an action is given using the query string
736 return if $input_params{'action'};
737 $path_info =~ s,^\Q$project\E/*,,;
739 # next, check if we have an action
740 my $action = $path_info;
741 $action =~ s,/.*$,,;
742 if (exists $actions{$action}) {
743 $path_info =~ s,^$action/*,,;
744 $input_params{'action'} = $action;
747 # list of actions that want hash_base instead of hash, but can have no
748 # pathname (f) parameter
749 my @wants_base = (
750 'tree',
751 'history',
754 # we want to catch
755 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
756 my ($parentrefname, $parentpathname, $refname, $pathname) =
757 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
759 # first, analyze the 'current' part
760 if (defined $pathname) {
761 # we got "branch:filename" or "branch:dir/"
762 # we could use git_get_type(branch:pathname), but:
763 # - it needs $git_dir
764 # - it does a git() call
765 # - the convention of terminating directories with a slash
766 # makes it superfluous
767 # - embedding the action in the PATH_INFO would make it even
768 # more superfluous
769 $pathname =~ s,^/+,,;
770 if (!$pathname || substr($pathname, -1) eq "/") {
771 $input_params{'action'} ||= "tree";
772 $pathname =~ s,/$,,;
773 } else {
774 # the default action depends on whether we had parent info
775 # or not
776 if ($parentrefname) {
777 $input_params{'action'} ||= "blobdiff_plain";
778 } else {
779 $input_params{'action'} ||= "blob_plain";
782 $input_params{'hash_base'} ||= $refname;
783 $input_params{'file_name'} ||= $pathname;
784 } elsif (defined $refname) {
785 # we got "branch". In this case we have to choose if we have to
786 # set hash or hash_base.
788 # Most of the actions without a pathname only want hash to be
789 # set, except for the ones specified in @wants_base that want
790 # hash_base instead. It should also be noted that hand-crafted
791 # links having 'history' as an action and no pathname or hash
792 # set will fail, but that happens regardless of PATH_INFO.
793 $input_params{'action'} ||= "shortlog";
794 if (grep { $_ eq $input_params{'action'} } @wants_base) {
795 $input_params{'hash_base'} ||= $refname;
796 } else {
797 $input_params{'hash'} ||= $refname;
801 # next, handle the 'parent' part, if present
802 if (defined $parentrefname) {
803 # a missing pathspec defaults to the 'current' filename, allowing e.g.
804 # someproject/blobdiff/oldrev..newrev:/filename
805 if ($parentpathname) {
806 $parentpathname =~ s,^/+,,;
807 $parentpathname =~ s,/$,,;
808 $input_params{'file_parent'} ||= $parentpathname;
809 } else {
810 $input_params{'file_parent'} ||= $input_params{'file_name'};
812 # we assume that hash_parent_base is wanted if a path was specified,
813 # or if the action wants hash_base instead of hash
814 if (defined $input_params{'file_parent'} ||
815 grep { $_ eq $input_params{'action'} } @wants_base) {
816 $input_params{'hash_parent_base'} ||= $parentrefname;
817 } else {
818 $input_params{'hash_parent'} ||= $parentrefname;
822 # for the snapshot action, we allow URLs in the form
823 # $project/snapshot/$hash.ext
824 # where .ext determines the snapshot and gets removed from the
825 # passed $refname to provide the $hash.
827 # To be able to tell that $refname includes the format extension, we
828 # require the following two conditions to be satisfied:
829 # - the hash input parameter MUST have been set from the $refname part
830 # of the URL (i.e. they must be equal)
831 # - the snapshot format MUST NOT have been defined already (e.g. from
832 # CGI parameter sf)
833 # It's also useless to try any matching unless $refname has a dot,
834 # so we check for that too
835 if (defined $input_params{'action'} &&
836 $input_params{'action'} eq 'snapshot' &&
837 defined $refname && index($refname, '.') != -1 &&
838 $refname eq $input_params{'hash'} &&
839 !defined $input_params{'snapshot_format'}) {
840 # We loop over the known snapshot formats, checking for
841 # extensions. Allowed extensions are both the defined suffix
842 # (which includes the initial dot already) and the snapshot
843 # format key itself, with a prepended dot
844 while (my ($fmt, $opt) = each %known_snapshot_formats) {
845 my $hash = $refname;
846 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
847 next;
849 my $sfx = $1;
850 # a valid suffix was found, so set the snapshot format
851 # and reset the hash parameter
852 $input_params{'snapshot_format'} = $fmt;
853 $input_params{'hash'} = $hash;
854 # we also set the format suffix to the one requested
855 # in the URL: this way a request for e.g. .tgz returns
856 # a .tgz instead of a .tar.gz
857 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
858 last;
863 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
864 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
865 $searchtext, $search_regexp);
866 sub evaluate_and_validate_params {
867 our $action = $input_params{'action'};
868 if (defined $action) {
869 if (!validate_action($action)) {
870 die_error(400, "Invalid action parameter");
874 # parameters which are pathnames
875 our $project = $input_params{'project'};
876 if (defined $project) {
877 if (!validate_project($project)) {
878 undef $project;
879 die_error(404, "No such project");
883 our $file_name = $input_params{'file_name'};
884 if (defined $file_name) {
885 if (!validate_pathname($file_name)) {
886 die_error(400, "Invalid file parameter");
890 our $file_parent = $input_params{'file_parent'};
891 if (defined $file_parent) {
892 if (!validate_pathname($file_parent)) {
893 die_error(400, "Invalid file parent parameter");
897 # parameters which are refnames
898 our $hash = $input_params{'hash'};
899 if (defined $hash) {
900 if (!validate_refname($hash)) {
901 die_error(400, "Invalid hash parameter");
905 our $hash_parent = $input_params{'hash_parent'};
906 if (defined $hash_parent) {
907 if (!validate_refname($hash_parent)) {
908 die_error(400, "Invalid hash parent parameter");
912 our $hash_base = $input_params{'hash_base'};
913 if (defined $hash_base) {
914 if (!validate_refname($hash_base)) {
915 die_error(400, "Invalid hash base parameter");
919 our @extra_options = @{$input_params{'extra_options'}};
920 # @extra_options is always defined, since it can only be (currently) set from
921 # CGI, and $cgi->param() returns the empty array in array context if the param
922 # is not set
923 foreach my $opt (@extra_options) {
924 if (not exists $allowed_options{$opt}) {
925 die_error(400, "Invalid option parameter");
927 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
928 die_error(400, "Invalid option parameter for this action");
932 our $hash_parent_base = $input_params{'hash_parent_base'};
933 if (defined $hash_parent_base) {
934 if (!validate_refname($hash_parent_base)) {
935 die_error(400, "Invalid hash parent base parameter");
939 # other parameters
940 our $page = $input_params{'page'};
941 if (defined $page) {
942 if ($page =~ m/[^0-9]/) {
943 die_error(400, "Invalid page parameter");
947 our $searchtype = $input_params{'searchtype'};
948 if (defined $searchtype) {
949 if ($searchtype =~ m/[^a-z]/) {
950 die_error(400, "Invalid searchtype parameter");
954 our $search_use_regexp = $input_params{'search_use_regexp'};
956 our $searchtext = $input_params{'searchtext'};
957 our $search_regexp;
958 if (defined $searchtext) {
959 if (length($searchtext) < 2) {
960 die_error(403, "At least two characters are required for search parameter");
962 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
966 # path to the current git repository
967 our $git_dir;
968 sub evaluate_git_dir {
969 our $git_dir = "$projectroot/$project" if $project;
972 our (@snapshot_fmts, $git_avatar);
973 sub configure_gitweb_features {
974 # list of supported snapshot formats
975 our @snapshot_fmts = gitweb_get_feature('snapshot');
976 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
978 # check that the avatar feature is set to a known provider name,
979 # and for each provider check if the dependencies are satisfied.
980 # if the provider name is invalid or the dependencies are not met,
981 # reset $git_avatar to the empty string.
982 our ($git_avatar) = gitweb_get_feature('avatar');
983 if ($git_avatar eq 'gravatar') {
984 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
985 } elsif ($git_avatar eq 'picon') {
986 # no dependencies
987 } else {
988 $git_avatar = '';
992 # custom error handler: 'die <message>' is Internal Server Error
993 sub handle_errors_html {
994 my $msg = shift; # it is already HTML escaped
996 # to avoid infinite loop where error occurs in die_error,
997 # change handler to default handler, disabling handle_errors_html
998 set_message("Error occured when inside die_error:\n$msg");
1000 # you cannot jump out of die_error when called as error handler;
1001 # the subroutine set via CGI::Carp::set_message is called _after_
1002 # HTTP headers are already written, so it cannot write them itself
1003 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1005 set_message(\&handle_errors_html);
1007 # dispatch
1008 sub dispatch {
1009 if (!defined $action) {
1010 if (defined $hash) {
1011 $action = git_get_type($hash);
1012 } elsif (defined $hash_base && defined $file_name) {
1013 $action = git_get_type("$hash_base:$file_name");
1014 } elsif (defined $project) {
1015 $action = 'summary';
1016 } else {
1017 $action = 'project_list';
1020 if (!defined($actions{$action})) {
1021 die_error(400, "Unknown action");
1023 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1024 !$project) {
1025 die_error(400, "Project needed");
1027 $actions{$action}->();
1030 sub run_request {
1031 our $t0 = [Time::HiRes::gettimeofday()]
1032 if defined $t0;
1034 evaluate_uri();
1035 evaluate_gitweb_config();
1036 evaluate_git_version();
1037 check_loadavg();
1039 # $projectroot and $projects_list might be set in gitweb config file
1040 $projects_list ||= $projectroot;
1042 evaluate_query_params();
1043 evaluate_path_info();
1044 evaluate_and_validate_params();
1045 evaluate_git_dir();
1047 configure_gitweb_features();
1049 dispatch();
1052 our $is_last_request = sub { 1 };
1053 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1054 our $CGI = 'CGI';
1055 our $cgi;
1056 sub evaluate_argv {
1057 return unless (@ARGV);
1059 require Getopt::Long;
1060 Getopt::Long::GetOptions(
1061 'fastcgi|fcgi|f' => sub {
1062 require CGI::Fast;
1063 our $CGI = 'CGI::Fast';
1065 my $request_number = 0;
1066 # let each child service 100 requests
1067 our $is_last_request = sub { ++$request_number > 100 };
1069 'nproc|n=i' => sub {
1070 my ($arg, $val) = @_;
1071 return unless eval { require FCGI::ProcManager; 1; };
1072 my $proc_manager = FCGI::ProcManager->new({
1073 n_processes => $val,
1075 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1076 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1077 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1082 sub run {
1083 evaluate_argv();
1085 $pre_listen_hook->()
1086 if $pre_listen_hook;
1088 REQUEST:
1089 while ($cgi = $CGI->new()) {
1090 $pre_dispatch_hook->()
1091 if $pre_dispatch_hook;
1093 run_request();
1095 $pre_dispatch_hook->()
1096 if $post_dispatch_hook;
1098 last REQUEST if ($is_last_request->());
1101 DONE_GITWEB:
1105 run();
1107 ## ======================================================================
1108 ## action links
1110 # possible values of extra options
1111 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1112 # -replay => 1 - start from a current view (replay with modifications)
1113 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1114 sub href {
1115 my %params = @_;
1116 # default is to use -absolute url() i.e. $my_uri
1117 my $href = $params{-full} ? $my_url : $my_uri;
1119 $params{'project'} = $project unless exists $params{'project'};
1121 if ($params{-replay}) {
1122 while (my ($name, $symbol) = each %cgi_param_mapping) {
1123 if (!exists $params{$name}) {
1124 $params{$name} = $input_params{$name};
1129 my $use_pathinfo = gitweb_check_feature('pathinfo');
1130 if (defined $params{'project'} &&
1131 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1132 # try to put as many parameters as possible in PATH_INFO:
1133 # - project name
1134 # - action
1135 # - hash_parent or hash_parent_base:/file_parent
1136 # - hash or hash_base:/filename
1137 # - the snapshot_format as an appropriate suffix
1139 # When the script is the root DirectoryIndex for the domain,
1140 # $href here would be something like http://gitweb.example.com/
1141 # Thus, we strip any trailing / from $href, to spare us double
1142 # slashes in the final URL
1143 $href =~ s,/$,,;
1145 # Then add the project name, if present
1146 $href .= "/".esc_url($params{'project'});
1147 delete $params{'project'};
1149 # since we destructively absorb parameters, we keep this
1150 # boolean that remembers if we're handling a snapshot
1151 my $is_snapshot = $params{'action'} eq 'snapshot';
1153 # Summary just uses the project path URL, any other action is
1154 # added to the URL
1155 if (defined $params{'action'}) {
1156 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1157 delete $params{'action'};
1160 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1161 # stripping nonexistent or useless pieces
1162 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1163 || $params{'hash_parent'} || $params{'hash'});
1164 if (defined $params{'hash_base'}) {
1165 if (defined $params{'hash_parent_base'}) {
1166 $href .= esc_url($params{'hash_parent_base'});
1167 # skip the file_parent if it's the same as the file_name
1168 if (defined $params{'file_parent'}) {
1169 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1170 delete $params{'file_parent'};
1171 } elsif ($params{'file_parent'} !~ /\.\./) {
1172 $href .= ":/".esc_url($params{'file_parent'});
1173 delete $params{'file_parent'};
1176 $href .= "..";
1177 delete $params{'hash_parent'};
1178 delete $params{'hash_parent_base'};
1179 } elsif (defined $params{'hash_parent'}) {
1180 $href .= esc_url($params{'hash_parent'}). "..";
1181 delete $params{'hash_parent'};
1184 $href .= esc_url($params{'hash_base'});
1185 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1186 $href .= ":/".esc_url($params{'file_name'});
1187 delete $params{'file_name'};
1189 delete $params{'hash'};
1190 delete $params{'hash_base'};
1191 } elsif (defined $params{'hash'}) {
1192 $href .= esc_url($params{'hash'});
1193 delete $params{'hash'};
1196 # If the action was a snapshot, we can absorb the
1197 # snapshot_format parameter too
1198 if ($is_snapshot) {
1199 my $fmt = $params{'snapshot_format'};
1200 # snapshot_format should always be defined when href()
1201 # is called, but just in case some code forgets, we
1202 # fall back to the default
1203 $fmt ||= $snapshot_fmts[0];
1204 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1205 delete $params{'snapshot_format'};
1209 # now encode the parameters explicitly
1210 my @result = ();
1211 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1212 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1213 if (defined $params{$name}) {
1214 if (ref($params{$name}) eq "ARRAY") {
1215 foreach my $par (@{$params{$name}}) {
1216 push @result, $symbol . "=" . esc_param($par);
1218 } else {
1219 push @result, $symbol . "=" . esc_param($params{$name});
1223 $href .= "?" . join(';', @result) if scalar @result;
1225 return $href;
1229 ## ======================================================================
1230 ## validation, quoting/unquoting and escaping
1232 sub validate_action {
1233 my $input = shift || return undef;
1234 return undef unless exists $actions{$input};
1235 return $input;
1238 sub validate_project {
1239 my $input = shift || return undef;
1240 if (!validate_pathname($input) ||
1241 !(-d "$projectroot/$input") ||
1242 !check_export_ok("$projectroot/$input") ||
1243 ($strict_export && !project_in_list($input))) {
1244 return undef;
1245 } else {
1246 return $input;
1250 sub validate_pathname {
1251 my $input = shift || return undef;
1253 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1254 # at the beginning, at the end, and between slashes.
1255 # also this catches doubled slashes
1256 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1257 return undef;
1259 # no null characters
1260 if ($input =~ m!\0!) {
1261 return undef;
1263 return $input;
1266 sub validate_refname {
1267 my $input = shift || return undef;
1269 # textual hashes are O.K.
1270 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1271 return $input;
1273 # it must be correct pathname
1274 $input = validate_pathname($input)
1275 or return undef;
1276 # restrictions on ref name according to git-check-ref-format
1277 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1278 return undef;
1280 return $input;
1283 # decode sequences of octets in utf8 into Perl's internal form,
1284 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1285 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1286 sub to_utf8 {
1287 my $str = shift;
1288 return undef unless defined $str;
1289 if (utf8::valid($str)) {
1290 utf8::decode($str);
1291 return $str;
1292 } else {
1293 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1297 # quote unsafe chars, but keep the slash, even when it's not
1298 # correct, but quoted slashes look too horrible in bookmarks
1299 sub esc_param {
1300 my $str = shift;
1301 return undef unless defined $str;
1302 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1303 $str =~ s/ /\+/g;
1304 return $str;
1307 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1308 sub esc_url {
1309 my $str = shift;
1310 return undef unless defined $str;
1311 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1312 $str =~ s/\+/%2B/g;
1313 $str =~ s/ /\+/g;
1314 return $str;
1317 # replace invalid utf8 character with SUBSTITUTION sequence
1318 sub esc_html {
1319 my $str = shift;
1320 my %opts = @_;
1322 return undef unless defined $str;
1324 $str = to_utf8($str);
1325 $str = $cgi->escapeHTML($str);
1326 if ($opts{'-nbsp'}) {
1327 $str =~ s/ /&nbsp;/g;
1329 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1330 return $str;
1333 # quote control characters and escape filename to HTML
1334 sub esc_path {
1335 my $str = shift;
1336 my %opts = @_;
1338 return undef unless defined $str;
1340 $str = to_utf8($str);
1341 $str = $cgi->escapeHTML($str);
1342 if ($opts{'-nbsp'}) {
1343 $str =~ s/ /&nbsp;/g;
1345 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1346 return $str;
1349 # Make control characters "printable", using character escape codes (CEC)
1350 sub quot_cec {
1351 my $cntrl = shift;
1352 my %opts = @_;
1353 my %es = ( # character escape codes, aka escape sequences
1354 "\t" => '\t', # tab (HT)
1355 "\n" => '\n', # line feed (LF)
1356 "\r" => '\r', # carrige return (CR)
1357 "\f" => '\f', # form feed (FF)
1358 "\b" => '\b', # backspace (BS)
1359 "\a" => '\a', # alarm (bell) (BEL)
1360 "\e" => '\e', # escape (ESC)
1361 "\013" => '\v', # vertical tab (VT)
1362 "\000" => '\0', # nul character (NUL)
1364 my $chr = ( (exists $es{$cntrl})
1365 ? $es{$cntrl}
1366 : sprintf('\%2x', ord($cntrl)) );
1367 if ($opts{-nohtml}) {
1368 return $chr;
1369 } else {
1370 return "<span class=\"cntrl\">$chr</span>";
1374 # Alternatively use unicode control pictures codepoints,
1375 # Unicode "printable representation" (PR)
1376 sub quot_upr {
1377 my $cntrl = shift;
1378 my %opts = @_;
1380 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1381 if ($opts{-nohtml}) {
1382 return $chr;
1383 } else {
1384 return "<span class=\"cntrl\">$chr</span>";
1388 # git may return quoted and escaped filenames
1389 sub unquote {
1390 my $str = shift;
1392 sub unq {
1393 my $seq = shift;
1394 my %es = ( # character escape codes, aka escape sequences
1395 't' => "\t", # tab (HT, TAB)
1396 'n' => "\n", # newline (NL)
1397 'r' => "\r", # return (CR)
1398 'f' => "\f", # form feed (FF)
1399 'b' => "\b", # backspace (BS)
1400 'a' => "\a", # alarm (bell) (BEL)
1401 'e' => "\e", # escape (ESC)
1402 'v' => "\013", # vertical tab (VT)
1405 if ($seq =~ m/^[0-7]{1,3}$/) {
1406 # octal char sequence
1407 return chr(oct($seq));
1408 } elsif (exists $es{$seq}) {
1409 # C escape sequence, aka character escape code
1410 return $es{$seq};
1412 # quoted ordinary character
1413 return $seq;
1416 if ($str =~ m/^"(.*)"$/) {
1417 # needs unquoting
1418 $str = $1;
1419 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1421 return $str;
1424 # escape tabs (convert tabs to spaces)
1425 sub untabify {
1426 my $line = shift;
1428 while ((my $pos = index($line, "\t")) != -1) {
1429 if (my $count = (8 - ($pos % 8))) {
1430 my $spaces = ' ' x $count;
1431 $line =~ s/\t/$spaces/;
1435 return $line;
1438 sub project_in_list {
1439 my $project = shift;
1440 my @list = git_get_projects_list();
1441 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1444 ## ----------------------------------------------------------------------
1445 ## HTML aware string manipulation
1447 # Try to chop given string on a word boundary between position
1448 # $len and $len+$add_len. If there is no word boundary there,
1449 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1450 # (marking chopped part) would be longer than given string.
1451 sub chop_str {
1452 my $str = shift;
1453 my $len = shift;
1454 my $add_len = shift || 10;
1455 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1457 # Make sure perl knows it is utf8 encoded so we don't
1458 # cut in the middle of a utf8 multibyte char.
1459 $str = to_utf8($str);
1461 # allow only $len chars, but don't cut a word if it would fit in $add_len
1462 # if it doesn't fit, cut it if it's still longer than the dots we would add
1463 # remove chopped character entities entirely
1465 # when chopping in the middle, distribute $len into left and right part
1466 # return early if chopping wouldn't make string shorter
1467 if ($where eq 'center') {
1468 return $str if ($len + 5 >= length($str)); # filler is length 5
1469 $len = int($len/2);
1470 } else {
1471 return $str if ($len + 4 >= length($str)); # filler is length 4
1474 # regexps: ending and beginning with word part up to $add_len
1475 my $endre = qr/.{$len}\w{0,$add_len}/;
1476 my $begre = qr/\w{0,$add_len}.{$len}/;
1478 if ($where eq 'left') {
1479 $str =~ m/^(.*?)($begre)$/;
1480 my ($lead, $body) = ($1, $2);
1481 if (length($lead) > 4) {
1482 $lead = " ...";
1484 return "$lead$body";
1486 } elsif ($where eq 'center') {
1487 $str =~ m/^($endre)(.*)$/;
1488 my ($left, $str) = ($1, $2);
1489 $str =~ m/^(.*?)($begre)$/;
1490 my ($mid, $right) = ($1, $2);
1491 if (length($mid) > 5) {
1492 $mid = " ... ";
1494 return "$left$mid$right";
1496 } else {
1497 $str =~ m/^($endre)(.*)$/;
1498 my $body = $1;
1499 my $tail = $2;
1500 if (length($tail) > 4) {
1501 $tail = "... ";
1503 return "$body$tail";
1507 # takes the same arguments as chop_str, but also wraps a <span> around the
1508 # result with a title attribute if it does get chopped. Additionally, the
1509 # string is HTML-escaped.
1510 sub chop_and_escape_str {
1511 my ($str) = @_;
1513 my $chopped = chop_str(@_);
1514 if ($chopped eq $str) {
1515 return esc_html($chopped);
1516 } else {
1517 $str =~ s/[[:cntrl:]]/?/g;
1518 return $cgi->span({-title=>$str}, esc_html($chopped));
1522 ## ----------------------------------------------------------------------
1523 ## functions returning short strings
1525 # CSS class for given age value (in seconds)
1526 sub age_class {
1527 my $age = shift;
1529 if (!defined $age) {
1530 return "noage";
1531 } elsif ($age < 60*60*2) {
1532 return "age0";
1533 } elsif ($age < 60*60*24*2) {
1534 return "age1";
1535 } else {
1536 return "age2";
1540 # convert age in seconds to "nn units ago" string
1541 sub age_string {
1542 my $age = shift;
1543 my $age_str;
1545 if ($age > 60*60*24*365*2) {
1546 $age_str = (int $age/60/60/24/365);
1547 $age_str .= " years ago";
1548 } elsif ($age > 60*60*24*(365/12)*2) {
1549 $age_str = int $age/60/60/24/(365/12);
1550 $age_str .= " months ago";
1551 } elsif ($age > 60*60*24*7*2) {
1552 $age_str = int $age/60/60/24/7;
1553 $age_str .= " weeks ago";
1554 } elsif ($age > 60*60*24*2) {
1555 $age_str = int $age/60/60/24;
1556 $age_str .= " days ago";
1557 } elsif ($age > 60*60*2) {
1558 $age_str = int $age/60/60;
1559 $age_str .= " hours ago";
1560 } elsif ($age > 60*2) {
1561 $age_str = int $age/60;
1562 $age_str .= " min ago";
1563 } elsif ($age > 2) {
1564 $age_str = int $age;
1565 $age_str .= " sec ago";
1566 } else {
1567 $age_str .= " right now";
1569 return $age_str;
1572 use constant {
1573 S_IFINVALID => 0030000,
1574 S_IFGITLINK => 0160000,
1577 # submodule/subproject, a commit object reference
1578 sub S_ISGITLINK {
1579 my $mode = shift;
1581 return (($mode & S_IFMT) == S_IFGITLINK)
1584 # convert file mode in octal to symbolic file mode string
1585 sub mode_str {
1586 my $mode = oct shift;
1588 if (S_ISGITLINK($mode)) {
1589 return 'm---------';
1590 } elsif (S_ISDIR($mode & S_IFMT)) {
1591 return 'drwxr-xr-x';
1592 } elsif (S_ISLNK($mode)) {
1593 return 'lrwxrwxrwx';
1594 } elsif (S_ISREG($mode)) {
1595 # git cares only about the executable bit
1596 if ($mode & S_IXUSR) {
1597 return '-rwxr-xr-x';
1598 } else {
1599 return '-rw-r--r--';
1601 } else {
1602 return '----------';
1606 # convert file mode in octal to file type string
1607 sub file_type {
1608 my $mode = shift;
1610 if ($mode !~ m/^[0-7]+$/) {
1611 return $mode;
1612 } else {
1613 $mode = oct $mode;
1616 if (S_ISGITLINK($mode)) {
1617 return "submodule";
1618 } elsif (S_ISDIR($mode & S_IFMT)) {
1619 return "directory";
1620 } elsif (S_ISLNK($mode)) {
1621 return "symlink";
1622 } elsif (S_ISREG($mode)) {
1623 return "file";
1624 } else {
1625 return "unknown";
1629 # convert file mode in octal to file type description string
1630 sub file_type_long {
1631 my $mode = shift;
1633 if ($mode !~ m/^[0-7]+$/) {
1634 return $mode;
1635 } else {
1636 $mode = oct $mode;
1639 if (S_ISGITLINK($mode)) {
1640 return "submodule";
1641 } elsif (S_ISDIR($mode & S_IFMT)) {
1642 return "directory";
1643 } elsif (S_ISLNK($mode)) {
1644 return "symlink";
1645 } elsif (S_ISREG($mode)) {
1646 if ($mode & S_IXUSR) {
1647 return "executable";
1648 } else {
1649 return "file";
1651 } else {
1652 return "unknown";
1657 ## ----------------------------------------------------------------------
1658 ## functions returning short HTML fragments, or transforming HTML fragments
1659 ## which don't belong to other sections
1661 # format line of commit message.
1662 sub format_log_line_html {
1663 my $line = shift;
1665 $line = esc_html($line, -nbsp=>1);
1666 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1667 $cgi->a({-href => href(action=>"object", hash=>$1),
1668 -class => "text"}, $1);
1669 }eg;
1671 return $line;
1674 # format marker of refs pointing to given object
1676 # the destination action is chosen based on object type and current context:
1677 # - for annotated tags, we choose the tag view unless it's the current view
1678 # already, in which case we go to shortlog view
1679 # - for other refs, we keep the current view if we're in history, shortlog or
1680 # log view, and select shortlog otherwise
1681 sub format_ref_marker {
1682 my ($refs, $id) = @_;
1683 my $markers = '';
1685 if (defined $refs->{$id}) {
1686 foreach my $ref (@{$refs->{$id}}) {
1687 # this code exploits the fact that non-lightweight tags are the
1688 # only indirect objects, and that they are the only objects for which
1689 # we want to use tag instead of shortlog as action
1690 my ($type, $name) = qw();
1691 my $indirect = ($ref =~ s/\^\{\}$//);
1692 # e.g. tags/v2.6.11 or heads/next
1693 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1694 $type = $1;
1695 $name = $2;
1696 } else {
1697 $type = "ref";
1698 $name = $ref;
1701 my $class = $type;
1702 $class .= " indirect" if $indirect;
1704 my $dest_action = "shortlog";
1706 if ($indirect) {
1707 $dest_action = "tag" unless $action eq "tag";
1708 } elsif ($action =~ /^(history|(short)?log)$/) {
1709 $dest_action = $action;
1712 my $dest = "";
1713 $dest .= "refs/" unless $ref =~ m!^refs/!;
1714 $dest .= $ref;
1716 my $link = $cgi->a({
1717 -href => href(
1718 action=>$dest_action,
1719 hash=>$dest
1720 )}, $name);
1722 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1723 $link . "</span>";
1727 if ($markers) {
1728 return ' <span class="refs">'. $markers . '</span>';
1729 } else {
1730 return "";
1734 # format, perhaps shortened and with markers, title line
1735 sub format_subject_html {
1736 my ($long, $short, $href, $extra) = @_;
1737 $extra = '' unless defined($extra);
1739 if (length($short) < length($long)) {
1740 $long =~ s/[[:cntrl:]]/?/g;
1741 return $cgi->a({-href => $href, -class => "list subject",
1742 -title => to_utf8($long)},
1743 esc_html($short)) . $extra;
1744 } else {
1745 return $cgi->a({-href => $href, -class => "list subject"},
1746 esc_html($long)) . $extra;
1750 # Rather than recomputing the url for an email multiple times, we cache it
1751 # after the first hit. This gives a visible benefit in views where the avatar
1752 # for the same email is used repeatedly (e.g. shortlog).
1753 # The cache is shared by all avatar engines (currently gravatar only), which
1754 # are free to use it as preferred. Since only one avatar engine is used for any
1755 # given page, there's no risk for cache conflicts.
1756 our %avatar_cache = ();
1758 # Compute the picon url for a given email, by using the picon search service over at
1759 # http://www.cs.indiana.edu/picons/search.html
1760 sub picon_url {
1761 my $email = lc shift;
1762 if (!$avatar_cache{$email}) {
1763 my ($user, $domain) = split('@', $email);
1764 $avatar_cache{$email} =
1765 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1766 "$domain/$user/" .
1767 "users+domains+unknown/up/single";
1769 return $avatar_cache{$email};
1772 # Compute the gravatar url for a given email, if it's not in the cache already.
1773 # Gravatar stores only the part of the URL before the size, since that's the
1774 # one computationally more expensive. This also allows reuse of the cache for
1775 # different sizes (for this particular engine).
1776 sub gravatar_url {
1777 my $email = lc shift;
1778 my $size = shift;
1779 $avatar_cache{$email} ||=
1780 "http://www.gravatar.com/avatar/" .
1781 Digest::MD5::md5_hex($email) . "?s=";
1782 return $avatar_cache{$email} . $size;
1785 # Insert an avatar for the given $email at the given $size if the feature
1786 # is enabled.
1787 sub git_get_avatar {
1788 my ($email, %opts) = @_;
1789 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1790 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1791 $opts{-size} ||= 'default';
1792 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1793 my $url = "";
1794 if ($git_avatar eq 'gravatar') {
1795 $url = gravatar_url($email, $size);
1796 } elsif ($git_avatar eq 'picon') {
1797 $url = picon_url($email);
1799 # Other providers can be added by extending the if chain, defining $url
1800 # as needed. If no variant puts something in $url, we assume avatars
1801 # are completely disabled/unavailable.
1802 if ($url) {
1803 return $pre_white .
1804 "<img width=\"$size\" " .
1805 "class=\"avatar\" " .
1806 "src=\"$url\" " .
1807 "alt=\"\" " .
1808 "/>" . $post_white;
1809 } else {
1810 return "";
1814 sub format_search_author {
1815 my ($author, $searchtype, $displaytext) = @_;
1816 my $have_search = gitweb_check_feature('search');
1818 if ($have_search) {
1819 my $performed = "";
1820 if ($searchtype eq 'author') {
1821 $performed = "authored";
1822 } elsif ($searchtype eq 'committer') {
1823 $performed = "committed";
1826 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1827 searchtext=>$author,
1828 searchtype=>$searchtype), class=>"list",
1829 title=>"Search for commits $performed by $author"},
1830 $displaytext);
1832 } else {
1833 return $displaytext;
1837 # format the author name of the given commit with the given tag
1838 # the author name is chopped and escaped according to the other
1839 # optional parameters (see chop_str).
1840 sub format_author_html {
1841 my $tag = shift;
1842 my $co = shift;
1843 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1844 return "<$tag class=\"author\">" .
1845 format_search_author($co->{'author_name'}, "author",
1846 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1847 $author) .
1848 "</$tag>";
1851 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1852 sub format_git_diff_header_line {
1853 my $line = shift;
1854 my $diffinfo = shift;
1855 my ($from, $to) = @_;
1857 if ($diffinfo->{'nparents'}) {
1858 # combined diff
1859 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1860 if ($to->{'href'}) {
1861 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1862 esc_path($to->{'file'}));
1863 } else { # file was deleted (no href)
1864 $line .= esc_path($to->{'file'});
1866 } else {
1867 # "ordinary" diff
1868 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1869 if ($from->{'href'}) {
1870 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1871 'a/' . esc_path($from->{'file'}));
1872 } else { # file was added (no href)
1873 $line .= 'a/' . esc_path($from->{'file'});
1875 $line .= ' ';
1876 if ($to->{'href'}) {
1877 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1878 'b/' . esc_path($to->{'file'}));
1879 } else { # file was deleted
1880 $line .= 'b/' . esc_path($to->{'file'});
1884 return "<div class=\"diff header\">$line</div>\n";
1887 # format extended diff header line, before patch itself
1888 sub format_extended_diff_header_line {
1889 my $line = shift;
1890 my $diffinfo = shift;
1891 my ($from, $to) = @_;
1893 # match <path>
1894 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1895 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1896 esc_path($from->{'file'}));
1898 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1899 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1900 esc_path($to->{'file'}));
1902 # match single <mode>
1903 if ($line =~ m/\s(\d{6})$/) {
1904 $line .= '<span class="info"> (' .
1905 file_type_long($1) .
1906 ')</span>';
1908 # match <hash>
1909 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1910 # can match only for combined diff
1911 $line = 'index ';
1912 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1913 if ($from->{'href'}[$i]) {
1914 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1915 -class=>"hash"},
1916 substr($diffinfo->{'from_id'}[$i],0,7));
1917 } else {
1918 $line .= '0' x 7;
1920 # separator
1921 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1923 $line .= '..';
1924 if ($to->{'href'}) {
1925 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1926 substr($diffinfo->{'to_id'},0,7));
1927 } else {
1928 $line .= '0' x 7;
1931 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1932 # can match only for ordinary diff
1933 my ($from_link, $to_link);
1934 if ($from->{'href'}) {
1935 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1936 substr($diffinfo->{'from_id'},0,7));
1937 } else {
1938 $from_link = '0' x 7;
1940 if ($to->{'href'}) {
1941 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1942 substr($diffinfo->{'to_id'},0,7));
1943 } else {
1944 $to_link = '0' x 7;
1946 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1947 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1950 return $line . "<br/>\n";
1953 # format from-file/to-file diff header
1954 sub format_diff_from_to_header {
1955 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1956 my $line;
1957 my $result = '';
1959 $line = $from_line;
1960 #assert($line =~ m/^---/) if DEBUG;
1961 # no extra formatting for "^--- /dev/null"
1962 if (! $diffinfo->{'nparents'}) {
1963 # ordinary (single parent) diff
1964 if ($line =~ m!^--- "?a/!) {
1965 if ($from->{'href'}) {
1966 $line = '--- a/' .
1967 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1968 esc_path($from->{'file'}));
1969 } else {
1970 $line = '--- a/' .
1971 esc_path($from->{'file'});
1974 $result .= qq!<div class="diff from_file">$line</div>\n!;
1976 } else {
1977 # combined diff (merge commit)
1978 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1979 if ($from->{'href'}[$i]) {
1980 $line = '--- ' .
1981 $cgi->a({-href=>href(action=>"blobdiff",
1982 hash_parent=>$diffinfo->{'from_id'}[$i],
1983 hash_parent_base=>$parents[$i],
1984 file_parent=>$from->{'file'}[$i],
1985 hash=>$diffinfo->{'to_id'},
1986 hash_base=>$hash,
1987 file_name=>$to->{'file'}),
1988 -class=>"path",
1989 -title=>"diff" . ($i+1)},
1990 $i+1) .
1991 '/' .
1992 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1993 esc_path($from->{'file'}[$i]));
1994 } else {
1995 $line = '--- /dev/null';
1997 $result .= qq!<div class="diff from_file">$line</div>\n!;
2001 $line = $to_line;
2002 #assert($line =~ m/^\+\+\+/) if DEBUG;
2003 # no extra formatting for "^+++ /dev/null"
2004 if ($line =~ m!^\+\+\+ "?b/!) {
2005 if ($to->{'href'}) {
2006 $line = '+++ b/' .
2007 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2008 esc_path($to->{'file'}));
2009 } else {
2010 $line = '+++ b/' .
2011 esc_path($to->{'file'});
2014 $result .= qq!<div class="diff to_file">$line</div>\n!;
2016 return $result;
2019 # create note for patch simplified by combined diff
2020 sub format_diff_cc_simplified {
2021 my ($diffinfo, @parents) = @_;
2022 my $result = '';
2024 $result .= "<div class=\"diff header\">" .
2025 "diff --cc ";
2026 if (!is_deleted($diffinfo)) {
2027 $result .= $cgi->a({-href => href(action=>"blob",
2028 hash_base=>$hash,
2029 hash=>$diffinfo->{'to_id'},
2030 file_name=>$diffinfo->{'to_file'}),
2031 -class => "path"},
2032 esc_path($diffinfo->{'to_file'}));
2033 } else {
2034 $result .= esc_path($diffinfo->{'to_file'});
2036 $result .= "</div>\n" . # class="diff header"
2037 "<div class=\"diff nodifferences\">" .
2038 "Simple merge" .
2039 "</div>\n"; # class="diff nodifferences"
2041 return $result;
2044 # format patch (diff) line (not to be used for diff headers)
2045 sub format_diff_line {
2046 my $line = shift;
2047 my ($from, $to) = @_;
2048 my $diff_class = "";
2050 chomp $line;
2052 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2053 # combined diff
2054 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2055 if ($line =~ m/^\@{3}/) {
2056 $diff_class = " chunk_header";
2057 } elsif ($line =~ m/^\\/) {
2058 $diff_class = " incomplete";
2059 } elsif ($prefix =~ tr/+/+/) {
2060 $diff_class = " add";
2061 } elsif ($prefix =~ tr/-/-/) {
2062 $diff_class = " rem";
2064 } else {
2065 # assume ordinary diff
2066 my $char = substr($line, 0, 1);
2067 if ($char eq '+') {
2068 $diff_class = " add";
2069 } elsif ($char eq '-') {
2070 $diff_class = " rem";
2071 } elsif ($char eq '@') {
2072 $diff_class = " chunk_header";
2073 } elsif ($char eq "\\") {
2074 $diff_class = " incomplete";
2077 $line = untabify($line);
2078 if ($from && $to && $line =~ m/^\@{2} /) {
2079 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2080 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2082 $from_lines = 0 unless defined $from_lines;
2083 $to_lines = 0 unless defined $to_lines;
2085 if ($from->{'href'}) {
2086 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2087 -class=>"list"}, $from_text);
2089 if ($to->{'href'}) {
2090 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2091 -class=>"list"}, $to_text);
2093 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2094 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2095 return "<div class=\"diff$diff_class\">$line</div>\n";
2096 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2097 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2098 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2100 @from_text = split(' ', $ranges);
2101 for (my $i = 0; $i < @from_text; ++$i) {
2102 ($from_start[$i], $from_nlines[$i]) =
2103 (split(',', substr($from_text[$i], 1)), 0);
2106 $to_text = pop @from_text;
2107 $to_start = pop @from_start;
2108 $to_nlines = pop @from_nlines;
2110 $line = "<span class=\"chunk_info\">$prefix ";
2111 for (my $i = 0; $i < @from_text; ++$i) {
2112 if ($from->{'href'}[$i]) {
2113 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2114 -class=>"list"}, $from_text[$i]);
2115 } else {
2116 $line .= $from_text[$i];
2118 $line .= " ";
2120 if ($to->{'href'}) {
2121 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2122 -class=>"list"}, $to_text);
2123 } else {
2124 $line .= $to_text;
2126 $line .= " $prefix</span>" .
2127 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2128 return "<div class=\"diff$diff_class\">$line</div>\n";
2130 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2133 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2134 # linked. Pass the hash of the tree/commit to snapshot.
2135 sub format_snapshot_links {
2136 my ($hash) = @_;
2137 my $num_fmts = @snapshot_fmts;
2138 if ($num_fmts > 1) {
2139 # A parenthesized list of links bearing format names.
2140 # e.g. "snapshot (_tar.gz_ _zip_)"
2141 return "snapshot (" . join(' ', map
2142 $cgi->a({
2143 -href => href(
2144 action=>"snapshot",
2145 hash=>$hash,
2146 snapshot_format=>$_
2148 }, $known_snapshot_formats{$_}{'display'})
2149 , @snapshot_fmts) . ")";
2150 } elsif ($num_fmts == 1) {
2151 # A single "snapshot" link whose tooltip bears the format name.
2152 # i.e. "_snapshot_"
2153 my ($fmt) = @snapshot_fmts;
2154 return
2155 $cgi->a({
2156 -href => href(
2157 action=>"snapshot",
2158 hash=>$hash,
2159 snapshot_format=>$fmt
2161 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2162 }, "snapshot");
2163 } else { # $num_fmts == 0
2164 return undef;
2168 ## ......................................................................
2169 ## functions returning values to be passed, perhaps after some
2170 ## transformation, to other functions; e.g. returning arguments to href()
2172 # returns hash to be passed to href to generate gitweb URL
2173 # in -title key it returns description of link
2174 sub get_feed_info {
2175 my $format = shift || 'Atom';
2176 my %res = (action => lc($format));
2178 # feed links are possible only for project views
2179 return unless (defined $project);
2180 # some views should link to OPML, or to generic project feed,
2181 # or don't have specific feed yet (so they should use generic)
2182 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2184 my $branch;
2185 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2186 # from tag links; this also makes possible to detect branch links
2187 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2188 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2189 $branch = $1;
2191 # find log type for feed description (title)
2192 my $type = 'log';
2193 if (defined $file_name) {
2194 $type = "history of $file_name";
2195 $type .= "/" if ($action eq 'tree');
2196 $type .= " on '$branch'" if (defined $branch);
2197 } else {
2198 $type = "log of $branch" if (defined $branch);
2201 $res{-title} = $type;
2202 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2203 $res{'file_name'} = $file_name;
2205 return %res;
2208 ## ----------------------------------------------------------------------
2209 ## git utility subroutines, invoking git commands
2211 # returns path to the core git executable and the --git-dir parameter as list
2212 sub git_cmd {
2213 $number_of_git_cmds++;
2214 return $GIT, '--git-dir='.$git_dir;
2217 # quote the given arguments for passing them to the shell
2218 # quote_command("command", "arg 1", "arg with ' and ! characters")
2219 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2220 # Try to avoid using this function wherever possible.
2221 sub quote_command {
2222 return join(' ',
2223 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2226 # get HEAD ref of given project as hash
2227 sub git_get_head_hash {
2228 return git_get_full_hash(shift, 'HEAD');
2231 sub git_get_full_hash {
2232 return git_get_hash(@_);
2235 sub git_get_short_hash {
2236 return git_get_hash(@_, '--short=7');
2239 sub git_get_hash {
2240 my ($project, $hash, @options) = @_;
2241 my $o_git_dir = $git_dir;
2242 my $retval = undef;
2243 $git_dir = "$projectroot/$project";
2244 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2245 '--verify', '-q', @options, $hash) {
2246 $retval = <$fd>;
2247 chomp $retval if defined $retval;
2248 close $fd;
2250 if (defined $o_git_dir) {
2251 $git_dir = $o_git_dir;
2253 return $retval;
2256 # get type of given object
2257 sub git_get_type {
2258 my $hash = shift;
2260 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2261 my $type = <$fd>;
2262 close $fd or return;
2263 chomp $type;
2264 return $type;
2267 # repository configuration
2268 our $config_file = '';
2269 our %config;
2271 # store multiple values for single key as anonymous array reference
2272 # single values stored directly in the hash, not as [ <value> ]
2273 sub hash_set_multi {
2274 my ($hash, $key, $value) = @_;
2276 if (!exists $hash->{$key}) {
2277 $hash->{$key} = $value;
2278 } elsif (!ref $hash->{$key}) {
2279 $hash->{$key} = [ $hash->{$key}, $value ];
2280 } else {
2281 push @{$hash->{$key}}, $value;
2285 # return hash of git project configuration
2286 # optionally limited to some section, e.g. 'gitweb'
2287 sub git_parse_project_config {
2288 my $section_regexp = shift;
2289 my %config;
2291 local $/ = "\0";
2293 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2294 or return;
2296 while (my $keyval = <$fh>) {
2297 chomp $keyval;
2298 my ($key, $value) = split(/\n/, $keyval, 2);
2300 hash_set_multi(\%config, $key, $value)
2301 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2303 close $fh;
2305 return %config;
2308 # convert config value to boolean: 'true' or 'false'
2309 # no value, number > 0, 'true' and 'yes' values are true
2310 # rest of values are treated as false (never as error)
2311 sub config_to_bool {
2312 my $val = shift;
2314 return 1 if !defined $val; # section.key
2316 # strip leading and trailing whitespace
2317 $val =~ s/^\s+//;
2318 $val =~ s/\s+$//;
2320 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2321 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2324 # convert config value to simple decimal number
2325 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2326 # to be multiplied by 1024, 1048576, or 1073741824
2327 sub config_to_int {
2328 my $val = shift;
2330 # strip leading and trailing whitespace
2331 $val =~ s/^\s+//;
2332 $val =~ s/\s+$//;
2334 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2335 $unit = lc($unit);
2336 # unknown unit is treated as 1
2337 return $num * ($unit eq 'g' ? 1073741824 :
2338 $unit eq 'm' ? 1048576 :
2339 $unit eq 'k' ? 1024 : 1);
2341 return $val;
2344 # convert config value to array reference, if needed
2345 sub config_to_multi {
2346 my $val = shift;
2348 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2351 sub git_get_project_config {
2352 my ($key, $type) = @_;
2354 return unless defined $git_dir;
2356 # key sanity check
2357 return unless ($key);
2358 $key =~ s/^gitweb\.//;
2359 return if ($key =~ m/\W/);
2361 # type sanity check
2362 if (defined $type) {
2363 $type =~ s/^--//;
2364 $type = undef
2365 unless ($type eq 'bool' || $type eq 'int');
2368 # get config
2369 if (!defined $config_file ||
2370 $config_file ne "$git_dir/config") {
2371 %config = git_parse_project_config('gitweb');
2372 $config_file = "$git_dir/config";
2375 # check if config variable (key) exists
2376 return unless exists $config{"gitweb.$key"};
2378 # ensure given type
2379 if (!defined $type) {
2380 return $config{"gitweb.$key"};
2381 } elsif ($type eq 'bool') {
2382 # backward compatibility: 'git config --bool' returns true/false
2383 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2384 } elsif ($type eq 'int') {
2385 return config_to_int($config{"gitweb.$key"});
2387 return $config{"gitweb.$key"};
2390 # get hash of given path at given ref
2391 sub git_get_hash_by_path {
2392 my $base = shift;
2393 my $path = shift || return undef;
2394 my $type = shift;
2396 $path =~ s,/+$,,;
2398 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2399 or die_error(500, "Open git-ls-tree failed");
2400 my $line = <$fd>;
2401 close $fd or return undef;
2403 if (!defined $line) {
2404 # there is no tree or hash given by $path at $base
2405 return undef;
2408 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2409 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2410 if (defined $type && $type ne $2) {
2411 # type doesn't match
2412 return undef;
2414 return $3;
2417 # get path of entry with given hash at given tree-ish (ref)
2418 # used to get 'from' filename for combined diff (merge commit) for renames
2419 sub git_get_path_by_hash {
2420 my $base = shift || return;
2421 my $hash = shift || return;
2423 local $/ = "\0";
2425 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2426 or return undef;
2427 while (my $line = <$fd>) {
2428 chomp $line;
2430 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2431 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2432 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2433 close $fd;
2434 return $1;
2437 close $fd;
2438 return undef;
2441 ## ......................................................................
2442 ## git utility functions, directly accessing git repository
2444 sub git_get_project_description {
2445 my $path = shift;
2447 $git_dir = "$projectroot/$path";
2448 open my $fd, '<', "$git_dir/description"
2449 or return git_get_project_config('description');
2450 my $descr = <$fd>;
2451 close $fd;
2452 if (defined $descr) {
2453 chomp $descr;
2455 return $descr;
2458 sub git_get_project_ctags {
2459 my $path = shift;
2460 my $ctags = {};
2462 $git_dir = "$projectroot/$path";
2463 opendir my $dh, "$git_dir/ctags"
2464 or return $ctags;
2465 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2466 open my $ct, '<', $_ or next;
2467 my $val = <$ct>;
2468 chomp $val;
2469 close $ct;
2470 my $ctag = $_; $ctag =~ s#.*/##;
2471 $ctags->{$ctag} = $val;
2473 closedir $dh;
2474 $ctags;
2477 sub git_populate_project_tagcloud {
2478 my $ctags = shift;
2480 # First, merge different-cased tags; tags vote on casing
2481 my %ctags_lc;
2482 foreach (keys %$ctags) {
2483 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2484 if (not $ctags_lc{lc $_}->{topcount}
2485 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2486 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2487 $ctags_lc{lc $_}->{topname} = $_;
2491 my $cloud;
2492 if (eval { require HTML::TagCloud; 1; }) {
2493 $cloud = HTML::TagCloud->new;
2494 foreach (sort keys %ctags_lc) {
2495 # Pad the title with spaces so that the cloud looks
2496 # less crammed.
2497 my $title = $ctags_lc{$_}->{topname};
2498 $title =~ s/ /&nbsp;/g;
2499 $title =~ s/^/&nbsp;/g;
2500 $title =~ s/$/&nbsp;/g;
2501 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2503 } else {
2504 $cloud = \%ctags_lc;
2506 $cloud;
2509 sub git_show_project_tagcloud {
2510 my ($cloud, $count) = @_;
2511 print STDERR ref($cloud)."..\n";
2512 if (ref $cloud eq 'HTML::TagCloud') {
2513 return $cloud->html_and_css($count);
2514 } else {
2515 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2516 return '<p align="center">' . join (', ', map {
2517 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2518 } splice(@tags, 0, $count)) . '</p>';
2522 sub git_get_project_url_list {
2523 my $path = shift;
2525 $git_dir = "$projectroot/$path";
2526 open my $fd, '<', "$git_dir/cloneurl"
2527 or return wantarray ?
2528 @{ config_to_multi(git_get_project_config('url')) } :
2529 config_to_multi(git_get_project_config('url'));
2530 my @git_project_url_list = map { chomp; $_ } <$fd>;
2531 close $fd;
2533 return wantarray ? @git_project_url_list : \@git_project_url_list;
2536 sub git_get_projects_list {
2537 my ($filter) = @_;
2538 my @list;
2540 $filter ||= '';
2541 $filter =~ s/\.git$//;
2543 my $check_forks = gitweb_check_feature('forks');
2545 if (-d $projects_list) {
2546 # search in directory
2547 my $dir = $projects_list . ($filter ? "/$filter" : '');
2548 # remove the trailing "/"
2549 $dir =~ s!/+$!!;
2550 my $pfxlen = length("$dir");
2551 my $pfxdepth = ($dir =~ tr!/!!);
2553 File::Find::find({
2554 follow_fast => 1, # follow symbolic links
2555 follow_skip => 2, # ignore duplicates
2556 dangling_symlinks => 0, # ignore dangling symlinks, silently
2557 wanted => sub {
2558 # global variables
2559 our $project_maxdepth;
2560 our $projectroot;
2561 # skip project-list toplevel, if we get it.
2562 return if (m!^[/.]$!);
2563 # only directories can be git repositories
2564 return unless (-d $_);
2565 # don't traverse too deep (Find is super slow on os x)
2566 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2567 $File::Find::prune = 1;
2568 return;
2571 my $subdir = substr($File::Find::name, $pfxlen + 1);
2572 # we check related file in $projectroot
2573 my $path = ($filter ? "$filter/" : '') . $subdir;
2574 if (check_export_ok("$projectroot/$path")) {
2575 push @list, { path => $path };
2576 $File::Find::prune = 1;
2579 }, "$dir");
2581 } elsif (-f $projects_list) {
2582 # read from file(url-encoded):
2583 # 'git%2Fgit.git Linus+Torvalds'
2584 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2585 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2586 my %paths;
2587 open my $fd, '<', $projects_list or return;
2588 PROJECT:
2589 while (my $line = <$fd>) {
2590 chomp $line;
2591 my ($path, $owner) = split ' ', $line;
2592 $path = unescape($path);
2593 $owner = unescape($owner);
2594 if (!defined $path) {
2595 next;
2597 if ($filter ne '') {
2598 # looking for forks;
2599 my $pfx = substr($path, 0, length($filter));
2600 if ($pfx ne $filter) {
2601 next PROJECT;
2603 my $sfx = substr($path, length($filter));
2604 if ($sfx !~ /^\/.*\.git$/) {
2605 next PROJECT;
2607 } elsif ($check_forks) {
2608 PATH:
2609 foreach my $filter (keys %paths) {
2610 # looking for forks;
2611 my $pfx = substr($path, 0, length($filter));
2612 if ($pfx ne $filter) {
2613 next PATH;
2615 my $sfx = substr($path, length($filter));
2616 if ($sfx !~ /^\/.*\.git$/) {
2617 next PATH;
2619 # is a fork, don't include it in
2620 # the list
2621 next PROJECT;
2624 if (check_export_ok("$projectroot/$path")) {
2625 my $pr = {
2626 path => $path,
2627 owner => to_utf8($owner),
2629 push @list, $pr;
2630 (my $forks_path = $path) =~ s/\.git$//;
2631 $paths{$forks_path}++;
2634 close $fd;
2636 return @list;
2639 our $gitweb_project_owner = undef;
2640 sub git_get_project_list_from_file {
2642 return if (defined $gitweb_project_owner);
2644 $gitweb_project_owner = {};
2645 # read from file (url-encoded):
2646 # 'git%2Fgit.git Linus+Torvalds'
2647 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2648 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2649 if (-f $projects_list) {
2650 open(my $fd, '<', $projects_list);
2651 while (my $line = <$fd>) {
2652 chomp $line;
2653 my ($pr, $ow) = split ' ', $line;
2654 $pr = unescape($pr);
2655 $ow = unescape($ow);
2656 $gitweb_project_owner->{$pr} = to_utf8($ow);
2658 close $fd;
2662 sub git_get_project_owner {
2663 my $project = shift;
2664 my $owner;
2666 return undef unless $project;
2667 $git_dir = "$projectroot/$project";
2669 if (!defined $gitweb_project_owner) {
2670 git_get_project_list_from_file();
2673 if (exists $gitweb_project_owner->{$project}) {
2674 $owner = $gitweb_project_owner->{$project};
2676 if (!defined $owner){
2677 $owner = git_get_project_config('owner');
2679 if (!defined $owner) {
2680 $owner = get_file_owner("$git_dir");
2683 return $owner;
2686 sub git_get_last_activity {
2687 my ($path) = @_;
2688 my $fd;
2690 $git_dir = "$projectroot/$path";
2691 open($fd, "-|", git_cmd(), 'for-each-ref',
2692 '--format=%(committer)',
2693 '--sort=-committerdate',
2694 '--count=1',
2695 'refs/heads') or return;
2696 my $most_recent = <$fd>;
2697 close $fd or return;
2698 if (defined $most_recent &&
2699 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2700 my $timestamp = $1;
2701 my $age = time - $timestamp;
2702 return ($age, age_string($age));
2704 return (undef, undef);
2707 sub git_get_references {
2708 my $type = shift || "";
2709 my %refs;
2710 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2711 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2712 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2713 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2714 or return;
2716 while (my $line = <$fd>) {
2717 chomp $line;
2718 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2719 if (defined $refs{$1}) {
2720 push @{$refs{$1}}, $2;
2721 } else {
2722 $refs{$1} = [ $2 ];
2726 close $fd or return;
2727 return \%refs;
2730 sub git_get_rev_name_tags {
2731 my $hash = shift || return undef;
2733 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2734 or return;
2735 my $name_rev = <$fd>;
2736 close $fd;
2738 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2739 return $1;
2740 } else {
2741 # catches also '$hash undefined' output
2742 return undef;
2746 ## ----------------------------------------------------------------------
2747 ## parse to hash functions
2749 sub parse_date {
2750 my $epoch = shift;
2751 my $tz = shift || "-0000";
2753 my %date;
2754 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2755 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2756 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2757 $date{'hour'} = $hour;
2758 $date{'minute'} = $min;
2759 $date{'mday'} = $mday;
2760 $date{'day'} = $days[$wday];
2761 $date{'month'} = $months[$mon];
2762 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2763 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2764 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2765 $mday, $months[$mon], $hour ,$min;
2766 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2767 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2769 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2770 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2771 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2772 $date{'hour_local'} = $hour;
2773 $date{'minute_local'} = $min;
2774 $date{'tz_local'} = $tz;
2775 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2776 1900+$year, $mon+1, $mday,
2777 $hour, $min, $sec, $tz);
2778 return %date;
2781 sub parse_tag {
2782 my $tag_id = shift;
2783 my %tag;
2784 my @comment;
2786 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2787 $tag{'id'} = $tag_id;
2788 while (my $line = <$fd>) {
2789 chomp $line;
2790 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2791 $tag{'object'} = $1;
2792 } elsif ($line =~ m/^type (.+)$/) {
2793 $tag{'type'} = $1;
2794 } elsif ($line =~ m/^tag (.+)$/) {
2795 $tag{'name'} = $1;
2796 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2797 $tag{'author'} = $1;
2798 $tag{'author_epoch'} = $2;
2799 $tag{'author_tz'} = $3;
2800 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2801 $tag{'author_name'} = $1;
2802 $tag{'author_email'} = $2;
2803 } else {
2804 $tag{'author_name'} = $tag{'author'};
2806 } elsif ($line =~ m/--BEGIN/) {
2807 push @comment, $line;
2808 last;
2809 } elsif ($line eq "") {
2810 last;
2813 push @comment, <$fd>;
2814 $tag{'comment'} = \@comment;
2815 close $fd or return;
2816 if (!defined $tag{'name'}) {
2817 return
2819 return %tag
2822 sub parse_commit_text {
2823 my ($commit_text, $withparents) = @_;
2824 my @commit_lines = split '\n', $commit_text;
2825 my %co;
2827 pop @commit_lines; # Remove '\0'
2829 if (! @commit_lines) {
2830 return;
2833 my $header = shift @commit_lines;
2834 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2835 return;
2837 ($co{'id'}, my @parents) = split ' ', $header;
2838 while (my $line = shift @commit_lines) {
2839 last if $line eq "\n";
2840 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2841 $co{'tree'} = $1;
2842 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2843 push @parents, $1;
2844 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2845 $co{'author'} = to_utf8($1);
2846 $co{'author_epoch'} = $2;
2847 $co{'author_tz'} = $3;
2848 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2849 $co{'author_name'} = $1;
2850 $co{'author_email'} = $2;
2851 } else {
2852 $co{'author_name'} = $co{'author'};
2854 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2855 $co{'committer'} = to_utf8($1);
2856 $co{'committer_epoch'} = $2;
2857 $co{'committer_tz'} = $3;
2858 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2859 $co{'committer_name'} = $1;
2860 $co{'committer_email'} = $2;
2861 } else {
2862 $co{'committer_name'} = $co{'committer'};
2866 if (!defined $co{'tree'}) {
2867 return;
2869 $co{'parents'} = \@parents;
2870 $co{'parent'} = $parents[0];
2872 foreach my $title (@commit_lines) {
2873 $title =~ s/^ //;
2874 if ($title ne "") {
2875 $co{'title'} = chop_str($title, 80, 5);
2876 # remove leading stuff of merges to make the interesting part visible
2877 if (length($title) > 50) {
2878 $title =~ s/^Automatic //;
2879 $title =~ s/^merge (of|with) /Merge ... /i;
2880 if (length($title) > 50) {
2881 $title =~ s/(http|rsync):\/\///;
2883 if (length($title) > 50) {
2884 $title =~ s/(master|www|rsync)\.//;
2886 if (length($title) > 50) {
2887 $title =~ s/kernel.org:?//;
2889 if (length($title) > 50) {
2890 $title =~ s/\/pub\/scm//;
2893 $co{'title_short'} = chop_str($title, 50, 5);
2894 last;
2897 if (! defined $co{'title'} || $co{'title'} eq "") {
2898 $co{'title'} = $co{'title_short'} = '(no commit message)';
2900 # remove added spaces
2901 foreach my $line (@commit_lines) {
2902 $line =~ s/^ //;
2904 $co{'comment'} = \@commit_lines;
2906 my $age = time - $co{'committer_epoch'};
2907 $co{'age'} = $age;
2908 $co{'age_string'} = age_string($age);
2909 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2910 if ($age > 60*60*24*7*2) {
2911 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2912 $co{'age_string_age'} = $co{'age_string'};
2913 } else {
2914 $co{'age_string_date'} = $co{'age_string'};
2915 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2917 return %co;
2920 sub parse_commit {
2921 my ($commit_id) = @_;
2922 my %co;
2924 local $/ = "\0";
2926 open my $fd, "-|", git_cmd(), "rev-list",
2927 "--parents",
2928 "--header",
2929 "--max-count=1",
2930 $commit_id,
2931 "--",
2932 or die_error(500, "Open git-rev-list failed");
2933 %co = parse_commit_text(<$fd>, 1);
2934 close $fd;
2936 return %co;
2939 sub parse_commits {
2940 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2941 my @cos;
2943 $maxcount ||= 1;
2944 $skip ||= 0;
2946 local $/ = "\0";
2948 open my $fd, "-|", git_cmd(), "rev-list",
2949 "--header",
2950 @args,
2951 ("--max-count=" . $maxcount),
2952 ("--skip=" . $skip),
2953 @extra_options,
2954 $commit_id,
2955 "--",
2956 ($filename ? ($filename) : ())
2957 or die_error(500, "Open git-rev-list failed");
2958 while (my $line = <$fd>) {
2959 my %co = parse_commit_text($line);
2960 push @cos, \%co;
2962 close $fd;
2964 return wantarray ? @cos : \@cos;
2967 # parse line of git-diff-tree "raw" output
2968 sub parse_difftree_raw_line {
2969 my $line = shift;
2970 my %res;
2972 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2973 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2974 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2975 $res{'from_mode'} = $1;
2976 $res{'to_mode'} = $2;
2977 $res{'from_id'} = $3;
2978 $res{'to_id'} = $4;
2979 $res{'status'} = $5;
2980 $res{'similarity'} = $6;
2981 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2982 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2983 } else {
2984 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2987 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2988 # combined diff (for merge commit)
2989 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2990 $res{'nparents'} = length($1);
2991 $res{'from_mode'} = [ split(' ', $2) ];
2992 $res{'to_mode'} = pop @{$res{'from_mode'}};
2993 $res{'from_id'} = [ split(' ', $3) ];
2994 $res{'to_id'} = pop @{$res{'from_id'}};
2995 $res{'status'} = [ split('', $4) ];
2996 $res{'to_file'} = unquote($5);
2998 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2999 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3000 $res{'commit'} = $1;
3003 return wantarray ? %res : \%res;
3006 # wrapper: return parsed line of git-diff-tree "raw" output
3007 # (the argument might be raw line, or parsed info)
3008 sub parsed_difftree_line {
3009 my $line_or_ref = shift;
3011 if (ref($line_or_ref) eq "HASH") {
3012 # pre-parsed (or generated by hand)
3013 return $line_or_ref;
3014 } else {
3015 return parse_difftree_raw_line($line_or_ref);
3019 # parse line of git-ls-tree output
3020 sub parse_ls_tree_line {
3021 my $line = shift;
3022 my %opts = @_;
3023 my %res;
3025 if ($opts{'-l'}) {
3026 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3027 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3029 $res{'mode'} = $1;
3030 $res{'type'} = $2;
3031 $res{'hash'} = $3;
3032 $res{'size'} = $4;
3033 if ($opts{'-z'}) {
3034 $res{'name'} = $5;
3035 } else {
3036 $res{'name'} = unquote($5);
3038 } else {
3039 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3040 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3042 $res{'mode'} = $1;
3043 $res{'type'} = $2;
3044 $res{'hash'} = $3;
3045 if ($opts{'-z'}) {
3046 $res{'name'} = $4;
3047 } else {
3048 $res{'name'} = unquote($4);
3052 return wantarray ? %res : \%res;
3055 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3056 sub parse_from_to_diffinfo {
3057 my ($diffinfo, $from, $to, @parents) = @_;
3059 if ($diffinfo->{'nparents'}) {
3060 # combined diff
3061 $from->{'file'} = [];
3062 $from->{'href'} = [];
3063 fill_from_file_info($diffinfo, @parents)
3064 unless exists $diffinfo->{'from_file'};
3065 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3066 $from->{'file'}[$i] =
3067 defined $diffinfo->{'from_file'}[$i] ?
3068 $diffinfo->{'from_file'}[$i] :
3069 $diffinfo->{'to_file'};
3070 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3071 $from->{'href'}[$i] = href(action=>"blob",
3072 hash_base=>$parents[$i],
3073 hash=>$diffinfo->{'from_id'}[$i],
3074 file_name=>$from->{'file'}[$i]);
3075 } else {
3076 $from->{'href'}[$i] = undef;
3079 } else {
3080 # ordinary (not combined) diff
3081 $from->{'file'} = $diffinfo->{'from_file'};
3082 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3083 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3084 hash=>$diffinfo->{'from_id'},
3085 file_name=>$from->{'file'});
3086 } else {
3087 delete $from->{'href'};
3091 $to->{'file'} = $diffinfo->{'to_file'};
3092 if (!is_deleted($diffinfo)) { # file exists in result
3093 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3094 hash=>$diffinfo->{'to_id'},
3095 file_name=>$to->{'file'});
3096 } else {
3097 delete $to->{'href'};
3101 ## ......................................................................
3102 ## parse to array of hashes functions
3104 sub git_get_heads_list {
3105 my $limit = shift;
3106 my @headslist;
3108 open my $fd, '-|', git_cmd(), 'for-each-ref',
3109 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3110 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3111 'refs/heads'
3112 or return;
3113 while (my $line = <$fd>) {
3114 my %ref_item;
3116 chomp $line;
3117 my ($refinfo, $committerinfo) = split(/\0/, $line);
3118 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3119 my ($committer, $epoch, $tz) =
3120 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3121 $ref_item{'fullname'} = $name;
3122 $name =~ s!^refs/heads/!!;
3124 $ref_item{'name'} = $name;
3125 $ref_item{'id'} = $hash;
3126 $ref_item{'title'} = $title || '(no commit message)';
3127 $ref_item{'epoch'} = $epoch;
3128 if ($epoch) {
3129 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3130 } else {
3131 $ref_item{'age'} = "unknown";
3134 push @headslist, \%ref_item;
3136 close $fd;
3138 return wantarray ? @headslist : \@headslist;
3141 sub git_get_tags_list {
3142 my $limit = shift;
3143 my @tagslist;
3145 open my $fd, '-|', git_cmd(), 'for-each-ref',
3146 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3147 '--format=%(objectname) %(objecttype) %(refname) '.
3148 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3149 'refs/tags'
3150 or return;
3151 while (my $line = <$fd>) {
3152 my %ref_item;
3154 chomp $line;
3155 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3156 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3157 my ($creator, $epoch, $tz) =
3158 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3159 $ref_item{'fullname'} = $name;
3160 $name =~ s!^refs/tags/!!;
3162 $ref_item{'type'} = $type;
3163 $ref_item{'id'} = $id;
3164 $ref_item{'name'} = $name;
3165 if ($type eq "tag") {
3166 $ref_item{'subject'} = $title;
3167 $ref_item{'reftype'} = $reftype;
3168 $ref_item{'refid'} = $refid;
3169 } else {
3170 $ref_item{'reftype'} = $type;
3171 $ref_item{'refid'} = $id;
3174 if ($type eq "tag" || $type eq "commit") {
3175 $ref_item{'epoch'} = $epoch;
3176 if ($epoch) {
3177 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3178 } else {
3179 $ref_item{'age'} = "unknown";
3183 push @tagslist, \%ref_item;
3185 close $fd;
3187 return wantarray ? @tagslist : \@tagslist;
3190 ## ----------------------------------------------------------------------
3191 ## filesystem-related functions
3193 sub get_file_owner {
3194 my $path = shift;
3196 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3197 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3198 if (!defined $gcos) {
3199 return undef;
3201 my $owner = $gcos;
3202 $owner =~ s/[,;].*$//;
3203 return to_utf8($owner);
3206 # assume that file exists
3207 sub insert_file {
3208 my $filename = shift;
3210 open my $fd, '<', $filename;
3211 print map { to_utf8($_) } <$fd>;
3212 close $fd;
3215 ## ......................................................................
3216 ## mimetype related functions
3218 sub mimetype_guess_file {
3219 my $filename = shift;
3220 my $mimemap = shift;
3221 -r $mimemap or return undef;
3223 my %mimemap;
3224 open(my $mh, '<', $mimemap) or return undef;
3225 while (<$mh>) {
3226 next if m/^#/; # skip comments
3227 my ($mimetype, $exts) = split(/\t+/);
3228 if (defined $exts) {
3229 my @exts = split(/\s+/, $exts);
3230 foreach my $ext (@exts) {
3231 $mimemap{$ext} = $mimetype;
3235 close($mh);
3237 $filename =~ /\.([^.]*)$/;
3238 return $mimemap{$1};
3241 sub mimetype_guess {
3242 my $filename = shift;
3243 my $mime;
3244 $filename =~ /\./ or return undef;
3246 if ($mimetypes_file) {
3247 my $file = $mimetypes_file;
3248 if ($file !~ m!^/!) { # if it is relative path
3249 # it is relative to project
3250 $file = "$projectroot/$project/$file";
3252 $mime = mimetype_guess_file($filename, $file);
3254 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3255 return $mime;
3258 sub blob_mimetype {
3259 my $fd = shift;
3260 my $filename = shift;
3262 if ($filename) {
3263 my $mime = mimetype_guess($filename);
3264 $mime and return $mime;
3267 # just in case
3268 return $default_blob_plain_mimetype unless $fd;
3270 if (-T $fd) {
3271 return 'text/plain';
3272 } elsif (! $filename) {
3273 return 'application/octet-stream';
3274 } elsif ($filename =~ m/\.png$/i) {
3275 return 'image/png';
3276 } elsif ($filename =~ m/\.gif$/i) {
3277 return 'image/gif';
3278 } elsif ($filename =~ m/\.jpe?g$/i) {
3279 return 'image/jpeg';
3280 } else {
3281 return 'application/octet-stream';
3285 sub blob_contenttype {
3286 my ($fd, $file_name, $type) = @_;
3288 $type ||= blob_mimetype($fd, $file_name);
3289 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3290 $type .= "; charset=$default_text_plain_charset";
3293 return $type;
3296 # guess file syntax for syntax highlighting; return undef if no highlighting
3297 # the name of syntax can (in the future) depend on syntax highlighter used
3298 sub guess_file_syntax {
3299 my ($highlight, $mimetype, $file_name) = @_;
3300 return undef unless ($highlight && defined $file_name);
3302 # configuration for 'highlight' (http://www.andre-simon.de/)
3303 # match by basename
3304 my %highlight_basename = (
3305 #'Program' => 'py',
3306 #'Library' => 'py',
3307 'SConstruct' => 'py', # SCons equivalent of Makefile
3308 'Makefile' => 'make',
3310 # match by extension
3311 my %highlight_ext = (
3312 # main extensions, defining name of syntax;
3313 # see files in /usr/share/highlight/langDefs/ directory
3314 map { $_ => $_ }
3315 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl),
3316 # alternate extensions, see /etc/highlight/filetypes.conf
3317 'h' => 'c',
3318 map { $_ => 'cpp' } qw(cxx c++ cc),
3319 map { $_ => 'php' } qw(php3 php4),
3320 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
3321 'mak' => 'make',
3322 map { $_ => 'xml' } qw(xhtml html htm),
3325 my $basename = basename($file_name, '.in');
3326 return $highlight_basename{$basename}
3327 if exists $highlight_basename{$basename};
3329 $basename =~ /\.([^.]*)$/;
3330 my $ext = $1 or return undef;
3331 return $highlight_ext{$ext}
3332 if exists $highlight_ext{$ext};
3334 return undef;
3337 # run highlighter and return FD of its output,
3338 # or return original FD if no highlighting
3339 sub run_highlighter {
3340 my ($fd, $highlight, $syntax) = @_;
3341 return $fd unless ($highlight && defined $syntax);
3343 close $fd
3344 or die_error(404, "Reading blob failed");
3345 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3346 "highlight --xhtml --fragment --syntax $syntax |"
3347 or die_error(500, "Couldn't open file or run syntax highlighter");
3348 return $fd;
3351 ## ======================================================================
3352 ## functions printing HTML: header, footer, error page
3354 sub get_page_title {
3355 my $title = to_utf8($site_name);
3357 return $title unless (defined $project);
3358 $title .= " - " . to_utf8($project);
3360 return $title unless (defined $action);
3361 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3363 return $title unless (defined $file_name);
3364 $title .= " - " . esc_path($file_name);
3365 if ($action eq "tree" && $file_name !~ m|/$|) {
3366 $title .= "/";
3369 return $title;
3372 sub git_header_html {
3373 my $status = shift || "200 OK";
3374 my $expires = shift;
3375 my %opts = @_;
3377 my $title = get_page_title();
3378 my $content_type;
3379 # require explicit support from the UA if we are to send the page as
3380 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3381 # we have to do this because MSIE sometimes globs '*/*', pretending to
3382 # support xhtml+xml but choking when it gets what it asked for.
3383 if (defined $cgi->http('HTTP_ACCEPT') &&
3384 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3385 $cgi->Accept('application/xhtml+xml') != 0) {
3386 $content_type = 'application/xhtml+xml';
3387 } else {
3388 $content_type = 'text/html';
3390 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3391 -status=> $status, -expires => $expires)
3392 unless ($opts{'-no_http_headers'});
3393 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3394 print <<EOF;
3395 <?xml version="1.0" encoding="utf-8"?>
3396 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3397 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3398 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3399 <!-- git core binaries version $git_version -->
3400 <head>
3401 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3402 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3403 <meta name="robots" content="index, nofollow"/>
3404 <title>$title</title>
3406 # the stylesheet, favicon etc urls won't work correctly with path_info
3407 # unless we set the appropriate base URL
3408 if ($ENV{'PATH_INFO'}) {
3409 print "<base href=\"".esc_url($base_url)."\" />\n";
3411 # print out each stylesheet that exist, providing backwards capability
3412 # for those people who defined $stylesheet in a config file
3413 if (defined $stylesheet) {
3414 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3415 } else {
3416 foreach my $stylesheet (@stylesheets) {
3417 next unless $stylesheet;
3418 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3421 if (defined $project) {
3422 my %href_params = get_feed_info();
3423 if (!exists $href_params{'-title'}) {
3424 $href_params{'-title'} = 'log';
3427 foreach my $format qw(RSS Atom) {
3428 my $type = lc($format);
3429 my %link_attr = (
3430 '-rel' => 'alternate',
3431 '-title' => "$project - $href_params{'-title'} - $format feed",
3432 '-type' => "application/$type+xml"
3435 $href_params{'action'} = $type;
3436 $link_attr{'-href'} = href(%href_params);
3437 print "<link ".
3438 "rel=\"$link_attr{'-rel'}\" ".
3439 "title=\"$link_attr{'-title'}\" ".
3440 "href=\"$link_attr{'-href'}\" ".
3441 "type=\"$link_attr{'-type'}\" ".
3442 "/>\n";
3444 $href_params{'extra_options'} = '--no-merges';
3445 $link_attr{'-href'} = href(%href_params);
3446 $link_attr{'-title'} .= ' (no merges)';
3447 print "<link ".
3448 "rel=\"$link_attr{'-rel'}\" ".
3449 "title=\"$link_attr{'-title'}\" ".
3450 "href=\"$link_attr{'-href'}\" ".
3451 "type=\"$link_attr{'-type'}\" ".
3452 "/>\n";
3455 } else {
3456 printf('<link rel="alternate" title="%s projects list" '.
3457 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3458 $site_name, href(project=>undef, action=>"project_index"));
3459 printf('<link rel="alternate" title="%s projects feeds" '.
3460 'href="%s" type="text/x-opml" />'."\n",
3461 $site_name, href(project=>undef, action=>"opml"));
3463 if (defined $favicon) {
3464 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3467 print "</head>\n" .
3468 "<body>\n";
3470 if (defined $site_header && -f $site_header) {
3471 insert_file($site_header);
3474 print "<div class=\"page_header\">\n" .
3475 $cgi->a({-href => esc_url($logo_url),
3476 -title => $logo_label},
3477 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3478 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3479 if (defined $project) {
3480 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3481 if (defined $action) {
3482 print " / $action";
3484 print "\n";
3486 print "</div>\n";
3488 my $have_search = gitweb_check_feature('search');
3489 if (defined $project && $have_search) {
3490 if (!defined $searchtext) {
3491 $searchtext = "";
3493 my $search_hash;
3494 if (defined $hash_base) {
3495 $search_hash = $hash_base;
3496 } elsif (defined $hash) {
3497 $search_hash = $hash;
3498 } else {
3499 $search_hash = "HEAD";
3501 my $action = $my_uri;
3502 my $use_pathinfo = gitweb_check_feature('pathinfo');
3503 if ($use_pathinfo) {
3504 $action .= "/".esc_url($project);
3506 print $cgi->startform(-method => "get", -action => $action) .
3507 "<div class=\"search\">\n" .
3508 (!$use_pathinfo &&
3509 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3510 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3511 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3512 $cgi->popup_menu(-name => 'st', -default => 'commit',
3513 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3514 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3515 " search:\n",
3516 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3517 "<span title=\"Extended regular expression\">" .
3518 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3519 -checked => $search_use_regexp) .
3520 "</span>" .
3521 "</div>" .
3522 $cgi->end_form() . "\n";
3526 sub git_footer_html {
3527 my $feed_class = 'rss_logo';
3529 print "<div class=\"page_footer\">\n";
3530 if (defined $project) {
3531 my $descr = git_get_project_description($project);
3532 if (defined $descr) {
3533 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3536 my %href_params = get_feed_info();
3537 if (!%href_params) {
3538 $feed_class .= ' generic';
3540 $href_params{'-title'} ||= 'log';
3542 foreach my $format qw(RSS Atom) {
3543 $href_params{'action'} = lc($format);
3544 print $cgi->a({-href => href(%href_params),
3545 -title => "$href_params{'-title'} $format feed",
3546 -class => $feed_class}, $format)."\n";
3549 } else {
3550 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3551 -class => $feed_class}, "OPML") . " ";
3552 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3553 -class => $feed_class}, "TXT") . "\n";
3555 print "</div>\n"; # class="page_footer"
3557 if (defined $t0 && gitweb_check_feature('timed')) {
3558 print "<div id=\"generating_info\">\n";
3559 print 'This page took '.
3560 '<span id="generating_time" class="time_span">'.
3561 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3562 ' seconds </span>'.
3563 ' and '.
3564 '<span id="generating_cmd">'.
3565 $number_of_git_cmds.
3566 '</span> git commands '.
3567 " to generate.\n";
3568 print "</div>\n"; # class="page_footer"
3571 if (defined $site_footer && -f $site_footer) {
3572 insert_file($site_footer);
3575 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3576 if (defined $action &&
3577 $action eq 'blame_incremental') {
3578 print qq!<script type="text/javascript">\n!.
3579 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3580 qq! "!. href() .qq!");\n!.
3581 qq!</script>\n!;
3582 } elsif (gitweb_check_feature('javascript-actions')) {
3583 print qq!<script type="text/javascript">\n!.
3584 qq!window.onload = fixLinks;\n!.
3585 qq!</script>\n!;
3588 print "</body>\n" .
3589 "</html>";
3592 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3593 # Example: die_error(404, 'Hash not found')
3594 # By convention, use the following status codes (as defined in RFC 2616):
3595 # 400: Invalid or missing CGI parameters, or
3596 # requested object exists but has wrong type.
3597 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3598 # this server or project.
3599 # 404: Requested object/revision/project doesn't exist.
3600 # 500: The server isn't configured properly, or
3601 # an internal error occurred (e.g. failed assertions caused by bugs), or
3602 # an unknown error occurred (e.g. the git binary died unexpectedly).
3603 # 503: The server is currently unavailable (because it is overloaded,
3604 # or down for maintenance). Generally, this is a temporary state.
3605 sub die_error {
3606 my $status = shift || 500;
3607 my $error = esc_html(shift) || "Internal Server Error";
3608 my $extra = shift;
3609 my %opts = @_;
3611 my %http_responses = (
3612 400 => '400 Bad Request',
3613 403 => '403 Forbidden',
3614 404 => '404 Not Found',
3615 500 => '500 Internal Server Error',
3616 503 => '503 Service Unavailable',
3618 git_header_html($http_responses{$status}, undef, %opts);
3619 print <<EOF;
3620 <div class="page_body">
3621 <br /><br />
3622 $status - $error
3623 <br />
3625 if (defined $extra) {
3626 print "<hr />\n" .
3627 "$extra\n";
3629 print "</div>\n";
3631 git_footer_html();
3632 goto DONE_GITWEB
3633 unless ($opts{'-error_handler'});
3636 ## ----------------------------------------------------------------------
3637 ## functions printing or outputting HTML: navigation
3639 sub git_print_page_nav {
3640 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3641 $extra = '' if !defined $extra; # pager or formats
3643 my @navs = qw(summary shortlog log commit commitdiff tree);
3644 if ($suppress) {
3645 @navs = grep { $_ ne $suppress } @navs;
3648 my %arg = map { $_ => {action=>$_} } @navs;
3649 if (defined $head) {
3650 for (qw(commit commitdiff)) {
3651 $arg{$_}{'hash'} = $head;
3653 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3654 for (qw(shortlog log)) {
3655 $arg{$_}{'hash'} = $head;
3660 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3661 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3663 my @actions = gitweb_get_feature('actions');
3664 my %repl = (
3665 '%' => '%',
3666 'n' => $project, # project name
3667 'f' => $git_dir, # project path within filesystem
3668 'h' => $treehead || '', # current hash ('h' parameter)
3669 'b' => $treebase || '', # hash base ('hb' parameter)
3671 while (@actions) {
3672 my ($label, $link, $pos) = splice(@actions,0,3);
3673 # insert
3674 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3675 # munch munch
3676 $link =~ s/%([%nfhb])/$repl{$1}/g;
3677 $arg{$label}{'_href'} = $link;
3680 print "<div class=\"page_nav\">\n" .
3681 (join " | ",
3682 map { $_ eq $current ?
3683 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3684 } @navs);
3685 print "<br/>\n$extra<br/>\n" .
3686 "</div>\n";
3689 sub format_paging_nav {
3690 my ($action, $page, $has_next_link) = @_;
3691 my $paging_nav;
3694 if ($page > 0) {
3695 $paging_nav .=
3696 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3697 " &sdot; " .
3698 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3699 -accesskey => "p", -title => "Alt-p"}, "prev");
3700 } else {
3701 $paging_nav .= "first &sdot; prev";
3704 if ($has_next_link) {
3705 $paging_nav .= " &sdot; " .
3706 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3707 -accesskey => "n", -title => "Alt-n"}, "next");
3708 } else {
3709 $paging_nav .= " &sdot; next";
3712 return $paging_nav;
3715 ## ......................................................................
3716 ## functions printing or outputting HTML: div
3718 sub git_print_header_div {
3719 my ($action, $title, $hash, $hash_base) = @_;
3720 my %args = ();
3722 $args{'action'} = $action;
3723 $args{'hash'} = $hash if $hash;
3724 $args{'hash_base'} = $hash_base if $hash_base;
3726 print "<div class=\"header\">\n" .
3727 $cgi->a({-href => href(%args), -class => "title"},
3728 $title ? $title : $action) .
3729 "\n</div>\n";
3732 sub print_local_time {
3733 print format_local_time(@_);
3736 sub format_local_time {
3737 my $localtime = '';
3738 my %date = @_;
3739 if ($date{'hour_local'} < 6) {
3740 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3741 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3742 } else {
3743 $localtime .= sprintf(" (%02d:%02d %s)",
3744 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3747 return $localtime;
3750 # Outputs the author name and date in long form
3751 sub git_print_authorship {
3752 my $co = shift;
3753 my %opts = @_;
3754 my $tag = $opts{-tag} || 'div';
3755 my $author = $co->{'author_name'};
3757 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3758 print "<$tag class=\"author_date\">" .
3759 format_search_author($author, "author", esc_html($author)) .
3760 " [$ad{'rfc2822'}";
3761 print_local_time(%ad) if ($opts{-localtime});
3762 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3763 . "</$tag>\n";
3766 # Outputs table rows containing the full author or committer information,
3767 # in the format expected for 'commit' view (& similia).
3768 # Parameters are a commit hash reference, followed by the list of people
3769 # to output information for. If the list is empty it defalts to both
3770 # author and committer.
3771 sub git_print_authorship_rows {
3772 my $co = shift;
3773 # too bad we can't use @people = @_ || ('author', 'committer')
3774 my @people = @_;
3775 @people = ('author', 'committer') unless @people;
3776 foreach my $who (@people) {
3777 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3778 print "<tr><td>$who</td><td>" .
3779 format_search_author($co->{"${who}_name"}, $who,
3780 esc_html($co->{"${who}_name"})) . " " .
3781 format_search_author($co->{"${who}_email"}, $who,
3782 esc_html("<" . $co->{"${who}_email"} . ">")) .
3783 "</td><td rowspan=\"2\">" .
3784 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3785 "</td></tr>\n" .
3786 "<tr>" .
3787 "<td></td><td> $wd{'rfc2822'}";
3788 print_local_time(%wd);
3789 print "</td>" .
3790 "</tr>\n";
3794 sub git_print_page_path {
3795 my $name = shift;
3796 my $type = shift;
3797 my $hb = shift;
3800 print "<div class=\"page_path\">";
3801 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3802 -title => 'tree root'}, to_utf8("[$project]"));
3803 print " / ";
3804 if (defined $name) {
3805 my @dirname = split '/', $name;
3806 my $basename = pop @dirname;
3807 my $fullname = '';
3809 foreach my $dir (@dirname) {
3810 $fullname .= ($fullname ? '/' : '') . $dir;
3811 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3812 hash_base=>$hb),
3813 -title => $fullname}, esc_path($dir));
3814 print " / ";
3816 if (defined $type && $type eq 'blob') {
3817 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3818 hash_base=>$hb),
3819 -title => $name}, esc_path($basename));
3820 } elsif (defined $type && $type eq 'tree') {
3821 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3822 hash_base=>$hb),
3823 -title => $name}, esc_path($basename));
3824 print " / ";
3825 } else {
3826 print esc_path($basename);
3829 print "<br/></div>\n";
3832 sub git_print_log {
3833 my $log = shift;
3834 my %opts = @_;
3836 if ($opts{'-remove_title'}) {
3837 # remove title, i.e. first line of log
3838 shift @$log;
3840 # remove leading empty lines
3841 while (defined $log->[0] && $log->[0] eq "") {
3842 shift @$log;
3845 # print log
3846 my $signoff = 0;
3847 my $empty = 0;
3848 foreach my $line (@$log) {
3849 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3850 $signoff = 1;
3851 $empty = 0;
3852 if (! $opts{'-remove_signoff'}) {
3853 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3854 next;
3855 } else {
3856 # remove signoff lines
3857 next;
3859 } else {
3860 $signoff = 0;
3863 # print only one empty line
3864 # do not print empty line after signoff
3865 if ($line eq "") {
3866 next if ($empty || $signoff);
3867 $empty = 1;
3868 } else {
3869 $empty = 0;
3872 print format_log_line_html($line) . "<br/>\n";
3875 if ($opts{'-final_empty_line'}) {
3876 # end with single empty line
3877 print "<br/>\n" unless $empty;
3881 # return link target (what link points to)
3882 sub git_get_link_target {
3883 my $hash = shift;
3884 my $link_target;
3886 # read link
3887 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3888 or return;
3890 local $/ = undef;
3891 $link_target = <$fd>;
3893 close $fd
3894 or return;
3896 return $link_target;
3899 # given link target, and the directory (basedir) the link is in,
3900 # return target of link relative to top directory (top tree);
3901 # return undef if it is not possible (including absolute links).
3902 sub normalize_link_target {
3903 my ($link_target, $basedir) = @_;
3905 # absolute symlinks (beginning with '/') cannot be normalized
3906 return if (substr($link_target, 0, 1) eq '/');
3908 # normalize link target to path from top (root) tree (dir)
3909 my $path;
3910 if ($basedir) {
3911 $path = $basedir . '/' . $link_target;
3912 } else {
3913 # we are in top (root) tree (dir)
3914 $path = $link_target;
3917 # remove //, /./, and /../
3918 my @path_parts;
3919 foreach my $part (split('/', $path)) {
3920 # discard '.' and ''
3921 next if (!$part || $part eq '.');
3922 # handle '..'
3923 if ($part eq '..') {
3924 if (@path_parts) {
3925 pop @path_parts;
3926 } else {
3927 # link leads outside repository (outside top dir)
3928 return;
3930 } else {
3931 push @path_parts, $part;
3934 $path = join('/', @path_parts);
3936 return $path;
3939 # print tree entry (row of git_tree), but without encompassing <tr> element
3940 sub git_print_tree_entry {
3941 my ($t, $basedir, $hash_base, $have_blame) = @_;
3943 my %base_key = ();
3944 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3946 # The format of a table row is: mode list link. Where mode is
3947 # the mode of the entry, list is the name of the entry, an href,
3948 # and link is the action links of the entry.
3950 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3951 if (exists $t->{'size'}) {
3952 print "<td class=\"size\">$t->{'size'}</td>\n";
3954 if ($t->{'type'} eq "blob") {
3955 print "<td class=\"list\">" .
3956 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3957 file_name=>"$basedir$t->{'name'}", %base_key),
3958 -class => "list"}, esc_path($t->{'name'}));
3959 if (S_ISLNK(oct $t->{'mode'})) {
3960 my $link_target = git_get_link_target($t->{'hash'});
3961 if ($link_target) {
3962 my $norm_target = normalize_link_target($link_target, $basedir);
3963 if (defined $norm_target) {
3964 print " -> " .
3965 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3966 file_name=>$norm_target),
3967 -title => $norm_target}, esc_path($link_target));
3968 } else {
3969 print " -> " . esc_path($link_target);
3973 print "</td>\n";
3974 print "<td class=\"link\">";
3975 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3976 file_name=>"$basedir$t->{'name'}", %base_key)},
3977 "blob");
3978 if ($have_blame) {
3979 print " | " .
3980 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3981 file_name=>"$basedir$t->{'name'}", %base_key)},
3982 "blame");
3984 if (defined $hash_base) {
3985 print " | " .
3986 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3987 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3988 "history");
3990 print " | " .
3991 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3992 file_name=>"$basedir$t->{'name'}")},
3993 "raw");
3994 print "</td>\n";
3996 } elsif ($t->{'type'} eq "tree") {
3997 print "<td class=\"list\">";
3998 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3999 file_name=>"$basedir$t->{'name'}",
4000 %base_key)},
4001 esc_path($t->{'name'}));
4002 print "</td>\n";
4003 print "<td class=\"link\">";
4004 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4005 file_name=>"$basedir$t->{'name'}",
4006 %base_key)},
4007 "tree");
4008 if (defined $hash_base) {
4009 print " | " .
4010 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4011 file_name=>"$basedir$t->{'name'}")},
4012 "history");
4014 print "</td>\n";
4015 } else {
4016 # unknown object: we can only present history for it
4017 # (this includes 'commit' object, i.e. submodule support)
4018 print "<td class=\"list\">" .
4019 esc_path($t->{'name'}) .
4020 "</td>\n";
4021 print "<td class=\"link\">";
4022 if (defined $hash_base) {
4023 print $cgi->a({-href => href(action=>"history",
4024 hash_base=>$hash_base,
4025 file_name=>"$basedir$t->{'name'}")},
4026 "history");
4028 print "</td>\n";
4032 ## ......................................................................
4033 ## functions printing large fragments of HTML
4035 # get pre-image filenames for merge (combined) diff
4036 sub fill_from_file_info {
4037 my ($diff, @parents) = @_;
4039 $diff->{'from_file'} = [ ];
4040 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4041 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4042 if ($diff->{'status'}[$i] eq 'R' ||
4043 $diff->{'status'}[$i] eq 'C') {
4044 $diff->{'from_file'}[$i] =
4045 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4049 return $diff;
4052 # is current raw difftree line of file deletion
4053 sub is_deleted {
4054 my $diffinfo = shift;
4056 return $diffinfo->{'to_id'} eq ('0' x 40);
4059 # does patch correspond to [previous] difftree raw line
4060 # $diffinfo - hashref of parsed raw diff format
4061 # $patchinfo - hashref of parsed patch diff format
4062 # (the same keys as in $diffinfo)
4063 sub is_patch_split {
4064 my ($diffinfo, $patchinfo) = @_;
4066 return defined $diffinfo && defined $patchinfo
4067 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4071 sub git_difftree_body {
4072 my ($difftree, $hash, @parents) = @_;
4073 my ($parent) = $parents[0];
4074 my $have_blame = gitweb_check_feature('blame');
4075 print "<div class=\"list_head\">\n";
4076 if ($#{$difftree} > 10) {
4077 print(($#{$difftree} + 1) . " files changed:\n");
4079 print "</div>\n";
4081 print "<table class=\"" .
4082 (@parents > 1 ? "combined " : "") .
4083 "diff_tree\">\n";
4085 # header only for combined diff in 'commitdiff' view
4086 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4087 if ($has_header) {
4088 # table header
4089 print "<thead><tr>\n" .
4090 "<th></th><th></th>\n"; # filename, patchN link
4091 for (my $i = 0; $i < @parents; $i++) {
4092 my $par = $parents[$i];
4093 print "<th>" .
4094 $cgi->a({-href => href(action=>"commitdiff",
4095 hash=>$hash, hash_parent=>$par),
4096 -title => 'commitdiff to parent number ' .
4097 ($i+1) . ': ' . substr($par,0,7)},
4098 $i+1) .
4099 "&nbsp;</th>\n";
4101 print "</tr></thead>\n<tbody>\n";
4104 my $alternate = 1;
4105 my $patchno = 0;
4106 foreach my $line (@{$difftree}) {
4107 my $diff = parsed_difftree_line($line);
4109 if ($alternate) {
4110 print "<tr class=\"dark\">\n";
4111 } else {
4112 print "<tr class=\"light\">\n";
4114 $alternate ^= 1;
4116 if (exists $diff->{'nparents'}) { # combined diff
4118 fill_from_file_info($diff, @parents)
4119 unless exists $diff->{'from_file'};
4121 if (!is_deleted($diff)) {
4122 # file exists in the result (child) commit
4123 print "<td>" .
4124 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4125 file_name=>$diff->{'to_file'},
4126 hash_base=>$hash),
4127 -class => "list"}, esc_path($diff->{'to_file'})) .
4128 "</td>\n";
4129 } else {
4130 print "<td>" .
4131 esc_path($diff->{'to_file'}) .
4132 "</td>\n";
4135 if ($action eq 'commitdiff') {
4136 # link to patch
4137 $patchno++;
4138 print "<td class=\"link\">" .
4139 $cgi->a({-href => "#patch$patchno"}, "patch") .
4140 " | " .
4141 "</td>\n";
4144 my $has_history = 0;
4145 my $not_deleted = 0;
4146 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4147 my $hash_parent = $parents[$i];
4148 my $from_hash = $diff->{'from_id'}[$i];
4149 my $from_path = $diff->{'from_file'}[$i];
4150 my $status = $diff->{'status'}[$i];
4152 $has_history ||= ($status ne 'A');
4153 $not_deleted ||= ($status ne 'D');
4155 if ($status eq 'A') {
4156 print "<td class=\"link\" align=\"right\"> | </td>\n";
4157 } elsif ($status eq 'D') {
4158 print "<td class=\"link\">" .
4159 $cgi->a({-href => href(action=>"blob",
4160 hash_base=>$hash,
4161 hash=>$from_hash,
4162 file_name=>$from_path)},
4163 "blob" . ($i+1)) .
4164 " | </td>\n";
4165 } else {
4166 if ($diff->{'to_id'} eq $from_hash) {
4167 print "<td class=\"link nochange\">";
4168 } else {
4169 print "<td class=\"link\">";
4171 print $cgi->a({-href => href(action=>"blobdiff",
4172 hash=>$diff->{'to_id'},
4173 hash_parent=>$from_hash,
4174 hash_base=>$hash,
4175 hash_parent_base=>$hash_parent,
4176 file_name=>$diff->{'to_file'},
4177 file_parent=>$from_path)},
4178 "diff" . ($i+1)) .
4179 " | </td>\n";
4183 print "<td class=\"link\">";
4184 if ($not_deleted) {
4185 print $cgi->a({-href => href(action=>"blob",
4186 hash=>$diff->{'to_id'},
4187 file_name=>$diff->{'to_file'},
4188 hash_base=>$hash)},
4189 "blob");
4190 print " | " if ($has_history);
4192 if ($has_history) {
4193 print $cgi->a({-href => href(action=>"history",
4194 file_name=>$diff->{'to_file'},
4195 hash_base=>$hash)},
4196 "history");
4198 print "</td>\n";
4200 print "</tr>\n";
4201 next; # instead of 'else' clause, to avoid extra indent
4203 # else ordinary diff
4205 my ($to_mode_oct, $to_mode_str, $to_file_type);
4206 my ($from_mode_oct, $from_mode_str, $from_file_type);
4207 if ($diff->{'to_mode'} ne ('0' x 6)) {
4208 $to_mode_oct = oct $diff->{'to_mode'};
4209 if (S_ISREG($to_mode_oct)) { # only for regular file
4210 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4212 $to_file_type = file_type($diff->{'to_mode'});
4214 if ($diff->{'from_mode'} ne ('0' x 6)) {
4215 $from_mode_oct = oct $diff->{'from_mode'};
4216 if (S_ISREG($to_mode_oct)) { # only for regular file
4217 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4219 $from_file_type = file_type($diff->{'from_mode'});
4222 if ($diff->{'status'} eq "A") { # created
4223 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4224 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4225 $mode_chng .= "]</span>";
4226 print "<td>";
4227 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4228 hash_base=>$hash, file_name=>$diff->{'file'}),
4229 -class => "list"}, esc_path($diff->{'file'}));
4230 print "</td>\n";
4231 print "<td>$mode_chng</td>\n";
4232 print "<td class=\"link\">";
4233 if ($action eq 'commitdiff') {
4234 # link to patch
4235 $patchno++;
4236 print $cgi->a({-href => "#patch$patchno"}, "patch");
4237 print " | ";
4239 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4240 hash_base=>$hash, file_name=>$diff->{'file'})},
4241 "blob");
4242 print "</td>\n";
4244 } elsif ($diff->{'status'} eq "D") { # deleted
4245 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4246 print "<td>";
4247 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4248 hash_base=>$parent, file_name=>$diff->{'file'}),
4249 -class => "list"}, esc_path($diff->{'file'}));
4250 print "</td>\n";
4251 print "<td>$mode_chng</td>\n";
4252 print "<td class=\"link\">";
4253 if ($action eq 'commitdiff') {
4254 # link to patch
4255 $patchno++;
4256 print $cgi->a({-href => "#patch$patchno"}, "patch");
4257 print " | ";
4259 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4260 hash_base=>$parent, file_name=>$diff->{'file'})},
4261 "blob") . " | ";
4262 if ($have_blame) {
4263 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4264 file_name=>$diff->{'file'})},
4265 "blame") . " | ";
4267 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4268 file_name=>$diff->{'file'})},
4269 "history");
4270 print "</td>\n";
4272 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4273 my $mode_chnge = "";
4274 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4275 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4276 if ($from_file_type ne $to_file_type) {
4277 $mode_chnge .= " from $from_file_type to $to_file_type";
4279 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4280 if ($from_mode_str && $to_mode_str) {
4281 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4282 } elsif ($to_mode_str) {
4283 $mode_chnge .= " mode: $to_mode_str";
4286 $mode_chnge .= "]</span>\n";
4288 print "<td>";
4289 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4290 hash_base=>$hash, file_name=>$diff->{'file'}),
4291 -class => "list"}, esc_path($diff->{'file'}));
4292 print "</td>\n";
4293 print "<td>$mode_chnge</td>\n";
4294 print "<td class=\"link\">";
4295 if ($action eq 'commitdiff') {
4296 # link to patch
4297 $patchno++;
4298 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4299 " | ";
4300 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4301 # "commit" view and modified file (not onlu mode changed)
4302 print $cgi->a({-href => href(action=>"blobdiff",
4303 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4304 hash_base=>$hash, hash_parent_base=>$parent,
4305 file_name=>$diff->{'file'})},
4306 "diff") .
4307 " | ";
4309 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4310 hash_base=>$hash, file_name=>$diff->{'file'})},
4311 "blob") . " | ";
4312 if ($have_blame) {
4313 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4314 file_name=>$diff->{'file'})},
4315 "blame") . " | ";
4317 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4318 file_name=>$diff->{'file'})},
4319 "history");
4320 print "</td>\n";
4322 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4323 my %status_name = ('R' => 'moved', 'C' => 'copied');
4324 my $nstatus = $status_name{$diff->{'status'}};
4325 my $mode_chng = "";
4326 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4327 # mode also for directories, so we cannot use $to_mode_str
4328 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4330 print "<td>" .
4331 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4332 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4333 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4334 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4335 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4336 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4337 -class => "list"}, esc_path($diff->{'from_file'})) .
4338 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4339 "<td class=\"link\">";
4340 if ($action eq 'commitdiff') {
4341 # link to patch
4342 $patchno++;
4343 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4344 " | ";
4345 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4346 # "commit" view and modified file (not only pure rename or copy)
4347 print $cgi->a({-href => href(action=>"blobdiff",
4348 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4349 hash_base=>$hash, hash_parent_base=>$parent,
4350 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4351 "diff") .
4352 " | ";
4354 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4355 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4356 "blob") . " | ";
4357 if ($have_blame) {
4358 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4359 file_name=>$diff->{'to_file'})},
4360 "blame") . " | ";
4362 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4363 file_name=>$diff->{'to_file'})},
4364 "history");
4365 print "</td>\n";
4367 } # we should not encounter Unmerged (U) or Unknown (X) status
4368 print "</tr>\n";
4370 print "</tbody>" if $has_header;
4371 print "</table>\n";
4374 sub git_patchset_body {
4375 my ($fd, $difftree, $hash, @hash_parents) = @_;
4376 my ($hash_parent) = $hash_parents[0];
4378 my $is_combined = (@hash_parents > 1);
4379 my $patch_idx = 0;
4380 my $patch_number = 0;
4381 my $patch_line;
4382 my $diffinfo;
4383 my $to_name;
4384 my (%from, %to);
4386 print "<div class=\"patchset\">\n";
4388 # skip to first patch
4389 while ($patch_line = <$fd>) {
4390 chomp $patch_line;
4392 last if ($patch_line =~ m/^diff /);
4395 PATCH:
4396 while ($patch_line) {
4398 # parse "git diff" header line
4399 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4400 # $1 is from_name, which we do not use
4401 $to_name = unquote($2);
4402 $to_name =~ s!^b/!!;
4403 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4404 # $1 is 'cc' or 'combined', which we do not use
4405 $to_name = unquote($2);
4406 } else {
4407 $to_name = undef;
4410 # check if current patch belong to current raw line
4411 # and parse raw git-diff line if needed
4412 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4413 # this is continuation of a split patch
4414 print "<div class=\"patch cont\">\n";
4415 } else {
4416 # advance raw git-diff output if needed
4417 $patch_idx++ if defined $diffinfo;
4419 # read and prepare patch information
4420 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4422 # compact combined diff output can have some patches skipped
4423 # find which patch (using pathname of result) we are at now;
4424 if ($is_combined) {
4425 while ($to_name ne $diffinfo->{'to_file'}) {
4426 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4427 format_diff_cc_simplified($diffinfo, @hash_parents) .
4428 "</div>\n"; # class="patch"
4430 $patch_idx++;
4431 $patch_number++;
4433 last if $patch_idx > $#$difftree;
4434 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4438 # modifies %from, %to hashes
4439 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4441 # this is first patch for raw difftree line with $patch_idx index
4442 # we index @$difftree array from 0, but number patches from 1
4443 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4446 # git diff header
4447 #assert($patch_line =~ m/^diff /) if DEBUG;
4448 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4449 $patch_number++;
4450 # print "git diff" header
4451 print format_git_diff_header_line($patch_line, $diffinfo,
4452 \%from, \%to);
4454 # print extended diff header
4455 print "<div class=\"diff extended_header\">\n";
4456 EXTENDED_HEADER:
4457 while ($patch_line = <$fd>) {
4458 chomp $patch_line;
4460 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4462 print format_extended_diff_header_line($patch_line, $diffinfo,
4463 \%from, \%to);
4465 print "</div>\n"; # class="diff extended_header"
4467 # from-file/to-file diff header
4468 if (! $patch_line) {
4469 print "</div>\n"; # class="patch"
4470 last PATCH;
4472 next PATCH if ($patch_line =~ m/^diff /);
4473 #assert($patch_line =~ m/^---/) if DEBUG;
4475 my $last_patch_line = $patch_line;
4476 $patch_line = <$fd>;
4477 chomp $patch_line;
4478 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4480 print format_diff_from_to_header($last_patch_line, $patch_line,
4481 $diffinfo, \%from, \%to,
4482 @hash_parents);
4484 # the patch itself
4485 LINE:
4486 while ($patch_line = <$fd>) {
4487 chomp $patch_line;
4489 next PATCH if ($patch_line =~ m/^diff /);
4491 print format_diff_line($patch_line, \%from, \%to);
4494 } continue {
4495 print "</div>\n"; # class="patch"
4498 # for compact combined (--cc) format, with chunk and patch simpliciaction
4499 # patchset might be empty, but there might be unprocessed raw lines
4500 for (++$patch_idx if $patch_number > 0;
4501 $patch_idx < @$difftree;
4502 ++$patch_idx) {
4503 # read and prepare patch information
4504 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4506 # generate anchor for "patch" links in difftree / whatchanged part
4507 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4508 format_diff_cc_simplified($diffinfo, @hash_parents) .
4509 "</div>\n"; # class="patch"
4511 $patch_number++;
4514 if ($patch_number == 0) {
4515 if (@hash_parents > 1) {
4516 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4517 } else {
4518 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4522 print "</div>\n"; # class="patchset"
4525 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4527 # fills project list info (age, description, owner, forks) for each
4528 # project in the list, removing invalid projects from returned list
4529 # NOTE: modifies $projlist, but does not remove entries from it
4530 sub fill_project_list_info {
4531 my ($projlist, $check_forks) = @_;
4532 my @projects;
4534 my $show_ctags = gitweb_check_feature('ctags');
4535 PROJECT:
4536 foreach my $pr (@$projlist) {
4537 my (@activity) = git_get_last_activity($pr->{'path'});
4538 unless (@activity) {
4539 next PROJECT;
4541 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4542 if (!defined $pr->{'descr'}) {
4543 my $descr = git_get_project_description($pr->{'path'}) || "";
4544 $descr = to_utf8($descr);
4545 $pr->{'descr_long'} = $descr;
4546 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4548 if (!defined $pr->{'owner'}) {
4549 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4551 if ($check_forks) {
4552 my $pname = $pr->{'path'};
4553 if (($pname =~ s/\.git$//) &&
4554 ($pname !~ /\/$/) &&
4555 (-d "$projectroot/$pname")) {
4556 $pr->{'forks'} = "-d $projectroot/$pname";
4557 } else {
4558 $pr->{'forks'} = 0;
4561 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4562 push @projects, $pr;
4565 return @projects;
4568 # print 'sort by' <th> element, generating 'sort by $name' replay link
4569 # if that order is not selected
4570 sub print_sort_th {
4571 print format_sort_th(@_);
4574 sub format_sort_th {
4575 my ($name, $order, $header) = @_;
4576 my $sort_th = "";
4577 $header ||= ucfirst($name);
4579 if ($order eq $name) {
4580 $sort_th .= "<th>$header</th>\n";
4581 } else {
4582 $sort_th .= "<th>" .
4583 $cgi->a({-href => href(-replay=>1, order=>$name),
4584 -class => "header"}, $header) .
4585 "</th>\n";
4588 return $sort_th;
4591 sub git_project_list_body {
4592 # actually uses global variable $project
4593 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4595 my $check_forks = gitweb_check_feature('forks');
4596 my @projects = fill_project_list_info($projlist, $check_forks);
4598 $order ||= $default_projects_order;
4599 $from = 0 unless defined $from;
4600 $to = $#projects if (!defined $to || $#projects < $to);
4602 my %order_info = (
4603 project => { key => 'path', type => 'str' },
4604 descr => { key => 'descr_long', type => 'str' },
4605 owner => { key => 'owner', type => 'str' },
4606 age => { key => 'age', type => 'num' }
4608 my $oi = $order_info{$order};
4609 if ($oi->{'type'} eq 'str') {
4610 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4611 } else {
4612 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4615 my $show_ctags = gitweb_check_feature('ctags');
4616 if ($show_ctags) {
4617 my %ctags;
4618 foreach my $p (@projects) {
4619 foreach my $ct (keys %{$p->{'ctags'}}) {
4620 $ctags{$ct} += $p->{'ctags'}->{$ct};
4623 my $cloud = git_populate_project_tagcloud(\%ctags);
4624 print git_show_project_tagcloud($cloud, 64);
4627 print "<table class=\"project_list\">\n";
4628 unless ($no_header) {
4629 print "<tr>\n";
4630 if ($check_forks) {
4631 print "<th></th>\n";
4633 print_sort_th('project', $order, 'Project');
4634 print_sort_th('descr', $order, 'Description');
4635 print_sort_th('owner', $order, 'Owner');
4636 print_sort_th('age', $order, 'Last Change');
4637 print "<th></th>\n" . # for links
4638 "</tr>\n";
4640 my $alternate = 1;
4641 my $tagfilter = $cgi->param('by_tag');
4642 for (my $i = $from; $i <= $to; $i++) {
4643 my $pr = $projects[$i];
4645 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4646 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4647 and not $pr->{'descr_long'} =~ /$searchtext/;
4648 # Weed out forks or non-matching entries of search
4649 if ($check_forks) {
4650 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4651 $forkbase="^$forkbase" if $forkbase;
4652 next if not $searchtext and not $tagfilter and $show_ctags
4653 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4656 if ($alternate) {
4657 print "<tr class=\"dark\">\n";
4658 } else {
4659 print "<tr class=\"light\">\n";
4661 $alternate ^= 1;
4662 if ($check_forks) {
4663 print "<td>";
4664 if ($pr->{'forks'}) {
4665 print "<!-- $pr->{'forks'} -->\n";
4666 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4668 print "</td>\n";
4670 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4671 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4672 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4673 -class => "list", -title => $pr->{'descr_long'}},
4674 esc_html($pr->{'descr'})) . "</td>\n" .
4675 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4676 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4677 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4678 "<td class=\"link\">" .
4679 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4680 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4681 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4682 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4683 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4684 "</td>\n" .
4685 "</tr>\n";
4687 if (defined $extra) {
4688 print "<tr>\n";
4689 if ($check_forks) {
4690 print "<td></td>\n";
4692 print "<td colspan=\"5\">$extra</td>\n" .
4693 "</tr>\n";
4695 print "</table>\n";
4698 sub git_log_body {
4699 # uses global variable $project
4700 my ($commitlist, $from, $to, $refs, $extra) = @_;
4702 $from = 0 unless defined $from;
4703 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4705 for (my $i = 0; $i <= $to; $i++) {
4706 my %co = %{$commitlist->[$i]};
4707 next if !%co;
4708 my $commit = $co{'id'};
4709 my $ref = format_ref_marker($refs, $commit);
4710 my %ad = parse_date($co{'author_epoch'});
4711 git_print_header_div('commit',
4712 "<span class=\"age\">$co{'age_string'}</span>" .
4713 esc_html($co{'title'}) . $ref,
4714 $commit);
4715 print "<div class=\"title_text\">\n" .
4716 "<div class=\"log_link\">\n" .
4717 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4718 " | " .
4719 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4720 " | " .
4721 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4722 "<br/>\n" .
4723 "</div>\n";
4724 git_print_authorship(\%co, -tag => 'span');
4725 print "<br/>\n</div>\n";
4727 print "<div class=\"log_body\">\n";
4728 git_print_log($co{'comment'}, -final_empty_line=> 1);
4729 print "</div>\n";
4731 if ($extra) {
4732 print "<div class=\"page_nav\">\n";
4733 print "$extra\n";
4734 print "</div>\n";
4738 sub git_shortlog_body {
4739 # uses global variable $project
4740 my ($commitlist, $from, $to, $refs, $extra) = @_;
4742 $from = 0 unless defined $from;
4743 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4745 print "<table class=\"shortlog\">\n";
4746 my $alternate = 1;
4747 for (my $i = $from; $i <= $to; $i++) {
4748 my %co = %{$commitlist->[$i]};
4749 my $commit = $co{'id'};
4750 my $ref = format_ref_marker($refs, $commit);
4751 if ($alternate) {
4752 print "<tr class=\"dark\">\n";
4753 } else {
4754 print "<tr class=\"light\">\n";
4756 $alternate ^= 1;
4757 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4758 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4759 format_author_html('td', \%co, 10) . "<td>";
4760 print format_subject_html($co{'title'}, $co{'title_short'},
4761 href(action=>"commit", hash=>$commit), $ref);
4762 print "</td>\n" .
4763 "<td class=\"link\">" .
4764 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4765 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4766 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4767 my $snapshot_links = format_snapshot_links($commit);
4768 if (defined $snapshot_links) {
4769 print " | " . $snapshot_links;
4771 print "</td>\n" .
4772 "</tr>\n";
4774 if (defined $extra) {
4775 print "<tr>\n" .
4776 "<td colspan=\"4\">$extra</td>\n" .
4777 "</tr>\n";
4779 print "</table>\n";
4782 sub git_history_body {
4783 # Warning: assumes constant type (blob or tree) during history
4784 my ($commitlist, $from, $to, $refs, $extra,
4785 $file_name, $file_hash, $ftype) = @_;
4787 $from = 0 unless defined $from;
4788 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4790 print "<table class=\"history\">\n";
4791 my $alternate = 1;
4792 for (my $i = $from; $i <= $to; $i++) {
4793 my %co = %{$commitlist->[$i]};
4794 if (!%co) {
4795 next;
4797 my $commit = $co{'id'};
4799 my $ref = format_ref_marker($refs, $commit);
4801 if ($alternate) {
4802 print "<tr class=\"dark\">\n";
4803 } else {
4804 print "<tr class=\"light\">\n";
4806 $alternate ^= 1;
4807 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4808 # shortlog: format_author_html('td', \%co, 10)
4809 format_author_html('td', \%co, 15, 3) . "<td>";
4810 # originally git_history used chop_str($co{'title'}, 50)
4811 print format_subject_html($co{'title'}, $co{'title_short'},
4812 href(action=>"commit", hash=>$commit), $ref);
4813 print "</td>\n" .
4814 "<td class=\"link\">" .
4815 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4816 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4818 if ($ftype eq 'blob') {
4819 my $blob_current = $file_hash;
4820 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4821 if (defined $blob_current && defined $blob_parent &&
4822 $blob_current ne $blob_parent) {
4823 print " | " .
4824 $cgi->a({-href => href(action=>"blobdiff",
4825 hash=>$blob_current, hash_parent=>$blob_parent,
4826 hash_base=>$hash_base, hash_parent_base=>$commit,
4827 file_name=>$file_name)},
4828 "diff to current");
4831 print "</td>\n" .
4832 "</tr>\n";
4834 if (defined $extra) {
4835 print "<tr>\n" .
4836 "<td colspan=\"4\">$extra</td>\n" .
4837 "</tr>\n";
4839 print "</table>\n";
4842 sub git_tags_body {
4843 # uses global variable $project
4844 my ($taglist, $from, $to, $extra) = @_;
4845 $from = 0 unless defined $from;
4846 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4848 print "<table class=\"tags\">\n";
4849 my $alternate = 1;
4850 for (my $i = $from; $i <= $to; $i++) {
4851 my $entry = $taglist->[$i];
4852 my %tag = %$entry;
4853 my $comment = $tag{'subject'};
4854 my $comment_short;
4855 if (defined $comment) {
4856 $comment_short = chop_str($comment, 30, 5);
4858 if ($alternate) {
4859 print "<tr class=\"dark\">\n";
4860 } else {
4861 print "<tr class=\"light\">\n";
4863 $alternate ^= 1;
4864 if (defined $tag{'age'}) {
4865 print "<td><i>$tag{'age'}</i></td>\n";
4866 } else {
4867 print "<td></td>\n";
4869 print "<td>" .
4870 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4871 -class => "list name"}, esc_html($tag{'name'})) .
4872 "</td>\n" .
4873 "<td>";
4874 if (defined $comment) {
4875 print format_subject_html($comment, $comment_short,
4876 href(action=>"tag", hash=>$tag{'id'}));
4878 print "</td>\n" .
4879 "<td class=\"selflink\">";
4880 if ($tag{'type'} eq "tag") {
4881 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4882 } else {
4883 print "&nbsp;";
4885 print "</td>\n" .
4886 "<td class=\"link\">" . " | " .
4887 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4888 if ($tag{'reftype'} eq "commit") {
4889 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4890 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4891 } elsif ($tag{'reftype'} eq "blob") {
4892 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4894 print "</td>\n" .
4895 "</tr>";
4897 if (defined $extra) {
4898 print "<tr>\n" .
4899 "<td colspan=\"5\">$extra</td>\n" .
4900 "</tr>\n";
4902 print "</table>\n";
4905 sub git_heads_body {
4906 # uses global variable $project
4907 my ($headlist, $head, $from, $to, $extra) = @_;
4908 $from = 0 unless defined $from;
4909 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4911 print "<table class=\"heads\">\n";
4912 my $alternate = 1;
4913 for (my $i = $from; $i <= $to; $i++) {
4914 my $entry = $headlist->[$i];
4915 my %ref = %$entry;
4916 my $curr = $ref{'id'} eq $head;
4917 if ($alternate) {
4918 print "<tr class=\"dark\">\n";
4919 } else {
4920 print "<tr class=\"light\">\n";
4922 $alternate ^= 1;
4923 print "<td><i>$ref{'age'}</i></td>\n" .
4924 ($curr ? "<td class=\"current_head\">" : "<td>") .
4925 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4926 -class => "list name"},esc_html($ref{'name'})) .
4927 "</td>\n" .
4928 "<td class=\"link\">" .
4929 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4930 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4931 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4932 "</td>\n" .
4933 "</tr>";
4935 if (defined $extra) {
4936 print "<tr>\n" .
4937 "<td colspan=\"3\">$extra</td>\n" .
4938 "</tr>\n";
4940 print "</table>\n";
4943 sub git_search_grep_body {
4944 my ($commitlist, $from, $to, $extra) = @_;
4945 $from = 0 unless defined $from;
4946 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4948 print "<table class=\"commit_search\">\n";
4949 my $alternate = 1;
4950 for (my $i = $from; $i <= $to; $i++) {
4951 my %co = %{$commitlist->[$i]};
4952 if (!%co) {
4953 next;
4955 my $commit = $co{'id'};
4956 if ($alternate) {
4957 print "<tr class=\"dark\">\n";
4958 } else {
4959 print "<tr class=\"light\">\n";
4961 $alternate ^= 1;
4962 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4963 format_author_html('td', \%co, 15, 5) .
4964 "<td>" .
4965 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4966 -class => "list subject"},
4967 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4968 my $comment = $co{'comment'};
4969 foreach my $line (@$comment) {
4970 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4971 my ($lead, $match, $trail) = ($1, $2, $3);
4972 $match = chop_str($match, 70, 5, 'center');
4973 my $contextlen = int((80 - length($match))/2);
4974 $contextlen = 30 if ($contextlen > 30);
4975 $lead = chop_str($lead, $contextlen, 10, 'left');
4976 $trail = chop_str($trail, $contextlen, 10, 'right');
4978 $lead = esc_html($lead);
4979 $match = esc_html($match);
4980 $trail = esc_html($trail);
4982 print "$lead<span class=\"match\">$match</span>$trail<br />";
4985 print "</td>\n" .
4986 "<td class=\"link\">" .
4987 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4988 " | " .
4989 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4990 " | " .
4991 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4992 print "</td>\n" .
4993 "</tr>\n";
4995 if (defined $extra) {
4996 print "<tr>\n" .
4997 "<td colspan=\"3\">$extra</td>\n" .
4998 "</tr>\n";
5000 print "</table>\n";
5003 ## ======================================================================
5004 ## ======================================================================
5005 ## actions
5007 sub git_project_list {
5008 my $order = $input_params{'order'};
5009 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5010 die_error(400, "Unknown order parameter");
5013 my @list = git_get_projects_list();
5014 if (!@list) {
5015 die_error(404, "No projects found");
5018 git_header_html();
5019 if (defined $home_text && -f $home_text) {
5020 print "<div class=\"index_include\">\n";
5021 insert_file($home_text);
5022 print "</div>\n";
5024 print $cgi->startform(-method => "get") .
5025 "<p class=\"projsearch\">Search:\n" .
5026 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5027 "</p>" .
5028 $cgi->end_form() . "\n";
5029 git_project_list_body(\@list, $order);
5030 git_footer_html();
5033 sub git_forks {
5034 my $order = $input_params{'order'};
5035 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5036 die_error(400, "Unknown order parameter");
5039 my @list = git_get_projects_list($project);
5040 if (!@list) {
5041 die_error(404, "No forks found");
5044 git_header_html();
5045 git_print_page_nav('','');
5046 git_print_header_div('summary', "$project forks");
5047 git_project_list_body(\@list, $order);
5048 git_footer_html();
5051 sub git_project_index {
5052 my @projects = git_get_projects_list($project);
5054 print $cgi->header(
5055 -type => 'text/plain',
5056 -charset => 'utf-8',
5057 -content_disposition => 'inline; filename="index.aux"');
5059 foreach my $pr (@projects) {
5060 if (!exists $pr->{'owner'}) {
5061 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5064 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5065 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5066 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5067 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5068 $path =~ s/ /\+/g;
5069 $owner =~ s/ /\+/g;
5071 print "$path $owner\n";
5075 sub git_summary {
5076 my $descr = git_get_project_description($project) || "none";
5077 my %co = parse_commit("HEAD");
5078 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5079 my $head = $co{'id'};
5081 my $owner = git_get_project_owner($project);
5083 my $refs = git_get_references();
5084 # These get_*_list functions return one more to allow us to see if
5085 # there are more ...
5086 my @taglist = git_get_tags_list(16);
5087 my @headlist = git_get_heads_list(16);
5088 my @forklist;
5089 my $check_forks = gitweb_check_feature('forks');
5091 if ($check_forks) {
5092 @forklist = git_get_projects_list($project);
5095 git_header_html();
5096 git_print_page_nav('summary','', $head);
5098 print "<div class=\"title\">&nbsp;</div>\n";
5099 print "<table class=\"projects_list\">\n" .
5100 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5101 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5102 if (defined $cd{'rfc2822'}) {
5103 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5106 # use per project git URL list in $projectroot/$project/cloneurl
5107 # or make project git URL from git base URL and project name
5108 my $url_tag = "URL";
5109 my @url_list = git_get_project_url_list($project);
5110 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5111 foreach my $git_url (@url_list) {
5112 next unless $git_url;
5113 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5114 $url_tag = "";
5117 # Tag cloud
5118 my $show_ctags = gitweb_check_feature('ctags');
5119 if ($show_ctags) {
5120 my $ctags = git_get_project_ctags($project);
5121 my $cloud = git_populate_project_tagcloud($ctags);
5122 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5123 print "</td>\n<td>" unless %$ctags;
5124 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
5125 print "</td>\n<td>" if %$ctags;
5126 print git_show_project_tagcloud($cloud, 48);
5127 print "</td></tr>";
5130 print "</table>\n";
5132 # If XSS prevention is on, we don't include README.html.
5133 # TODO: Allow a readme in some safe format.
5134 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5135 print "<div class=\"title\">readme</div>\n" .
5136 "<div class=\"readme\">\n";
5137 insert_file("$projectroot/$project/README.html");
5138 print "\n</div>\n"; # class="readme"
5141 # we need to request one more than 16 (0..15) to check if
5142 # those 16 are all
5143 my @commitlist = $head ? parse_commits($head, 17) : ();
5144 if (@commitlist) {
5145 git_print_header_div('shortlog');
5146 git_shortlog_body(\@commitlist, 0, 15, $refs,
5147 $#commitlist <= 15 ? undef :
5148 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5151 if (@taglist) {
5152 git_print_header_div('tags');
5153 git_tags_body(\@taglist, 0, 15,
5154 $#taglist <= 15 ? undef :
5155 $cgi->a({-href => href(action=>"tags")}, "..."));
5158 if (@headlist) {
5159 git_print_header_div('heads');
5160 git_heads_body(\@headlist, $head, 0, 15,
5161 $#headlist <= 15 ? undef :
5162 $cgi->a({-href => href(action=>"heads")}, "..."));
5165 if (@forklist) {
5166 git_print_header_div('forks');
5167 git_project_list_body(\@forklist, 'age', 0, 15,
5168 $#forklist <= 15 ? undef :
5169 $cgi->a({-href => href(action=>"forks")}, "..."),
5170 'no_header');
5173 git_footer_html();
5176 sub git_tag {
5177 my $head = git_get_head_hash($project);
5178 git_header_html();
5179 git_print_page_nav('','', $head,undef,$head);
5180 my %tag = parse_tag($hash);
5182 if (! %tag) {
5183 die_error(404, "Unknown tag object");
5186 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5187 print "<div class=\"title_text\">\n" .
5188 "<table class=\"object_header\">\n" .
5189 "<tr>\n" .
5190 "<td>object</td>\n" .
5191 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5192 $tag{'object'}) . "</td>\n" .
5193 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5194 $tag{'type'}) . "</td>\n" .
5195 "</tr>\n";
5196 if (defined($tag{'author'})) {
5197 git_print_authorship_rows(\%tag, 'author');
5199 print "</table>\n\n" .
5200 "</div>\n";
5201 print "<div class=\"page_body\">";
5202 my $comment = $tag{'comment'};
5203 foreach my $line (@$comment) {
5204 chomp $line;
5205 print esc_html($line, -nbsp=>1) . "<br/>\n";
5207 print "</div>\n";
5208 git_footer_html();
5211 sub git_blame_common {
5212 my $format = shift || 'porcelain';
5213 if ($format eq 'porcelain' && $cgi->param('js')) {
5214 $format = 'incremental';
5215 $action = 'blame_incremental'; # for page title etc
5218 # permissions
5219 gitweb_check_feature('blame')
5220 or die_error(403, "Blame view not allowed");
5222 # error checking
5223 die_error(400, "No file name given") unless $file_name;
5224 $hash_base ||= git_get_head_hash($project);
5225 die_error(404, "Couldn't find base commit") unless $hash_base;
5226 my %co = parse_commit($hash_base)
5227 or die_error(404, "Commit not found");
5228 my $ftype = "blob";
5229 if (!defined $hash) {
5230 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5231 or die_error(404, "Error looking up file");
5232 } else {
5233 $ftype = git_get_type($hash);
5234 if ($ftype !~ "blob") {
5235 die_error(400, "Object is not a blob");
5239 my $fd;
5240 if ($format eq 'incremental') {
5241 # get file contents (as base)
5242 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5243 or die_error(500, "Open git-cat-file failed");
5244 } elsif ($format eq 'data') {
5245 # run git-blame --incremental
5246 open $fd, "-|", git_cmd(), "blame", "--incremental",
5247 $hash_base, "--", $file_name
5248 or die_error(500, "Open git-blame --incremental failed");
5249 } else {
5250 # run git-blame --porcelain
5251 open $fd, "-|", git_cmd(), "blame", '-p',
5252 $hash_base, '--', $file_name
5253 or die_error(500, "Open git-blame --porcelain failed");
5256 # incremental blame data returns early
5257 if ($format eq 'data') {
5258 print $cgi->header(
5259 -type=>"text/plain", -charset => "utf-8",
5260 -status=> "200 OK");
5261 local $| = 1; # output autoflush
5262 print while <$fd>;
5263 close $fd
5264 or print "ERROR $!\n";
5266 print 'END';
5267 if (defined $t0 && gitweb_check_feature('timed')) {
5268 print ' '.
5269 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5270 ' '.$number_of_git_cmds;
5272 print "\n";
5274 return;
5277 # page header
5278 git_header_html();
5279 my $formats_nav =
5280 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5281 "blob") .
5282 " | ";
5283 if ($format eq 'incremental') {
5284 $formats_nav .=
5285 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5286 "blame") . " (non-incremental)";
5287 } else {
5288 $formats_nav .=
5289 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5290 "blame") . " (incremental)";
5292 $formats_nav .=
5293 " | " .
5294 $cgi->a({-href => href(action=>"history", -replay=>1)},
5295 "history") .
5296 " | " .
5297 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5298 "HEAD");
5299 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5300 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5301 git_print_page_path($file_name, $ftype, $hash_base);
5303 # page body
5304 if ($format eq 'incremental') {
5305 print "<noscript>\n<div class=\"error\"><center><b>\n".
5306 "This page requires JavaScript to run.\n Use ".
5307 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5308 'this page').
5309 " instead.\n".
5310 "</b></center></div>\n</noscript>\n";
5312 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5315 print qq!<div class="page_body">\n!;
5316 print qq!<div id="progress_info">... / ...</div>\n!
5317 if ($format eq 'incremental');
5318 print qq!<table id="blame_table" class="blame" width="100%">\n!.
5319 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5320 qq!<thead>\n!.
5321 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5322 qq!</thead>\n!.
5323 qq!<tbody>\n!;
5325 my @rev_color = qw(light dark);
5326 my $num_colors = scalar(@rev_color);
5327 my $current_color = 0;
5329 if ($format eq 'incremental') {
5330 my $color_class = $rev_color[$current_color];
5332 #contents of a file
5333 my $linenr = 0;
5334 LINE:
5335 while (my $line = <$fd>) {
5336 chomp $line;
5337 $linenr++;
5339 print qq!<tr id="l$linenr" class="$color_class">!.
5340 qq!<td class="sha1"><a href=""> </a></td>!.
5341 qq!<td class="linenr">!.
5342 qq!<a class="linenr" href="">$linenr</a></td>!;
5343 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
5344 print qq!</tr>\n!;
5347 } else { # porcelain, i.e. ordinary blame
5348 my %metainfo = (); # saves information about commits
5350 # blame data
5351 LINE:
5352 while (my $line = <$fd>) {
5353 chomp $line;
5354 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5355 # no <lines in group> for subsequent lines in group of lines
5356 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5357 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5358 if (!exists $metainfo{$full_rev}) {
5359 $metainfo{$full_rev} = { 'nprevious' => 0 };
5361 my $meta = $metainfo{$full_rev};
5362 my $data;
5363 while ($data = <$fd>) {
5364 chomp $data;
5365 last if ($data =~ s/^\t//); # contents of line
5366 if ($data =~ /^(\S+)(?: (.*))?$/) {
5367 $meta->{$1} = $2 unless exists $meta->{$1};
5369 if ($data =~ /^previous /) {
5370 $meta->{'nprevious'}++;
5373 my $short_rev = substr($full_rev, 0, 8);
5374 my $author = $meta->{'author'};
5375 my %date =
5376 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5377 my $date = $date{'iso-tz'};
5378 if ($group_size) {
5379 $current_color = ($current_color + 1) % $num_colors;
5381 my $tr_class = $rev_color[$current_color];
5382 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5383 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5384 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5385 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5386 if ($group_size) {
5387 print "<td class=\"sha1\"";
5388 print " title=\"". esc_html($author) . ", $date\"";
5389 print " rowspan=\"$group_size\"" if ($group_size > 1);
5390 print ">";
5391 print $cgi->a({-href => href(action=>"commit",
5392 hash=>$full_rev,
5393 file_name=>$file_name)},
5394 esc_html($short_rev));
5395 if ($group_size >= 2) {
5396 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5397 if (@author_initials) {
5398 print "<br />" .
5399 esc_html(join('', @author_initials));
5400 # or join('.', ...)
5403 print "</td>\n";
5405 # 'previous' <sha1 of parent commit> <filename at commit>
5406 if (exists $meta->{'previous'} &&
5407 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5408 $meta->{'parent'} = $1;
5409 $meta->{'file_parent'} = unquote($2);
5411 my $linenr_commit =
5412 exists($meta->{'parent'}) ?
5413 $meta->{'parent'} : $full_rev;
5414 my $linenr_filename =
5415 exists($meta->{'file_parent'}) ?
5416 $meta->{'file_parent'} : unquote($meta->{'filename'});
5417 my $blamed = href(action => 'blame',
5418 file_name => $linenr_filename,
5419 hash_base => $linenr_commit);
5420 print "<td class=\"linenr\">";
5421 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5422 -class => "linenr" },
5423 esc_html($lineno));
5424 print "</td>";
5425 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5426 print "</tr>\n";
5427 } # end while
5431 # footer
5432 print "</tbody>\n".
5433 "</table>\n"; # class="blame"
5434 print "</div>\n"; # class="blame_body"
5435 close $fd
5436 or print "Reading blob failed\n";
5438 git_footer_html();
5441 sub git_blame {
5442 git_blame_common();
5445 sub git_blame_incremental {
5446 git_blame_common('incremental');
5449 sub git_blame_data {
5450 git_blame_common('data');
5453 sub git_tags {
5454 my $head = git_get_head_hash($project);
5455 git_header_html();
5456 git_print_page_nav('','', $head,undef,$head);
5457 git_print_header_div('summary', $project);
5459 my @tagslist = git_get_tags_list();
5460 if (@tagslist) {
5461 git_tags_body(\@tagslist);
5463 git_footer_html();
5466 sub git_heads {
5467 my $head = git_get_head_hash($project);
5468 git_header_html();
5469 git_print_page_nav('','', $head,undef,$head);
5470 git_print_header_div('summary', $project);
5472 my @headslist = git_get_heads_list();
5473 if (@headslist) {
5474 git_heads_body(\@headslist, $head);
5476 git_footer_html();
5479 sub git_blob_plain {
5480 my $type = shift;
5481 my $expires;
5483 if (!defined $hash) {
5484 if (defined $file_name) {
5485 my $base = $hash_base || git_get_head_hash($project);
5486 $hash = git_get_hash_by_path($base, $file_name, "blob")
5487 or die_error(404, "Cannot find file");
5488 } else {
5489 die_error(400, "No file name defined");
5491 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5492 # blobs defined by non-textual hash id's can be cached
5493 $expires = "+1d";
5496 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5497 or die_error(500, "Open git-cat-file blob '$hash' failed");
5499 # content-type (can include charset)
5500 $type = blob_contenttype($fd, $file_name, $type);
5502 # "save as" filename, even when no $file_name is given
5503 my $save_as = "$hash";
5504 if (defined $file_name) {
5505 $save_as = $file_name;
5506 } elsif ($type =~ m/^text\//) {
5507 $save_as .= '.txt';
5510 # With XSS prevention on, blobs of all types except a few known safe
5511 # ones are served with "Content-Disposition: attachment" to make sure
5512 # they don't run in our security domain. For certain image types,
5513 # blob view writes an <img> tag referring to blob_plain view, and we
5514 # want to be sure not to break that by serving the image as an
5515 # attachment (though Firefox 3 doesn't seem to care).
5516 my $sandbox = $prevent_xss &&
5517 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5519 print $cgi->header(
5520 -type => $type,
5521 -expires => $expires,
5522 -content_disposition =>
5523 ($sandbox ? 'attachment' : 'inline')
5524 . '; filename="' . $save_as . '"');
5525 local $/ = undef;
5526 binmode STDOUT, ':raw';
5527 print <$fd>;
5528 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5529 close $fd;
5532 sub git_blob {
5533 my $expires;
5535 if (!defined $hash) {
5536 if (defined $file_name) {
5537 my $base = $hash_base || git_get_head_hash($project);
5538 $hash = git_get_hash_by_path($base, $file_name, "blob")
5539 or die_error(404, "Cannot find file");
5540 } else {
5541 die_error(400, "No file name defined");
5543 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5544 # blobs defined by non-textual hash id's can be cached
5545 $expires = "+1d";
5548 my $have_blame = gitweb_check_feature('blame');
5549 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5550 or die_error(500, "Couldn't cat $file_name, $hash");
5551 my $mimetype = blob_mimetype($fd, $file_name);
5552 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
5553 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5554 close $fd;
5555 return git_blob_plain($mimetype);
5557 # we can have blame only for text/* mimetype
5558 $have_blame &&= ($mimetype =~ m!^text/!);
5560 my $highlight = gitweb_check_feature('highlight');
5561 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
5562 $fd = run_highlighter($fd, $highlight, $syntax)
5563 if $syntax;
5565 git_header_html(undef, $expires);
5566 my $formats_nav = '';
5567 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5568 if (defined $file_name) {
5569 if ($have_blame) {
5570 $formats_nav .=
5571 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5572 "blame") .
5573 " | ";
5575 $formats_nav .=
5576 $cgi->a({-href => href(action=>"history", -replay=>1)},
5577 "history") .
5578 " | " .
5579 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5580 "raw") .
5581 " | " .
5582 $cgi->a({-href => href(action=>"blob",
5583 hash_base=>"HEAD", file_name=>$file_name)},
5584 "HEAD");
5585 } else {
5586 $formats_nav .=
5587 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5588 "raw");
5590 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5591 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5592 } else {
5593 print "<div class=\"page_nav\">\n" .
5594 "<br/><br/></div>\n" .
5595 "<div class=\"title\">$hash</div>\n";
5597 git_print_page_path($file_name, "blob", $hash_base);
5598 print "<div class=\"page_body\">\n";
5599 if ($mimetype =~ m!^image/!) {
5600 print qq!<img type="$mimetype"!;
5601 if ($file_name) {
5602 print qq! alt="$file_name" title="$file_name"!;
5604 print qq! src="! .
5605 href(action=>"blob_plain", hash=>$hash,
5606 hash_base=>$hash_base, file_name=>$file_name) .
5607 qq!" />\n!;
5608 } else {
5609 my $nr;
5610 while (my $line = <$fd>) {
5611 chomp $line;
5612 $nr++;
5613 $line = untabify($line);
5614 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
5615 $nr, href(-replay => 1), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
5618 close $fd
5619 or print "Reading blob failed.\n";
5620 print "</div>";
5621 git_footer_html();
5624 sub git_tree {
5625 if (!defined $hash_base) {
5626 $hash_base = "HEAD";
5628 if (!defined $hash) {
5629 if (defined $file_name) {
5630 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5631 } else {
5632 $hash = $hash_base;
5635 die_error(404, "No such tree") unless defined($hash);
5637 my $show_sizes = gitweb_check_feature('show-sizes');
5638 my $have_blame = gitweb_check_feature('blame');
5640 my @entries = ();
5642 local $/ = "\0";
5643 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5644 ($show_sizes ? '-l' : ()), @extra_options, $hash
5645 or die_error(500, "Open git-ls-tree failed");
5646 @entries = map { chomp; $_ } <$fd>;
5647 close $fd
5648 or die_error(404, "Reading tree failed");
5651 my $refs = git_get_references();
5652 my $ref = format_ref_marker($refs, $hash_base);
5653 git_header_html();
5654 my $basedir = '';
5655 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5656 my @views_nav = ();
5657 if (defined $file_name) {
5658 push @views_nav,
5659 $cgi->a({-href => href(action=>"history", -replay=>1)},
5660 "history"),
5661 $cgi->a({-href => href(action=>"tree",
5662 hash_base=>"HEAD", file_name=>$file_name)},
5663 "HEAD"),
5665 my $snapshot_links = format_snapshot_links($hash);
5666 if (defined $snapshot_links) {
5667 # FIXME: Should be available when we have no hash base as well.
5668 push @views_nav, $snapshot_links;
5670 git_print_page_nav('tree','', $hash_base, undef, undef,
5671 join(' | ', @views_nav));
5672 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5673 } else {
5674 undef $hash_base;
5675 print "<div class=\"page_nav\">\n";
5676 print "<br/><br/></div>\n";
5677 print "<div class=\"title\">$hash</div>\n";
5679 if (defined $file_name) {
5680 $basedir = $file_name;
5681 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5682 $basedir .= '/';
5684 git_print_page_path($file_name, 'tree', $hash_base);
5686 print "<div class=\"page_body\">\n";
5687 print "<table class=\"tree\">\n";
5688 my $alternate = 1;
5689 # '..' (top directory) link if possible
5690 if (defined $hash_base &&
5691 defined $file_name && $file_name =~ m![^/]+$!) {
5692 if ($alternate) {
5693 print "<tr class=\"dark\">\n";
5694 } else {
5695 print "<tr class=\"light\">\n";
5697 $alternate ^= 1;
5699 my $up = $file_name;
5700 $up =~ s!/?[^/]+$!!;
5701 undef $up unless $up;
5702 # based on git_print_tree_entry
5703 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5704 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5705 print '<td class="list">';
5706 print $cgi->a({-href => href(action=>"tree",
5707 hash_base=>$hash_base,
5708 file_name=>$up)},
5709 "..");
5710 print "</td>\n";
5711 print "<td class=\"link\"></td>\n";
5713 print "</tr>\n";
5715 foreach my $line (@entries) {
5716 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5718 if ($alternate) {
5719 print "<tr class=\"dark\">\n";
5720 } else {
5721 print "<tr class=\"light\">\n";
5723 $alternate ^= 1;
5725 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5727 print "</tr>\n";
5729 print "</table>\n" .
5730 "</div>";
5731 git_footer_html();
5734 sub snapshot_name {
5735 my ($project, $hash) = @_;
5737 # path/to/project.git -> project
5738 # path/to/project/.git -> project
5739 my $name = to_utf8($project);
5740 $name =~ s,([^/])/*\.git$,$1,;
5741 $name = basename($name);
5742 # sanitize name
5743 $name =~ s/[[:cntrl:]]/?/g;
5745 my $ver = $hash;
5746 if ($hash =~ /^[0-9a-fA-F]+$/) {
5747 # shorten SHA-1 hash
5748 my $full_hash = git_get_full_hash($project, $hash);
5749 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5750 $ver = git_get_short_hash($project, $hash);
5752 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5753 # tags don't need shortened SHA-1 hash
5754 $ver = $1;
5755 } else {
5756 # branches and other need shortened SHA-1 hash
5757 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5758 $ver = $1;
5760 $ver .= '-' . git_get_short_hash($project, $hash);
5762 # in case of hierarchical branch names
5763 $ver =~ s!/!.!g;
5765 # name = project-version_string
5766 $name = "$name-$ver";
5768 return wantarray ? ($name, $name) : $name;
5771 sub git_snapshot {
5772 my $format = $input_params{'snapshot_format'};
5773 if (!@snapshot_fmts) {
5774 die_error(403, "Snapshots not allowed");
5776 # default to first supported snapshot format
5777 $format ||= $snapshot_fmts[0];
5778 if ($format !~ m/^[a-z0-9]+$/) {
5779 die_error(400, "Invalid snapshot format parameter");
5780 } elsif (!exists($known_snapshot_formats{$format})) {
5781 die_error(400, "Unknown snapshot format");
5782 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5783 die_error(403, "Snapshot format not allowed");
5784 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5785 die_error(403, "Unsupported snapshot format");
5788 my $type = git_get_type("$hash^{}");
5789 if (!$type) {
5790 die_error(404, 'Object does not exist');
5791 } elsif ($type eq 'blob') {
5792 die_error(400, 'Object is not a tree-ish');
5795 my ($name, $prefix) = snapshot_name($project, $hash);
5796 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
5797 my $cmd = quote_command(
5798 git_cmd(), 'archive',
5799 "--format=$known_snapshot_formats{$format}{'format'}",
5800 "--prefix=$prefix/", $hash);
5801 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5802 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5805 $filename =~ s/(["\\])/\\$1/g;
5806 print $cgi->header(
5807 -type => $known_snapshot_formats{$format}{'type'},
5808 -content_disposition => 'inline; filename="' . $filename . '"',
5809 -status => '200 OK');
5811 open my $fd, "-|", $cmd
5812 or die_error(500, "Execute git-archive failed");
5813 binmode STDOUT, ':raw';
5814 print <$fd>;
5815 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5816 close $fd;
5819 sub git_log_generic {
5820 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
5822 my $head = git_get_head_hash($project);
5823 if (!defined $base) {
5824 $base = $head;
5826 if (!defined $page) {
5827 $page = 0;
5829 my $refs = git_get_references();
5831 my $commit_hash = $base;
5832 if (defined $parent) {
5833 $commit_hash = "$parent..$base";
5835 my @commitlist =
5836 parse_commits($commit_hash, 101, (100 * $page),
5837 defined $file_name ? ($file_name, "--full-history") : ());
5839 my $ftype;
5840 if (!defined $file_hash && defined $file_name) {
5841 # some commits could have deleted file in question,
5842 # and not have it in tree, but one of them has to have it
5843 for (my $i = 0; $i < @commitlist; $i++) {
5844 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5845 last if defined $file_hash;
5848 if (defined $file_hash) {
5849 $ftype = git_get_type($file_hash);
5851 if (defined $file_name && !defined $ftype) {
5852 die_error(500, "Unknown type of object");
5854 my %co;
5855 if (defined $file_name) {
5856 %co = parse_commit($base)
5857 or die_error(404, "Unknown commit object");
5861 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
5862 my $next_link = '';
5863 if ($#commitlist >= 100) {
5864 $next_link =
5865 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5866 -accesskey => "n", -title => "Alt-n"}, "next");
5868 my $patch_max = gitweb_get_feature('patches');
5869 if ($patch_max && !defined $file_name) {
5870 if ($patch_max < 0 || @commitlist <= $patch_max) {
5871 $paging_nav .= " &sdot; " .
5872 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5873 "patches");
5877 git_header_html();
5878 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
5879 if (defined $file_name) {
5880 git_print_header_div('commit', esc_html($co{'title'}), $base);
5881 } else {
5882 git_print_header_div('summary', $project)
5884 git_print_page_path($file_name, $ftype, $hash_base)
5885 if (defined $file_name);
5887 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
5888 $file_name, $file_hash, $ftype);
5890 git_footer_html();
5893 sub git_log {
5894 git_log_generic('log', \&git_log_body,
5895 $hash, $hash_parent);
5898 sub git_commit {
5899 $hash ||= $hash_base || "HEAD";
5900 my %co = parse_commit($hash)
5901 or die_error(404, "Unknown commit object");
5903 my $parent = $co{'parent'};
5904 my $parents = $co{'parents'}; # listref
5906 # we need to prepare $formats_nav before any parameter munging
5907 my $formats_nav;
5908 if (!defined $parent) {
5909 # --root commitdiff
5910 $formats_nav .= '(initial)';
5911 } elsif (@$parents == 1) {
5912 # single parent commit
5913 $formats_nav .=
5914 '(parent: ' .
5915 $cgi->a({-href => href(action=>"commit",
5916 hash=>$parent)},
5917 esc_html(substr($parent, 0, 7))) .
5918 ')';
5919 } else {
5920 # merge commit
5921 $formats_nav .=
5922 '(merge: ' .
5923 join(' ', map {
5924 $cgi->a({-href => href(action=>"commit",
5925 hash=>$_)},
5926 esc_html(substr($_, 0, 7)));
5927 } @$parents ) .
5928 ')';
5930 if (gitweb_check_feature('patches') && @$parents <= 1) {
5931 $formats_nav .= " | " .
5932 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5933 "patch");
5936 if (!defined $parent) {
5937 $parent = "--root";
5939 my @difftree;
5940 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5941 @diff_opts,
5942 (@$parents <= 1 ? $parent : '-c'),
5943 $hash, "--"
5944 or die_error(500, "Open git-diff-tree failed");
5945 @difftree = map { chomp; $_ } <$fd>;
5946 close $fd or die_error(404, "Reading git-diff-tree failed");
5948 # non-textual hash id's can be cached
5949 my $expires;
5950 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5951 $expires = "+1d";
5953 my $refs = git_get_references();
5954 my $ref = format_ref_marker($refs, $co{'id'});
5956 git_header_html(undef, $expires);
5957 git_print_page_nav('commit', '',
5958 $hash, $co{'tree'}, $hash,
5959 $formats_nav);
5961 if (defined $co{'parent'}) {
5962 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5963 } else {
5964 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5966 print "<div class=\"title_text\">\n" .
5967 "<table class=\"object_header\">\n";
5968 git_print_authorship_rows(\%co);
5969 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5970 print "<tr>" .
5971 "<td>tree</td>" .
5972 "<td class=\"sha1\">" .
5973 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5974 class => "list"}, $co{'tree'}) .
5975 "</td>" .
5976 "<td class=\"link\">" .
5977 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5978 "tree");
5979 my $snapshot_links = format_snapshot_links($hash);
5980 if (defined $snapshot_links) {
5981 print " | " . $snapshot_links;
5983 print "</td>" .
5984 "</tr>\n";
5986 foreach my $par (@$parents) {
5987 print "<tr>" .
5988 "<td>parent</td>" .
5989 "<td class=\"sha1\">" .
5990 $cgi->a({-href => href(action=>"commit", hash=>$par),
5991 class => "list"}, $par) .
5992 "</td>" .
5993 "<td class=\"link\">" .
5994 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5995 " | " .
5996 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5997 "</td>" .
5998 "</tr>\n";
6000 print "</table>".
6001 "</div>\n";
6003 print "<div class=\"page_body\">\n";
6004 git_print_log($co{'comment'});
6005 print "</div>\n";
6007 git_difftree_body(\@difftree, $hash, @$parents);
6009 git_footer_html();
6012 sub git_object {
6013 # object is defined by:
6014 # - hash or hash_base alone
6015 # - hash_base and file_name
6016 my $type;
6018 # - hash or hash_base alone
6019 if ($hash || ($hash_base && !defined $file_name)) {
6020 my $object_id = $hash || $hash_base;
6022 open my $fd, "-|", quote_command(
6023 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6024 or die_error(404, "Object does not exist");
6025 $type = <$fd>;
6026 chomp $type;
6027 close $fd
6028 or die_error(404, "Object does not exist");
6030 # - hash_base and file_name
6031 } elsif ($hash_base && defined $file_name) {
6032 $file_name =~ s,/+$,,;
6034 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6035 or die_error(404, "Base object does not exist");
6037 # here errors should not hapen
6038 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6039 or die_error(500, "Open git-ls-tree failed");
6040 my $line = <$fd>;
6041 close $fd;
6043 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6044 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6045 die_error(404, "File or directory for given base does not exist");
6047 $type = $2;
6048 $hash = $3;
6049 } else {
6050 die_error(400, "Not enough information to find object");
6053 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6054 hash=>$hash, hash_base=>$hash_base,
6055 file_name=>$file_name),
6056 -status => '302 Found');
6059 sub git_blobdiff {
6060 my $format = shift || 'html';
6062 my $fd;
6063 my @difftree;
6064 my %diffinfo;
6065 my $expires;
6067 # preparing $fd and %diffinfo for git_patchset_body
6068 # new style URI
6069 if (defined $hash_base && defined $hash_parent_base) {
6070 if (defined $file_name) {
6071 # read raw output
6072 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6073 $hash_parent_base, $hash_base,
6074 "--", (defined $file_parent ? $file_parent : ()), $file_name
6075 or die_error(500, "Open git-diff-tree failed");
6076 @difftree = map { chomp; $_ } <$fd>;
6077 close $fd
6078 or die_error(404, "Reading git-diff-tree failed");
6079 @difftree
6080 or die_error(404, "Blob diff not found");
6082 } elsif (defined $hash &&
6083 $hash =~ /[0-9a-fA-F]{40}/) {
6084 # try to find filename from $hash
6086 # read filtered raw output
6087 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6088 $hash_parent_base, $hash_base, "--"
6089 or die_error(500, "Open git-diff-tree failed");
6090 @difftree =
6091 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6092 # $hash == to_id
6093 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6094 map { chomp; $_ } <$fd>;
6095 close $fd
6096 or die_error(404, "Reading git-diff-tree failed");
6097 @difftree
6098 or die_error(404, "Blob diff not found");
6100 } else {
6101 die_error(400, "Missing one of the blob diff parameters");
6104 if (@difftree > 1) {
6105 die_error(400, "Ambiguous blob diff specification");
6108 %diffinfo = parse_difftree_raw_line($difftree[0]);
6109 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6110 $file_name ||= $diffinfo{'to_file'};
6112 $hash_parent ||= $diffinfo{'from_id'};
6113 $hash ||= $diffinfo{'to_id'};
6115 # non-textual hash id's can be cached
6116 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6117 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6118 $expires = '+1d';
6121 # open patch output
6122 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6123 '-p', ($format eq 'html' ? "--full-index" : ()),
6124 $hash_parent_base, $hash_base,
6125 "--", (defined $file_parent ? $file_parent : ()), $file_name
6126 or die_error(500, "Open git-diff-tree failed");
6129 # old/legacy style URI -- not generated anymore since 1.4.3.
6130 if (!%diffinfo) {
6131 die_error('404 Not Found', "Missing one of the blob diff parameters")
6134 # header
6135 if ($format eq 'html') {
6136 my $formats_nav =
6137 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6138 "raw");
6139 git_header_html(undef, $expires);
6140 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6141 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6142 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6143 } else {
6144 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6145 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
6147 if (defined $file_name) {
6148 git_print_page_path($file_name, "blob", $hash_base);
6149 } else {
6150 print "<div class=\"page_path\"></div>\n";
6153 } elsif ($format eq 'plain') {
6154 print $cgi->header(
6155 -type => 'text/plain',
6156 -charset => 'utf-8',
6157 -expires => $expires,
6158 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6160 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6162 } else {
6163 die_error(400, "Unknown blobdiff format");
6166 # patch
6167 if ($format eq 'html') {
6168 print "<div class=\"page_body\">\n";
6170 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6171 close $fd;
6173 print "</div>\n"; # class="page_body"
6174 git_footer_html();
6176 } else {
6177 while (my $line = <$fd>) {
6178 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6179 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6181 print $line;
6183 last if $line =~ m!^\+\+\+!;
6185 local $/ = undef;
6186 print <$fd>;
6187 close $fd;
6191 sub git_blobdiff_plain {
6192 git_blobdiff('plain');
6195 sub git_commitdiff {
6196 my %params = @_;
6197 my $format = $params{-format} || 'html';
6199 my ($patch_max) = gitweb_get_feature('patches');
6200 if ($format eq 'patch') {
6201 die_error(403, "Patch view not allowed") unless $patch_max;
6204 $hash ||= $hash_base || "HEAD";
6205 my %co = parse_commit($hash)
6206 or die_error(404, "Unknown commit object");
6208 # choose format for commitdiff for merge
6209 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6210 $hash_parent = '--cc';
6212 # we need to prepare $formats_nav before almost any parameter munging
6213 my $formats_nav;
6214 if ($format eq 'html') {
6215 $formats_nav =
6216 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6217 "raw");
6218 if ($patch_max && @{$co{'parents'}} <= 1) {
6219 $formats_nav .= " | " .
6220 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6221 "patch");
6224 if (defined $hash_parent &&
6225 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6226 # commitdiff with two commits given
6227 my $hash_parent_short = $hash_parent;
6228 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6229 $hash_parent_short = substr($hash_parent, 0, 7);
6231 $formats_nav .=
6232 ' (from';
6233 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6234 if ($co{'parents'}[$i] eq $hash_parent) {
6235 $formats_nav .= ' parent ' . ($i+1);
6236 last;
6239 $formats_nav .= ': ' .
6240 $cgi->a({-href => href(action=>"commitdiff",
6241 hash=>$hash_parent)},
6242 esc_html($hash_parent_short)) .
6243 ')';
6244 } elsif (!$co{'parent'}) {
6245 # --root commitdiff
6246 $formats_nav .= ' (initial)';
6247 } elsif (scalar @{$co{'parents'}} == 1) {
6248 # single parent commit
6249 $formats_nav .=
6250 ' (parent: ' .
6251 $cgi->a({-href => href(action=>"commitdiff",
6252 hash=>$co{'parent'})},
6253 esc_html(substr($co{'parent'}, 0, 7))) .
6254 ')';
6255 } else {
6256 # merge commit
6257 if ($hash_parent eq '--cc') {
6258 $formats_nav .= ' | ' .
6259 $cgi->a({-href => href(action=>"commitdiff",
6260 hash=>$hash, hash_parent=>'-c')},
6261 'combined');
6262 } else { # $hash_parent eq '-c'
6263 $formats_nav .= ' | ' .
6264 $cgi->a({-href => href(action=>"commitdiff",
6265 hash=>$hash, hash_parent=>'--cc')},
6266 'compact');
6268 $formats_nav .=
6269 ' (merge: ' .
6270 join(' ', map {
6271 $cgi->a({-href => href(action=>"commitdiff",
6272 hash=>$_)},
6273 esc_html(substr($_, 0, 7)));
6274 } @{$co{'parents'}} ) .
6275 ')';
6279 my $hash_parent_param = $hash_parent;
6280 if (!defined $hash_parent_param) {
6281 # --cc for multiple parents, --root for parentless
6282 $hash_parent_param =
6283 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6286 # read commitdiff
6287 my $fd;
6288 my @difftree;
6289 if ($format eq 'html') {
6290 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6291 "--no-commit-id", "--patch-with-raw", "--full-index",
6292 $hash_parent_param, $hash, "--"
6293 or die_error(500, "Open git-diff-tree failed");
6295 while (my $line = <$fd>) {
6296 chomp $line;
6297 # empty line ends raw part of diff-tree output
6298 last unless $line;
6299 push @difftree, scalar parse_difftree_raw_line($line);
6302 } elsif ($format eq 'plain') {
6303 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6304 '-p', $hash_parent_param, $hash, "--"
6305 or die_error(500, "Open git-diff-tree failed");
6306 } elsif ($format eq 'patch') {
6307 # For commit ranges, we limit the output to the number of
6308 # patches specified in the 'patches' feature.
6309 # For single commits, we limit the output to a single patch,
6310 # diverging from the git-format-patch default.
6311 my @commit_spec = ();
6312 if ($hash_parent) {
6313 if ($patch_max > 0) {
6314 push @commit_spec, "-$patch_max";
6316 push @commit_spec, '-n', "$hash_parent..$hash";
6317 } else {
6318 if ($params{-single}) {
6319 push @commit_spec, '-1';
6320 } else {
6321 if ($patch_max > 0) {
6322 push @commit_spec, "-$patch_max";
6324 push @commit_spec, "-n";
6326 push @commit_spec, '--root', $hash;
6328 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
6329 '--encoding=utf8', '--stdout', @commit_spec
6330 or die_error(500, "Open git-format-patch failed");
6331 } else {
6332 die_error(400, "Unknown commitdiff format");
6335 # non-textual hash id's can be cached
6336 my $expires;
6337 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6338 $expires = "+1d";
6341 # write commit message
6342 if ($format eq 'html') {
6343 my $refs = git_get_references();
6344 my $ref = format_ref_marker($refs, $co{'id'});
6346 git_header_html(undef, $expires);
6347 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6348 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6349 print "<div class=\"title_text\">\n" .
6350 "<table class=\"object_header\">\n";
6351 git_print_authorship_rows(\%co);
6352 print "</table>".
6353 "</div>\n";
6354 print "<div class=\"page_body\">\n";
6355 if (@{$co{'comment'}} > 1) {
6356 print "<div class=\"log\">\n";
6357 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6358 print "</div>\n"; # class="log"
6361 } elsif ($format eq 'plain') {
6362 my $refs = git_get_references("tags");
6363 my $tagname = git_get_rev_name_tags($hash);
6364 my $filename = basename($project) . "-$hash.patch";
6366 print $cgi->header(
6367 -type => 'text/plain',
6368 -charset => 'utf-8',
6369 -expires => $expires,
6370 -content_disposition => 'inline; filename="' . "$filename" . '"');
6371 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6372 print "From: " . to_utf8($co{'author'}) . "\n";
6373 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6374 print "Subject: " . to_utf8($co{'title'}) . "\n";
6376 print "X-Git-Tag: $tagname\n" if $tagname;
6377 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
6379 foreach my $line (@{$co{'comment'}}) {
6380 print to_utf8($line) . "\n";
6382 print "---\n\n";
6383 } elsif ($format eq 'patch') {
6384 my $filename = basename($project) . "-$hash.patch";
6386 print $cgi->header(
6387 -type => 'text/plain',
6388 -charset => 'utf-8',
6389 -expires => $expires,
6390 -content_disposition => 'inline; filename="' . "$filename" . '"');
6393 # write patch
6394 if ($format eq 'html') {
6395 my $use_parents = !defined $hash_parent ||
6396 $hash_parent eq '-c' || $hash_parent eq '--cc';
6397 git_difftree_body(\@difftree, $hash,
6398 $use_parents ? @{$co{'parents'}} : $hash_parent);
6399 print "<br/>\n";
6401 git_patchset_body($fd, \@difftree, $hash,
6402 $use_parents ? @{$co{'parents'}} : $hash_parent);
6403 close $fd;
6404 print "</div>\n"; # class="page_body"
6405 git_footer_html();
6407 } elsif ($format eq 'plain') {
6408 local $/ = undef;
6409 print <$fd>;
6410 close $fd
6411 or print "Reading git-diff-tree failed\n";
6412 } elsif ($format eq 'patch') {
6413 local $/ = undef;
6414 print <$fd>;
6415 close $fd
6416 or print "Reading git-format-patch failed\n";
6420 sub git_commitdiff_plain {
6421 git_commitdiff(-format => 'plain');
6424 # format-patch-style patches
6425 sub git_patch {
6426 git_commitdiff(-format => 'patch', -single => 1);
6429 sub git_patches {
6430 git_commitdiff(-format => 'patch');
6433 sub git_history {
6434 git_log_generic('history', \&git_history_body,
6435 $hash_base, $hash_parent_base,
6436 $file_name, $hash);
6439 sub git_search {
6440 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6441 if (!defined $searchtext) {
6442 die_error(400, "Text field is empty");
6444 if (!defined $hash) {
6445 $hash = git_get_head_hash($project);
6447 my %co = parse_commit($hash);
6448 if (!%co) {
6449 die_error(404, "Unknown commit object");
6451 if (!defined $page) {
6452 $page = 0;
6455 $searchtype ||= 'commit';
6456 if ($searchtype eq 'pickaxe') {
6457 # pickaxe may take all resources of your box and run for several minutes
6458 # with every query - so decide by yourself how public you make this feature
6459 gitweb_check_feature('pickaxe')
6460 or die_error(403, "Pickaxe is disabled");
6462 if ($searchtype eq 'grep') {
6463 gitweb_check_feature('grep')
6464 or die_error(403, "Grep is disabled");
6467 git_header_html();
6469 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6470 my $greptype;
6471 if ($searchtype eq 'commit') {
6472 $greptype = "--grep=";
6473 } elsif ($searchtype eq 'author') {
6474 $greptype = "--author=";
6475 } elsif ($searchtype eq 'committer') {
6476 $greptype = "--committer=";
6478 $greptype .= $searchtext;
6479 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6480 $greptype, '--regexp-ignore-case',
6481 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6483 my $paging_nav = '';
6484 if ($page > 0) {
6485 $paging_nav .=
6486 $cgi->a({-href => href(action=>"search", hash=>$hash,
6487 searchtext=>$searchtext,
6488 searchtype=>$searchtype)},
6489 "first");
6490 $paging_nav .= " &sdot; " .
6491 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6492 -accesskey => "p", -title => "Alt-p"}, "prev");
6493 } else {
6494 $paging_nav .= "first";
6495 $paging_nav .= " &sdot; prev";
6497 my $next_link = '';
6498 if ($#commitlist >= 100) {
6499 $next_link =
6500 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6501 -accesskey => "n", -title => "Alt-n"}, "next");
6502 $paging_nav .= " &sdot; $next_link";
6503 } else {
6504 $paging_nav .= " &sdot; next";
6507 if ($#commitlist >= 100) {
6510 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6511 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6512 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6515 if ($searchtype eq 'pickaxe') {
6516 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6517 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6519 print "<table class=\"pickaxe search\">\n";
6520 my $alternate = 1;
6521 local $/ = "\n";
6522 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6523 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6524 ($search_use_regexp ? '--pickaxe-regex' : ());
6525 undef %co;
6526 my @files;
6527 while (my $line = <$fd>) {
6528 chomp $line;
6529 next unless $line;
6531 my %set = parse_difftree_raw_line($line);
6532 if (defined $set{'commit'}) {
6533 # finish previous commit
6534 if (%co) {
6535 print "</td>\n" .
6536 "<td class=\"link\">" .
6537 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6538 " | " .
6539 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6540 print "</td>\n" .
6541 "</tr>\n";
6544 if ($alternate) {
6545 print "<tr class=\"dark\">\n";
6546 } else {
6547 print "<tr class=\"light\">\n";
6549 $alternate ^= 1;
6550 %co = parse_commit($set{'commit'});
6551 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6552 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6553 "<td><i>$author</i></td>\n" .
6554 "<td>" .
6555 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6556 -class => "list subject"},
6557 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6558 } elsif (defined $set{'to_id'}) {
6559 next if ($set{'to_id'} =~ m/^0{40}$/);
6561 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6562 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6563 -class => "list"},
6564 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6565 "<br/>\n";
6568 close $fd;
6570 # finish last commit (warning: repetition!)
6571 if (%co) {
6572 print "</td>\n" .
6573 "<td class=\"link\">" .
6574 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6575 " | " .
6576 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6577 print "</td>\n" .
6578 "</tr>\n";
6581 print "</table>\n";
6584 if ($searchtype eq 'grep') {
6585 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6586 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6588 print "<table class=\"grep_search\">\n";
6589 my $alternate = 1;
6590 my $matches = 0;
6591 local $/ = "\n";
6592 open my $fd, "-|", git_cmd(), 'grep', '-n',
6593 $search_use_regexp ? ('-E', '-i') : '-F',
6594 $searchtext, $co{'tree'};
6595 my $lastfile = '';
6596 while (my $line = <$fd>) {
6597 chomp $line;
6598 my ($file, $lno, $ltext, $binary);
6599 last if ($matches++ > 1000);
6600 if ($line =~ /^Binary file (.+) matches$/) {
6601 $file = $1;
6602 $binary = 1;
6603 } else {
6604 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6606 if ($file ne $lastfile) {
6607 $lastfile and print "</td></tr>\n";
6608 if ($alternate++) {
6609 print "<tr class=\"dark\">\n";
6610 } else {
6611 print "<tr class=\"light\">\n";
6613 print "<td class=\"list\">".
6614 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6615 file_name=>"$file"),
6616 -class => "list"}, esc_path($file));
6617 print "</td><td>\n";
6618 $lastfile = $file;
6620 if ($binary) {
6621 print "<div class=\"binary\">Binary file</div>\n";
6622 } else {
6623 $ltext = untabify($ltext);
6624 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6625 $ltext = esc_html($1, -nbsp=>1);
6626 $ltext .= '<span class="match">';
6627 $ltext .= esc_html($2, -nbsp=>1);
6628 $ltext .= '</span>';
6629 $ltext .= esc_html($3, -nbsp=>1);
6630 } else {
6631 $ltext = esc_html($ltext, -nbsp=>1);
6633 print "<div class=\"pre\">" .
6634 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6635 file_name=>"$file").'#l'.$lno,
6636 -class => "linenr"}, sprintf('%4i', $lno))
6637 . ' ' . $ltext . "</div>\n";
6640 if ($lastfile) {
6641 print "</td></tr>\n";
6642 if ($matches > 1000) {
6643 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6645 } else {
6646 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6648 close $fd;
6650 print "</table>\n";
6652 git_footer_html();
6655 sub git_search_help {
6656 git_header_html();
6657 git_print_page_nav('','', $hash,$hash,$hash);
6658 print <<EOT;
6659 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6660 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6661 the pattern entered is recognized as the POSIX extended
6662 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6663 insensitive).</p>
6664 <dl>
6665 <dt><b>commit</b></dt>
6666 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6668 my $have_grep = gitweb_check_feature('grep');
6669 if ($have_grep) {
6670 print <<EOT;
6671 <dt><b>grep</b></dt>
6672 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6673 a different one) are searched for the given pattern. On large trees, this search can take
6674 a while and put some strain on the server, so please use it with some consideration. Note that
6675 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6676 case-sensitive.</dd>
6679 print <<EOT;
6680 <dt><b>author</b></dt>
6681 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6682 <dt><b>committer</b></dt>
6683 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6685 my $have_pickaxe = gitweb_check_feature('pickaxe');
6686 if ($have_pickaxe) {
6687 print <<EOT;
6688 <dt><b>pickaxe</b></dt>
6689 <dd>All commits that caused the string to appear or disappear from any file (changes that
6690 added, removed or "modified" the string) will be listed. This search can take a while and
6691 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6692 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6695 print "</dl>\n";
6696 git_footer_html();
6699 sub git_shortlog {
6700 git_log_generic('shortlog', \&git_shortlog_body,
6701 $hash, $hash_parent);
6704 ## ......................................................................
6705 ## feeds (RSS, Atom; OPML)
6707 sub git_feed {
6708 my $format = shift || 'atom';
6709 my $have_blame = gitweb_check_feature('blame');
6711 # Atom: http://www.atomenabled.org/developers/syndication/
6712 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6713 if ($format ne 'rss' && $format ne 'atom') {
6714 die_error(400, "Unknown web feed format");
6717 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6718 my $head = $hash || 'HEAD';
6719 my @commitlist = parse_commits($head, 150, 0, $file_name);
6721 my %latest_commit;
6722 my %latest_date;
6723 my $content_type = "application/$format+xml";
6724 if (defined $cgi->http('HTTP_ACCEPT') &&
6725 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6726 # browser (feed reader) prefers text/xml
6727 $content_type = 'text/xml';
6729 if (defined($commitlist[0])) {
6730 %latest_commit = %{$commitlist[0]};
6731 my $latest_epoch = $latest_commit{'committer_epoch'};
6732 %latest_date = parse_date($latest_epoch);
6733 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6734 if (defined $if_modified) {
6735 my $since;
6736 if (eval { require HTTP::Date; 1; }) {
6737 $since = HTTP::Date::str2time($if_modified);
6738 } elsif (eval { require Time::ParseDate; 1; }) {
6739 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6741 if (defined $since && $latest_epoch <= $since) {
6742 print $cgi->header(
6743 -type => $content_type,
6744 -charset => 'utf-8',
6745 -last_modified => $latest_date{'rfc2822'},
6746 -status => '304 Not Modified');
6747 return;
6750 print $cgi->header(
6751 -type => $content_type,
6752 -charset => 'utf-8',
6753 -last_modified => $latest_date{'rfc2822'});
6754 } else {
6755 print $cgi->header(
6756 -type => $content_type,
6757 -charset => 'utf-8');
6760 # Optimization: skip generating the body if client asks only
6761 # for Last-Modified date.
6762 return if ($cgi->request_method() eq 'HEAD');
6764 # header variables
6765 my $title = "$site_name - $project/$action";
6766 my $feed_type = 'log';
6767 if (defined $hash) {
6768 $title .= " - '$hash'";
6769 $feed_type = 'branch log';
6770 if (defined $file_name) {
6771 $title .= " :: $file_name";
6772 $feed_type = 'history';
6774 } elsif (defined $file_name) {
6775 $title .= " - $file_name";
6776 $feed_type = 'history';
6778 $title .= " $feed_type";
6779 my $descr = git_get_project_description($project);
6780 if (defined $descr) {
6781 $descr = esc_html($descr);
6782 } else {
6783 $descr = "$project " .
6784 ($format eq 'rss' ? 'RSS' : 'Atom') .
6785 " feed";
6787 my $owner = git_get_project_owner($project);
6788 $owner = esc_html($owner);
6790 #header
6791 my $alt_url;
6792 if (defined $file_name) {
6793 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6794 } elsif (defined $hash) {
6795 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6796 } else {
6797 $alt_url = href(-full=>1, action=>"summary");
6799 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6800 if ($format eq 'rss') {
6801 print <<XML;
6802 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6803 <channel>
6805 print "<title>$title</title>\n" .
6806 "<link>$alt_url</link>\n" .
6807 "<description>$descr</description>\n" .
6808 "<language>en</language>\n" .
6809 # project owner is responsible for 'editorial' content
6810 "<managingEditor>$owner</managingEditor>\n";
6811 if (defined $logo || defined $favicon) {
6812 # prefer the logo to the favicon, since RSS
6813 # doesn't allow both
6814 my $img = esc_url($logo || $favicon);
6815 print "<image>\n" .
6816 "<url>$img</url>\n" .
6817 "<title>$title</title>\n" .
6818 "<link>$alt_url</link>\n" .
6819 "</image>\n";
6821 if (%latest_date) {
6822 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6823 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6825 print "<generator>gitweb v.$version/$git_version</generator>\n";
6826 } elsif ($format eq 'atom') {
6827 print <<XML;
6828 <feed xmlns="http://www.w3.org/2005/Atom">
6830 print "<title>$title</title>\n" .
6831 "<subtitle>$descr</subtitle>\n" .
6832 '<link rel="alternate" type="text/html" href="' .
6833 $alt_url . '" />' . "\n" .
6834 '<link rel="self" type="' . $content_type . '" href="' .
6835 $cgi->self_url() . '" />' . "\n" .
6836 "<id>" . href(-full=>1) . "</id>\n" .
6837 # use project owner for feed author
6838 "<author><name>$owner</name></author>\n";
6839 if (defined $favicon) {
6840 print "<icon>" . esc_url($favicon) . "</icon>\n";
6842 if (defined $logo_url) {
6843 # not twice as wide as tall: 72 x 27 pixels
6844 print "<logo>" . esc_url($logo) . "</logo>\n";
6846 if (! %latest_date) {
6847 # dummy date to keep the feed valid until commits trickle in:
6848 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6849 } else {
6850 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6852 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6855 # contents
6856 for (my $i = 0; $i <= $#commitlist; $i++) {
6857 my %co = %{$commitlist[$i]};
6858 my $commit = $co{'id'};
6859 # we read 150, we always show 30 and the ones more recent than 48 hours
6860 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6861 last;
6863 my %cd = parse_date($co{'author_epoch'});
6865 # get list of changed files
6866 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6867 $co{'parent'} || "--root",
6868 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6869 or next;
6870 my @difftree = map { chomp; $_ } <$fd>;
6871 close $fd
6872 or next;
6874 # print element (entry, item)
6875 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6876 if ($format eq 'rss') {
6877 print "<item>\n" .
6878 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6879 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6880 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6881 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6882 "<link>$co_url</link>\n" .
6883 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6884 "<content:encoded>" .
6885 "<![CDATA[\n";
6886 } elsif ($format eq 'atom') {
6887 print "<entry>\n" .
6888 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6889 "<updated>$cd{'iso-8601'}</updated>\n" .
6890 "<author>\n" .
6891 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6892 if ($co{'author_email'}) {
6893 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6895 print "</author>\n" .
6896 # use committer for contributor
6897 "<contributor>\n" .
6898 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6899 if ($co{'committer_email'}) {
6900 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6902 print "</contributor>\n" .
6903 "<published>$cd{'iso-8601'}</published>\n" .
6904 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6905 "<id>$co_url</id>\n" .
6906 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6907 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6909 my $comment = $co{'comment'};
6910 print "<pre>\n";
6911 foreach my $line (@$comment) {
6912 $line = esc_html($line);
6913 print "$line\n";
6915 print "</pre><ul>\n";
6916 foreach my $difftree_line (@difftree) {
6917 my %difftree = parse_difftree_raw_line($difftree_line);
6918 next if !$difftree{'from_id'};
6920 my $file = $difftree{'file'} || $difftree{'to_file'};
6922 print "<li>" .
6923 "[" .
6924 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6925 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6926 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6927 file_name=>$file, file_parent=>$difftree{'from_file'}),
6928 -title => "diff"}, 'D');
6929 if ($have_blame) {
6930 print $cgi->a({-href => href(-full=>1, action=>"blame",
6931 file_name=>$file, hash_base=>$commit),
6932 -title => "blame"}, 'B');
6934 # if this is not a feed of a file history
6935 if (!defined $file_name || $file_name ne $file) {
6936 print $cgi->a({-href => href(-full=>1, action=>"history",
6937 file_name=>$file, hash=>$commit),
6938 -title => "history"}, 'H');
6940 $file = esc_path($file);
6941 print "] ".
6942 "$file</li>\n";
6944 if ($format eq 'rss') {
6945 print "</ul>]]>\n" .
6946 "</content:encoded>\n" .
6947 "</item>\n";
6948 } elsif ($format eq 'atom') {
6949 print "</ul>\n</div>\n" .
6950 "</content>\n" .
6951 "</entry>\n";
6955 # end of feed
6956 if ($format eq 'rss') {
6957 print "</channel>\n</rss>\n";
6958 } elsif ($format eq 'atom') {
6959 print "</feed>\n";
6963 sub git_rss {
6964 git_feed('rss');
6967 sub git_atom {
6968 git_feed('atom');
6971 sub git_opml {
6972 my @list = git_get_projects_list();
6974 print $cgi->header(
6975 -type => 'text/xml',
6976 -charset => 'utf-8',
6977 -content_disposition => 'inline; filename="opml.xml"');
6979 print <<XML;
6980 <?xml version="1.0" encoding="utf-8"?>
6981 <opml version="1.0">
6982 <head>
6983 <title>$site_name OPML Export</title>
6984 </head>
6985 <body>
6986 <outline text="git RSS feeds">
6989 foreach my $pr (@list) {
6990 my %proj = %$pr;
6991 my $head = git_get_head_hash($proj{'path'});
6992 if (!defined $head) {
6993 next;
6995 $git_dir = "$projectroot/$proj{'path'}";
6996 my %co = parse_commit($head);
6997 if (!%co) {
6998 next;
7001 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7002 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7003 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7004 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
7006 print <<XML;
7007 </outline>
7008 </body>
7009 </opml>