gitweb: Ajax-y "Generating..." page when regenerating cache (WIP)
[git/jnareb-git.git] / gitweb / gitweb.perl
blobd422a4b9ea48364ba7c42f57c4fc0223704047ea
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);
15 use Encode;
16 use Fcntl qw(:mode :flock);
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 $cgi = new CGI;
32 our $version = "++GIT_VERSION++";
33 our $my_url = $cgi->url();
34 our $my_uri = $cgi->url(-absolute => 1);
36 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
37 # needed and used only for URLs with nonempty PATH_INFO
38 our $base_url = $my_url;
40 # When the script is used as DirectoryIndex, the URL does not contain the name
41 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
42 # have to do it ourselves. We make $path_info global because it's also used
43 # later on.
45 # Another issue with the script being the DirectoryIndex is that the resulting
46 # $my_url data is not the full script URL: this is good, because we want
47 # generated links to keep implying the script name if it wasn't explicitly
48 # indicated in the URL we're handling, but it means that $my_url cannot be used
49 # as base URL.
50 # Therefore, if we needed to strip PATH_INFO, then we know that we have
51 # to build the base URL ourselves:
52 our $path_info = $ENV{"PATH_INFO"};
53 if ($path_info) {
54 if ($my_url =~ s,\Q$path_info\E$,, &&
55 $my_uri =~ s,\Q$path_info\E$,, &&
56 defined $ENV{'SCRIPT_NAME'}) {
57 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
61 # core git executable to use
62 # this can just be "git" if your webserver has a sensible PATH
63 our $GIT = "++GIT_BINDIR++/git";
65 # absolute fs-path which will be prepended to the project path
66 #our $projectroot = "/pub/scm";
67 our $projectroot = "++GITWEB_PROJECTROOT++";
69 # fs traversing limit for getting project list
70 # the number is relative to the projectroot
71 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
73 # target of the home link on top of all pages
74 our $home_link = $my_uri || "/";
76 # string of the home link on top of all pages
77 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
79 # name of your site or organization to appear in page titles
80 # replace this with something more descriptive for clearer bookmarks
81 our $site_name = "++GITWEB_SITENAME++"
82 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
84 # filename of html text to include at top of each page
85 our $site_header = "++GITWEB_SITE_HEADER++";
86 # html text to include at home page
87 our $home_text = "++GITWEB_HOMETEXT++";
88 # filename of html text to include at bottom of each page
89 our $site_footer = "++GITWEB_SITE_FOOTER++";
91 # URI of stylesheets
92 our @stylesheets = ("++GITWEB_CSS++");
93 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
94 our $stylesheet = undef;
95 # URI of GIT logo (72x27 size)
96 our $logo = "++GITWEB_LOGO++";
97 # URI of GIT favicon, assumed to be image/png type
98 our $favicon = "++GITWEB_FAVICON++";
99 # URI of gitweb.js (JavaScript code for gitweb)
100 our $javascript = "++GITWEB_JS++";
102 # URI and label (title) of GIT logo link
103 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
104 #our $logo_label = "git documentation";
105 our $logo_url = "http://git-scm.com/";
106 our $logo_label = "git homepage";
108 # source of projects list
109 our $projects_list = "++GITWEB_LIST++";
111 # the width (in characters) of the projects list "Description" column
112 our $projects_list_description_width = 25;
114 # default order of projects list
115 # valid values are none, project, descr, owner, and age
116 our $default_projects_order = "project";
118 # show repository only if this file exists
119 # (only effective if this variable evaluates to true)
120 our $export_ok = "++GITWEB_EXPORT_OK++";
122 # show repository only if this subroutine returns true
123 # when given the path to the project, for example:
124 # sub { return -e "$_[0]/git-daemon-export-ok"; }
125 our $export_auth_hook = undef;
127 # only allow viewing of repositories also shown on the overview page
128 our $strict_export = "++GITWEB_STRICT_EXPORT++";
130 # list of git base URLs used for URL to where fetch project from,
131 # i.e. full URL is "$git_base_url/$project"
132 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
134 # default blob_plain mimetype and default charset for text/plain blob
135 our $default_blob_plain_mimetype = 'text/plain';
136 our $default_text_plain_charset = undef;
138 # file to use for guessing MIME types before trying /etc/mime.types
139 # (relative to the current git repository)
140 our $mimetypes_file = undef;
142 # assume this charset if line contains non-UTF-8 characters;
143 # it should be valid encoding (see Encoding::Supported(3pm) for list),
144 # for which encoding all byte sequences are valid, for example
145 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
146 # could be even 'utf-8' for the old behavior)
147 our $fallback_encoding = 'latin1';
149 # rename detection options for git-diff and git-diff-tree
150 # - default is '-M', with the cost proportional to
151 # (number of removed files) * (number of new files).
152 # - more costly is '-C' (which implies '-M'), with the cost proportional to
153 # (number of changed files + number of removed files) * (number of new files)
154 # - even more costly is '-C', '--find-copies-harder' with cost
155 # (number of files in the original tree) * (number of new files)
156 # - one might want to include '-B' option, e.g. '-B', '-M'
157 our @diff_opts = ('-M'); # taken from git_commit
159 # Disables features that would allow repository owners to inject script into
160 # the gitweb domain.
161 our $prevent_xss = 0;
163 # information about snapshot formats that gitweb is capable of serving
164 our %known_snapshot_formats = (
165 # name => {
166 # 'display' => display name,
167 # 'type' => mime type,
168 # 'suffix' => filename suffix,
169 # 'format' => --format for git-archive,
170 # 'compressor' => [compressor command and arguments]
171 # (array reference, optional)
172 # 'disabled' => boolean (optional)}
174 'tgz' => {
175 'display' => 'tar.gz',
176 'type' => 'application/x-gzip',
177 'suffix' => '.tar.gz',
178 'format' => 'tar',
179 'compressor' => ['gzip']},
181 'tbz2' => {
182 'display' => 'tar.bz2',
183 'type' => 'application/x-bzip2',
184 'suffix' => '.tar.bz2',
185 'format' => 'tar',
186 'compressor' => ['bzip2']},
188 'txz' => {
189 'display' => 'tar.xz',
190 'type' => 'application/x-xz',
191 'suffix' => '.tar.xz',
192 'format' => 'tar',
193 'compressor' => ['xz'],
194 'disabled' => 1},
196 'zip' => {
197 'display' => 'zip',
198 'type' => 'application/x-zip',
199 'suffix' => '.zip',
200 'format' => 'zip'},
203 # Aliases so we understand old gitweb.snapshot values in repository
204 # configuration.
205 our %known_snapshot_format_aliases = (
206 'gzip' => 'tgz',
207 'bzip2' => 'tbz2',
208 'xz' => 'txz',
210 # backward compatibility: legacy gitweb config support
211 'x-gzip' => undef, 'gz' => undef,
212 'x-bzip2' => undef, 'bz2' => undef,
213 'x-zip' => undef, '' => undef,
216 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
217 # are changed, it may be appropriate to change these values too via
218 # $GITWEB_CONFIG.
219 our %avatar_size = (
220 'default' => 16,
221 'double' => 32
224 # If it is true, exit if gitweb version and git binary version don't match
225 our $git_versions_must_match = 0;
227 # If this variable is set and not empty, add an extra link called "git"
228 # for each project in project list. Full URL is "$gitlinkurl_base/$project".
229 our $gitlinkurl_base = ("++GITWEB_BASE_URL++" =~ m!^(git://.*)$!) ? $1 : '';
231 # Used to set the maximum load that we will still respond to gitweb queries.
232 # If server load exceed this value then return "503 server busy" error.
233 # If gitweb cannot determined server load, it is taken to be 0.
234 # Leave it undefined (or set to 'undef') to turn off load checking.
235 our $maxload = 300;
237 # This enables/disables the caching layer in gitweb. Currently supported
238 # is only output (response) caching, similar to the one used on git.kernel.org.
239 our $caching_enabled = 0;
240 # Set to _initialized_ instance of cache interface implementing (at least)
241 # get($key) and set($key, $data) methods (Cache::Cache and CHI interfaces).
242 # If unset, GitwebCache::SimpleFileCache would be used, which is 'dumb'
243 # (but fast) file based caching layer, currently without any support for
244 # cache size limiting. It is therefore recommended that the cache directory
245 # be periodically completely deleted; this operation is safe to perform.
246 # Suggested mechanism:
247 # mv $cachedir $cachedir.flush && mkdir $cachedir && rm -rf $cachedir.flush
248 our $cache;
249 # Locations of 'cache.pm' file; if it is relative path, it is relative to
250 # the directory gitweb is run from
251 our $cache_pm = 'cache.pm';
253 # You define site-wide feature defaults here; override them with
254 # $GITWEB_CONFIG as necessary.
255 our %feature = (
256 # feature => {
257 # 'sub' => feature-sub (subroutine),
258 # 'override' => allow-override (boolean),
259 # 'default' => [ default options...] (array reference)}
261 # if feature is overridable (it means that allow-override has true value),
262 # then feature-sub will be called with default options as parameters;
263 # return value of feature-sub indicates if to enable specified feature
265 # if there is no 'sub' key (no feature-sub), then feature cannot be
266 # overriden
268 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
269 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
270 # is enabled
272 # Enable the 'blame' blob view, showing the last commit that modified
273 # each line in the file. This can be very CPU-intensive.
275 # To enable system wide have in $GITWEB_CONFIG
276 # $feature{'blame'}{'default'} = [1];
277 # To have project specific config enable override in $GITWEB_CONFIG
278 # $feature{'blame'}{'override'} = 1;
279 # and in project config gitweb.blame = 0|1;
280 'blame' => {
281 'sub' => sub { feature_bool('blame', @_) },
282 'override' => 0,
283 'default' => [0]},
285 # Enable the 'snapshot' link, providing a compressed archive of any
286 # tree. This can potentially generate high traffic if you have large
287 # project.
289 # Value is a list of formats defined in %known_snapshot_formats that
290 # you wish to offer.
291 # To disable system wide have in $GITWEB_CONFIG
292 # $feature{'snapshot'}{'default'} = [];
293 # To have project specific config enable override in $GITWEB_CONFIG
294 # $feature{'snapshot'}{'override'} = 1;
295 # and in project config, a comma-separated list of formats or "none"
296 # to disable. Example: gitweb.snapshot = tbz2,zip;
297 'snapshot' => {
298 'sub' => \&feature_snapshot,
299 'override' => 0,
300 'default' => ['tgz']},
302 # Enable text search, which will list the commits which match author,
303 # committer or commit text to a given string. Enabled by default.
304 # Project specific override is not supported.
305 'search' => {
306 'override' => 0,
307 'default' => [1]},
309 # Enable grep search, which will list the files in currently selected
310 # tree containing the given string. Enabled by default. This can be
311 # potentially CPU-intensive, of course.
313 # To enable system wide have in $GITWEB_CONFIG
314 # $feature{'grep'}{'default'} = [1];
315 # To have project specific config enable override in $GITWEB_CONFIG
316 # $feature{'grep'}{'override'} = 1;
317 # and in project config gitweb.grep = 0|1;
318 'grep' => {
319 'sub' => sub { feature_bool('grep', @_) },
320 'override' => 0,
321 'default' => [1]},
323 # Enable the pickaxe search, which will list the commits that modified
324 # a given string in a file. This can be practical and quite faster
325 # alternative to 'blame', but still potentially CPU-intensive.
327 # To enable system wide have in $GITWEB_CONFIG
328 # $feature{'pickaxe'}{'default'} = [1];
329 # To have project specific config enable override in $GITWEB_CONFIG
330 # $feature{'pickaxe'}{'override'} = 1;
331 # and in project config gitweb.pickaxe = 0|1;
332 'pickaxe' => {
333 'sub' => sub { feature_bool('pickaxe', @_) },
334 'override' => 0,
335 'default' => [1]},
337 # Enable showing size of blobs in a 'tree' view, in a separate
338 # column, similar to what 'ls -l' does. This cost a bit of IO.
340 # To disable system wide have in $GITWEB_CONFIG
341 # $feature{'show-sizes'}{'default'} = [0];
342 # To have project specific config enable override in $GITWEB_CONFIG
343 # $feature{'show-sizes'}{'override'} = 1;
344 # and in project config gitweb.showsizes = 0|1;
345 'show-sizes' => {
346 'sub' => sub { feature_bool('showsizes', @_) },
347 'override' => 0,
348 'default' => [1]},
350 # Make gitweb use an alternative format of the URLs which can be
351 # more readable and natural-looking: project name is embedded
352 # directly in the path and the query string contains other
353 # auxiliary information. All gitweb installations recognize
354 # URL in either format; this configures in which formats gitweb
355 # generates links.
357 # To enable system wide have in $GITWEB_CONFIG
358 # $feature{'pathinfo'}{'default'} = [1];
359 # Project specific override is not supported.
361 # Note that you will need to change the default location of CSS,
362 # favicon, logo and possibly other files to an absolute URL. Also,
363 # if gitweb.cgi serves as your indexfile, you will need to force
364 # $my_uri to contain the script name in your $GITWEB_CONFIG.
365 'pathinfo' => {
366 'override' => 0,
367 'default' => [0]},
369 # Make gitweb consider projects in project root subdirectories
370 # to be forks of existing projects. Given project $projname.git,
371 # projects matching $projname/*.git will not be shown in the main
372 # projects list, instead a '+' mark will be added to $projname
373 # there and a 'forks' view will be enabled for the project, listing
374 # all the forks. If project list is taken from a file, forks have
375 # to be listed after the main project.
377 # To enable system wide have in $GITWEB_CONFIG
378 # $feature{'forks'}{'default'} = [1];
379 # Project specific override is not supported.
380 'forks' => {
381 'override' => 0,
382 'default' => [0]},
384 # Insert custom links to the action bar of all project pages.
385 # This enables you mainly to link to third-party scripts integrating
386 # into gitweb; e.g. git-browser for graphical history representation
387 # or custom web-based repository administration interface.
389 # The 'default' value consists of a list of triplets in the form
390 # (label, link, position) where position is the label after which
391 # to insert the link and link is a format string where %n expands
392 # to the project name, %f to the project path within the filesystem,
393 # %h to the current hash (h gitweb parameter) and %b to the current
394 # hash base (hb gitweb parameter); %% expands to %.
396 # To enable system wide have in $GITWEB_CONFIG e.g.
397 # $feature{'actions'}{'default'} = [('graphiclog',
398 # '/git-browser/by-commit.html?r=%n', 'summary')];
399 # Project specific override is not supported.
400 'actions' => {
401 'override' => 0,
402 'default' => []},
404 # Allow gitweb scan project content tags described in ctags/
405 # of project repository, and display the popular Web 2.0-ish
406 # "tag cloud" near the project list. Note that this is something
407 # COMPLETELY different from the normal Git tags.
409 # gitweb by itself can show existing tags, but it does not handle
410 # tagging itself; you need an external application for that.
411 # For an example script, check Girocco's cgi/tagproj.cgi.
412 # You may want to install the HTML::TagCloud Perl module to get
413 # a pretty tag cloud instead of just a list of tags.
415 # To enable system wide have in $GITWEB_CONFIG
416 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
417 # Project specific override is not supported.
418 'ctags' => {
419 'override' => 0,
420 'default' => [0]},
422 # The maximum number of patches in a patchset generated in patch
423 # view. Set this to 0 or undef to disable patch view, or to a
424 # negative number to remove any limit.
426 # To disable system wide have in $GITWEB_CONFIG
427 # $feature{'patches'}{'default'} = [0];
428 # To have project specific config enable override in $GITWEB_CONFIG
429 # $feature{'patches'}{'override'} = 1;
430 # and in project config gitweb.patches = 0|n;
431 # where n is the maximum number of patches allowed in a patchset.
432 'patches' => {
433 'sub' => \&feature_patches,
434 'override' => 0,
435 'default' => [16]},
437 # Avatar support. When this feature is enabled, views such as
438 # shortlog or commit will display an avatar associated with
439 # the email of the committer(s) and/or author(s).
441 # Currently available providers are gravatar and picon.
442 # If an unknown provider is specified, the feature is disabled.
444 # Gravatar depends on Digest::MD5.
445 # Picon currently relies on the indiana.edu database.
447 # To enable system wide have in $GITWEB_CONFIG
448 # $feature{'avatar'}{'default'} = ['<provider>'];
449 # where <provider> is either gravatar or picon.
450 # To have project specific config enable override in $GITWEB_CONFIG
451 # $feature{'avatar'}{'override'} = 1;
452 # and in project config gitweb.avatar = <provider>;
453 'avatar' => {
454 'sub' => \&feature_avatar,
455 'override' => 0,
456 'default' => ['']},
458 # Enable displaying how much time and how many git commands
459 # it took to generate and display page. Disabled by default.
460 # Project specific override is not supported.
461 'timed' => {
462 'override' => 0,
463 'default' => [0]},
465 # Enable turning some links into links to actions which require
466 # JavaScript to run (like 'blame_incremental'). Not enabled by
467 # default. Project specific override is currently not supported.
468 'javascript-actions' => {
469 'override' => 0,
470 'default' => [0]},
473 sub gitweb_get_feature {
474 my ($name) = @_;
475 return unless exists $feature{$name};
476 my ($sub, $override, @defaults) = (
477 $feature{$name}{'sub'},
478 $feature{$name}{'override'},
479 @{$feature{$name}{'default'}});
480 if (!$override) { return @defaults; }
481 if (!defined $sub) {
482 warn "feature $name is not overridable";
483 return @defaults;
485 return $sub->(@defaults);
488 # A wrapper to check if a given feature is enabled.
489 # With this, you can say
491 # my $bool_feat = gitweb_check_feature('bool_feat');
492 # gitweb_check_feature('bool_feat') or somecode;
494 # instead of
496 # my ($bool_feat) = gitweb_get_feature('bool_feat');
497 # (gitweb_get_feature('bool_feat'))[0] or somecode;
499 sub gitweb_check_feature {
500 return (gitweb_get_feature(@_))[0];
504 sub feature_bool {
505 my $key = shift;
506 my ($val) = git_get_project_config($key, '--bool');
508 if (!defined $val) {
509 return ($_[0]);
510 } elsif ($val eq 'true') {
511 return (1);
512 } elsif ($val eq 'false') {
513 return (0);
517 sub feature_snapshot {
518 my (@fmts) = @_;
520 my ($val) = git_get_project_config('snapshot');
522 if ($val) {
523 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
526 return @fmts;
529 sub feature_patches {
530 my @val = (git_get_project_config('patches', '--int'));
532 if (@val) {
533 return @val;
536 return ($_[0]);
539 sub feature_avatar {
540 my @val = (git_get_project_config('avatar'));
542 return @val ? @val : @_;
545 # checking HEAD file with -e is fragile if the repository was
546 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
547 # and then pruned.
548 sub check_head_link {
549 my ($dir) = @_;
550 my $headfile = "$dir/HEAD";
551 return ((-e $headfile) ||
552 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
555 sub check_export_ok {
556 my ($dir) = @_;
557 return (check_head_link($dir) &&
558 (!$export_ok || -e "$dir/$export_ok") &&
559 (!$export_auth_hook || $export_auth_hook->($dir)));
562 # process alternate names for backward compatibility
563 # filter out unsupported (unknown) snapshot formats
564 sub filter_snapshot_fmts {
565 my @fmts = @_;
567 @fmts = map {
568 exists $known_snapshot_format_aliases{$_} ?
569 $known_snapshot_format_aliases{$_} : $_} @fmts;
570 @fmts = grep {
571 exists $known_snapshot_formats{$_} &&
572 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
575 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
576 if (-e $GITWEB_CONFIG) {
577 do $GITWEB_CONFIG;
578 } else {
579 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
580 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
583 # Where to write gitweb output (filehandle)
584 our $out = \*STDOUT;
586 # Get loadavg of system, to compare against $maxload.
587 # Currently it requires '/proc/loadavg' present to get loadavg;
588 # if it is not present it returns 0, which means no load checking.
589 sub get_loadavg {
590 open my $fd, '<', '/proc/loadavg'
591 or return 0;
592 my @load = split(/\s+/, scalar <$fd>);
593 close $fd;
595 # The first three columns measure CPU and IO utilization of the last one,
596 # five, and 10 minute periods. The fourth column shows the number of
597 # currently running processes and the total number of processes in the m/n
598 # format. The last column displays the last process ID used.
599 return $load[0] || 0;
602 if (defined $maxload && get_loadavg() > $maxload) {
603 die_error(503, "The load average on the server is too high");
606 # version of the core git binary
607 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
608 $number_of_git_cmds++;
610 # Throw an error if git versions does not match, if $git_versions_must_match is true.
611 if ($git_versions_must_match &&
612 $git_version ne $version) {
613 git_header_html('500 - Internal Server Error');
614 my $admin_contact =
615 defined $ENV{'SERVER_ADMIN'} ? ", $ENV{'SERVER_ADMIN'}," : '';
616 print {$out} <<"EOT";
617 <div class="page_body">
618 <br /><br />
619 500 - Internal Server Error
620 <br />
621 </div>
622 <hr />
623 <div class="readme">
624 <h1 align="center">*** Warning ***</h1>
626 This version of gitweb was compiled for <b>@{[esc_html($version)]}</b>,
627 however git version <b>@{[esc_html($git_version)]}</b> was found on server,
628 and administrator requested strict version checking.
629 </p>
631 Please contact the server administrator${admin_contact} to either configure
632 gitweb to allow mismatched versions, or update git or gitweb installation.
633 </p>
634 </div>
636 git_footer_html();
637 exit;
640 $projects_list ||= $projectroot;
642 # ======================================================================
643 # input validation and dispatch
645 # input parameters can be collected from a variety of sources (presently, CGI
646 # and PATH_INFO), so we define an %input_params hash that collects them all
647 # together during validation: this allows subsequent uses (e.g. href()) to be
648 # agnostic of the parameter origin
650 our %input_params = ();
652 # input parameters are stored with the long parameter name as key. This will
653 # also be used in the href subroutine to convert parameters to their CGI
654 # equivalent, and since the href() usage is the most frequent one, we store
655 # the name -> CGI key mapping here, instead of the reverse.
657 # XXX: Warning: If you touch this, check the search form for updating,
658 # too.
660 our @cgi_param_mapping = (
661 project => "p",
662 action => "a",
663 file_name => "f",
664 file_parent => "fp",
665 hash => "h",
666 hash_parent => "hp",
667 hash_base => "hb",
668 hash_parent_base => "hpb",
669 page => "pg",
670 order => "o",
671 searchtext => "s",
672 searchtype => "st",
673 snapshot_format => "sf",
674 extra_options => "opt",
675 search_use_regexp => "sr",
676 # this must be last entry (for manipulation from JavaScript)
677 javascript => "js"
679 our %cgi_param_mapping = @cgi_param_mapping;
681 # we will also need to know the possible actions, for validation
682 our %actions = (
683 "blame" => \&git_blame,
684 "blame_incremental" => \&git_blame_incremental,
685 "blame_data" => \&git_blame_data,
686 "blobdiff" => \&git_blobdiff,
687 "blobdiff_plain" => \&git_blobdiff_plain,
688 "blob" => \&git_blob,
689 "blob_plain" => \&git_blob_plain,
690 "commitdiff" => \&git_commitdiff,
691 "commitdiff_plain" => \&git_commitdiff_plain,
692 "commit" => \&git_commit,
693 "forks" => \&git_forks,
694 "heads" => \&git_heads,
695 "history" => \&git_history,
696 "log" => \&git_log,
697 "patch" => \&git_patch,
698 "patches" => \&git_patches,
699 "rss" => \&git_rss,
700 "atom" => \&git_atom,
701 "search" => \&git_search,
702 "search_help" => \&git_search_help,
703 "shortlog" => \&git_shortlog,
704 "summary" => \&git_summary,
705 "tag" => \&git_tag,
706 "tags" => \&git_tags,
707 "tree" => \&git_tree,
708 "snapshot" => \&git_snapshot,
709 "object" => \&git_object,
710 # those below don't need $project
711 "opml" => \&git_opml,
712 "project_list" => \&git_project_list,
713 "project_index" => \&git_project_index,
716 # finally, we have the hash of allowed extra_options for the commands that
717 # allow them
718 our %allowed_options = (
719 "--no-merges" => [ qw(rss atom log shortlog history) ],
722 # fill %input_params with the CGI parameters. All values except for 'opt'
723 # should be single values, but opt can be an array. We should probably
724 # build an array of parameters that can be multi-valued, but since for the time
725 # being it's only this one, we just single it out
726 while (my ($name, $symbol) = each %cgi_param_mapping) {
727 if ($symbol eq 'opt') {
728 $input_params{$name} = [ $cgi->param($symbol) ];
729 } else {
730 $input_params{$name} = $cgi->param($symbol);
734 # now read PATH_INFO and update the parameter list for missing parameters
735 sub evaluate_path_info {
736 return if defined $input_params{'project'};
737 return if !$path_info;
738 $path_info =~ s,^/+,,;
739 return if !$path_info;
741 # find which part of PATH_INFO is project
742 my $project = $path_info;
743 $project =~ s,/+$,,;
744 while ($project && !check_head_link("$projectroot/$project")) {
745 $project =~ s,/*[^/]*$,,;
747 return unless $project;
748 $input_params{'project'} = $project;
750 # do not change any parameters if an action is given using the query string
751 return if $input_params{'action'};
752 $path_info =~ s,^\Q$project\E/*,,;
754 # next, check if we have an action
755 my $action = $path_info;
756 $action =~ s,/.*$,,;
757 if (exists $actions{$action}) {
758 $path_info =~ s,^$action/*,,;
759 $input_params{'action'} = $action;
762 # list of actions that want hash_base instead of hash, but can have no
763 # pathname (f) parameter
764 my @wants_base = (
765 'tree',
766 'history',
769 # we want to catch
770 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
771 my ($parentrefname, $parentpathname, $refname, $pathname) =
772 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
774 # first, analyze the 'current' part
775 if (defined $pathname) {
776 # we got "branch:filename" or "branch:dir/"
777 # we could use git_get_type(branch:pathname), but:
778 # - it needs $git_dir
779 # - it does a git() call
780 # - the convention of terminating directories with a slash
781 # makes it superfluous
782 # - embedding the action in the PATH_INFO would make it even
783 # more superfluous
784 $pathname =~ s,^/+,,;
785 if (!$pathname || substr($pathname, -1) eq "/") {
786 $input_params{'action'} ||= "tree";
787 $pathname =~ s,/$,,;
788 } else {
789 # the default action depends on whether we had parent info
790 # or not
791 if ($parentrefname) {
792 $input_params{'action'} ||= "blobdiff_plain";
793 } else {
794 $input_params{'action'} ||= "blob_plain";
797 $input_params{'hash_base'} ||= $refname;
798 $input_params{'file_name'} ||= $pathname;
799 } elsif (defined $refname) {
800 # we got "branch". In this case we have to choose if we have to
801 # set hash or hash_base.
803 # Most of the actions without a pathname only want hash to be
804 # set, except for the ones specified in @wants_base that want
805 # hash_base instead. It should also be noted that hand-crafted
806 # links having 'history' as an action and no pathname or hash
807 # set will fail, but that happens regardless of PATH_INFO.
808 $input_params{'action'} ||= "shortlog";
809 if (grep { $_ eq $input_params{'action'} } @wants_base) {
810 $input_params{'hash_base'} ||= $refname;
811 } else {
812 $input_params{'hash'} ||= $refname;
816 # next, handle the 'parent' part, if present
817 if (defined $parentrefname) {
818 # a missing pathspec defaults to the 'current' filename, allowing e.g.
819 # someproject/blobdiff/oldrev..newrev:/filename
820 if ($parentpathname) {
821 $parentpathname =~ s,^/+,,;
822 $parentpathname =~ s,/$,,;
823 $input_params{'file_parent'} ||= $parentpathname;
824 } else {
825 $input_params{'file_parent'} ||= $input_params{'file_name'};
827 # we assume that hash_parent_base is wanted if a path was specified,
828 # or if the action wants hash_base instead of hash
829 if (defined $input_params{'file_parent'} ||
830 grep { $_ eq $input_params{'action'} } @wants_base) {
831 $input_params{'hash_parent_base'} ||= $parentrefname;
832 } else {
833 $input_params{'hash_parent'} ||= $parentrefname;
837 # for the snapshot action, we allow URLs in the form
838 # $project/snapshot/$hash.ext
839 # where .ext determines the snapshot and gets removed from the
840 # passed $refname to provide the $hash.
842 # To be able to tell that $refname includes the format extension, we
843 # require the following two conditions to be satisfied:
844 # - the hash input parameter MUST have been set from the $refname part
845 # of the URL (i.e. they must be equal)
846 # - the snapshot format MUST NOT have been defined already (e.g. from
847 # CGI parameter sf)
848 # It's also useless to try any matching unless $refname has a dot,
849 # so we check for that too
850 if (defined $input_params{'action'} &&
851 $input_params{'action'} eq 'snapshot' &&
852 defined $refname && index($refname, '.') != -1 &&
853 $refname eq $input_params{'hash'} &&
854 !defined $input_params{'snapshot_format'}) {
855 # We loop over the known snapshot formats, checking for
856 # extensions. Allowed extensions are both the defined suffix
857 # (which includes the initial dot already) and the snapshot
858 # format key itself, with a prepended dot
859 while (my ($fmt, $opt) = each %known_snapshot_formats) {
860 my $hash = $refname;
861 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
862 next;
864 my $sfx = $1;
865 # a valid suffix was found, so set the snapshot format
866 # and reset the hash parameter
867 $input_params{'snapshot_format'} = $fmt;
868 $input_params{'hash'} = $hash;
869 # we also set the format suffix to the one requested
870 # in the URL: this way a request for e.g. .tgz returns
871 # a .tgz instead of a .tar.gz
872 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
873 last;
877 evaluate_path_info();
879 our $action = $input_params{'action'};
880 if (defined $action) {
881 if (!validate_action($action)) {
882 die_error(400, "Invalid action parameter");
886 # parameters which are pathnames
887 our $project = $input_params{'project'};
888 if (defined $project) {
889 if (!validate_project($project)) {
890 undef $project;
891 die_error(404, "No such project");
895 our $file_name = $input_params{'file_name'};
896 if (defined $file_name) {
897 if (!validate_pathname($file_name)) {
898 die_error(400, "Invalid file parameter");
902 our $file_parent = $input_params{'file_parent'};
903 if (defined $file_parent) {
904 if (!validate_pathname($file_parent)) {
905 die_error(400, "Invalid file parent parameter");
909 # parameters which are refnames
910 our $hash = $input_params{'hash'};
911 if (defined $hash) {
912 if (!validate_refname($hash)) {
913 die_error(400, "Invalid hash parameter");
917 our $hash_parent = $input_params{'hash_parent'};
918 if (defined $hash_parent) {
919 if (!validate_refname($hash_parent)) {
920 die_error(400, "Invalid hash parent parameter");
924 our $hash_base = $input_params{'hash_base'};
925 if (defined $hash_base) {
926 if (!validate_refname($hash_base)) {
927 die_error(400, "Invalid hash base parameter");
931 our @extra_options = @{$input_params{'extra_options'}};
932 # @extra_options is always defined, since it can only be (currently) set from
933 # CGI, and $cgi->param() returns the empty array in array context if the param
934 # is not set
935 foreach my $opt (@extra_options) {
936 if (not exists $allowed_options{$opt}) {
937 die_error(400, "Invalid option parameter");
939 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
940 die_error(400, "Invalid option parameter for this action");
944 our $hash_parent_base = $input_params{'hash_parent_base'};
945 if (defined $hash_parent_base) {
946 if (!validate_refname($hash_parent_base)) {
947 die_error(400, "Invalid hash parent base parameter");
951 # other parameters
952 our $page = $input_params{'page'};
953 if (defined $page) {
954 if ($page =~ m/[^0-9]/) {
955 die_error(400, "Invalid page parameter");
959 our $searchtype = $input_params{'searchtype'};
960 if (defined $searchtype) {
961 if ($searchtype =~ m/[^a-z]/) {
962 die_error(400, "Invalid searchtype parameter");
966 our $search_use_regexp = $input_params{'search_use_regexp'};
968 our $searchtext = $input_params{'searchtext'};
969 our $search_regexp;
970 if (defined $searchtext) {
971 if (length($searchtext) < 2) {
972 die_error(403, "At least two characters are required for search parameter");
974 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
977 # path to the current git repository
978 our $git_dir;
979 $git_dir = "$projectroot/$project" if $project;
981 # list of supported snapshot formats
982 our @snapshot_fmts = gitweb_get_feature('snapshot');
983 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
985 # check that the avatar feature is set to a known provider name,
986 # and for each provider check if the dependencies are satisfied.
987 # if the provider name is invalid or the dependencies are not met,
988 # reset $git_avatar to the empty string.
989 our ($git_avatar) = gitweb_get_feature('avatar');
990 if ($git_avatar eq 'gravatar') {
991 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
992 } elsif ($git_avatar eq 'picon') {
993 # no dependencies
994 } else {
995 $git_avatar = '';
998 # dispatch
999 if (!defined $action) {
1000 if (defined $hash) {
1001 $action = git_get_type($hash);
1002 } elsif (defined $hash_base && defined $file_name) {
1003 $action = git_get_type("$hash_base:$file_name");
1004 } elsif (defined $project) {
1005 $action = 'summary';
1006 } else {
1007 $action = 'project_list';
1010 if (!defined($actions{$action})) {
1011 die_error(400, "Unknown action");
1013 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1014 !$project) {
1015 die_error(400, "Project needed");
1018 if ($caching_enabled) {
1019 do $cache_pm;
1020 die $@ if $@;
1022 $cache ||= GitwebCache::SimpleFileCache->new({
1023 'cache_root' => '/tmp/cache',
1024 'cache_depth' => 2,
1025 'expires_in' => 20, # in seconds
1026 'generating_info' => \&git_generating_data_html,
1028 cache_fetch($cache, $action);
1029 } else {
1030 $actions{$action}->();
1033 exit;
1035 ## ======================================================================
1036 ## action links
1038 # possible values of extra options
1039 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1040 # -replay => 1 - start from a current view (replay with modifications)
1041 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1042 sub href {
1043 my %params = @_;
1044 # default is to use -absolute url() i.e. $my_uri
1045 my $href = $params{-full} ? $my_url : $my_uri;
1047 $params{'project'} = $project unless exists $params{'project'};
1049 if ($params{-replay}) {
1050 while (my ($name, $symbol) = each %cgi_param_mapping) {
1051 if (!exists $params{$name}) {
1052 $params{$name} = $input_params{$name};
1057 my $use_pathinfo = gitweb_check_feature('pathinfo');
1058 if (defined $params{'project'} &&
1059 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1060 # try to put as many parameters as possible in PATH_INFO:
1061 # - project name
1062 # - action
1063 # - hash_parent or hash_parent_base:/file_parent
1064 # - hash or hash_base:/filename
1065 # - the snapshot_format as an appropriate suffix
1067 # When the script is the root DirectoryIndex for the domain,
1068 # $href here would be something like http://gitweb.example.com/
1069 # Thus, we strip any trailing / from $href, to spare us double
1070 # slashes in the final URL
1071 $href =~ s,/$,,;
1073 # Then add the project name, if present
1074 $href .= "/".esc_url($params{'project'});
1075 delete $params{'project'};
1077 # since we destructively absorb parameters, we keep this
1078 # boolean that remembers if we're handling a snapshot
1079 my $is_snapshot = $params{'action'} eq 'snapshot';
1081 # Summary just uses the project path URL, any other action is
1082 # added to the URL
1083 if (defined $params{'action'}) {
1084 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
1085 delete $params{'action'};
1088 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1089 # stripping nonexistent or useless pieces
1090 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1091 || $params{'hash_parent'} || $params{'hash'});
1092 if (defined $params{'hash_base'}) {
1093 if (defined $params{'hash_parent_base'}) {
1094 $href .= esc_url($params{'hash_parent_base'});
1095 # skip the file_parent if it's the same as the file_name
1096 if (defined $params{'file_parent'}) {
1097 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1098 delete $params{'file_parent'};
1099 } elsif ($params{'file_parent'} !~ /\.\./) {
1100 $href .= ":/".esc_url($params{'file_parent'});
1101 delete $params{'file_parent'};
1104 $href .= "..";
1105 delete $params{'hash_parent'};
1106 delete $params{'hash_parent_base'};
1107 } elsif (defined $params{'hash_parent'}) {
1108 $href .= esc_url($params{'hash_parent'}). "..";
1109 delete $params{'hash_parent'};
1112 $href .= esc_url($params{'hash_base'});
1113 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1114 $href .= ":/".esc_url($params{'file_name'});
1115 delete $params{'file_name'};
1117 delete $params{'hash'};
1118 delete $params{'hash_base'};
1119 } elsif (defined $params{'hash'}) {
1120 $href .= esc_url($params{'hash'});
1121 delete $params{'hash'};
1124 # If the action was a snapshot, we can absorb the
1125 # snapshot_format parameter too
1126 if ($is_snapshot) {
1127 my $fmt = $params{'snapshot_format'};
1128 # snapshot_format should always be defined when href()
1129 # is called, but just in case some code forgets, we
1130 # fall back to the default
1131 $fmt ||= $snapshot_fmts[0];
1132 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1133 delete $params{'snapshot_format'};
1137 # now encode the parameters explicitly
1138 my @result = ();
1139 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1140 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1141 if (defined $params{$name}) {
1142 if (ref($params{$name}) eq "ARRAY") {
1143 foreach my $par (@{$params{$name}}) {
1144 push @result, $symbol . "=" . esc_param($par);
1146 } else {
1147 push @result, $symbol . "=" . esc_param($params{$name});
1151 $href .= "?" . join(';', @result) if scalar @result;
1153 return $href;
1157 ## ======================================================================
1158 ## validation, quoting/unquoting and escaping
1160 sub validate_action {
1161 my $input = shift || return undef;
1162 return undef unless exists $actions{$input};
1163 return $input;
1166 sub validate_project {
1167 my $input = shift || return undef;
1168 if (!validate_pathname($input) ||
1169 !(-d "$projectroot/$input") ||
1170 !check_export_ok("$projectroot/$input") ||
1171 ($strict_export && !project_in_list($input))) {
1172 return undef;
1173 } else {
1174 return $input;
1178 sub validate_pathname {
1179 my $input = shift || return undef;
1181 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1182 # at the beginning, at the end, and between slashes.
1183 # also this catches doubled slashes
1184 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1185 return undef;
1187 # no null characters
1188 if ($input =~ m!\0!) {
1189 return undef;
1191 return $input;
1194 sub validate_refname {
1195 my $input = shift || return undef;
1197 # textual hashes are O.K.
1198 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1199 return $input;
1201 # it must be correct pathname
1202 $input = validate_pathname($input)
1203 or return undef;
1204 # restrictions on ref name according to git-check-ref-format
1205 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1206 return undef;
1208 return $input;
1211 # decode sequences of octets in utf8 into Perl's internal form,
1212 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1213 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1214 sub to_utf8 {
1215 my $str = shift;
1216 if (utf8::valid($str)) {
1217 utf8::decode($str);
1218 return $str;
1219 } else {
1220 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1224 # quote unsafe chars, but keep the slash, even when it's not
1225 # correct, but quoted slashes look too horrible in bookmarks
1226 sub esc_param {
1227 my $str = shift;
1228 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1229 $str =~ s/ /\+/g;
1230 return $str;
1233 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1234 sub esc_url {
1235 my $str = shift;
1236 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1237 $str =~ s/\+/%2B/g;
1238 $str =~ s/ /\+/g;
1239 return $str;
1242 # replace invalid utf8 character with SUBSTITUTION sequence
1243 sub esc_html {
1244 my $str = shift;
1245 my %opts = @_;
1247 $str = to_utf8($str);
1248 $str = $cgi->escapeHTML($str);
1249 if ($opts{'-nbsp'}) {
1250 $str =~ s/ /&nbsp;/g;
1252 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1253 return $str;
1256 # quote control characters and escape filename to HTML
1257 sub esc_path {
1258 my $str = shift;
1259 my %opts = @_;
1261 $str = to_utf8($str);
1262 $str = $cgi->escapeHTML($str);
1263 if ($opts{'-nbsp'}) {
1264 $str =~ s/ /&nbsp;/g;
1266 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1267 return $str;
1270 # Make control characters "printable", using character escape codes (CEC)
1271 sub quot_cec {
1272 my $cntrl = shift;
1273 my %opts = @_;
1274 my %es = ( # character escape codes, aka escape sequences
1275 "\t" => '\t', # tab (HT)
1276 "\n" => '\n', # line feed (LF)
1277 "\r" => '\r', # carrige return (CR)
1278 "\f" => '\f', # form feed (FF)
1279 "\b" => '\b', # backspace (BS)
1280 "\a" => '\a', # alarm (bell) (BEL)
1281 "\e" => '\e', # escape (ESC)
1282 "\013" => '\v', # vertical tab (VT)
1283 "\000" => '\0', # nul character (NUL)
1285 my $chr = ( (exists $es{$cntrl})
1286 ? $es{$cntrl}
1287 : sprintf('\%2x', ord($cntrl)) );
1288 if ($opts{-nohtml}) {
1289 return $chr;
1290 } else {
1291 return "<span class=\"cntrl\">$chr</span>";
1295 # Alternatively use unicode control pictures codepoints,
1296 # Unicode "printable representation" (PR)
1297 sub quot_upr {
1298 my $cntrl = shift;
1299 my %opts = @_;
1301 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1302 if ($opts{-nohtml}) {
1303 return $chr;
1304 } else {
1305 return "<span class=\"cntrl\">$chr</span>";
1309 # git may return quoted and escaped filenames
1310 sub unquote {
1311 my $str = shift;
1313 sub unq {
1314 my $seq = shift;
1315 my %es = ( # character escape codes, aka escape sequences
1316 't' => "\t", # tab (HT, TAB)
1317 'n' => "\n", # newline (NL)
1318 'r' => "\r", # return (CR)
1319 'f' => "\f", # form feed (FF)
1320 'b' => "\b", # backspace (BS)
1321 'a' => "\a", # alarm (bell) (BEL)
1322 'e' => "\e", # escape (ESC)
1323 'v' => "\013", # vertical tab (VT)
1326 if ($seq =~ m/^[0-7]{1,3}$/) {
1327 # octal char sequence
1328 return chr(oct($seq));
1329 } elsif (exists $es{$seq}) {
1330 # C escape sequence, aka character escape code
1331 return $es{$seq};
1333 # quoted ordinary character
1334 return $seq;
1337 if ($str =~ m/^"(.*)"$/) {
1338 # needs unquoting
1339 $str = $1;
1340 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1342 return $str;
1345 # escape tabs (convert tabs to spaces)
1346 sub untabify {
1347 my $line = shift;
1349 while ((my $pos = index($line, "\t")) != -1) {
1350 if (my $count = (8 - ($pos % 8))) {
1351 my $spaces = ' ' x $count;
1352 $line =~ s/\t/$spaces/;
1356 return $line;
1359 sub project_in_list {
1360 my $project = shift;
1361 my @list = git_get_projects_list();
1362 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1365 ## ----------------------------------------------------------------------
1366 ## HTML aware string manipulation
1368 # Try to chop given string on a word boundary between position
1369 # $len and $len+$add_len. If there is no word boundary there,
1370 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1371 # (marking chopped part) would be longer than given string.
1372 sub chop_str {
1373 my $str = shift;
1374 my $len = shift;
1375 my $add_len = shift || 10;
1376 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1378 # Make sure perl knows it is utf8 encoded so we don't
1379 # cut in the middle of a utf8 multibyte char.
1380 $str = to_utf8($str);
1382 # allow only $len chars, but don't cut a word if it would fit in $add_len
1383 # if it doesn't fit, cut it if it's still longer than the dots we would add
1384 # remove chopped character entities entirely
1386 # when chopping in the middle, distribute $len into left and right part
1387 # return early if chopping wouldn't make string shorter
1388 if ($where eq 'center') {
1389 return $str if ($len + 5 >= length($str)); # filler is length 5
1390 $len = int($len/2);
1391 } else {
1392 return $str if ($len + 4 >= length($str)); # filler is length 4
1395 # regexps: ending and beginning with word part up to $add_len
1396 my $endre = qr/.{$len}\w{0,$add_len}/;
1397 my $begre = qr/\w{0,$add_len}.{$len}/;
1399 if ($where eq 'left') {
1400 $str =~ m/^(.*?)($begre)$/;
1401 my ($lead, $body) = ($1, $2);
1402 if (length($lead) > 4) {
1403 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1404 $lead = " ...";
1406 return "$lead$body";
1408 } elsif ($where eq 'center') {
1409 $str =~ m/^($endre)(.*)$/;
1410 my ($left, $str) = ($1, $2);
1411 $str =~ m/^(.*?)($begre)$/;
1412 my ($mid, $right) = ($1, $2);
1413 if (length($mid) > 5) {
1414 $left =~ s/&[^;]*$//;
1415 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1416 $mid = " ... ";
1418 return "$left$mid$right";
1420 } else {
1421 $str =~ m/^($endre)(.*)$/;
1422 my $body = $1;
1423 my $tail = $2;
1424 if (length($tail) > 4) {
1425 $body =~ s/&[^;]*$//;
1426 $tail = "... ";
1428 return "$body$tail";
1432 # takes the same arguments as chop_str, but also wraps a <span> around the
1433 # result with a title attribute if it does get chopped. Additionally, the
1434 # string is HTML-escaped.
1435 sub chop_and_escape_str {
1436 my ($str) = @_;
1438 my $chopped = chop_str(@_);
1439 if ($chopped eq $str) {
1440 return esc_html($chopped);
1441 } else {
1442 $str =~ s/[[:cntrl:]]/?/g;
1443 return $cgi->span({-title=>$str}, esc_html($chopped));
1447 ## ----------------------------------------------------------------------
1448 ## functions returning short strings
1450 # CSS class for given age value (in seconds)
1451 sub age_class {
1452 my $age = shift;
1454 if (!defined $age) {
1455 return "noage";
1456 } elsif ($age < 60*60*2) {
1457 return "age0";
1458 } elsif ($age < 60*60*24*2) {
1459 return "age1";
1460 } else {
1461 return "age2";
1465 # convert age in seconds to "nn units ago" string
1466 sub age_string {
1467 my $age = shift;
1468 my $age_str;
1470 if ($age > 60*60*24*365*2) {
1471 $age_str = (int $age/60/60/24/365);
1472 $age_str .= " years ago";
1473 } elsif ($age > 60*60*24*(365/12)*2) {
1474 $age_str = int $age/60/60/24/(365/12);
1475 $age_str .= " months ago";
1476 } elsif ($age > 60*60*24*7*2) {
1477 $age_str = int $age/60/60/24/7;
1478 $age_str .= " weeks ago";
1479 } elsif ($age > 60*60*24*2) {
1480 $age_str = int $age/60/60/24;
1481 $age_str .= " days ago";
1482 } elsif ($age > 60*60*2) {
1483 $age_str = int $age/60/60;
1484 $age_str .= " hours ago";
1485 } elsif ($age > 60*2) {
1486 $age_str = int $age/60;
1487 $age_str .= " min ago";
1488 } elsif ($age > 2) {
1489 $age_str = int $age;
1490 $age_str .= " sec ago";
1491 } else {
1492 $age_str .= " right now";
1494 return $age_str;
1497 use constant {
1498 S_IFINVALID => 0030000,
1499 S_IFGITLINK => 0160000,
1502 # submodule/subproject, a commit object reference
1503 sub S_ISGITLINK {
1504 my $mode = shift;
1506 return (($mode & S_IFMT) == S_IFGITLINK)
1509 # convert file mode in octal to symbolic file mode string
1510 sub mode_str {
1511 my $mode = oct shift;
1513 if (S_ISGITLINK($mode)) {
1514 return 'm---------';
1515 } elsif (S_ISDIR($mode & S_IFMT)) {
1516 return 'drwxr-xr-x';
1517 } elsif (S_ISLNK($mode)) {
1518 return 'lrwxrwxrwx';
1519 } elsif (S_ISREG($mode)) {
1520 # git cares only about the executable bit
1521 if ($mode & S_IXUSR) {
1522 return '-rwxr-xr-x';
1523 } else {
1524 return '-rw-r--r--';
1526 } else {
1527 return '----------';
1531 # convert file mode in octal to file type string
1532 sub file_type {
1533 my $mode = shift;
1535 if ($mode !~ m/^[0-7]+$/) {
1536 return $mode;
1537 } else {
1538 $mode = oct $mode;
1541 if (S_ISGITLINK($mode)) {
1542 return "submodule";
1543 } elsif (S_ISDIR($mode & S_IFMT)) {
1544 return "directory";
1545 } elsif (S_ISLNK($mode)) {
1546 return "symlink";
1547 } elsif (S_ISREG($mode)) {
1548 return "file";
1549 } else {
1550 return "unknown";
1554 # convert file mode in octal to file type description string
1555 sub file_type_long {
1556 my $mode = shift;
1558 if ($mode !~ m/^[0-7]+$/) {
1559 return $mode;
1560 } else {
1561 $mode = oct $mode;
1564 if (S_ISGITLINK($mode)) {
1565 return "submodule";
1566 } elsif (S_ISDIR($mode & S_IFMT)) {
1567 return "directory";
1568 } elsif (S_ISLNK($mode)) {
1569 return "symlink";
1570 } elsif (S_ISREG($mode)) {
1571 if ($mode & S_IXUSR) {
1572 return "executable";
1573 } else {
1574 return "file";
1576 } else {
1577 return "unknown";
1582 ## ----------------------------------------------------------------------
1583 ## functions returning short HTML fragments, or transforming HTML fragments
1584 ## which don't belong to other sections
1586 # format line of commit message.
1587 sub format_log_line_html {
1588 my $line = shift;
1590 $line = esc_html($line, -nbsp=>1);
1591 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1592 $cgi->a({-href => href(action=>"object", hash=>$1),
1593 -class => "text"}, $1);
1594 }eg;
1596 return $line;
1599 # format marker of refs pointing to given object
1601 # the destination action is chosen based on object type and current context:
1602 # - for annotated tags, we choose the tag view unless it's the current view
1603 # already, in which case we go to shortlog view
1604 # - for other refs, we keep the current view if we're in history, shortlog or
1605 # log view, and select shortlog otherwise
1606 sub format_ref_marker {
1607 my ($refs, $id) = @_;
1608 my $markers = '';
1610 if (defined $refs->{$id}) {
1611 foreach my $ref (@{$refs->{$id}}) {
1612 # this code exploits the fact that non-lightweight tags are the
1613 # only indirect objects, and that they are the only objects for which
1614 # we want to use tag instead of shortlog as action
1615 my ($type, $name) = qw();
1616 my $indirect = ($ref =~ s/\^\{\}$//);
1617 # e.g. tags/v2.6.11 or heads/next
1618 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1619 $type = $1;
1620 $name = $2;
1621 } else {
1622 $type = "ref";
1623 $name = $ref;
1626 my $class = $type;
1627 $class .= " indirect" if $indirect;
1629 my $dest_action = "shortlog";
1631 if ($indirect) {
1632 $dest_action = "tag" unless $action eq "tag";
1633 } elsif ($action =~ /^(history|(short)?log)$/) {
1634 $dest_action = $action;
1637 my $dest = "";
1638 $dest .= "refs/" unless $ref =~ m!^refs/!;
1639 $dest .= $ref;
1641 my $link = $cgi->a({
1642 -href => href(
1643 action=>$dest_action,
1644 hash=>$dest
1645 )}, $name);
1647 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1648 $link . "</span>";
1652 if ($markers) {
1653 return ' <span class="refs">'. $markers . '</span>';
1654 } else {
1655 return "";
1659 # format, perhaps shortened and with markers, title line
1660 sub format_subject_html {
1661 my ($long, $short, $href, $extra) = @_;
1662 $extra = '' unless defined($extra);
1664 if (length($short) < length($long)) {
1665 $long =~ s/[[:cntrl:]]/?/g;
1666 return $cgi->a({-href => $href, -class => "list subject",
1667 -title => to_utf8($long)},
1668 esc_html($short)) . $extra;
1669 } else {
1670 return $cgi->a({-href => $href, -class => "list subject"},
1671 esc_html($long)) . $extra;
1675 # Rather than recomputing the url for an email multiple times, we cache it
1676 # after the first hit. This gives a visible benefit in views where the avatar
1677 # for the same email is used repeatedly (e.g. shortlog).
1678 # The cache is shared by all avatar engines (currently gravatar only), which
1679 # are free to use it as preferred. Since only one avatar engine is used for any
1680 # given page, there's no risk for cache conflicts.
1681 our %avatar_cache = ();
1683 # Compute the picon url for a given email, by using the picon search service over at
1684 # http://www.cs.indiana.edu/picons/search.html
1685 sub picon_url {
1686 my $email = lc shift;
1687 if (!$avatar_cache{$email}) {
1688 my ($user, $domain) = split('@', $email);
1689 $avatar_cache{$email} =
1690 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1691 "$domain/$user/" .
1692 "users+domains+unknown/up/single";
1694 return $avatar_cache{$email};
1697 # Compute the gravatar url for a given email, if it's not in the cache already.
1698 # Gravatar stores only the part of the URL before the size, since that's the
1699 # one computationally more expensive. This also allows reuse of the cache for
1700 # different sizes (for this particular engine).
1701 sub gravatar_url {
1702 my $email = lc shift;
1703 my $size = shift;
1704 $avatar_cache{$email} ||=
1705 "http://www.gravatar.com/avatar/" .
1706 Digest::MD5::md5_hex($email) . "?s=";
1707 return $avatar_cache{$email} . $size;
1710 # Insert an avatar for the given $email at the given $size if the feature
1711 # is enabled.
1712 sub git_get_avatar {
1713 my ($email, %opts) = @_;
1714 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1715 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1716 $opts{-size} ||= 'default';
1717 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1718 my $url = "";
1719 if ($git_avatar eq 'gravatar') {
1720 $url = gravatar_url($email, $size);
1721 } elsif ($git_avatar eq 'picon') {
1722 $url = picon_url($email);
1724 # Other providers can be added by extending the if chain, defining $url
1725 # as needed. If no variant puts something in $url, we assume avatars
1726 # are completely disabled/unavailable.
1727 if ($url) {
1728 return $pre_white .
1729 "<img width=\"$size\" " .
1730 "class=\"avatar\" " .
1731 "src=\"$url\" " .
1732 "alt=\"\" " .
1733 "/>" . $post_white;
1734 } else {
1735 return "";
1739 sub format_search_author {
1740 my ($author, $searchtype, $displaytext) = @_;
1741 my $have_search = gitweb_check_feature('search');
1743 if ($have_search) {
1744 my $performed = "";
1745 if ($searchtype eq 'author') {
1746 $performed = "authored";
1747 } elsif ($searchtype eq 'committer') {
1748 $performed = "committed";
1751 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1752 searchtext=>$author,
1753 searchtype=>$searchtype), class=>"list",
1754 title=>"Search for commits $performed by $author"},
1755 $displaytext);
1757 } else {
1758 return $displaytext;
1762 # format the author name of the given commit with the given tag
1763 # the author name is chopped and escaped according to the other
1764 # optional parameters (see chop_str).
1765 sub format_author_html {
1766 my $tag = shift;
1767 my $co = shift;
1768 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1769 return "<$tag class=\"author\">" .
1770 format_search_author($co->{'author_name'}, "author",
1771 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1772 $author) .
1773 "</$tag>";
1776 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1777 sub format_git_diff_header_line {
1778 my $line = shift;
1779 my $diffinfo = shift;
1780 my ($from, $to) = @_;
1782 if ($diffinfo->{'nparents'}) {
1783 # combined diff
1784 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1785 if ($to->{'href'}) {
1786 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1787 esc_path($to->{'file'}));
1788 } else { # file was deleted (no href)
1789 $line .= esc_path($to->{'file'});
1791 } else {
1792 # "ordinary" diff
1793 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1794 if ($from->{'href'}) {
1795 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1796 'a/' . esc_path($from->{'file'}));
1797 } else { # file was added (no href)
1798 $line .= 'a/' . esc_path($from->{'file'});
1800 $line .= ' ';
1801 if ($to->{'href'}) {
1802 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1803 'b/' . esc_path($to->{'file'}));
1804 } else { # file was deleted
1805 $line .= 'b/' . esc_path($to->{'file'});
1809 return "<div class=\"diff header\">$line</div>\n";
1812 # format extended diff header line, before patch itself
1813 sub format_extended_diff_header_line {
1814 my $line = shift;
1815 my $diffinfo = shift;
1816 my ($from, $to) = @_;
1818 # match <path>
1819 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1820 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1821 esc_path($from->{'file'}));
1823 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1824 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1825 esc_path($to->{'file'}));
1827 # match single <mode>
1828 if ($line =~ m/\s(\d{6})$/) {
1829 $line .= '<span class="info"> (' .
1830 file_type_long($1) .
1831 ')</span>';
1833 # match <hash>
1834 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1835 # can match only for combined diff
1836 $line = 'index ';
1837 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1838 if ($from->{'href'}[$i]) {
1839 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1840 -class=>"hash"},
1841 substr($diffinfo->{'from_id'}[$i],0,7));
1842 } else {
1843 $line .= '0' x 7;
1845 # separator
1846 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1848 $line .= '..';
1849 if ($to->{'href'}) {
1850 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1851 substr($diffinfo->{'to_id'},0,7));
1852 } else {
1853 $line .= '0' x 7;
1856 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1857 # can match only for ordinary diff
1858 my ($from_link, $to_link);
1859 if ($from->{'href'}) {
1860 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1861 substr($diffinfo->{'from_id'},0,7));
1862 } else {
1863 $from_link = '0' x 7;
1865 if ($to->{'href'}) {
1866 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1867 substr($diffinfo->{'to_id'},0,7));
1868 } else {
1869 $to_link = '0' x 7;
1871 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1872 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1875 return $line . "<br/>\n";
1878 # format from-file/to-file diff header
1879 sub format_diff_from_to_header {
1880 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1881 my $line;
1882 my $result = '';
1884 $line = $from_line;
1885 #assert($line =~ m/^---/) if DEBUG;
1886 # no extra formatting for "^--- /dev/null"
1887 if (! $diffinfo->{'nparents'}) {
1888 # ordinary (single parent) diff
1889 if ($line =~ m!^--- "?a/!) {
1890 if ($from->{'href'}) {
1891 $line = '--- a/' .
1892 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1893 esc_path($from->{'file'}));
1894 } else {
1895 $line = '--- a/' .
1896 esc_path($from->{'file'});
1899 $result .= qq!<div class="diff from_file">$line</div>\n!;
1901 } else {
1902 # combined diff (merge commit)
1903 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1904 if ($from->{'href'}[$i]) {
1905 $line = '--- ' .
1906 $cgi->a({-href=>href(action=>"blobdiff",
1907 hash_parent=>$diffinfo->{'from_id'}[$i],
1908 hash_parent_base=>$parents[$i],
1909 file_parent=>$from->{'file'}[$i],
1910 hash=>$diffinfo->{'to_id'},
1911 hash_base=>$hash,
1912 file_name=>$to->{'file'}),
1913 -class=>"path",
1914 -title=>"diff" . ($i+1)},
1915 $i+1) .
1916 '/' .
1917 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1918 esc_path($from->{'file'}[$i]));
1919 } else {
1920 $line = '--- /dev/null';
1922 $result .= qq!<div class="diff from_file">$line</div>\n!;
1926 $line = $to_line;
1927 #assert($line =~ m/^\+\+\+/) if DEBUG;
1928 # no extra formatting for "^+++ /dev/null"
1929 if ($line =~ m!^\+\+\+ "?b/!) {
1930 if ($to->{'href'}) {
1931 $line = '+++ b/' .
1932 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1933 esc_path($to->{'file'}));
1934 } else {
1935 $line = '+++ b/' .
1936 esc_path($to->{'file'});
1939 $result .= qq!<div class="diff to_file">$line</div>\n!;
1941 return $result;
1944 # create note for patch simplified by combined diff
1945 sub format_diff_cc_simplified {
1946 my ($diffinfo, @parents) = @_;
1947 my $result = '';
1949 $result .= "<div class=\"diff header\">" .
1950 "diff --cc ";
1951 if (!is_deleted($diffinfo)) {
1952 $result .= $cgi->a({-href => href(action=>"blob",
1953 hash_base=>$hash,
1954 hash=>$diffinfo->{'to_id'},
1955 file_name=>$diffinfo->{'to_file'}),
1956 -class => "path"},
1957 esc_path($diffinfo->{'to_file'}));
1958 } else {
1959 $result .= esc_path($diffinfo->{'to_file'});
1961 $result .= "</div>\n" . # class="diff header"
1962 "<div class=\"diff nodifferences\">" .
1963 "Simple merge" .
1964 "</div>\n"; # class="diff nodifferences"
1966 return $result;
1969 # format patch (diff) line (not to be used for diff headers)
1970 sub format_diff_line {
1971 my $line = shift;
1972 my ($from, $to) = @_;
1973 my $diff_class = "";
1975 chomp $line;
1977 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1978 # combined diff
1979 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1980 if ($line =~ m/^\@{3}/) {
1981 $diff_class = " chunk_header";
1982 } elsif ($line =~ m/^\\/) {
1983 $diff_class = " incomplete";
1984 } elsif ($prefix =~ tr/+/+/) {
1985 $diff_class = " add";
1986 } elsif ($prefix =~ tr/-/-/) {
1987 $diff_class = " rem";
1989 } else {
1990 # assume ordinary diff
1991 my $char = substr($line, 0, 1);
1992 if ($char eq '+') {
1993 $diff_class = " add";
1994 } elsif ($char eq '-') {
1995 $diff_class = " rem";
1996 } elsif ($char eq '@') {
1997 $diff_class = " chunk_header";
1998 } elsif ($char eq "\\") {
1999 $diff_class = " incomplete";
2002 $line = untabify($line);
2003 if ($from && $to && $line =~ m/^\@{2} /) {
2004 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2005 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2007 $from_lines = 0 unless defined $from_lines;
2008 $to_lines = 0 unless defined $to_lines;
2010 if ($from->{'href'}) {
2011 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2012 -class=>"list"}, $from_text);
2014 if ($to->{'href'}) {
2015 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2016 -class=>"list"}, $to_text);
2018 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2019 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2020 return "<div class=\"diff$diff_class\">$line</div>\n";
2021 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2022 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2023 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2025 @from_text = split(' ', $ranges);
2026 for (my $i = 0; $i < @from_text; ++$i) {
2027 ($from_start[$i], $from_nlines[$i]) =
2028 (split(',', substr($from_text[$i], 1)), 0);
2031 $to_text = pop @from_text;
2032 $to_start = pop @from_start;
2033 $to_nlines = pop @from_nlines;
2035 $line = "<span class=\"chunk_info\">$prefix ";
2036 for (my $i = 0; $i < @from_text; ++$i) {
2037 if ($from->{'href'}[$i]) {
2038 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2039 -class=>"list"}, $from_text[$i]);
2040 } else {
2041 $line .= $from_text[$i];
2043 $line .= " ";
2045 if ($to->{'href'}) {
2046 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2047 -class=>"list"}, $to_text);
2048 } else {
2049 $line .= $to_text;
2051 $line .= " $prefix</span>" .
2052 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2053 return "<div class=\"diff$diff_class\">$line</div>\n";
2055 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2058 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2059 # linked. Pass the hash of the tree/commit to snapshot.
2060 sub format_snapshot_links {
2061 my ($hash) = @_;
2062 my $num_fmts = @snapshot_fmts;
2063 if ($num_fmts > 1) {
2064 # A parenthesized list of links bearing format names.
2065 # e.g. "snapshot (_tar.gz_ _zip_)"
2066 return "snapshot (" . join(' ', map
2067 $cgi->a({
2068 -href => href(
2069 action=>"snapshot",
2070 hash=>$hash,
2071 snapshot_format=>$_
2073 }, $known_snapshot_formats{$_}{'display'})
2074 , @snapshot_fmts) . ")";
2075 } elsif ($num_fmts == 1) {
2076 # A single "snapshot" link whose tooltip bears the format name.
2077 # i.e. "_snapshot_"
2078 my ($fmt) = @snapshot_fmts;
2079 return
2080 $cgi->a({
2081 -href => href(
2082 action=>"snapshot",
2083 hash=>$hash,
2084 snapshot_format=>$fmt
2086 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2087 }, "snapshot");
2088 } else { # $num_fmts == 0
2089 return undef;
2093 ## ......................................................................
2094 ## functions returning values to be passed, perhaps after some
2095 ## transformation, to other functions; e.g. returning arguments to href()
2097 # returns hash to be passed to href to generate gitweb URL
2098 # in -title key it returns description of link
2099 sub get_feed_info {
2100 my $format = shift || 'Atom';
2101 my %res = (action => lc($format));
2103 # feed links are possible only for project views
2104 return unless (defined $project);
2105 # some views should link to OPML, or to generic project feed,
2106 # or don't have specific feed yet (so they should use generic)
2107 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2109 my $branch;
2110 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2111 # from tag links; this also makes possible to detect branch links
2112 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2113 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2114 $branch = $1;
2116 # find log type for feed description (title)
2117 my $type = 'log';
2118 if (defined $file_name) {
2119 $type = "history of $file_name";
2120 $type .= "/" if ($action eq 'tree');
2121 $type .= " on '$branch'" if (defined $branch);
2122 } else {
2123 $type = "log of $branch" if (defined $branch);
2126 $res{-title} = $type;
2127 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2128 $res{'file_name'} = $file_name;
2130 return %res;
2133 ## ----------------------------------------------------------------------
2134 ## git utility subroutines, invoking git commands
2136 # returns path to the core git executable and the --git-dir parameter as list
2137 sub git_cmd {
2138 $number_of_git_cmds++;
2139 return $GIT, '--git-dir='.$git_dir;
2142 # quote the given arguments for passing them to the shell
2143 # quote_command("command", "arg 1", "arg with ' and ! characters")
2144 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2145 # Try to avoid using this function wherever possible.
2146 sub quote_command {
2147 return join(' ',
2148 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2151 # get HEAD ref of given project as hash
2152 sub git_get_head_hash {
2153 return git_get_full_hash(shift, 'HEAD');
2156 sub git_get_full_hash {
2157 return git_get_hash(@_);
2160 sub git_get_short_hash {
2161 return git_get_hash(@_, '--short=7');
2164 sub git_get_hash {
2165 my ($project, $hash, @options) = @_;
2166 my $o_git_dir = $git_dir;
2167 my $retval = undef;
2168 $git_dir = "$projectroot/$project";
2169 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2170 '--verify', '-q', @options, $hash) {
2171 $retval = <$fd>;
2172 chomp $retval if defined $retval;
2173 close $fd;
2175 if (defined $o_git_dir) {
2176 $git_dir = $o_git_dir;
2178 return $retval;
2181 # get type of given object
2182 sub git_get_type {
2183 my $hash = shift;
2185 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2186 my $type = <$fd>;
2187 close $fd or return;
2188 chomp $type;
2189 return $type;
2192 # repository configuration
2193 our $config_file = '';
2194 our %config;
2196 # store multiple values for single key as anonymous array reference
2197 # single values stored directly in the hash, not as [ <value> ]
2198 sub hash_set_multi {
2199 my ($hash, $key, $value) = @_;
2201 if (!exists $hash->{$key}) {
2202 $hash->{$key} = $value;
2203 } elsif (!ref $hash->{$key}) {
2204 $hash->{$key} = [ $hash->{$key}, $value ];
2205 } else {
2206 push @{$hash->{$key}}, $value;
2210 # return hash of git project configuration
2211 # optionally limited to some section, e.g. 'gitweb'
2212 sub git_parse_project_config {
2213 my $section_regexp = shift;
2214 my %config;
2216 local $/ = "\0";
2218 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2219 or return;
2221 while (my $keyval = <$fh>) {
2222 chomp $keyval;
2223 my ($key, $value) = split(/\n/, $keyval, 2);
2225 hash_set_multi(\%config, $key, $value)
2226 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2228 close $fh;
2230 return %config;
2233 # convert config value to boolean: 'true' or 'false'
2234 # no value, number > 0, 'true' and 'yes' values are true
2235 # rest of values are treated as false (never as error)
2236 sub config_to_bool {
2237 my $val = shift;
2239 return 1 if !defined $val; # section.key
2241 # strip leading and trailing whitespace
2242 $val =~ s/^\s+//;
2243 $val =~ s/\s+$//;
2245 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2246 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2249 # convert config value to simple decimal number
2250 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2251 # to be multiplied by 1024, 1048576, or 1073741824
2252 sub config_to_int {
2253 my $val = shift;
2255 # strip leading and trailing whitespace
2256 $val =~ s/^\s+//;
2257 $val =~ s/\s+$//;
2259 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2260 $unit = lc($unit);
2261 # unknown unit is treated as 1
2262 return $num * ($unit eq 'g' ? 1073741824 :
2263 $unit eq 'm' ? 1048576 :
2264 $unit eq 'k' ? 1024 : 1);
2266 return $val;
2269 # convert config value to array reference, if needed
2270 sub config_to_multi {
2271 my $val = shift;
2273 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2276 sub git_get_project_config {
2277 my ($key, $type) = @_;
2279 # key sanity check
2280 return unless ($key);
2281 $key =~ s/^gitweb\.//;
2282 return if ($key =~ m/\W/);
2284 # type sanity check
2285 if (defined $type) {
2286 $type =~ s/^--//;
2287 $type = undef
2288 unless ($type eq 'bool' || $type eq 'int');
2291 # get config
2292 if (!defined $config_file ||
2293 $config_file ne "$git_dir/config") {
2294 %config = git_parse_project_config('gitweb');
2295 $config_file = "$git_dir/config";
2298 # check if config variable (key) exists
2299 return unless exists $config{"gitweb.$key"};
2301 # ensure given type
2302 if (!defined $type) {
2303 return $config{"gitweb.$key"};
2304 } elsif ($type eq 'bool') {
2305 # backward compatibility: 'git config --bool' returns true/false
2306 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2307 } elsif ($type eq 'int') {
2308 return config_to_int($config{"gitweb.$key"});
2310 return $config{"gitweb.$key"};
2313 # get hash of given path at given ref
2314 sub git_get_hash_by_path {
2315 my $base = shift;
2316 my $path = shift || return undef;
2317 my $type = shift;
2319 $path =~ s,/+$,,;
2321 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2322 or die_error(500, "Open git-ls-tree failed");
2323 my $line = <$fd>;
2324 close $fd or return undef;
2326 if (!defined $line) {
2327 # there is no tree or hash given by $path at $base
2328 return undef;
2331 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2332 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2333 if (defined $type && $type ne $2) {
2334 # type doesn't match
2335 return undef;
2337 return $3;
2340 # get path of entry with given hash at given tree-ish (ref)
2341 # used to get 'from' filename for combined diff (merge commit) for renames
2342 sub git_get_path_by_hash {
2343 my $base = shift || return;
2344 my $hash = shift || return;
2346 local $/ = "\0";
2348 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2349 or return undef;
2350 while (my $line = <$fd>) {
2351 chomp $line;
2353 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2354 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2355 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2356 close $fd;
2357 return $1;
2360 close $fd;
2361 return undef;
2364 ## ......................................................................
2365 ## git utility functions, directly accessing git repository
2367 sub git_get_project_description {
2368 my $path = shift;
2370 $git_dir = "$projectroot/$path";
2371 open my $fd, '<', "$git_dir/description"
2372 or return git_get_project_config('description');
2373 my $descr = <$fd>;
2374 close $fd;
2375 if (defined $descr) {
2376 chomp $descr;
2378 return $descr;
2381 sub git_get_project_ctags {
2382 my $path = shift;
2383 my $ctags = {};
2385 $git_dir = "$projectroot/$path";
2386 opendir my $dh, "$git_dir/ctags"
2387 or return $ctags;
2388 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2389 open my $ct, '<', $_ or next;
2390 my $val = <$ct>;
2391 chomp $val;
2392 close $ct;
2393 my $ctag = $_; $ctag =~ s#.*/##;
2394 $ctags->{$ctag} = $val;
2396 closedir $dh;
2397 $ctags;
2400 sub git_populate_project_tagcloud {
2401 my $ctags = shift;
2403 # First, merge different-cased tags; tags vote on casing
2404 my %ctags_lc;
2405 foreach (keys %$ctags) {
2406 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2407 if (not $ctags_lc{lc $_}->{topcount}
2408 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2409 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2410 $ctags_lc{lc $_}->{topname} = $_;
2414 my $cloud;
2415 if (eval { require HTML::TagCloud; 1; }) {
2416 $cloud = HTML::TagCloud->new;
2417 foreach (sort keys %ctags_lc) {
2418 # Pad the title with spaces so that the cloud looks
2419 # less crammed.
2420 my $title = $ctags_lc{$_}->{topname};
2421 $title =~ s/ /&nbsp;/g;
2422 $title =~ s/^/&nbsp;/g;
2423 $title =~ s/$/&nbsp;/g;
2424 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2426 } else {
2427 $cloud = \%ctags_lc;
2429 $cloud;
2432 sub git_show_project_tagcloud {
2433 my ($cloud, $count) = @_;
2434 print STDERR ref($cloud)."..\n";
2435 if (ref $cloud eq 'HTML::TagCloud') {
2436 return $cloud->html_and_css($count);
2437 } else {
2438 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2439 return '<p align="center">' . join (', ', map {
2440 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2441 } splice(@tags, 0, $count)) . '</p>';
2445 sub git_get_project_url_list {
2446 my $path = shift;
2448 $git_dir = "$projectroot/$path";
2449 open my $fd, '<', "$git_dir/cloneurl"
2450 or return wantarray ?
2451 @{ config_to_multi(git_get_project_config('url')) } :
2452 config_to_multi(git_get_project_config('url'));
2453 my @git_project_url_list = map { chomp; $_ } <$fd>;
2454 close $fd;
2456 return wantarray ? @git_project_url_list : \@git_project_url_list;
2459 sub git_get_projects_list {
2460 my ($filter) = @_;
2461 my @list;
2463 $filter ||= '';
2464 $filter =~ s/\.git$//;
2466 my $check_forks = gitweb_check_feature('forks');
2468 if (-d $projects_list) {
2469 # search in directory
2470 my $dir = $projects_list . ($filter ? "/$filter" : '');
2471 # remove the trailing "/"
2472 $dir =~ s!/+$!!;
2473 my $pfxlen = length("$dir");
2474 my $pfxdepth = ($dir =~ tr!/!!);
2476 File::Find::find({
2477 follow_fast => 1, # follow symbolic links
2478 follow_skip => 2, # ignore duplicates
2479 dangling_symlinks => 0, # ignore dangling symlinks, silently
2480 wanted => sub {
2481 # skip project-list toplevel, if we get it.
2482 return if (m!^[/.]$!);
2483 # only directories can be git repositories
2484 return unless (-d $_);
2485 # don't traverse too deep (Find is super slow on os x)
2486 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2487 $File::Find::prune = 1;
2488 return;
2491 my $subdir = substr($File::Find::name, $pfxlen + 1);
2492 # we check related file in $projectroot
2493 my $path = ($filter ? "$filter/" : '') . $subdir;
2494 if (check_export_ok("$projectroot/$path")) {
2495 push @list, { path => $path };
2496 $File::Find::prune = 1;
2499 }, "$dir");
2501 } elsif (-f $projects_list) {
2502 # read from file(url-encoded):
2503 # 'git%2Fgit.git Linus+Torvalds'
2504 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2505 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2506 my %paths;
2507 open my $fd, '<', $projects_list or return;
2508 PROJECT:
2509 while (my $line = <$fd>) {
2510 chomp $line;
2511 my ($path, $owner) = split ' ', $line;
2512 $path = unescape($path);
2513 $owner = unescape($owner);
2514 if (!defined $path) {
2515 next;
2517 if ($filter ne '') {
2518 # looking for forks;
2519 my $pfx = substr($path, 0, length($filter));
2520 if ($pfx ne $filter) {
2521 next PROJECT;
2523 my $sfx = substr($path, length($filter));
2524 if ($sfx !~ /^\/.*\.git$/) {
2525 next PROJECT;
2527 } elsif ($check_forks) {
2528 PATH:
2529 foreach my $filter (keys %paths) {
2530 # looking for forks;
2531 my $pfx = substr($path, 0, length($filter));
2532 if ($pfx ne $filter) {
2533 next PATH;
2535 my $sfx = substr($path, length($filter));
2536 if ($sfx !~ /^\/.*\.git$/) {
2537 next PATH;
2539 # is a fork, don't include it in
2540 # the list
2541 next PROJECT;
2544 if (check_export_ok("$projectroot/$path")) {
2545 my $pr = {
2546 path => $path,
2547 owner => to_utf8($owner),
2549 push @list, $pr;
2550 (my $forks_path = $path) =~ s/\.git$//;
2551 $paths{$forks_path}++;
2554 close $fd;
2556 return @list;
2559 our $gitweb_project_owner = undef;
2560 sub git_get_project_list_from_file {
2562 return if (defined $gitweb_project_owner);
2564 $gitweb_project_owner = {};
2565 # read from file (url-encoded):
2566 # 'git%2Fgit.git Linus+Torvalds'
2567 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2568 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2569 if (-f $projects_list) {
2570 open(my $fd, '<', $projects_list);
2571 while (my $line = <$fd>) {
2572 chomp $line;
2573 my ($pr, $ow) = split ' ', $line;
2574 $pr = unescape($pr);
2575 $ow = unescape($ow);
2576 $gitweb_project_owner->{$pr} = to_utf8($ow);
2578 close $fd;
2582 sub git_get_project_owner {
2583 my $project = shift;
2584 my $owner;
2586 return undef unless $project;
2587 $git_dir = "$projectroot/$project";
2589 if (!defined $gitweb_project_owner) {
2590 git_get_project_list_from_file();
2593 if (exists $gitweb_project_owner->{$project}) {
2594 $owner = $gitweb_project_owner->{$project};
2596 if (!defined $owner){
2597 $owner = git_get_project_config('owner');
2599 if (!defined $owner) {
2600 $owner = get_file_owner("$git_dir");
2603 return $owner;
2606 sub git_get_last_activity {
2607 my ($path) = @_;
2608 my $fd;
2610 $git_dir = "$projectroot/$path";
2611 open($fd, "-|", git_cmd(), 'for-each-ref',
2612 '--format=%(committer)',
2613 '--sort=-committerdate',
2614 '--count=1',
2615 'refs/heads') or return;
2616 my $most_recent = <$fd>;
2617 close $fd or return;
2618 if (defined $most_recent &&
2619 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2620 my $timestamp = $1;
2621 my $age = time - $timestamp;
2622 return ($age, age_string($age));
2624 return (undef, undef);
2627 sub git_get_references {
2628 my $type = shift || "";
2629 my %refs;
2630 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2631 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2632 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2633 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2634 or return;
2636 while (my $line = <$fd>) {
2637 chomp $line;
2638 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2639 if (defined $refs{$1}) {
2640 push @{$refs{$1}}, $2;
2641 } else {
2642 $refs{$1} = [ $2 ];
2646 close $fd or return;
2647 return \%refs;
2650 sub git_get_rev_name_tags {
2651 my $hash = shift || return undef;
2653 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2654 or return;
2655 my $name_rev = <$fd>;
2656 close $fd;
2658 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2659 return $1;
2660 } else {
2661 # catches also '$hash undefined' output
2662 return undef;
2666 ## ----------------------------------------------------------------------
2667 ## parse to hash functions
2669 sub parse_date {
2670 my $epoch = shift;
2671 my $tz = shift || "-0000";
2673 my %date;
2674 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2675 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2676 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2677 $date{'hour'} = $hour;
2678 $date{'minute'} = $min;
2679 $date{'mday'} = $mday;
2680 $date{'day'} = $days[$wday];
2681 $date{'month'} = $months[$mon];
2682 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2683 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2684 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2685 $mday, $months[$mon], $hour ,$min;
2686 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2687 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2689 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2690 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2691 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2692 $date{'hour_local'} = $hour;
2693 $date{'minute_local'} = $min;
2694 $date{'tz_local'} = $tz;
2695 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2696 1900+$year, $mon+1, $mday,
2697 $hour, $min, $sec, $tz);
2698 return %date;
2701 sub parse_tag {
2702 my $tag_id = shift;
2703 my %tag;
2704 my @comment;
2706 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2707 $tag{'id'} = $tag_id;
2708 while (my $line = <$fd>) {
2709 chomp $line;
2710 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2711 $tag{'object'} = $1;
2712 } elsif ($line =~ m/^type (.+)$/) {
2713 $tag{'type'} = $1;
2714 } elsif ($line =~ m/^tag (.+)$/) {
2715 $tag{'name'} = $1;
2716 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2717 $tag{'author'} = $1;
2718 $tag{'author_epoch'} = $2;
2719 $tag{'author_tz'} = $3;
2720 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2721 $tag{'author_name'} = $1;
2722 $tag{'author_email'} = $2;
2723 } else {
2724 $tag{'author_name'} = $tag{'author'};
2726 } elsif ($line =~ m/--BEGIN/) {
2727 push @comment, $line;
2728 last;
2729 } elsif ($line eq "") {
2730 last;
2733 push @comment, <$fd>;
2734 $tag{'comment'} = \@comment;
2735 close $fd or return;
2736 if (!defined $tag{'name'}) {
2737 return
2739 return %tag
2742 sub parse_commit_text {
2743 my ($commit_text, $withparents) = @_;
2744 my @commit_lines = split '\n', $commit_text;
2745 my %co;
2747 pop @commit_lines; # Remove '\0'
2749 if (! @commit_lines) {
2750 return;
2753 my $header = shift @commit_lines;
2754 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2755 return;
2757 ($co{'id'}, my @parents) = split ' ', $header;
2758 while (my $line = shift @commit_lines) {
2759 last if $line eq "\n";
2760 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2761 $co{'tree'} = $1;
2762 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2763 push @parents, $1;
2764 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2765 $co{'author'} = to_utf8($1);
2766 $co{'author_epoch'} = $2;
2767 $co{'author_tz'} = $3;
2768 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2769 $co{'author_name'} = $1;
2770 $co{'author_email'} = $2;
2771 } else {
2772 $co{'author_name'} = $co{'author'};
2774 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2775 $co{'committer'} = to_utf8($1);
2776 $co{'committer_epoch'} = $2;
2777 $co{'committer_tz'} = $3;
2778 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2779 $co{'committer_name'} = $1;
2780 $co{'committer_email'} = $2;
2781 } else {
2782 $co{'committer_name'} = $co{'committer'};
2786 if (!defined $co{'tree'}) {
2787 return;
2789 $co{'parents'} = \@parents;
2790 $co{'parent'} = $parents[0];
2792 foreach my $title (@commit_lines) {
2793 $title =~ s/^ //;
2794 if ($title ne "") {
2795 $co{'title'} = chop_str($title, 80, 5);
2796 # remove leading stuff of merges to make the interesting part visible
2797 if (length($title) > 50) {
2798 $title =~ s/^Automatic //;
2799 $title =~ s/^merge (of|with) /Merge ... /i;
2800 if (length($title) > 50) {
2801 $title =~ s/(http|rsync):\/\///;
2803 if (length($title) > 50) {
2804 $title =~ s/(master|www|rsync)\.//;
2806 if (length($title) > 50) {
2807 $title =~ s/kernel.org:?//;
2809 if (length($title) > 50) {
2810 $title =~ s/\/pub\/scm//;
2813 $co{'title_short'} = chop_str($title, 50, 5);
2814 last;
2817 if (! defined $co{'title'} || $co{'title'} eq "") {
2818 $co{'title'} = $co{'title_short'} = '(no commit message)';
2820 # remove added spaces
2821 foreach my $line (@commit_lines) {
2822 $line =~ s/^ //;
2824 $co{'comment'} = \@commit_lines;
2826 my $age = time - $co{'committer_epoch'};
2827 $co{'age'} = $age;
2828 $co{'age_string'} = age_string($age);
2829 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2830 if ($age > 60*60*24*7*2) {
2831 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2832 $co{'age_string_age'} = $co{'age_string'};
2833 } else {
2834 $co{'age_string_date'} = $co{'age_string'};
2835 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2837 return %co;
2840 sub parse_commit {
2841 my ($commit_id) = @_;
2842 my %co;
2844 local $/ = "\0";
2846 open my $fd, "-|", git_cmd(), "rev-list",
2847 "--parents",
2848 "--header",
2849 "--max-count=1",
2850 $commit_id,
2851 "--",
2852 or die_error(500, "Open git-rev-list failed");
2853 %co = parse_commit_text(<$fd>, 1);
2854 close $fd;
2856 return %co;
2859 sub parse_commits {
2860 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2861 my @cos;
2863 $maxcount ||= 1;
2864 $skip ||= 0;
2866 local $/ = "\0";
2868 open my $fd, "-|", git_cmd(), "rev-list",
2869 "--header",
2870 @args,
2871 ("--max-count=" . $maxcount),
2872 ("--skip=" . $skip),
2873 @extra_options,
2874 $commit_id,
2875 "--",
2876 ($filename ? ($filename) : ())
2877 or die_error(500, "Open git-rev-list failed");
2878 while (my $line = <$fd>) {
2879 my %co = parse_commit_text($line);
2880 push @cos, \%co;
2882 close $fd;
2884 return wantarray ? @cos : \@cos;
2887 # parse line of git-diff-tree "raw" output
2888 sub parse_difftree_raw_line {
2889 my $line = shift;
2890 my %res;
2892 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2893 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2894 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2895 $res{'from_mode'} = $1;
2896 $res{'to_mode'} = $2;
2897 $res{'from_id'} = $3;
2898 $res{'to_id'} = $4;
2899 $res{'status'} = $5;
2900 $res{'similarity'} = $6;
2901 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2902 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2903 } else {
2904 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2907 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2908 # combined diff (for merge commit)
2909 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2910 $res{'nparents'} = length($1);
2911 $res{'from_mode'} = [ split(' ', $2) ];
2912 $res{'to_mode'} = pop @{$res{'from_mode'}};
2913 $res{'from_id'} = [ split(' ', $3) ];
2914 $res{'to_id'} = pop @{$res{'from_id'}};
2915 $res{'status'} = [ split('', $4) ];
2916 $res{'to_file'} = unquote($5);
2918 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2919 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2920 $res{'commit'} = $1;
2923 return wantarray ? %res : \%res;
2926 # wrapper: return parsed line of git-diff-tree "raw" output
2927 # (the argument might be raw line, or parsed info)
2928 sub parsed_difftree_line {
2929 my $line_or_ref = shift;
2931 if (ref($line_or_ref) eq "HASH") {
2932 # pre-parsed (or generated by hand)
2933 return $line_or_ref;
2934 } else {
2935 return parse_difftree_raw_line($line_or_ref);
2939 # parse line of git-ls-tree output
2940 sub parse_ls_tree_line {
2941 my $line = shift;
2942 my %opts = @_;
2943 my %res;
2945 if ($opts{'-l'}) {
2946 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
2947 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
2949 $res{'mode'} = $1;
2950 $res{'type'} = $2;
2951 $res{'hash'} = $3;
2952 $res{'size'} = $4;
2953 if ($opts{'-z'}) {
2954 $res{'name'} = $5;
2955 } else {
2956 $res{'name'} = unquote($5);
2958 } else {
2959 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2960 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2962 $res{'mode'} = $1;
2963 $res{'type'} = $2;
2964 $res{'hash'} = $3;
2965 if ($opts{'-z'}) {
2966 $res{'name'} = $4;
2967 } else {
2968 $res{'name'} = unquote($4);
2972 return wantarray ? %res : \%res;
2975 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2976 sub parse_from_to_diffinfo {
2977 my ($diffinfo, $from, $to, @parents) = @_;
2979 if ($diffinfo->{'nparents'}) {
2980 # combined diff
2981 $from->{'file'} = [];
2982 $from->{'href'} = [];
2983 fill_from_file_info($diffinfo, @parents)
2984 unless exists $diffinfo->{'from_file'};
2985 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2986 $from->{'file'}[$i] =
2987 defined $diffinfo->{'from_file'}[$i] ?
2988 $diffinfo->{'from_file'}[$i] :
2989 $diffinfo->{'to_file'};
2990 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2991 $from->{'href'}[$i] = href(action=>"blob",
2992 hash_base=>$parents[$i],
2993 hash=>$diffinfo->{'from_id'}[$i],
2994 file_name=>$from->{'file'}[$i]);
2995 } else {
2996 $from->{'href'}[$i] = undef;
2999 } else {
3000 # ordinary (not combined) diff
3001 $from->{'file'} = $diffinfo->{'from_file'};
3002 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3003 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3004 hash=>$diffinfo->{'from_id'},
3005 file_name=>$from->{'file'});
3006 } else {
3007 delete $from->{'href'};
3011 $to->{'file'} = $diffinfo->{'to_file'};
3012 if (!is_deleted($diffinfo)) { # file exists in result
3013 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3014 hash=>$diffinfo->{'to_id'},
3015 file_name=>$to->{'file'});
3016 } else {
3017 delete $to->{'href'};
3021 ## ......................................................................
3022 ## parse to array of hashes functions
3024 sub git_get_heads_list {
3025 my $limit = shift;
3026 my @headslist;
3028 open my $fd, '-|', git_cmd(), 'for-each-ref',
3029 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3030 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3031 'refs/heads'
3032 or return;
3033 while (my $line = <$fd>) {
3034 my %ref_item;
3036 chomp $line;
3037 my ($refinfo, $committerinfo) = split(/\0/, $line);
3038 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3039 my ($committer, $epoch, $tz) =
3040 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3041 $ref_item{'fullname'} = $name;
3042 $name =~ s!^refs/heads/!!;
3044 $ref_item{'name'} = $name;
3045 $ref_item{'id'} = $hash;
3046 $ref_item{'title'} = $title || '(no commit message)';
3047 $ref_item{'epoch'} = $epoch;
3048 if ($epoch) {
3049 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3050 } else {
3051 $ref_item{'age'} = "unknown";
3054 push @headslist, \%ref_item;
3056 close $fd;
3058 return wantarray ? @headslist : \@headslist;
3061 sub git_get_tags_list {
3062 my $limit = shift;
3063 my @tagslist;
3065 open my $fd, '-|', git_cmd(), 'for-each-ref',
3066 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3067 '--format=%(objectname) %(objecttype) %(refname) '.
3068 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3069 'refs/tags'
3070 or return;
3071 while (my $line = <$fd>) {
3072 my %ref_item;
3074 chomp $line;
3075 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3076 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3077 my ($creator, $epoch, $tz) =
3078 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3079 $ref_item{'fullname'} = $name;
3080 $name =~ s!^refs/tags/!!;
3082 $ref_item{'type'} = $type;
3083 $ref_item{'id'} = $id;
3084 $ref_item{'name'} = $name;
3085 if ($type eq "tag") {
3086 $ref_item{'subject'} = $title;
3087 $ref_item{'reftype'} = $reftype;
3088 $ref_item{'refid'} = $refid;
3089 } else {
3090 $ref_item{'reftype'} = $type;
3091 $ref_item{'refid'} = $id;
3094 if ($type eq "tag" || $type eq "commit") {
3095 $ref_item{'epoch'} = $epoch;
3096 if ($epoch) {
3097 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3098 } else {
3099 $ref_item{'age'} = "unknown";
3103 push @tagslist, \%ref_item;
3105 close $fd;
3107 return wantarray ? @tagslist : \@tagslist;
3110 ## ----------------------------------------------------------------------
3111 ## filesystem-related functions
3113 sub get_file_owner {
3114 my $path = shift;
3116 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3117 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3118 if (!defined $gcos) {
3119 return undef;
3121 my $owner = $gcos;
3122 $owner =~ s/[,;].*$//;
3123 return to_utf8($owner);
3126 # assume that file exists
3127 sub insert_file {
3128 my $filename = shift;
3130 open my $fd, '<', $filename;
3131 print {$out} map { to_utf8($_) } <$fd>;
3132 close $fd;
3135 ## ......................................................................
3136 ## mimetype related functions
3138 sub mimetype_guess_file {
3139 my $filename = shift;
3140 my $mimemap = shift;
3141 -r $mimemap or return undef;
3143 my %mimemap;
3144 open(my $mh, '<', $mimemap) or return undef;
3145 while (<$mh>) {
3146 next if m/^#/; # skip comments
3147 my ($mimetype, $exts) = split(/\t+/);
3148 if (defined $exts) {
3149 my @exts = split(/\s+/, $exts);
3150 foreach my $ext (@exts) {
3151 $mimemap{$ext} = $mimetype;
3155 close($mh);
3157 $filename =~ /\.([^.]*)$/;
3158 return $mimemap{$1};
3161 sub mimetype_guess {
3162 my $filename = shift;
3163 my $mime;
3164 $filename =~ /\./ or return undef;
3166 if ($mimetypes_file) {
3167 my $file = $mimetypes_file;
3168 if ($file !~ m!^/!) { # if it is relative path
3169 # it is relative to project
3170 $file = "$projectroot/$project/$file";
3172 $mime = mimetype_guess_file($filename, $file);
3174 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3175 return $mime;
3178 sub blob_mimetype {
3179 my $fd = shift;
3180 my $filename = shift;
3182 if ($filename) {
3183 my $mime = mimetype_guess($filename);
3184 $mime and return $mime;
3187 # just in case
3188 return $default_blob_plain_mimetype unless $fd;
3190 if (-T $fd) {
3191 return 'text/plain';
3192 } elsif (! $filename) {
3193 return 'application/octet-stream';
3194 } elsif ($filename =~ m/\.png$/i) {
3195 return 'image/png';
3196 } elsif ($filename =~ m/\.gif$/i) {
3197 return 'image/gif';
3198 } elsif ($filename =~ m/\.jpe?g$/i) {
3199 return 'image/jpeg';
3200 } else {
3201 return 'application/octet-stream';
3205 sub blob_contenttype {
3206 my ($fd, $file_name, $type) = @_;
3208 $type ||= blob_mimetype($fd, $file_name);
3209 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3210 $type .= "; charset=$default_text_plain_charset";
3213 return $type;
3216 ## ======================================================================
3217 ## functions printing HTML: header, footer, error page
3219 sub git_generating_data_html {
3220 my ($cache, $key, $lock_fh) = @_;
3222 if ($cgi->http('X-Ajax')) {
3223 return;
3225 if ($action eq 'atom' || $action eq 'rss' || $action eq 'opml' || # feeds
3226 $action eq 'blob_plain' || # unknown mimetype
3227 $action eq 'commitdiff_plain' || # text/plain
3228 $action eq 'patch' || $action eq 'patches' || # text/plain
3229 $action eq 'snapshot') { # binary
3230 return;
3233 my $title = "[Generating...] $site_name";
3234 if (defined $project) {
3235 $title .= " - " . to_utf8($project);
3236 if (defined $action) {
3237 $title .= "/$action";
3238 if (defined $file_name) {
3239 $title .= " - " . esc_path($file_name);
3240 if ($action eq "tree" && $file_name !~ m|/$|) {
3241 $title .= "/";
3247 my $use_javascript = $cgi->param('js');
3248 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3249 print STDOUT $cgi->header(-type => 'text/html', -charset => 'utf-8',
3250 -status=> '200 OK', -expires => 'now');
3251 print STDOUT <<"EOF";
3252 <?xml version="1.0" encoding="utf-8"?>
3253 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3254 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3255 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3256 <!-- git web interface version $version -->
3257 <!-- git core binaries version $git_version -->
3258 <head>
3259 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
3261 if (!$use_javascript) {
3262 print STDOUT qq!<meta http-equiv="refresh" content="0" />\n!;
3264 print STDOUT <<"EOF";
3265 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version" />
3266 <meta name="robots" content="noindex, nofollow" />
3267 <title>$title</title>
3268 </head>
3269 <body>
3271 if ($use_javascript) {
3272 my $url_self = href(-replay=>1);
3273 print STDOUT <<"EOF";
3274 Generating...<br />
3275 <script type="text/javascript" src="$javascript"></script>
3276 <script type="text/javascript">
3277 window.onload = function () {
3278 xhr = createRequestObject();
3279 xhr.onreadystatechange = function () {
3280 if (xhr.readyState === 4 && xhr.status === 200) {
3281 // intentionally overwrite document
3282 document.write(xhr.responseText);
3285 xhr.open('GET', $url_self);
3286 // mark request to not show "Generating..." page
3287 xhr.setRequestHeader('X-Ajax', 'Yes');
3288 xhr.send(null);
3290 </script>
3292 } else {
3293 print STDOUT 'Generating..';
3295 my $ready;
3296 my ($wait, $wait_step, $wait_max); # in seconds
3297 $wait = 0;
3298 $wait_step = 2;
3299 $wait_max = 20;
3300 $| = 1; # autoflush
3301 do {
3302 print STDOUT '.';
3304 sleep $wait_step if ($wait > 0);
3305 $wait += $wait_step;
3307 $ready = flock($lock_fh, LOCK_SH|LOCK_NB)
3308 if $lock_fh;
3310 } while (!$ready && ($wait < $wait_max));
3313 print STDOUT <<"EOF";
3315 </body>
3316 </html>
3318 #exit 0;
3319 return;
3322 sub git_header_html {
3323 my $status = shift || "200 OK";
3324 my $expires = shift;
3326 my $title = "$site_name";
3327 if (defined $project) {
3328 $title .= " - " . to_utf8($project);
3329 if (defined $action) {
3330 $title .= "/$action";
3331 if (defined $file_name) {
3332 $title .= " - " . esc_path($file_name);
3333 if ($action eq "tree" && $file_name !~ m|/$|) {
3334 $title .= "/";
3339 my $content_type;
3340 # require explicit support from the UA if we are to send the page as
3341 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3342 # we have to do this because MSIE sometimes globs '*/*', pretending to
3343 # support xhtml+xml but choking when it gets what it asked for.
3344 # Disable content-type negotiation when caching (use mimetype good for all).
3345 if (!$caching_enabled &&
3346 defined $cgi->http('HTTP_ACCEPT') &&
3347 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3348 $cgi->Accept('application/xhtml+xml') != 0) {
3349 $content_type = 'application/xhtml+xml';
3350 } else {
3351 $content_type = 'text/html';
3353 print {$out} $cgi->header(-type=>$content_type, -charset => 'utf-8',
3354 -status=> $status, -expires => $expires);
3355 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3356 print {$out} <<EOF;
3357 <?xml version="1.0" encoding="utf-8"?>
3358 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3359 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3360 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3361 <!-- git core binaries version $git_version -->
3362 <head>
3363 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3364 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3365 <meta name="robots" content="index, nofollow"/>
3366 <title>$title</title>
3368 # the stylesheet, favicon etc urls won't work correctly with path_info
3369 # unless we set the appropriate base URL
3370 if ($ENV{'PATH_INFO'}) {
3371 print {$out} '<base href="'.esc_url($base_url).'" />'."\n";
3373 # print out each stylesheet that exist, providing backwards capability
3374 # for those people who defined $stylesheet in a config file
3375 if (defined $stylesheet) {
3376 print {$out} '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3377 } else {
3378 foreach my $stylesheet (@stylesheets) {
3379 next unless $stylesheet;
3380 print {$out} '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3383 if (defined $project) {
3384 my %href_params = get_feed_info();
3385 if (!exists $href_params{'-title'}) {
3386 $href_params{'-title'} = 'log';
3389 foreach my $format qw(RSS Atom) {
3390 my $type = lc($format);
3391 my %link_attr = (
3392 '-rel' => 'alternate',
3393 '-title' => "$project - $href_params{'-title'} - $format feed",
3394 '-type' => "application/$type+xml"
3397 $href_params{'action'} = $type;
3398 $link_attr{'-href'} = href(%href_params);
3399 print {$out} "<link ".
3400 "rel=\"$link_attr{'-rel'}\" ".
3401 "title=\"$link_attr{'-title'}\" ".
3402 "href=\"$link_attr{'-href'}\" ".
3403 "type=\"$link_attr{'-type'}\" ".
3404 "/>\n";
3406 $href_params{'extra_options'} = '--no-merges';
3407 $link_attr{'-href'} = href(%href_params);
3408 $link_attr{'-title'} .= ' (no merges)';
3409 print {$out} "<link ".
3410 "rel=\"$link_attr{'-rel'}\" ".
3411 "title=\"$link_attr{'-title'}\" ".
3412 "href=\"$link_attr{'-href'}\" ".
3413 "type=\"$link_attr{'-type'}\" ".
3414 "/>\n";
3417 } else {
3418 printf {$out} '<link rel="alternate" title="%s projects list" '.
3419 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3420 $site_name, href(project=>undef, action=>"project_index");
3421 printf {$out} '<link rel="alternate" title="%s projects feeds" '.
3422 'href="%s" type="text/x-opml" />'."\n",
3423 $site_name, href(project=>undef, action=>"opml");
3425 if (defined $favicon) {
3426 print {$out} qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3429 print {$out} "</head>\n" .
3430 "<body>\n";
3432 if (-f $site_header) {
3433 insert_file($site_header);
3436 print {$out} "<div class=\"page_header\">\n" .
3437 $cgi->a({-href => esc_url($logo_url),
3438 -title => $logo_label},
3439 qq(<img src="$logo" width="72" height="27" alt="git" class="logo" />));
3440 print {$out} $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3441 if (defined $project) {
3442 print {$out} $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3443 if (defined $action) {
3444 print {$out} " / $action";
3446 print {$out} "\n";
3448 print {$out} "</div>\n";
3450 my $have_search = gitweb_check_feature('search');
3451 if (defined $project && $have_search) {
3452 if (!defined $searchtext) {
3453 $searchtext = "";
3455 my $search_hash;
3456 if (defined $hash_base) {
3457 $search_hash = $hash_base;
3458 } elsif (defined $hash) {
3459 $search_hash = $hash;
3460 } else {
3461 $search_hash = "HEAD";
3463 my $action = $my_uri;
3464 my $use_pathinfo = gitweb_check_feature('pathinfo');
3465 if ($use_pathinfo) {
3466 $action .= "/".esc_url($project);
3468 print {$out} $cgi->startform(-method => "get", -action => $action) .
3469 "<div class=\"search\">\n" .
3470 (!$use_pathinfo &&
3471 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3472 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3473 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3474 $cgi->popup_menu(-name => 'st', -default => 'commit',
3475 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3476 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3477 " search:\n",
3478 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3479 "<span title=\"Extended regular expression\">" .
3480 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3481 -checked => $search_use_regexp) .
3482 "</span>" .
3483 "</div>" .
3484 $cgi->end_form() . "\n";
3488 sub git_footer_html {
3489 my $feed_class = 'rss_logo';
3491 print {$out} "<div class=\"page_footer\">\n";
3492 if (defined $project) {
3493 my $descr = git_get_project_description($project);
3494 if (defined $descr) {
3495 print {$out} "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3498 my %href_params = get_feed_info();
3499 if (!%href_params) {
3500 $feed_class .= ' generic';
3502 $href_params{'-title'} ||= 'log';
3504 foreach my $format qw(RSS Atom) {
3505 $href_params{'action'} = lc($format);
3506 print {$out} $cgi->a({-href => href(%href_params),
3507 -title => "$href_params{'-title'} $format feed",
3508 -class => $feed_class}, $format)."\n";
3511 } else {
3512 print {$out} $cgi->a({-href => href(project=>undef, action=>"opml"),
3513 -class => $feed_class}, "OPML") . " ";
3514 print {$out} $cgi->a({-href => href(project=>undef, action=>"project_index"),
3515 -class => $feed_class}, "TXT") . "\n";
3517 print {$out} "</div>\n"; # class="page_footer"
3519 # timing info doesn't make much sense with output (response) caching
3520 if (!$caching_enabled &&
3521 defined $t0 && gitweb_check_feature('timed')) {
3522 print {$out} "<div id=\"generating_info\">\n";
3523 print {$out} 'This page took '.
3524 '<span id="generating_time" class="time_span">'.
3525 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3526 ' seconds </span>'.
3527 ' and '.
3528 '<span id="generating_cmd">'.
3529 $number_of_git_cmds.
3530 '</span> git commands '.
3531 " to generate.\n";
3532 print {$out} "</div>\n"; # class="page_footer"
3535 if (-f $site_footer) {
3536 insert_file($site_footer);
3539 print {$out} qq!<script type="text/javascript" src="$javascript"></script>\n!;
3540 if (defined $action &&
3541 $action eq 'blame_incremental') {
3542 print {$out} qq!<script type="text/javascript">\n!.
3543 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3544 qq! "!. href() .qq!");\n!.
3545 qq!</script>\n!;
3546 } elsif (gitweb_check_feature('javascript-actions')) {
3547 print {$out} qq!<script type="text/javascript">\n!.
3548 qq!window.onload = fixLinks;\n!.
3549 qq!</script>\n!;
3552 print {$out} "</body>\n" .
3553 "</html>";
3556 # die_error(<http_status_code>, <error_message>)
3557 # Example: die_error(404, 'Hash not found')
3558 # By convention, use the following status codes (as defined in RFC 2616):
3559 # 400: Invalid or missing CGI parameters, or
3560 # requested object exists but has wrong type.
3561 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3562 # this server or project.
3563 # 404: Requested object/revision/project doesn't exist.
3564 # 500: The server isn't configured properly, or
3565 # an internal error occurred (e.g. failed assertions caused by bugs), or
3566 # an unknown error occurred (e.g. the git binary died unexpectedly).
3567 # 503: The server is currently unavailable (because it is overloaded,
3568 # or down for maintenance). Generally, this is a temporary state.
3569 sub die_error {
3570 my $status = shift || 500;
3571 my $error = shift || "Internal server error";
3573 my %http_responses = (
3574 400 => '400 Bad Request',
3575 403 => '403 Forbidden',
3576 404 => '404 Not Found',
3577 500 => '500 Internal Server Error',
3578 503 => '503 Service Unavailable',
3580 $out = \*STDOUT;
3581 git_header_html($http_responses{$status});
3582 print {$out} <<EOF;
3583 <div class="page_body">
3584 <br /><br />
3585 $status - $error
3586 <br />
3587 </div>
3589 git_footer_html();
3590 exit;
3593 ## ----------------------------------------------------------------------
3594 ## functions printing or outputting HTML: navigation
3596 sub git_print_page_nav {
3597 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3598 $extra = '' if !defined $extra; # pager or formats
3600 my @navs = qw(summary shortlog log commit commitdiff tree);
3601 if ($suppress) {
3602 @navs = grep { $_ ne $suppress } @navs;
3605 my %arg = map { $_ => {action=>$_} } @navs;
3606 if (defined $head) {
3607 for (qw(commit commitdiff)) {
3608 $arg{$_}{'hash'} = $head;
3610 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3611 for (qw(shortlog log)) {
3612 $arg{$_}{'hash'} = $head;
3617 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3618 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3620 my @actions = gitweb_get_feature('actions');
3621 my %repl = (
3622 '%' => '%',
3623 'n' => $project, # project name
3624 'f' => $git_dir, # project path within filesystem
3625 'h' => $treehead || '', # current hash ('h' parameter)
3626 'b' => $treebase || '', # hash base ('hb' parameter)
3628 while (@actions) {
3629 my ($label, $link, $pos) = splice(@actions,0,3);
3630 # insert
3631 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3632 # munch munch
3633 $link =~ s/%([%nfhb])/$repl{$1}/g;
3634 $arg{$label}{'_href'} = $link;
3637 print {$out} "<div class=\"page_nav\">\n" .
3638 (join " | ",
3639 map { $_ eq $current ?
3640 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3641 } @navs);
3642 print {$out} "<br/>\n$extra<br/>\n" .
3643 "</div>\n";
3646 sub format_paging_nav {
3647 my ($action, $page, $has_next_link) = @_;
3648 my $paging_nav;
3651 if ($page > 0) {
3652 $paging_nav .=
3653 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
3654 " &sdot; " .
3655 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3656 -accesskey => "p", -title => "Alt-p"}, "prev");
3657 } else {
3658 $paging_nav .= "first &sdot; prev";
3661 if ($has_next_link) {
3662 $paging_nav .= " &sdot; " .
3663 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3664 -accesskey => "n", -title => "Alt-n"}, "next");
3665 } else {
3666 $paging_nav .= " &sdot; next";
3669 return $paging_nav;
3672 ## ......................................................................
3673 ## functions printing or outputting HTML: div
3675 sub git_print_header_div {
3676 my ($action, $title, $hash, $hash_base) = @_;
3677 my %args = ();
3679 $args{'action'} = $action;
3680 $args{'hash'} = $hash if $hash;
3681 $args{'hash_base'} = $hash_base if $hash_base;
3683 print {$out} "<div class=\"header\">\n" .
3684 $cgi->a({-href => href(%args), -class => "title"},
3685 $title ? $title : $action) .
3686 "\n</div>\n";
3689 sub print_local_time {
3690 my %date = @_;
3691 if ($date{'hour_local'} < 6) {
3692 printf {$out} " (<span class=\"atnight\">%02d:%02d</span> %s)",
3693 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'};
3694 } else {
3695 printf {$out} " (%02d:%02d %s)",
3696 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'};
3700 # Outputs the author name and date in long form
3701 sub git_print_authorship {
3702 my $co = shift;
3703 my %opts = @_;
3704 my $tag = $opts{-tag} || 'div';
3705 my $author = $co->{'author_name'};
3707 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3708 print {$out} "<$tag class=\"author_date\">" .
3709 format_search_author($author, "author", esc_html($author)) .
3710 " [$ad{'rfc2822'}";
3711 print_local_time(%ad) if ($opts{-localtime});
3712 print {$out} "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1) .
3713 "</$tag>\n";
3716 # Outputs table rows containing the full author or committer information,
3717 # in the format expected for 'commit' view (& similia).
3718 # Parameters are a commit hash reference, followed by the list of people
3719 # to output information for. If the list is empty it defalts to both
3720 # author and committer.
3721 sub git_print_authorship_rows {
3722 my $co = shift;
3723 # too bad we can't use @people = @_ || ('author', 'committer')
3724 my @people = @_;
3725 @people = ('author', 'committer') unless @people;
3726 foreach my $who (@people) {
3727 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3728 print {$out} "<tr><td>$who</td><td>" .
3729 format_search_author($co->{"${who}_name"}, $who,
3730 esc_html($co->{"${who}_name"})) . " " .
3731 format_search_author($co->{"${who}_email"}, $who,
3732 esc_html("<" . $co->{"${who}_email"} . ">")) .
3733 "</td><td rowspan=\"2\">" .
3734 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3735 "</td></tr>\n" .
3736 "<tr>" .
3737 "<td></td><td> $wd{'rfc2822'}";
3738 print_local_time(%wd);
3739 print {$out} "</td>" .
3740 "</tr>\n";
3744 sub git_print_page_path {
3745 my $name = shift;
3746 my $type = shift;
3747 my $hb = shift;
3750 print {$out} "<div class=\"page_path\">";
3751 print {$out} $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3752 -title => 'tree root'}, to_utf8("[$project]"));
3753 print {$out} " / ";
3754 if (defined $name) {
3755 my @dirname = split '/', $name;
3756 my $basename = pop @dirname;
3757 my $fullname = '';
3759 foreach my $dir (@dirname) {
3760 $fullname .= ($fullname ? '/' : '') . $dir;
3761 print {$out} $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3762 hash_base=>$hb),
3763 -title => $fullname}, esc_path($dir));
3764 print {$out} " / ";
3766 if (defined $type && $type eq 'blob') {
3767 print {$out} $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3768 hash_base=>$hb),
3769 -title => $name}, esc_path($basename));
3770 } elsif (defined $type && $type eq 'tree') {
3771 print {$out} $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3772 hash_base=>$hb),
3773 -title => $name}, esc_path($basename));
3774 print {$out} " / ";
3775 } else {
3776 print {$out} esc_path($basename);
3779 print {$out} "<br/></div>\n";
3782 sub git_print_log {
3783 my $log = shift;
3784 my %opts = @_;
3786 if ($opts{'-remove_title'}) {
3787 # remove title, i.e. first line of log
3788 shift @$log;
3790 # remove leading empty lines
3791 while (defined $log->[0] && $log->[0] eq "") {
3792 shift @$log;
3795 # print log
3796 my $signoff = 0;
3797 my $empty = 0;
3798 foreach my $line (@$log) {
3799 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3800 $signoff = 1;
3801 $empty = 0;
3802 if (! $opts{'-remove_signoff'}) {
3803 print {$out} "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3804 next;
3805 } else {
3806 # remove signoff lines
3807 next;
3809 } else {
3810 $signoff = 0;
3813 # print only one empty line
3814 # do not print empty line after signoff
3815 if ($line eq "") {
3816 next if ($empty || $signoff);
3817 $empty = 1;
3818 } else {
3819 $empty = 0;
3822 print {$out} format_log_line_html($line) . "<br/>\n";
3825 if ($opts{'-final_empty_line'}) {
3826 # end with single empty line
3827 print {$out} "<br/>\n" unless $empty;
3831 # return link target (what link points to)
3832 sub git_get_link_target {
3833 my $hash = shift;
3834 my $link_target;
3836 # read link
3837 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3838 or return;
3840 local $/ = undef;
3841 $link_target = <$fd>;
3843 close $fd
3844 or return;
3846 return $link_target;
3849 # given link target, and the directory (basedir) the link is in,
3850 # return target of link relative to top directory (top tree);
3851 # return undef if it is not possible (including absolute links).
3852 sub normalize_link_target {
3853 my ($link_target, $basedir) = @_;
3855 # absolute symlinks (beginning with '/') cannot be normalized
3856 return if (substr($link_target, 0, 1) eq '/');
3858 # normalize link target to path from top (root) tree (dir)
3859 my $path;
3860 if ($basedir) {
3861 $path = $basedir . '/' . $link_target;
3862 } else {
3863 # we are in top (root) tree (dir)
3864 $path = $link_target;
3867 # remove //, /./, and /../
3868 my @path_parts;
3869 foreach my $part (split('/', $path)) {
3870 # discard '.' and ''
3871 next if (!$part || $part eq '.');
3872 # handle '..'
3873 if ($part eq '..') {
3874 if (@path_parts) {
3875 pop @path_parts;
3876 } else {
3877 # link leads outside repository (outside top dir)
3878 return;
3880 } else {
3881 push @path_parts, $part;
3884 $path = join('/', @path_parts);
3886 return $path;
3889 # print tree entry (row of git_tree), but without encompassing <tr> element
3890 sub git_print_tree_entry {
3891 my ($t, $basedir, $hash_base, $have_blame) = @_;
3893 my %base_key = ();
3894 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3896 # The format of a table row is: mode list link. Where mode is
3897 # the mode of the entry, list is the name of the entry, an href,
3898 # and link is the action links of the entry.
3900 print {$out} "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3901 if (exists $t->{'size'}) {
3902 print {$out} "<td class=\"size\">$t->{'size'}</td>\n";
3904 if ($t->{'type'} eq "blob") {
3905 print {$out} "<td class=\"list\">" .
3906 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3907 file_name=>"$basedir$t->{'name'}", %base_key),
3908 -class => "list"}, esc_path($t->{'name'}));
3909 if (S_ISLNK(oct $t->{'mode'})) {
3910 my $link_target = git_get_link_target($t->{'hash'});
3911 if ($link_target) {
3912 my $norm_target = normalize_link_target($link_target, $basedir);
3913 if (defined $norm_target) {
3914 print {$out} " -> " .
3915 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3916 file_name=>$norm_target),
3917 -title => $norm_target}, esc_path($link_target));
3918 } else {
3919 print {$out} " -> " . esc_path($link_target);
3923 print {$out} "</td>\n";
3924 print {$out} "<td class=\"link\">";
3925 print {$out} $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3926 file_name=>"$basedir$t->{'name'}", %base_key)},
3927 "blob");
3928 if ($have_blame) {
3929 print {$out} " | " .
3930 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3931 file_name=>"$basedir$t->{'name'}", %base_key)},
3932 "blame");
3934 if (defined $hash_base) {
3935 print {$out} " | " .
3936 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3937 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3938 "history");
3940 print {$out} " | " .
3941 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3942 file_name=>"$basedir$t->{'name'}")},
3943 "raw");
3944 print {$out} "</td>\n";
3946 } elsif ($t->{'type'} eq "tree") {
3947 print {$out} "<td class=\"list\">";
3948 print {$out} $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3949 file_name=>"$basedir$t->{'name'}",
3950 %base_key)},
3951 esc_path($t->{'name'}));
3952 print {$out} "</td>\n";
3953 print {$out} "<td class=\"link\">";
3954 print {$out} $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3955 file_name=>"$basedir$t->{'name'}",
3956 %base_key)},
3957 "tree");
3958 if (defined $hash_base) {
3959 print {$out} " | " .
3960 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3961 file_name=>"$basedir$t->{'name'}")},
3962 "history");
3964 print {$out} "</td>\n";
3966 } else {
3967 # unknown object: we can only present history for it
3968 # (this includes 'commit' object, i.e. submodule support)
3969 print {$out} "<td class=\"list\">" .
3970 esc_path($t->{'name'}) .
3971 "</td>\n";
3972 print {$out} "<td class=\"link\">";
3973 if (defined $hash_base) {
3974 print {$out} $cgi->a({-href => href(action=>"history",
3975 hash_base=>$hash_base,
3976 file_name=>"$basedir$t->{'name'}")},
3977 "history");
3979 print {$out} "</td>\n";
3983 ## ......................................................................
3984 ## functions printing large fragments of HTML
3986 # get pre-image filenames for merge (combined) diff
3987 sub fill_from_file_info {
3988 my ($diff, @parents) = @_;
3990 $diff->{'from_file'} = [ ];
3991 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3992 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3993 if ($diff->{'status'}[$i] eq 'R' ||
3994 $diff->{'status'}[$i] eq 'C') {
3995 $diff->{'from_file'}[$i] =
3996 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4000 return $diff;
4003 # is current raw difftree line of file deletion
4004 sub is_deleted {
4005 my $diffinfo = shift;
4007 return $diffinfo->{'to_id'} eq ('0' x 40);
4010 # does patch correspond to [previous] difftree raw line
4011 # $diffinfo - hashref of parsed raw diff format
4012 # $patchinfo - hashref of parsed patch diff format
4013 # (the same keys as in $diffinfo)
4014 sub is_patch_split {
4015 my ($diffinfo, $patchinfo) = @_;
4017 return defined $diffinfo && defined $patchinfo
4018 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4022 sub git_difftree_body {
4023 my ($difftree, $hash, @parents) = @_;
4024 my ($parent) = $parents[0];
4025 my $have_blame = gitweb_check_feature('blame');
4026 print {$out} "<div class=\"list_head\">\n";
4027 if ($#{$difftree} > 10) {
4028 print {$out} (($#{$difftree} + 1) . " files changed:\n");
4030 print {$out} "</div>\n";
4032 print {$out} "<table class=\"" .
4033 (@parents > 1 ? "combined " : "") .
4034 "diff_tree\">\n";
4036 # header only for combined diff in 'commitdiff' view
4037 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4038 if ($has_header) {
4039 # table header
4040 print {$out} "<thead><tr>\n" .
4041 "<th></th><th></th>\n"; # filename, patchN link
4042 for (my $i = 0; $i < @parents; $i++) {
4043 my $par = $parents[$i];
4044 print {$out} "<th>" .
4045 $cgi->a({-href => href(action=>"commitdiff",
4046 hash=>$hash, hash_parent=>$par),
4047 -title => 'commitdiff to parent number ' .
4048 ($i+1) . ': ' . substr($par,0,7)},
4049 $i+1) .
4050 "&nbsp;</th>\n";
4052 print {$out} "</tr></thead>\n<tbody>\n";
4055 my $alternate = 1;
4056 my $patchno = 0;
4057 foreach my $line (@{$difftree}) {
4058 my $diff = parsed_difftree_line($line);
4060 if ($alternate) {
4061 print {$out} "<tr class=\"dark\">\n";
4062 } else {
4063 print {$out} "<tr class=\"light\">\n";
4065 $alternate ^= 1;
4067 if (exists $diff->{'nparents'}) { # combined diff
4069 fill_from_file_info($diff, @parents)
4070 unless exists $diff->{'from_file'};
4072 if (!is_deleted($diff)) {
4073 # file exists in the result (child) commit
4074 print {$out} "<td>" .
4075 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4076 file_name=>$diff->{'to_file'},
4077 hash_base=>$hash),
4078 -class => "list"}, esc_path($diff->{'to_file'})) .
4079 "</td>\n";
4080 } else {
4081 print {$out} "<td>" .
4082 esc_path($diff->{'to_file'}) .
4083 "</td>\n";
4086 if ($action eq 'commitdiff') {
4087 # link to patch
4088 $patchno++;
4089 print {$out} "<td class=\"link\">" .
4090 $cgi->a({-href => "#patch$patchno"}, "patch") .
4091 " | " .
4092 "</td>\n";
4095 my $has_history = 0;
4096 my $not_deleted = 0;
4097 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4098 my $hash_parent = $parents[$i];
4099 my $from_hash = $diff->{'from_id'}[$i];
4100 my $from_path = $diff->{'from_file'}[$i];
4101 my $status = $diff->{'status'}[$i];
4103 $has_history ||= ($status ne 'A');
4104 $not_deleted ||= ($status ne 'D');
4106 if ($status eq 'A') {
4107 print {$out} "<td class=\"link\" align=\"right\"> | </td>\n";
4108 } elsif ($status eq 'D') {
4109 print {$out} "<td class=\"link\">" .
4110 $cgi->a({-href => href(action=>"blob",
4111 hash_base=>$hash,
4112 hash=>$from_hash,
4113 file_name=>$from_path)},
4114 "blob" . ($i+1)) .
4115 " | </td>\n";
4116 } else {
4117 if ($diff->{'to_id'} eq $from_hash) {
4118 print {$out} "<td class=\"link nochange\">";
4119 } else {
4120 print {$out} "<td class=\"link\">";
4122 print {$out} $cgi->a({-href => href(action=>"blobdiff",
4123 hash=>$diff->{'to_id'},
4124 hash_parent=>$from_hash,
4125 hash_base=>$hash,
4126 hash_parent_base=>$hash_parent,
4127 file_name=>$diff->{'to_file'},
4128 file_parent=>$from_path)},
4129 "diff" . ($i+1)) .
4130 " | </td>\n";
4134 print {$out} "<td class=\"link\">";
4135 if ($not_deleted) {
4136 print {$out} $cgi->a({-href => href(action=>"blob",
4137 hash=>$diff->{'to_id'},
4138 file_name=>$diff->{'to_file'},
4139 hash_base=>$hash)},
4140 "blob");
4141 print {$out} " | " if ($has_history);
4143 if ($has_history) {
4144 print {$out} $cgi->a({-href => href(action=>"history",
4145 file_name=>$diff->{'to_file'},
4146 hash_base=>$hash)},
4147 "history");
4149 print {$out} "</td>\n";
4151 print {$out} "</tr>\n";
4152 next; # instead of 'else' clause, to avoid extra indent
4154 # else ordinary diff
4156 my ($to_mode_oct, $to_mode_str, $to_file_type);
4157 my ($from_mode_oct, $from_mode_str, $from_file_type);
4158 if ($diff->{'to_mode'} ne ('0' x 6)) {
4159 $to_mode_oct = oct $diff->{'to_mode'};
4160 if (S_ISREG($to_mode_oct)) { # only for regular file
4161 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4163 $to_file_type = file_type($diff->{'to_mode'});
4165 if ($diff->{'from_mode'} ne ('0' x 6)) {
4166 $from_mode_oct = oct $diff->{'from_mode'};
4167 if (S_ISREG($to_mode_oct)) { # only for regular file
4168 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4170 $from_file_type = file_type($diff->{'from_mode'});
4173 if ($diff->{'status'} eq "A") { # created
4174 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4175 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4176 $mode_chng .= "]</span>";
4177 print {$out} "<td>";
4178 print {$out} $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4179 hash_base=>$hash, file_name=>$diff->{'file'}),
4180 -class => "list"}, esc_path($diff->{'file'}));
4181 print {$out} "</td>\n";
4182 print {$out} "<td>$mode_chng</td>\n";
4183 print {$out} "<td class=\"link\">";
4184 if ($action eq 'commitdiff') {
4185 # link to patch
4186 $patchno++;
4187 print {$out} $cgi->a({-href => "#patch$patchno"}, "patch");
4188 print {$out} " | ";
4190 print {$out} $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4191 hash_base=>$hash, file_name=>$diff->{'file'})},
4192 "blob");
4193 print {$out} "</td>\n";
4195 } elsif ($diff->{'status'} eq "D") { # deleted
4196 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4197 print {$out} "<td>";
4198 print {$out} $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4199 hash_base=>$parent, file_name=>$diff->{'file'}),
4200 -class => "list"}, esc_path($diff->{'file'}));
4201 print {$out} "</td>\n";
4202 print {$out} "<td>$mode_chng</td>\n";
4203 print {$out} "<td class=\"link\">";
4204 if ($action eq 'commitdiff') {
4205 # link to patch
4206 $patchno++;
4207 print {$out} $cgi->a({-href => "#patch$patchno"}, "patch");
4208 print {$out} " | ";
4210 print {$out} $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4211 hash_base=>$parent, file_name=>$diff->{'file'})},
4212 "blob") . " | ";
4213 if ($have_blame) {
4214 print {$out} $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4215 file_name=>$diff->{'file'})},
4216 "blame") . " | ";
4218 print {$out} $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4219 file_name=>$diff->{'file'})},
4220 "history");
4221 print {$out} "</td>\n";
4223 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4224 my $mode_chnge = "";
4225 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4226 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4227 if ($from_file_type ne $to_file_type) {
4228 $mode_chnge .= " from $from_file_type to $to_file_type";
4230 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4231 if ($from_mode_str && $to_mode_str) {
4232 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4233 } elsif ($to_mode_str) {
4234 $mode_chnge .= " mode: $to_mode_str";
4237 $mode_chnge .= "]</span>\n";
4239 print {$out} "<td>";
4240 print {$out} $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4241 hash_base=>$hash, file_name=>$diff->{'file'}),
4242 -class => "list"}, esc_path($diff->{'file'}));
4243 print {$out} "</td>\n";
4244 print {$out} "<td>$mode_chnge</td>\n";
4245 print {$out} "<td class=\"link\">";
4246 if ($action eq 'commitdiff') {
4247 # link to patch
4248 $patchno++;
4249 print {$out} $cgi->a({-href => "#patch$patchno"}, "patch") .
4250 " | ";
4251 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4252 # "commit" view and modified file (not onlu mode changed)
4253 print {$out} $cgi->a({-href => href(action=>"blobdiff",
4254 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4255 hash_base=>$hash, hash_parent_base=>$parent,
4256 file_name=>$diff->{'file'})},
4257 "diff") .
4258 " | ";
4260 print {$out} $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4261 hash_base=>$hash, file_name=>$diff->{'file'})},
4262 "blob") . " | ";
4263 if ($have_blame) {
4264 print {$out} $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4265 file_name=>$diff->{'file'})},
4266 "blame") . " | ";
4268 print {$out} $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4269 file_name=>$diff->{'file'})},
4270 "history");
4271 print {$out} "</td>\n";
4273 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4274 my %status_name = ('R' => 'moved', 'C' => 'copied');
4275 my $nstatus = $status_name{$diff->{'status'}};
4276 my $mode_chng = "";
4277 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4278 # mode also for directories, so we cannot use $to_mode_str
4279 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4281 print {$out} "<td>" .
4282 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4283 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4284 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4285 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4286 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4287 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4288 -class => "list"}, esc_path($diff->{'from_file'})) .
4289 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4290 "<td class=\"link\">";
4291 if ($action eq 'commitdiff') {
4292 # link to patch
4293 $patchno++;
4294 print {$out} $cgi->a({-href => "#patch$patchno"}, "patch") .
4295 " | ";
4296 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4297 # "commit" view and modified file (not only pure rename or copy)
4298 print {$out} $cgi->a({-href => href(action=>"blobdiff",
4299 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4300 hash_base=>$hash, hash_parent_base=>$parent,
4301 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4302 "diff") .
4303 " | ";
4305 print {$out} $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4306 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4307 "blob") . " | ";
4308 if ($have_blame) {
4309 print {$out} $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4310 file_name=>$diff->{'to_file'})},
4311 "blame") . " | ";
4313 print {$out} $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4314 file_name=>$diff->{'to_file'})},
4315 "history");
4316 print {$out} "</td>\n";
4318 } # we should not encounter Unmerged (U) or Unknown (X) status
4319 print {$out} "</tr>\n";
4321 print {$out} "</tbody>" if $has_header;
4322 print {$out} "</table>\n";
4325 sub git_patchset_body {
4326 my ($fd, $difftree, $hash, @hash_parents) = @_;
4327 my ($hash_parent) = $hash_parents[0];
4329 my $is_combined = (@hash_parents > 1);
4330 my $patch_idx = 0;
4331 my $patch_number = 0;
4332 my $patch_line;
4333 my $diffinfo;
4334 my $to_name;
4335 my (%from, %to);
4337 print {$out} "<div class=\"patchset\">\n";
4339 # skip to first patch
4340 while ($patch_line = <$fd>) {
4341 chomp $patch_line;
4343 last if ($patch_line =~ m/^diff /);
4346 PATCH:
4347 while ($patch_line) {
4349 # parse "git diff" header line
4350 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4351 # $1 is from_name, which we do not use
4352 $to_name = unquote($2);
4353 $to_name =~ s!^b/!!;
4354 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4355 # $1 is 'cc' or 'combined', which we do not use
4356 $to_name = unquote($2);
4357 } else {
4358 $to_name = undef;
4361 # check if current patch belong to current raw line
4362 # and parse raw git-diff line if needed
4363 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4364 # this is continuation of a split patch
4365 print {$out} "<div class=\"patch cont\">\n";
4366 } else {
4367 # advance raw git-diff output if needed
4368 $patch_idx++ if defined $diffinfo;
4370 # read and prepare patch information
4371 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4373 # compact combined diff output can have some patches skipped
4374 # find which patch (using pathname of result) we are at now;
4375 if ($is_combined) {
4376 while ($to_name ne $diffinfo->{'to_file'}) {
4377 print {$out} "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4378 format_diff_cc_simplified($diffinfo, @hash_parents) .
4379 "</div>\n"; # class="patch"
4381 $patch_idx++;
4382 $patch_number++;
4384 last if $patch_idx > $#$difftree;
4385 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4389 # modifies %from, %to hashes
4390 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4392 # this is first patch for raw difftree line with $patch_idx index
4393 # we index @$difftree array from 0, but number patches from 1
4394 print {$out} "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4397 # git diff header
4398 #assert($patch_line =~ m/^diff /) if DEBUG;
4399 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4400 $patch_number++;
4401 # print "git diff" header
4402 print {$out} format_git_diff_header_line($patch_line, $diffinfo,
4403 \%from, \%to);
4405 # print extended diff header
4406 print {$out} "<div class=\"diff extended_header\">\n";
4407 EXTENDED_HEADER:
4408 while ($patch_line = <$fd>) {
4409 chomp $patch_line;
4411 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4413 print {$out} format_extended_diff_header_line($patch_line, $diffinfo,
4414 \%from, \%to);
4416 print {$out} "</div>\n"; # class="diff extended_header"
4418 # from-file/to-file diff header
4419 if (! $patch_line) {
4420 print {$out} "</div>\n"; # class="patch"
4421 last PATCH;
4423 next PATCH if ($patch_line =~ m/^diff /);
4424 #assert($patch_line =~ m/^---/) if DEBUG;
4426 my $last_patch_line = $patch_line;
4427 $patch_line = <$fd>;
4428 chomp $patch_line;
4429 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4431 print {$out} format_diff_from_to_header($last_patch_line, $patch_line,
4432 $diffinfo, \%from, \%to,
4433 @hash_parents);
4435 # the patch itself
4436 LINE:
4437 while ($patch_line = <$fd>) {
4438 chomp $patch_line;
4440 next PATCH if ($patch_line =~ m/^diff /);
4442 print {$out} format_diff_line($patch_line, \%from, \%to);
4445 } continue {
4446 print {$out} "</div>\n"; # class="patch"
4449 # for compact combined (--cc) format, with chunk and patch simpliciaction
4450 # patchset might be empty, but there might be unprocessed raw lines
4451 for (++$patch_idx if $patch_number > 0;
4452 $patch_idx < @$difftree;
4453 ++$patch_idx) {
4454 # read and prepare patch information
4455 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4457 # generate anchor for "patch" links in difftree / whatchanged part
4458 print {$out} "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4459 format_diff_cc_simplified($diffinfo, @hash_parents) .
4460 "</div>\n"; # class="patch"
4462 $patch_number++;
4465 if ($patch_number == 0) {
4466 if (@hash_parents > 1) {
4467 print {$out} "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4468 } else {
4469 print {$out} "<div class=\"diff nodifferences\">No differences found</div>\n";
4473 print {$out} "</div>\n"; # class="patchset"
4476 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4478 # fills project list info (age, description, owner, forks) for each
4479 # project in the list, removing invalid projects from returned list
4480 # NOTE: modifies $projlist, but does not remove entries from it
4481 sub fill_project_list_info {
4482 my ($projlist, $check_forks) = @_;
4483 my @projects;
4485 my $show_ctags = gitweb_check_feature('ctags');
4486 PROJECT:
4487 foreach my $pr (@$projlist) {
4488 my (@activity) = git_get_last_activity($pr->{'path'});
4489 unless (@activity) {
4490 next PROJECT;
4492 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4493 if (!defined $pr->{'descr'}) {
4494 my $descr = git_get_project_description($pr->{'path'}) || "";
4495 $descr = to_utf8($descr);
4496 $pr->{'descr_long'} = $descr;
4497 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4499 if (!defined $pr->{'owner'}) {
4500 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4502 if ($check_forks) {
4503 my $pname = $pr->{'path'};
4504 if (($pname =~ s/\.git$//) &&
4505 ($pname !~ /\/$/) &&
4506 (-d "$projectroot/$pname")) {
4507 $pr->{'forks'} = "-d $projectroot/$pname";
4508 } else {
4509 $pr->{'forks'} = 0;
4512 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4513 push @projects, $pr;
4516 return @projects;
4519 # print 'sort by' <th> element, generating 'sort by $name' replay link
4520 # if that order is not selected
4521 sub print_sort_th {
4522 my ($name, $order, $header) = @_;
4523 $header ||= ucfirst($name);
4525 if ($order eq $name) {
4526 print {$out} "<th>$header</th>\n";
4527 } else {
4528 print {$out} "<th>" .
4529 $cgi->a({-href => href(-replay=>1, order=>$name),
4530 -class => "header"}, $header) .
4531 "</th>\n";
4535 sub git_project_list_body {
4536 # actually uses global variable $project
4537 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4539 my $check_forks = gitweb_check_feature('forks');
4540 my @projects = fill_project_list_info($projlist, $check_forks);
4542 $order ||= $default_projects_order;
4543 $from = 0 unless defined $from;
4544 $to = $#projects if (!defined $to || $#projects < $to);
4546 my %order_info = (
4547 project => { key => 'path', type => 'str' },
4548 descr => { key => 'descr_long', type => 'str' },
4549 owner => { key => 'owner', type => 'str' },
4550 age => { key => 'age', type => 'num' }
4552 my $oi = $order_info{$order};
4553 if ($oi->{'type'} eq 'str') {
4554 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4555 } else {
4556 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4559 my $show_ctags = gitweb_check_feature('ctags');
4560 if ($show_ctags) {
4561 my %ctags;
4562 foreach my $p (@projects) {
4563 foreach my $ct (keys %{$p->{'ctags'}}) {
4564 $ctags{$ct} += $p->{'ctags'}->{$ct};
4567 my $cloud = git_populate_project_tagcloud(\%ctags);
4568 print {$out} git_show_project_tagcloud($cloud, 64);
4571 print {$out} "<table class=\"project_list\">\n";
4572 unless ($no_header) {
4573 print {$out} "<tr>\n";
4574 if ($check_forks) {
4575 print {$out} "<th></th>\n";
4577 print_sort_th('project', $order, 'Project');
4578 print_sort_th('descr', $order, 'Description');
4579 print_sort_th('owner', $order, 'Owner');
4580 print_sort_th('age', $order, 'Last Change');
4581 print {$out} "<th></th>\n" . # for links
4582 "</tr>\n";
4584 my $alternate = 1;
4585 my $tagfilter = $cgi->param('by_tag');
4586 for (my $i = $from; $i <= $to; $i++) {
4587 my $pr = $projects[$i];
4589 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4590 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4591 and not $pr->{'descr_long'} =~ /$searchtext/;
4592 # Weed out forks or non-matching entries of search
4593 if ($check_forks) {
4594 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4595 $forkbase="^$forkbase" if $forkbase;
4596 next if not $searchtext and not $tagfilter and $show_ctags
4597 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4600 if ($alternate) {
4601 print {$out} "<tr class=\"dark\">\n";
4602 } else {
4603 print {$out} "<tr class=\"light\">\n";
4605 $alternate ^= 1;
4606 if ($check_forks) {
4607 print {$out} "<td>";
4608 if ($pr->{'forks'}) {
4609 print {$out} "<!-- $pr->{'forks'} -->\n";
4610 print {$out} $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4612 print {$out} "</td>\n";
4614 print {$out} "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4615 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4616 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4617 -class => "list", -title => $pr->{'descr_long'}},
4618 esc_html($pr->{'descr'})) . "</td>\n" .
4619 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4620 print {$out} "<td class=\"". age_class($pr->{'age'}) . "\">" .
4621 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4622 "<td class=\"link\">" .
4623 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4624 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4625 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4626 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4627 ($pr->{'forks'} ?
4628 " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},
4629 "forks")
4630 : '') .
4631 ($gitlinkurl_base ?
4632 " | " . $cgi->a({-href=>"$gitlinkurl_base/$pr->{'path'}",
4633 -rel=>"vcs-git"}, "git")
4634 : '') .
4635 "</td>\n" .
4636 "</tr>\n";
4638 if (defined $extra) {
4639 print {$out} "<tr>\n";
4640 if ($check_forks) {
4641 print {$out} "<td></td>\n";
4643 print {$out} "<td colspan=\"5\">$extra</td>\n" .
4644 "</tr>\n";
4646 print {$out} "</table>\n";
4649 sub git_log_body {
4650 # uses global variable $project
4651 my ($commitlist, $from, $to, $refs, $extra) = @_;
4653 $from = 0 unless defined $from;
4654 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4656 for (my $i = 0; $i <= $to; $i++) {
4657 my %co = %{$commitlist->[$i]};
4658 next if !%co;
4659 my $commit = $co{'id'};
4660 my $ref = format_ref_marker($refs, $commit);
4661 my %ad = parse_date($co{'author_epoch'});
4662 git_print_header_div('commit',
4663 "<span class=\"age\">$co{'age_string'}</span>" .
4664 esc_html($co{'title'}) . $ref,
4665 $commit);
4666 print {$out} "<div class=\"title_text\">\n" .
4667 "<div class=\"log_link\">\n" .
4668 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4669 " | " .
4670 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4671 " | " .
4672 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4673 "<br/>\n" .
4674 "</div>\n";
4675 git_print_authorship(\%co, -tag => 'span');
4676 print {$out} "<br/>\n</div>\n";
4678 print {$out} "<div class=\"log_body\">\n";
4679 git_print_log($co{'comment'}, -final_empty_line=> 1);
4680 print {$out} "</div>\n";
4682 if ($extra) {
4683 print {$out} "<div class=\"page_nav\">\n";
4684 print {$out} "$extra\n";
4685 print {$out} "</div>\n";
4689 sub git_shortlog_body {
4690 # uses global variable $project
4691 my ($commitlist, $from, $to, $refs, $extra) = @_;
4693 $from = 0 unless defined $from;
4694 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4696 print {$out} "<table class=\"shortlog\">\n";
4697 my $alternate = 1;
4698 for (my $i = $from; $i <= $to; $i++) {
4699 my %co = %{$commitlist->[$i]};
4700 my $commit = $co{'id'};
4701 my $ref = format_ref_marker($refs, $commit);
4702 if ($alternate) {
4703 print {$out} "<tr class=\"dark\">\n";
4704 } else {
4705 print {$out} "<tr class=\"light\">\n";
4707 $alternate ^= 1;
4708 # git_summary() used 'print {$out} "<td><i>$co{'age_string'}</i></td>\n" .'
4709 print {$out} "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4710 format_author_html('td', \%co, 10) . "<td>";
4711 print {$out} format_subject_html($co{'title'}, $co{'title_short'},
4712 href(action=>"commit", hash=>$commit), $ref);
4713 print {$out} "</td>\n" .
4714 "<td class=\"link\">" .
4715 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4716 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4717 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4718 my $snapshot_links = format_snapshot_links($commit);
4719 if (defined $snapshot_links) {
4720 print {$out} " | " . $snapshot_links;
4722 print {$out} "</td>\n" .
4723 "</tr>\n";
4725 if (defined $extra) {
4726 print {$out} "<tr>\n" .
4727 "<td colspan=\"4\">$extra</td>\n" .
4728 "</tr>\n";
4730 print {$out} "</table>\n";
4733 sub git_history_body {
4734 # Warning: assumes constant type (blob or tree) during history
4735 my ($commitlist, $from, $to, $refs, $extra,
4736 $file_name, $file_hash, $ftype) = @_;
4738 $from = 0 unless defined $from;
4739 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4741 print {$out} "<table class=\"history\">\n";
4742 my $alternate = 1;
4743 for (my $i = $from; $i <= $to; $i++) {
4744 my %co = %{$commitlist->[$i]};
4745 if (!%co) {
4746 next;
4748 my $commit = $co{'id'};
4750 my $ref = format_ref_marker($refs, $commit);
4752 if ($alternate) {
4753 print {$out} "<tr class=\"dark\">\n";
4754 } else {
4755 print {$out} "<tr class=\"light\">\n";
4757 $alternate ^= 1;
4758 print {$out} "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4759 # shortlog: format_author_html('td', \%co, 10)
4760 format_author_html('td', \%co, 15, 3) . "<td>";
4761 # originally git_history used chop_str($co{'title'}, 50)
4762 print {$out} format_subject_html($co{'title'}, $co{'title_short'},
4763 href(action=>"commit", hash=>$commit), $ref);
4764 print {$out} "</td>\n" .
4765 "<td class=\"link\">" .
4766 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit,
4767 file_name=>$file_name)}, $ftype) . " | " .
4768 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4770 if ($ftype eq 'blob') {
4771 my $blob_current = $file_hash;
4772 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4773 if (defined $blob_current && defined $blob_parent &&
4774 $blob_current ne $blob_parent) {
4775 print {$out} " | " .
4776 $cgi->a({-href => href(action=>"blobdiff",
4777 hash=>$blob_current, hash_parent=>$blob_parent,
4778 hash_base=>$hash_base, hash_parent_base=>$commit,
4779 file_name=>$file_name)},
4780 "diff to current");
4783 print {$out} "</td>\n" .
4784 "</tr>\n";
4786 if (defined $extra) {
4787 print {$out} "<tr>\n" .
4788 "<td colspan=\"4\">$extra</td>\n" .
4789 "</tr>\n";
4791 print {$out} "</table>\n";
4794 sub git_tags_body {
4795 # uses global variable $project
4796 my ($taglist, $from, $to, $extra) = @_;
4797 $from = 0 unless defined $from;
4798 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4800 print {$out} "<table class=\"tags\">\n";
4801 my $alternate = 1;
4802 for (my $i = $from; $i <= $to; $i++) {
4803 my $entry = $taglist->[$i];
4804 my %tag = %$entry;
4805 my $comment = $tag{'subject'};
4806 my $comment_short;
4807 if (defined $comment) {
4808 $comment_short = chop_str($comment, 30, 5);
4810 if ($alternate) {
4811 print {$out} "<tr class=\"dark\">\n";
4812 } else {
4813 print {$out} "<tr class=\"light\">\n";
4815 $alternate ^= 1;
4816 if (defined $tag{'age'}) {
4817 print {$out} "<td><i>$tag{'age'}</i></td>\n";
4818 } else {
4819 print {$out} "<td></td>\n";
4821 print {$out} "<td>" .
4822 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4823 -class => "list name"}, esc_html($tag{'name'})) .
4824 "</td>\n" .
4825 "<td>";
4826 if (defined $comment) {
4827 print {$out} format_subject_html($comment, $comment_short,
4828 href(action=>"tag", hash=>$tag{'id'}));
4830 print {$out} "</td>\n" .
4831 "<td class=\"selflink\">";
4832 if ($tag{'type'} eq "tag") {
4833 print {$out} $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4834 } else {
4835 print {$out} "&nbsp;";
4837 print {$out} "</td>\n" .
4838 "<td class=\"link\">" . " | " .
4839 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4840 if ($tag{'reftype'} eq "commit") {
4841 print {$out} " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4842 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4843 } elsif ($tag{'reftype'} eq "blob") {
4844 print {$out} " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4846 print {$out} "</td>\n" .
4847 "</tr>";
4849 if (defined $extra) {
4850 print {$out} "<tr>\n" .
4851 "<td colspan=\"5\">$extra</td>\n" .
4852 "</tr>\n";
4854 print {$out} "</table>\n";
4857 sub git_heads_body {
4858 # uses global variable $project
4859 my ($headlist, $head, $from, $to, $extra) = @_;
4860 $from = 0 unless defined $from;
4861 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4863 print {$out} "<table class=\"heads\">\n";
4864 my $alternate = 1;
4865 for (my $i = $from; $i <= $to; $i++) {
4866 my $entry = $headlist->[$i];
4867 my %ref = %$entry;
4868 my $curr = $ref{'id'} eq $head;
4869 if ($alternate) {
4870 print {$out} "<tr class=\"dark\">\n";
4871 } else {
4872 print {$out} "<tr class=\"light\">\n";
4874 $alternate ^= 1;
4875 print {$out} "<td><i>$ref{'age'}</i></td>\n" .
4876 ($curr ? "<td class=\"current_head\">" : "<td>") .
4877 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4878 -class => "list name"},esc_html($ref{'name'})) .
4879 "</td>\n" .
4880 "<td class=\"link\">" .
4881 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4882 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4883 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'},
4884 hash_base=>$ref{'name'})}, "tree") .
4885 "</td>\n" .
4886 "</tr>";
4888 if (defined $extra) {
4889 print {$out} "<tr>\n" .
4890 "<td colspan=\"3\">$extra</td>\n" .
4891 "</tr>\n";
4893 print {$out} "</table>\n";
4896 sub git_search_grep_body {
4897 my ($commitlist, $from, $to, $extra) = @_;
4898 $from = 0 unless defined $from;
4899 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4901 print {$out} "<table class=\"commit_search\">\n";
4902 my $alternate = 1;
4903 for (my $i = $from; $i <= $to; $i++) {
4904 my %co = %{$commitlist->[$i]};
4905 if (!%co) {
4906 next;
4908 my $commit = $co{'id'};
4909 if ($alternate) {
4910 print {$out} "<tr class=\"dark\">\n";
4911 } else {
4912 print {$out} "<tr class=\"light\">\n";
4914 $alternate ^= 1;
4915 print {$out} "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4916 format_author_html('td', \%co, 15, 5) .
4917 "<td>" .
4918 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4919 -class => "list subject"},
4920 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4921 my $comment = $co{'comment'};
4922 foreach my $line (@$comment) {
4923 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4924 my ($lead, $match, $trail) = ($1, $2, $3);
4925 $match = chop_str($match, 70, 5, 'center');
4926 my $contextlen = int((80 - length($match))/2);
4927 $contextlen = 30 if ($contextlen > 30);
4928 $lead = chop_str($lead, $contextlen, 10, 'left');
4929 $trail = chop_str($trail, $contextlen, 10, 'right');
4931 $lead = esc_html($lead);
4932 $match = esc_html($match);
4933 $trail = esc_html($trail);
4935 print {$out} "$lead<span class=\"match\">$match</span>$trail<br />";
4938 print {$out} "</td>\n" .
4939 "<td class=\"link\">" .
4940 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4941 " | " .
4942 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4943 " | " .
4944 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4945 print {$out} "</td>\n" .
4946 "</tr>\n";
4948 if (defined $extra) {
4949 print {$out} "<tr>\n" .
4950 "<td colspan=\"3\">$extra</td>\n" .
4951 "</tr>\n";
4953 print {$out} "</table>\n";
4956 ## ======================================================================
4957 ## ======================================================================
4958 ## actions
4960 sub git_project_list {
4961 my $order = $input_params{'order'};
4962 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4963 die_error(400, "Unknown order parameter");
4966 my @list = git_get_projects_list();
4967 if (!@list) {
4968 die_error(404, "No projects found");
4971 git_header_html();
4972 if (-f $home_text) {
4973 print {$out} "<div class=\"index_include\">\n";
4974 insert_file($home_text);
4975 print {$out} "</div>\n";
4977 print {$out} $cgi->startform(-method => "get") .
4978 "<p class=\"projsearch\">Search:\n" .
4979 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4980 "</p>" .
4981 $cgi->end_form() . "\n";
4982 git_project_list_body(\@list, $order);
4983 git_footer_html();
4986 sub git_forks {
4987 my $order = $input_params{'order'};
4988 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4989 die_error(400, "Unknown order parameter");
4992 my @list = git_get_projects_list($project);
4993 if (!@list) {
4994 die_error(404, "No forks found");
4997 git_header_html();
4998 git_print_page_nav('','');
4999 git_print_header_div('summary', "$project forks");
5000 git_project_list_body(\@list, $order);
5001 git_footer_html();
5004 sub git_project_index {
5005 my @projects = git_get_projects_list($project);
5007 print {$out} $cgi->header(
5008 -type => 'text/plain',
5009 -charset => 'utf-8',
5010 -content_disposition => 'inline; filename="index.aux"');
5012 foreach my $pr (@projects) {
5013 if (!exists $pr->{'owner'}) {
5014 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5017 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5018 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5019 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5020 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5021 $path =~ s/ /\+/g;
5022 $owner =~ s/ /\+/g;
5024 print {$out} "$path $owner\n";
5028 sub git_summary {
5029 my $descr = git_get_project_description($project) || "none";
5030 my %co = parse_commit("HEAD");
5031 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5032 my $head = $co{'id'};
5034 my $owner = git_get_project_owner($project);
5036 my $refs = git_get_references();
5037 # These get_*_list functions return one more to allow us to see if
5038 # there are more ...
5039 my @taglist = git_get_tags_list(16);
5040 my @headlist = git_get_heads_list(16);
5041 my @forklist;
5042 my $check_forks = gitweb_check_feature('forks');
5044 if ($check_forks) {
5045 @forklist = git_get_projects_list($project);
5048 git_header_html();
5049 git_print_page_nav('summary','', $head);
5051 print {$out} "<div class=\"title\">&nbsp;</div>\n";
5052 print {$out} "<table class=\"projects_list\">\n" .
5053 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5054 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5055 if (defined $cd{'rfc2822'}) {
5056 print {$out} "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
5059 # use per project git URL list in $projectroot/$project/cloneurl
5060 # or make project git URL from git base URL and project name
5061 my $url_tag = "URL";
5062 my @url_list = git_get_project_url_list($project);
5063 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5064 foreach my $git_url (@url_list) {
5065 next unless $git_url;
5066 print {$out} "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
5067 $url_tag = "";
5070 # Tag cloud
5071 my $show_ctags = gitweb_check_feature('ctags');
5072 if ($show_ctags) {
5073 my $ctags = git_get_project_ctags($project);
5074 my $cloud = git_populate_project_tagcloud($ctags);
5075 print {$out} "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
5076 print {$out} "</td>\n<td>" unless %$ctags;
5077 print {$out} "<form action=\"$show_ctags\" method=\"post\">" .
5078 "<input type=\"hidden\" name=\"p\" value=\"$project\" />" .
5079 "Add: <input type=\"text\" name=\"t\" size=\"8\" />" .
5080 "</form>";
5081 print {$out} "</td>\n<td>" if %$ctags;
5082 print {$out} git_show_project_tagcloud($cloud, 48);
5083 print {$out} "</td></tr>";
5086 print {$out} "</table>\n";
5088 # If XSS prevention is on, we don't include README.html.
5089 # TODO: Allow a readme in some safe format.
5090 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5091 print {$out} "<div class=\"title\">readme</div>\n" .
5092 "<div class=\"readme\">\n";
5093 insert_file("$projectroot/$project/README.html");
5094 print {$out} "\n</div>\n"; # class="readme"
5097 # we need to request one more than 16 (0..15) to check if
5098 # those 16 are all
5099 my @commitlist = $head ? parse_commits($head, 17) : ();
5100 if (@commitlist) {
5101 git_print_header_div('shortlog');
5102 git_shortlog_body(\@commitlist, 0, 15, $refs,
5103 $#commitlist <= 15 ? undef :
5104 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5107 if (@taglist) {
5108 git_print_header_div('tags');
5109 git_tags_body(\@taglist, 0, 15,
5110 $#taglist <= 15 ? undef :
5111 $cgi->a({-href => href(action=>"tags")}, "..."));
5114 if (@headlist) {
5115 git_print_header_div('heads');
5116 git_heads_body(\@headlist, $head, 0, 15,
5117 $#headlist <= 15 ? undef :
5118 $cgi->a({-href => href(action=>"heads")}, "..."));
5121 if (@forklist) {
5122 git_print_header_div('forks');
5123 git_project_list_body(\@forklist, 'age', 0, 15,
5124 $#forklist <= 15 ? undef :
5125 $cgi->a({-href => href(action=>"forks")}, "..."),
5126 'no_header');
5129 git_footer_html();
5132 sub git_tag {
5133 my $head = git_get_head_hash($project);
5134 git_header_html();
5135 git_print_page_nav('','', $head,undef,$head);
5136 my %tag = parse_tag($hash);
5138 if (! %tag) {
5139 die_error(404, "Unknown tag object");
5142 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5143 print {$out} "<div class=\"title_text\">\n" .
5144 "<table class=\"object_header\">\n" .
5145 "<tr>\n" .
5146 "<td>object</td>\n" .
5147 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5148 $tag{'object'}) . "</td>\n" .
5149 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
5150 $tag{'type'}) . "</td>\n" .
5151 "</tr>\n";
5152 if (defined($tag{'author'})) {
5153 git_print_authorship_rows(\%tag, 'author');
5155 print {$out} "</table>\n\n" .
5156 "</div>\n";
5157 print {$out} "<div class=\"page_body\">";
5158 my $comment = $tag{'comment'};
5159 foreach my $line (@$comment) {
5160 chomp $line;
5161 print {$out} esc_html($line, -nbsp=>1) . "<br/>\n";
5163 print {$out} "</div>\n";
5164 git_footer_html();
5167 sub git_blame_common {
5168 my $format = shift || 'porcelain';
5169 if ($format eq 'porcelain' && $cgi->param('js')) {
5170 $format = 'incremental';
5171 $action = 'blame_incremental'; # for page title etc
5174 # permissions
5175 gitweb_check_feature('blame')
5176 or die_error(403, "Blame view not allowed");
5178 # error checking
5179 die_error(400, "No file name given") unless $file_name;
5180 $hash_base ||= git_get_head_hash($project);
5181 die_error(404, "Couldn't find base commit") unless $hash_base;
5182 my %co = parse_commit($hash_base)
5183 or die_error(404, "Commit not found");
5184 my $ftype = "blob";
5185 if (!defined $hash) {
5186 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
5187 or die_error(404, "Error looking up file");
5188 } else {
5189 $ftype = git_get_type($hash);
5190 if ($ftype !~ "blob") {
5191 die_error(400, "Object is not a blob");
5195 my $fd;
5196 if ($format eq 'incremental') {
5197 # get file contents (as base)
5198 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
5199 or die_error(500, "Open git-cat-file failed");
5200 } elsif ($format eq 'data') {
5201 # run git-blame --incremental
5202 open $fd, "-|", git_cmd(), "blame", "--incremental",
5203 $hash_base, "--", $file_name
5204 or die_error(500, "Open git-blame --incremental failed");
5205 } else {
5206 # run git-blame --porcelain
5207 open $fd, "-|", git_cmd(), "blame", '-p',
5208 $hash_base, '--', $file_name
5209 or die_error(500, "Open git-blame --porcelain failed");
5212 # incremental blame data returns early
5213 if ($format eq 'data') {
5214 print {$out} $cgi->header(
5215 -type=>"text/plain", -charset => "utf-8",
5216 -status=> "200 OK");
5217 local $| = 1; # output autoflush
5218 print {$out} $_ while <$fd>;
5219 close $fd
5220 or print {$out} "ERROR $!\n";
5222 print {$out} 'END';
5223 if (defined $t0 && gitweb_check_feature('timed')) {
5224 print {$out} ' '.
5225 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
5226 ' '.$number_of_git_cmds;
5228 print {$out} "\n";
5230 return;
5233 # page header
5234 git_header_html();
5235 my $formats_nav =
5236 $cgi->a({-href => href(action=>"blob", -replay=>1)},
5237 "blob") .
5238 " | ";
5239 if ($format eq 'incremental') {
5240 $formats_nav .=
5241 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
5242 "blame") . " (non-incremental)";
5243 } else {
5244 $formats_nav .=
5245 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
5246 "blame") . " (incremental)";
5248 $formats_nav .=
5249 " | " .
5250 $cgi->a({-href => href(action=>"history", -replay=>1)},
5251 "history") .
5252 " | " .
5253 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
5254 "HEAD");
5255 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5256 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5257 git_print_page_path($file_name, $ftype, $hash_base);
5259 # page body
5260 if ($format eq 'incremental') {
5261 print {$out} "<noscript>\n<div class=\"error\"><center><b>\n".
5262 "This page requires JavaScript to run.\n Use ".
5263 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
5264 'this page').
5265 " instead.\n".
5266 "</b></center></div>\n</noscript>\n";
5268 print {$out} qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
5271 print {$out} qq!<div class="page_body">\n!;
5272 print {$out} qq!<div id="progress_info">... / ...</div>\n!
5273 if ($format eq 'incremental');
5274 print {$out} qq!<table id="blame_table" class="blame" width="100%">\n!.
5275 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
5276 qq!<thead>\n!.
5277 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
5278 qq!</thead>\n!.
5279 qq!<tbody>\n!;
5281 my @rev_color = qw(light dark);
5282 my $num_colors = scalar(@rev_color);
5283 my $current_color = 0;
5285 if ($format eq 'incremental') {
5286 my $color_class = $rev_color[$current_color];
5288 #contents of a file
5289 my $linenr = 0;
5290 LINE:
5291 while (my $line = <$fd>) {
5292 chomp $line;
5293 $linenr++;
5295 print {$out} qq!<tr id="l$linenr" class="$color_class">!.
5296 qq!<td class="sha1"><a href=""> </a></td>!.
5297 qq!<td class="linenr">!.
5298 qq!<a class="linenr" href="">$linenr</a></td>!;
5299 print {$out} qq!<td class="pre">! . esc_html($line) . "</td>\n";
5300 print {$out} qq!</tr>\n!;
5303 } else { # porcelain, i.e. ordinary blame
5304 my %metainfo = (); # saves information about commits
5306 # blame data
5307 LINE:
5308 while (my $line = <$fd>) {
5309 chomp $line;
5310 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
5311 # no <lines in group> for subsequent lines in group of lines
5312 my ($full_rev, $orig_lineno, $lineno, $group_size) =
5313 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5314 if (!exists $metainfo{$full_rev}) {
5315 $metainfo{$full_rev} = { 'nprevious' => 0 };
5317 my $meta = $metainfo{$full_rev};
5318 my $data;
5319 while ($data = <$fd>) {
5320 chomp $data;
5321 last if ($data =~ s/^\t//); # contents of line
5322 if ($data =~ /^(\S+)(?: (.*))?$/) {
5323 $meta->{$1} = $2 unless exists $meta->{$1};
5325 if ($data =~ /^previous /) {
5326 $meta->{'nprevious'}++;
5329 my $short_rev = substr($full_rev, 0, 8);
5330 my $author = $meta->{'author'};
5331 my %date =
5332 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5333 my $date = $date{'iso-tz'};
5334 if ($group_size) {
5335 $current_color = ($current_color + 1) % $num_colors;
5337 my $tr_class = $rev_color[$current_color];
5338 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5339 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5340 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5341 print {$out} "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5342 if ($group_size) {
5343 print {$out} "<td class=\"sha1\"";
5344 print {$out} " title=\"". esc_html($author) . ", $date\"";
5345 print {$out} " rowspan=\"$group_size\"" if ($group_size > 1);
5346 print {$out} ">";
5347 print {$out} $cgi->a({-href => href(action=>"commit",
5348 hash=>$full_rev,
5349 file_name=>$file_name)},
5350 esc_html($short_rev));
5351 if ($group_size >= 2) {
5352 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5353 if (@author_initials) {
5354 print {$out} "<br />" .
5355 esc_html(join('', @author_initials));
5356 # or join('.', ...)
5359 print {$out} "</td>\n";
5361 # 'previous' <sha1 of parent commit> <filename at commit>
5362 if (exists $meta->{'previous'} &&
5363 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5364 $meta->{'parent'} = $1;
5365 $meta->{'file_parent'} = unquote($2);
5367 my $linenr_commit =
5368 exists($meta->{'parent'}) ?
5369 $meta->{'parent'} : $full_rev;
5370 my $linenr_filename =
5371 exists($meta->{'file_parent'}) ?
5372 $meta->{'file_parent'} : unquote($meta->{'filename'});
5373 my $blamed = href(action => 'blame',
5374 file_name => $linenr_filename,
5375 hash_base => $linenr_commit);
5376 print {$out} "<td class=\"linenr\">";
5377 print {$out} $cgi->a({ -href => "$blamed#l$orig_lineno",
5378 -class => "linenr" },
5379 esc_html($lineno));
5380 print {$out} "</td>";
5381 print {$out} "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5382 print {$out} "</tr>\n";
5383 } # end while
5387 # footer
5388 print {$out} "</tbody>\n".
5389 "</table>\n"; # class="blame"
5390 print {$out} "</div>\n"; # class="blame_body"
5391 close $fd
5392 or print {$out} "Reading blob failed\n";
5394 git_footer_html();
5397 sub git_blame {
5398 git_blame_common();
5401 sub git_blame_incremental {
5402 git_blame_common('incremental');
5405 sub git_blame_data {
5406 git_blame_common('data');
5409 sub git_tags {
5410 my $head = git_get_head_hash($project);
5411 git_header_html();
5412 git_print_page_nav('','', $head,undef,$head);
5413 git_print_header_div('summary', $project);
5415 my @tagslist = git_get_tags_list();
5416 if (@tagslist) {
5417 git_tags_body(\@tagslist);
5419 git_footer_html();
5422 sub git_heads {
5423 my $head = git_get_head_hash($project);
5424 git_header_html();
5425 git_print_page_nav('','', $head,undef,$head);
5426 git_print_header_div('summary', $project);
5428 my @headslist = git_get_heads_list();
5429 if (@headslist) {
5430 git_heads_body(\@headslist, $head);
5432 git_footer_html();
5435 sub git_blob_plain {
5436 my $type = shift;
5437 my $expires;
5439 if (!defined $hash) {
5440 if (defined $file_name) {
5441 my $base = $hash_base || git_get_head_hash($project);
5442 $hash = git_get_hash_by_path($base, $file_name, "blob")
5443 or die_error(404, "Cannot find file");
5444 } else {
5445 die_error(400, "No file name defined");
5447 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5448 # blobs defined by non-textual hash id's can be cached
5449 $expires = "+1d";
5452 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5453 or die_error(500, "Open git-cat-file blob '$hash' failed");
5455 # content-type (can include charset)
5456 $type = blob_contenttype($fd, $file_name, $type);
5458 # "save as" filename, even when no $file_name is given
5459 my $save_as = "$hash";
5460 if (defined $file_name) {
5461 $save_as = $file_name;
5462 } elsif ($type =~ m/^text\//) {
5463 $save_as .= '.txt';
5466 # With XSS prevention on, blobs of all types except a few known safe
5467 # ones are served with "Content-Disposition: attachment" to make sure
5468 # they don't run in our security domain. For certain image types,
5469 # blob view writes an <img> tag referring to blob_plain view, and we
5470 # want to be sure not to break that by serving the image as an
5471 # attachment (though Firefox 3 doesn't seem to care).
5472 my $sandbox = $prevent_xss &&
5473 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5475 print {$out} $cgi->header(
5476 -type => $type,
5477 -expires => $expires,
5478 -content_disposition =>
5479 ($sandbox ? 'attachment' : 'inline')
5480 . '; filename="' . $save_as . '"');
5481 local $/ = undef;
5482 binmode $out, ':raw';
5483 print {$out} <$fd>;
5484 binmode $out, ':utf8'; # as set at the beginning of gitweb.cgi
5485 close $fd;
5488 sub git_blob {
5489 my $expires;
5491 if (!defined $hash) {
5492 if (defined $file_name) {
5493 my $base = $hash_base || git_get_head_hash($project);
5494 $hash = git_get_hash_by_path($base, $file_name, "blob")
5495 or die_error(404, "Cannot find file");
5496 } else {
5497 die_error(400, "No file name defined");
5499 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5500 # blobs defined by non-textual hash id's can be cached
5501 $expires = "+1d";
5504 my $have_blame = gitweb_check_feature('blame');
5505 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5506 or die_error(500, "Couldn't cat $file_name, $hash");
5507 my $mimetype = blob_mimetype($fd, $file_name);
5508 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5509 close $fd;
5510 return git_blob_plain($mimetype);
5512 # we can have blame only for text/* mimetype
5513 $have_blame &&= ($mimetype =~ m!^text/!);
5515 git_header_html(undef, $expires);
5516 my $formats_nav = '';
5517 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5518 if (defined $file_name) {
5519 if ($have_blame) {
5520 $formats_nav .=
5521 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5522 "blame") .
5523 " | ";
5525 $formats_nav .=
5526 $cgi->a({-href => href(action=>"history", -replay=>1)},
5527 "history") .
5528 " | " .
5529 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5530 "raw") .
5531 " | " .
5532 $cgi->a({-href => href(action=>"blob",
5533 hash_base=>"HEAD", file_name=>$file_name)},
5534 "HEAD");
5535 } else {
5536 $formats_nav .=
5537 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5538 "raw");
5540 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5541 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5542 } else {
5543 print {$out} "<div class=\"page_nav\">\n" .
5544 "<br/><br/></div>\n" .
5545 "<div class=\"title\">$hash</div>\n";
5547 git_print_page_path($file_name, "blob", $hash_base);
5548 print {$out} "<div class=\"page_body\">\n";
5549 if ($mimetype =~ m!^image/!) {
5550 print {$out} qq!<img type="$mimetype"!;
5551 if ($file_name) {
5552 print {$out} qq! alt="$file_name" title="$file_name"!;
5554 print {$out} qq! src="! .
5555 href(action=>"blob_plain", hash=>$hash,
5556 hash_base=>$hash_base, file_name=>$file_name) .
5557 qq!" />\n!;
5558 } else {
5559 my $nr;
5560 while (my $line = <$fd>) {
5561 chomp $line;
5562 $nr++;
5563 $line = untabify($line);
5564 printf {$out} "<div class=\"pre\"><a id=\"l%i\" href=\"" .
5565 href(-replay => 1) .
5566 "#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5567 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5570 close $fd
5571 or print {$out} "Reading blob failed.\n";
5572 print {$out} "</div>";
5573 git_footer_html();
5576 sub git_tree {
5577 if (!defined $hash_base) {
5578 $hash_base = "HEAD";
5580 if (!defined $hash) {
5581 if (defined $file_name) {
5582 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5583 } else {
5584 $hash = $hash_base;
5587 die_error(404, "No such tree") unless defined($hash);
5589 my $show_sizes = gitweb_check_feature('show-sizes');
5590 my $have_blame = gitweb_check_feature('blame');
5592 my @entries = ();
5594 local $/ = "\0";
5595 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5596 ($show_sizes ? '-l' : ()), @extra_options, $hash
5597 or die_error(500, "Open git-ls-tree failed");
5598 @entries = map { chomp; $_ } <$fd>;
5599 close $fd
5600 or die_error(404, "Reading tree failed");
5603 my $refs = git_get_references();
5604 my $ref = format_ref_marker($refs, $hash_base);
5605 git_header_html();
5606 my $basedir = '';
5607 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5608 my @views_nav = ();
5609 if (defined $file_name) {
5610 push @views_nav,
5611 $cgi->a({-href => href(action=>"history", -replay=>1)},
5612 "history"),
5613 $cgi->a({-href => href(action=>"tree",
5614 hash_base=>"HEAD", file_name=>$file_name)},
5615 "HEAD"),
5617 my $snapshot_links = format_snapshot_links($hash);
5618 if (defined $snapshot_links) {
5619 # FIXME: Should be available when we have no hash base as well.
5620 push @views_nav, $snapshot_links;
5622 git_print_page_nav('tree','', $hash_base, undef, undef,
5623 join(' | ', @views_nav));
5624 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5625 } else {
5626 undef $hash_base;
5627 print {$out} "<div class=\"page_nav\">\n";
5628 print {$out} "<br/><br/></div>\n";
5629 print {$out} "<div class=\"title\">$hash</div>\n";
5631 if (defined $file_name) {
5632 $basedir = $file_name;
5633 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5634 $basedir .= '/';
5636 git_print_page_path($file_name, 'tree', $hash_base);
5638 print {$out} "<div class=\"page_body\">\n";
5639 print {$out} "<table class=\"tree\">\n";
5640 my $alternate = 1;
5641 # '..' (top directory) link if possible
5642 if (defined $hash_base &&
5643 defined $file_name && $file_name =~ m![^/]+$!) {
5644 if ($alternate) {
5645 print {$out} "<tr class=\"dark\">\n";
5646 } else {
5647 print {$out} "<tr class=\"light\">\n";
5649 $alternate ^= 1;
5651 my $up = $file_name;
5652 $up =~ s!/?[^/]+$!!;
5653 undef $up unless $up;
5654 # based on git_print_tree_entry
5655 print {$out} '<td class="mode">' . mode_str('040000') . "</td>\n";
5656 print {$out} '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5657 print {$out} '<td class="list">';
5658 print {$out} $cgi->a({-href => href(action=>"tree",
5659 hash_base=>$hash_base,
5660 file_name=>$up)},
5661 "..");
5662 print {$out} "</td>\n";
5663 print {$out} "<td class=\"link\"></td>\n";
5665 print {$out} "</tr>\n";
5667 foreach my $line (@entries) {
5668 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5670 if ($alternate) {
5671 print {$out} "<tr class=\"dark\">\n";
5672 } else {
5673 print {$out} "<tr class=\"light\">\n";
5675 $alternate ^= 1;
5677 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5679 print {$out} "</tr>\n";
5681 print {$out} "</table>\n" .
5682 "</div>";
5683 git_footer_html();
5686 sub snapshot_name {
5687 my ($project, $hash) = @_;
5689 # path/to/project.git -> project
5690 # path/to/project/.git -> project
5691 my $name = to_utf8($project);
5692 $name =~ s,([^/])/*\.git$,$1,;
5693 $name = basename($name);
5694 # sanitize name
5695 $name =~ s/[[:cntrl:]]/?/g;
5697 my $ver = $hash;
5698 if ($hash =~ /^[0-9a-fA-F]+$/) {
5699 # shorten SHA-1 hash
5700 my $full_hash = git_get_full_hash($project, $hash);
5701 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
5702 $ver = git_get_short_hash($project, $hash);
5704 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
5705 # tags don't need shortened SHA-1 hash
5706 $ver = $1;
5707 } else {
5708 # branches and other need shortened SHA-1 hash
5709 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
5710 $ver = $1;
5712 $ver .= '-' . git_get_short_hash($project, $hash);
5714 # in case of hierarchical branch names
5715 $ver =~ s!/!.!g;
5717 # name = project-version_string
5718 $name = "$name-$ver";
5720 return wantarray ? ($name, $name) : $name;
5723 sub git_snapshot {
5724 my $format = $input_params{'snapshot_format'};
5725 if (!@snapshot_fmts) {
5726 die_error(403, "Snapshots not allowed");
5728 # default to first supported snapshot format
5729 $format ||= $snapshot_fmts[0];
5730 if ($format !~ m/^[a-z0-9]+$/) {
5731 die_error(400, "Invalid snapshot format parameter");
5732 } elsif (!exists($known_snapshot_formats{$format})) {
5733 die_error(400, "Unknown snapshot format");
5734 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5735 die_error(403, "Snapshot format not allowed");
5736 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5737 die_error(403, "Unsupported snapshot format");
5740 my $type = git_get_type("$hash^{}");
5741 if (!$type) {
5742 die_error(404, 'Object does not exist');
5743 } elsif ($type eq 'blob') {
5744 die_error(400, 'Object is not a tree-ish');
5747 my ($name, $prefix) = snapshot_name($project, $hash);
5748 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
5749 my $cmd = quote_command(
5750 git_cmd(), 'archive',
5751 "--format=$known_snapshot_formats{$format}{'format'}",
5752 "--prefix=$prefix/", $hash);
5753 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5754 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5757 $filename =~ s/(["\\])/\\$1/g;
5758 print {$out} $cgi->header(
5759 -type => $known_snapshot_formats{$format}{'type'},
5760 -content_disposition => 'inline; filename="' . $filename . '"',
5761 -status => '200 OK');
5763 open my $fd, "-|", $cmd
5764 or die_error(500, "Execute git-archive failed");
5765 binmode $out, ':raw';
5766 print {$out} <$fd>;
5767 binmode $out, ':utf8'; # as set at the beginning of gitweb.cgi
5768 close $fd;
5771 sub git_log_generic {
5772 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
5774 my $head = git_get_head_hash($project);
5775 if (!defined $base) {
5776 $base = $head;
5778 if (!defined $page) {
5779 $page = 0;
5781 my $refs = git_get_references();
5783 my $commit_hash = $base;
5784 if (defined $parent) {
5785 $commit_hash = "$parent..$base";
5787 my @commitlist =
5788 parse_commits($commit_hash, 101, (100 * $page),
5789 defined $file_name ? ($file_name, "--full-history") : ());
5791 my $ftype;
5792 if (!defined $file_hash && defined $file_name) {
5793 # some commits could have deleted file in question,
5794 # and not have it in tree, but one of them has to have it
5795 for (my $i = 0; $i < @commitlist; $i++) {
5796 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5797 last if defined $file_hash;
5800 if (defined $file_hash) {
5801 $ftype = git_get_type($file_hash);
5803 if (defined $file_name && !defined $ftype) {
5804 die_error(500, "Unknown type of object");
5806 my %co;
5807 if (defined $file_name) {
5808 %co = parse_commit($base)
5809 or die_error(404, "Unknown commit object");
5813 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
5814 my $next_link = '';
5815 if ($#commitlist >= 100) {
5816 $next_link =
5817 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5818 -accesskey => "n", -title => "Alt-n"}, "next");
5820 my $patch_max = gitweb_get_feature('patches');
5821 if ($patch_max && !defined $file_name) {
5822 if ($patch_max < 0 || @commitlist <= $patch_max) {
5823 $paging_nav .= " &sdot; " .
5824 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5825 "patches");
5829 git_header_html();
5830 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
5831 if (defined $file_name) {
5832 git_print_header_div('commit', esc_html($co{'title'}), $base);
5833 } else {
5834 git_print_header_div('summary', $project)
5836 git_print_page_path($file_name, $ftype, $hash_base)
5837 if (defined $file_name);
5839 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
5840 $file_name, $file_hash, $ftype);
5842 git_footer_html();
5845 sub git_log {
5846 git_log_generic('log', \&git_log_body,
5847 $hash, $hash_parent);
5850 sub git_commit {
5851 $hash ||= $hash_base || "HEAD";
5852 my %co = parse_commit($hash)
5853 or die_error(404, "Unknown commit object");
5855 my $parent = $co{'parent'};
5856 my $parents = $co{'parents'}; # listref
5858 # we need to prepare $formats_nav before any parameter munging
5859 my $formats_nav;
5860 if (!defined $parent) {
5861 # --root commitdiff
5862 $formats_nav .= '(initial)';
5863 } elsif (@$parents == 1) {
5864 # single parent commit
5865 $formats_nav .=
5866 '(parent: ' .
5867 $cgi->a({-href => href(action=>"commit",
5868 hash=>$parent)},
5869 esc_html(substr($parent, 0, 7))) .
5870 ')';
5871 } else {
5872 # merge commit
5873 $formats_nav .=
5874 '(merge: ' .
5875 join(' ', map {
5876 $cgi->a({-href => href(action=>"commit",
5877 hash=>$_)},
5878 esc_html(substr($_, 0, 7)));
5879 } @$parents ) .
5880 ')';
5882 if (gitweb_check_feature('patches') && @$parents <= 1) {
5883 $formats_nav .= " | " .
5884 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5885 "patch");
5888 if (!defined $parent) {
5889 $parent = "--root";
5891 my @difftree;
5892 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5893 @diff_opts,
5894 (@$parents <= 1 ? $parent : '-c'),
5895 $hash, "--"
5896 or die_error(500, "Open git-diff-tree failed");
5897 @difftree = map { chomp; $_ } <$fd>;
5898 close $fd or die_error(404, "Reading git-diff-tree failed");
5900 # non-textual hash id's can be cached
5901 my $expires;
5902 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5903 $expires = "+1d";
5905 my $refs = git_get_references();
5906 my $ref = format_ref_marker($refs, $co{'id'});
5908 git_header_html(undef, $expires);
5909 git_print_page_nav('commit', '',
5910 $hash, $co{'tree'}, $hash,
5911 $formats_nav);
5913 if (defined $co{'parent'}) {
5914 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5915 } else {
5916 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5918 print {$out} "<div class=\"title_text\">\n" .
5919 "<table class=\"object_header\">\n";
5920 git_print_authorship_rows(\%co);
5921 print {$out} "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5922 print {$out} "<tr>" .
5923 "<td>tree</td>" .
5924 "<td class=\"sha1\">" .
5925 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5926 class => "list"}, $co{'tree'}) .
5927 "</td>" .
5928 "<td class=\"link\">" .
5929 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5930 "tree");
5931 my $snapshot_links = format_snapshot_links($hash);
5932 if (defined $snapshot_links) {
5933 print {$out} " | " . $snapshot_links;
5935 print {$out} "</td>" .
5936 "</tr>\n";
5938 foreach my $par (@$parents) {
5939 print {$out} "<tr>" .
5940 "<td>parent</td>" .
5941 "<td class=\"sha1\">" .
5942 $cgi->a({-href => href(action=>"commit", hash=>$par),
5943 class => "list"}, $par) .
5944 "</td>" .
5945 "<td class=\"link\">" .
5946 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5947 " | " .
5948 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5949 "</td>" .
5950 "</tr>\n";
5952 print {$out} "</table>".
5953 "</div>\n";
5955 print {$out} "<div class=\"page_body\">\n";
5956 git_print_log($co{'comment'});
5957 print {$out} "</div>\n";
5959 git_difftree_body(\@difftree, $hash, @$parents);
5961 git_footer_html();
5964 sub git_object {
5965 # object is defined by:
5966 # - hash or hash_base alone
5967 # - hash_base and file_name
5968 my $type;
5970 # - hash or hash_base alone
5971 if ($hash || ($hash_base && !defined $file_name)) {
5972 my $object_id = $hash || $hash_base;
5974 open my $fd, "-|", quote_command(
5975 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5976 or die_error(404, "Object does not exist");
5977 $type = <$fd>;
5978 chomp $type;
5979 close $fd
5980 or die_error(404, "Object does not exist");
5982 # - hash_base and file_name
5983 } elsif ($hash_base && defined $file_name) {
5984 $file_name =~ s,/+$,,;
5986 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5987 or die_error(404, "Base object does not exist");
5989 # here errors should not hapen
5990 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5991 or die_error(500, "Open git-ls-tree failed");
5992 my $line = <$fd>;
5993 close $fd;
5995 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5996 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5997 die_error(404, "File or directory for given base does not exist");
5999 $type = $2;
6000 $hash = $3;
6001 } else {
6002 die_error(400, "Not enough information to find object");
6005 print {$out} $cgi->redirect(-uri => href(action=>$type, -full=>1,
6006 hash=>$hash, hash_base=>$hash_base,
6007 file_name=>$file_name),
6008 -status => '302 Found');
6011 sub git_blobdiff {
6012 my $format = shift || 'html';
6014 my $fd;
6015 my @difftree;
6016 my %diffinfo;
6017 my $expires;
6019 # preparing $fd and %diffinfo for git_patchset_body
6020 # new style URI
6021 if (defined $hash_base && defined $hash_parent_base) {
6022 if (defined $file_name) {
6023 # read raw output
6024 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6025 $hash_parent_base, $hash_base,
6026 "--", (defined $file_parent ? $file_parent : ()), $file_name
6027 or die_error(500, "Open git-diff-tree failed");
6028 @difftree = map { chomp; $_ } <$fd>;
6029 close $fd
6030 or die_error(404, "Reading git-diff-tree failed");
6031 @difftree
6032 or die_error(404, "Blob diff not found");
6034 } elsif (defined $hash &&
6035 $hash =~ /[0-9a-fA-F]{40}/) {
6036 # try to find filename from $hash
6038 # read filtered raw output
6039 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6040 $hash_parent_base, $hash_base, "--"
6041 or die_error(500, "Open git-diff-tree failed");
6042 @difftree =
6043 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6044 # $hash == to_id
6045 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6046 map { chomp; $_ } <$fd>;
6047 close $fd
6048 or die_error(404, "Reading git-diff-tree failed");
6049 @difftree
6050 or die_error(404, "Blob diff not found");
6052 } else {
6053 die_error(400, "Missing one of the blob diff parameters");
6056 if (@difftree > 1) {
6057 die_error(400, "Ambiguous blob diff specification");
6060 %diffinfo = parse_difftree_raw_line($difftree[0]);
6061 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6062 $file_name ||= $diffinfo{'to_file'};
6064 $hash_parent ||= $diffinfo{'from_id'};
6065 $hash ||= $diffinfo{'to_id'};
6067 # non-textual hash id's can be cached
6068 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6069 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6070 $expires = '+1d';
6073 # open patch output
6074 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6075 '-p', ($format eq 'html' ? "--full-index" : ()),
6076 $hash_parent_base, $hash_base,
6077 "--", (defined $file_parent ? $file_parent : ()), $file_name
6078 or die_error(500, "Open git-diff-tree failed");
6081 # old/legacy style URI -- not generated anymore since 1.4.3.
6082 if (!%diffinfo) {
6083 die_error('404 Not Found', "Missing one of the blob diff parameters")
6086 # header
6087 if ($format eq 'html') {
6088 my $formats_nav =
6089 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6090 "raw");
6091 git_header_html(undef, $expires);
6092 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6093 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6094 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6095 } else {
6096 print {$out} "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6097 print {$out} "<div class=\"title\">$hash vs $hash_parent</div>\n";
6099 if (defined $file_name) {
6100 git_print_page_path($file_name, "blob", $hash_base);
6101 } else {
6102 print {$out} "<div class=\"page_path\"></div>\n";
6105 } elsif ($format eq 'plain') {
6106 print {$out} $cgi->header(
6107 -type => 'text/plain',
6108 -charset => 'utf-8',
6109 -expires => $expires,
6110 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
6112 print {$out} "X-Git-Url: " . $cgi->self_url() . "\n\n";
6114 } else {
6115 die_error(400, "Unknown blobdiff format");
6118 # patch
6119 if ($format eq 'html') {
6120 print {$out} "<div class=\"page_body\">\n";
6122 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
6123 close $fd;
6125 print {$out} "</div>\n"; # class="page_body"
6126 git_footer_html();
6128 } else {
6129 while (my $line = <$fd>) {
6130 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
6131 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
6133 print {$out} $line;
6135 last if $line =~ m!^\+\+\+!;
6137 local $/ = undef;
6138 print {$out} <$fd>;
6139 close $fd;
6143 sub git_blobdiff_plain {
6144 git_blobdiff('plain');
6147 sub git_commitdiff {
6148 my %params = @_;
6149 my $format = $params{-format} || 'html';
6151 my ($patch_max) = gitweb_get_feature('patches');
6152 if ($format eq 'patch') {
6153 die_error(403, "Patch view not allowed") unless $patch_max;
6156 $hash ||= $hash_base || "HEAD";
6157 my %co = parse_commit($hash)
6158 or die_error(404, "Unknown commit object");
6160 # choose format for commitdiff for merge
6161 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
6162 $hash_parent = '--cc';
6164 # we need to prepare $formats_nav before almost any parameter munging
6165 my $formats_nav;
6166 if ($format eq 'html') {
6167 $formats_nav =
6168 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
6169 "raw");
6170 if ($patch_max && @{$co{'parents'}} <= 1) {
6171 $formats_nav .= " | " .
6172 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6173 "patch");
6176 if (defined $hash_parent &&
6177 $hash_parent ne '-c' && $hash_parent ne '--cc') {
6178 # commitdiff with two commits given
6179 my $hash_parent_short = $hash_parent;
6180 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
6181 $hash_parent_short = substr($hash_parent, 0, 7);
6183 $formats_nav .=
6184 ' (from';
6185 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
6186 if ($co{'parents'}[$i] eq $hash_parent) {
6187 $formats_nav .= ' parent ' . ($i+1);
6188 last;
6191 $formats_nav .= ': ' .
6192 $cgi->a({-href => href(action=>"commitdiff",
6193 hash=>$hash_parent)},
6194 esc_html($hash_parent_short)) .
6195 ')';
6196 } elsif (!$co{'parent'}) {
6197 # --root commitdiff
6198 $formats_nav .= ' (initial)';
6199 } elsif (scalar @{$co{'parents'}} == 1) {
6200 # single parent commit
6201 $formats_nav .=
6202 ' (parent: ' .
6203 $cgi->a({-href => href(action=>"commitdiff",
6204 hash=>$co{'parent'})},
6205 esc_html(substr($co{'parent'}, 0, 7))) .
6206 ')';
6207 } else {
6208 # merge commit
6209 if ($hash_parent eq '--cc') {
6210 $formats_nav .= ' | ' .
6211 $cgi->a({-href => href(action=>"commitdiff",
6212 hash=>$hash, hash_parent=>'-c')},
6213 'combined');
6214 } else { # $hash_parent eq '-c'
6215 $formats_nav .= ' | ' .
6216 $cgi->a({-href => href(action=>"commitdiff",
6217 hash=>$hash, hash_parent=>'--cc')},
6218 'compact');
6220 $formats_nav .=
6221 ' (merge: ' .
6222 join(' ', map {
6223 $cgi->a({-href => href(action=>"commitdiff",
6224 hash=>$_)},
6225 esc_html(substr($_, 0, 7)));
6226 } @{$co{'parents'}} ) .
6227 ')';
6231 my $hash_parent_param = $hash_parent;
6232 if (!defined $hash_parent_param) {
6233 # --cc for multiple parents, --root for parentless
6234 $hash_parent_param =
6235 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
6238 # read commitdiff
6239 my $fd;
6240 my @difftree;
6241 if ($format eq 'html') {
6242 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6243 "--no-commit-id", "--patch-with-raw", "--full-index",
6244 $hash_parent_param, $hash, "--"
6245 or die_error(500, "Open git-diff-tree failed");
6247 while (my $line = <$fd>) {
6248 chomp $line;
6249 # empty line ends raw part of diff-tree output
6250 last unless $line;
6251 push @difftree, scalar parse_difftree_raw_line($line);
6254 } elsif ($format eq 'plain') {
6255 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6256 '-p', $hash_parent_param, $hash, "--"
6257 or die_error(500, "Open git-diff-tree failed");
6258 } elsif ($format eq 'patch') {
6259 # For commit ranges, we limit the output to the number of
6260 # patches specified in the 'patches' feature.
6261 # For single commits, we limit the output to a single patch,
6262 # diverging from the git-format-patch default.
6263 my @commit_spec = ();
6264 if ($hash_parent) {
6265 if ($patch_max > 0) {
6266 push @commit_spec, "-$patch_max";
6268 push @commit_spec, '-n', "$hash_parent..$hash";
6269 } else {
6270 if ($params{-single}) {
6271 push @commit_spec, '-1';
6272 } else {
6273 if ($patch_max > 0) {
6274 push @commit_spec, "-$patch_max";
6276 push @commit_spec, "-n";
6278 push @commit_spec, '--root', $hash;
6280 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
6281 '--stdout', @commit_spec
6282 or die_error(500, "Open git-format-patch failed");
6283 } else {
6284 die_error(400, "Unknown commitdiff format");
6287 # non-textual hash id's can be cached
6288 my $expires;
6289 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6290 $expires = "+1d";
6293 # write commit message
6294 if ($format eq 'html') {
6295 my $refs = git_get_references();
6296 my $ref = format_ref_marker($refs, $co{'id'});
6298 git_header_html(undef, $expires);
6299 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
6300 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
6301 print {$out} "<div class=\"title_text\">\n" .
6302 "<table class=\"object_header\">\n";
6303 git_print_authorship_rows(\%co);
6304 print {$out} "</table>".
6305 "</div>\n";
6306 print {$out} "<div class=\"page_body\">\n";
6307 if (@{$co{'comment'}} > 1) {
6308 print {$out} "<div class=\"log\">\n";
6309 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
6310 print {$out} "</div>\n"; # class="log"
6313 } elsif ($format eq 'plain') {
6314 my $refs = git_get_references("tags");
6315 my $tagname = git_get_rev_name_tags($hash);
6316 my $filename = basename($project) . "-$hash.patch";
6318 print {$out} $cgi->header(
6319 -type => 'text/plain',
6320 -charset => 'utf-8',
6321 -expires => $expires,
6322 -content_disposition => 'inline; filename="' . "$filename" . '"');
6323 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
6324 print {$out} "From: " . to_utf8($co{'author'}) . "\n";
6325 print {$out} "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
6326 print {$out} "Subject: " . to_utf8($co{'title'}) . "\n";
6328 print {$out} "X-Git-Tag: $tagname\n" if $tagname;
6329 print {$out} "X-Git-Url: " . $cgi->self_url() . "\n\n";
6331 foreach my $line (@{$co{'comment'}}) {
6332 print {$out} to_utf8($line) . "\n";
6334 print {$out} "---\n\n";
6335 } elsif ($format eq 'patch') {
6336 my $filename = basename($project) . "-$hash.patch";
6338 print {$out} $cgi->header(
6339 -type => 'text/plain',
6340 -charset => 'utf-8',
6341 -expires => $expires,
6342 -content_disposition => 'inline; filename="' . "$filename" . '"');
6345 # write patch
6346 if ($format eq 'html') {
6347 my $use_parents = !defined $hash_parent ||
6348 $hash_parent eq '-c' || $hash_parent eq '--cc';
6349 git_difftree_body(\@difftree, $hash,
6350 $use_parents ? @{$co{'parents'}} : $hash_parent);
6351 print {$out} "<br/>\n";
6353 git_patchset_body($fd, \@difftree, $hash,
6354 $use_parents ? @{$co{'parents'}} : $hash_parent);
6355 close $fd;
6356 print {$out} "</div>\n"; # class="page_body"
6357 git_footer_html();
6359 } elsif ($format eq 'plain') {
6360 local $/ = undef;
6361 print {$out} <$fd>;
6362 close $fd
6363 or print {$out} "Reading git-diff-tree failed\n";
6364 } elsif ($format eq 'patch') {
6365 local $/ = undef;
6366 print {$out} <$fd>;
6367 close $fd
6368 or print {$out} "Reading git-format-patch failed\n";
6372 sub git_commitdiff_plain {
6373 git_commitdiff(-format => 'plain');
6376 # format-patch-style patches
6377 sub git_patch {
6378 git_commitdiff(-format => 'patch', -single => 1);
6381 sub git_patches {
6382 git_commitdiff(-format => 'patch');
6385 sub git_history {
6386 git_log_generic('history', \&git_history_body,
6387 $hash_base, $hash_parent_base,
6388 $file_name, $hash);
6391 sub git_search {
6392 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6393 if (!defined $searchtext) {
6394 die_error(400, "Text field is empty");
6396 if (!defined $hash) {
6397 $hash = git_get_head_hash($project);
6399 my %co = parse_commit($hash);
6400 if (!%co) {
6401 die_error(404, "Unknown commit object");
6403 if (!defined $page) {
6404 $page = 0;
6407 $searchtype ||= 'commit';
6408 if ($searchtype eq 'pickaxe') {
6409 # pickaxe may take all resources of your box and run for several minutes
6410 # with every query - so decide by yourself how public you make this feature
6411 gitweb_check_feature('pickaxe')
6412 or die_error(403, "Pickaxe is disabled");
6414 if ($searchtype eq 'grep') {
6415 gitweb_check_feature('grep')
6416 or die_error(403, "Grep is disabled");
6419 git_header_html();
6421 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6422 my $greptype;
6423 if ($searchtype eq 'commit') {
6424 $greptype = "--grep=";
6425 } elsif ($searchtype eq 'author') {
6426 $greptype = "--author=";
6427 } elsif ($searchtype eq 'committer') {
6428 $greptype = "--committer=";
6430 $greptype .= $searchtext;
6431 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6432 $greptype, '--regexp-ignore-case',
6433 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6435 my $paging_nav = '';
6436 if ($page > 0) {
6437 $paging_nav .=
6438 $cgi->a({-href => href(action=>"search", hash=>$hash,
6439 searchtext=>$searchtext,
6440 searchtype=>$searchtype)},
6441 "first");
6442 $paging_nav .= " &sdot; " .
6443 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6444 -accesskey => "p", -title => "Alt-p"}, "prev");
6445 } else {
6446 $paging_nav .= "first";
6447 $paging_nav .= " &sdot; prev";
6449 my $next_link = '';
6450 if ($#commitlist >= 100) {
6451 $next_link =
6452 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6453 -accesskey => "n", -title => "Alt-n"}, "next");
6454 $paging_nav .= " &sdot; $next_link";
6455 } else {
6456 $paging_nav .= " &sdot; next";
6459 if ($#commitlist >= 100) {
6462 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6463 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6464 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6467 if ($searchtype eq 'pickaxe') {
6468 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6469 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6471 print {$out} "<table class=\"pickaxe search\">\n";
6472 my $alternate = 1;
6473 local $/ = "\n";
6474 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6475 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6476 ($search_use_regexp ? '--pickaxe-regex' : ());
6477 undef %co;
6478 my @files;
6479 while (my $line = <$fd>) {
6480 chomp $line;
6481 next unless $line;
6483 my %set = parse_difftree_raw_line($line);
6484 if (defined $set{'commit'}) {
6485 # finish previous commit
6486 if (%co) {
6487 print {$out} "</td>\n" .
6488 "<td class=\"link\">" .
6489 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6490 " | " .
6491 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6492 hash_base=>$co{'id'})}, "tree");
6493 print {$out} "</td>\n" .
6494 "</tr>\n";
6497 if ($alternate) {
6498 print {$out} "<tr class=\"dark\">\n";
6499 } else {
6500 print {$out} "<tr class=\"light\">\n";
6502 $alternate ^= 1;
6503 %co = parse_commit($set{'commit'});
6504 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6505 print {$out} "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6506 "<td><i>$author</i></td>\n" .
6507 "<td>" .
6508 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6509 -class => "list subject"},
6510 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6511 } elsif (defined $set{'to_id'}) {
6512 next if ($set{'to_id'} =~ m/^0{40}$/);
6514 print {$out} $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6515 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6516 -class => "list"},
6517 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6518 "<br/>\n";
6521 close $fd;
6523 # finish last commit (warning: repetition!)
6524 if (%co) {
6525 print {$out} "</td>\n" .
6526 "<td class=\"link\">" .
6527 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6528 " | " .
6529 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6530 print {$out} "</td>\n" .
6531 "</tr>\n";
6534 print {$out} "</table>\n";
6537 if ($searchtype eq 'grep') {
6538 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6539 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6541 print {$out} "<table class=\"grep_search\">\n";
6542 my $alternate = 1;
6543 my $matches = 0;
6544 local $/ = "\n";
6545 open my $fd, "-|", git_cmd(), 'grep', '-n',
6546 $search_use_regexp ? ('-E', '-i') : '-F',
6547 $searchtext, $co{'tree'};
6548 my $lastfile = '';
6549 while (my $line = <$fd>) {
6550 chomp $line;
6551 my ($file, $lno, $ltext, $binary);
6552 last if ($matches++ > 1000);
6553 if ($line =~ /^Binary file (.+) matches$/) {
6554 $file = $1;
6555 $binary = 1;
6556 } else {
6557 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6559 if ($file ne $lastfile) {
6560 $lastfile and print {$out} "</td></tr>\n";
6561 if ($alternate++) {
6562 print {$out} "<tr class=\"dark\">\n";
6563 } else {
6564 print {$out} "<tr class=\"light\">\n";
6566 print {$out} "<td class=\"list\">".
6567 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6568 file_name=>"$file"),
6569 -class => "list"}, esc_path($file));
6570 print {$out} "</td><td>\n";
6571 $lastfile = $file;
6573 if ($binary) {
6574 print {$out} "<div class=\"binary\">Binary file</div>\n";
6575 } else {
6576 $ltext = untabify($ltext);
6577 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6578 $ltext = esc_html($1, -nbsp=>1);
6579 $ltext .= '<span class="match">';
6580 $ltext .= esc_html($2, -nbsp=>1);
6581 $ltext .= '</span>';
6582 $ltext .= esc_html($3, -nbsp=>1);
6583 } else {
6584 $ltext = esc_html($ltext, -nbsp=>1);
6586 print {$out} "<div class=\"pre\">" .
6587 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6588 file_name=>"$file").'#l'.$lno,
6589 -class => "linenr"}, sprintf('%4i', $lno)) .
6590 ' ' . $ltext . "</div>\n";
6593 if ($lastfile) {
6594 print {$out} "</td></tr>\n";
6595 if ($matches > 1000) {
6596 print {$out} "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6598 } else {
6599 print {$out} "<div class=\"diff nodifferences\">No matches found</div>\n";
6601 close $fd;
6603 print {$out} "</table>\n";
6605 git_footer_html();
6608 sub git_search_help {
6609 git_header_html();
6610 git_print_page_nav('','', $hash,$hash,$hash);
6611 print {$out} <<EOT;
6612 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6613 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6614 the pattern entered is recognized as the POSIX extended
6615 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6616 insensitive).</p>
6617 <dl>
6618 <dt><b>commit</b></dt>
6619 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6621 my $have_grep = gitweb_check_feature('grep');
6622 if ($have_grep) {
6623 print {$out} <<EOT;
6624 <dt><b>grep</b></dt>
6625 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6626 a different one) are searched for the given pattern. On large trees, this search can take
6627 a while and put some strain on the server, so please use it with some consideration. Note that
6628 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6629 case-sensitive.</dd>
6632 print {$out} <<EOT;
6633 <dt><b>author</b></dt>
6634 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6635 <dt><b>committer</b></dt>
6636 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6638 my $have_pickaxe = gitweb_check_feature('pickaxe');
6639 if ($have_pickaxe) {
6640 print {$out} <<EOT;
6641 <dt><b>pickaxe</b></dt>
6642 <dd>All commits that caused the string to appear or disappear from any file (changes that
6643 added, removed or "modified" the string) will be listed. This search can take a while and
6644 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6645 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6648 print {$out} "</dl>\n";
6649 git_footer_html();
6652 sub git_shortlog {
6653 git_log_generic('shortlog', \&git_shortlog_body,
6654 $hash, $hash_parent);
6657 ## ......................................................................
6658 ## feeds (RSS, Atom; OPML)
6660 sub git_feed {
6661 my $format = shift || 'atom';
6662 my $have_blame = gitweb_check_feature('blame');
6664 # Atom: http://www.atomenabled.org/developers/syndication/
6665 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6666 if ($format ne 'rss' && $format ne 'atom') {
6667 die_error(400, "Unknown web feed format");
6670 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6671 my $head = $hash || 'HEAD';
6672 my @commitlist = parse_commits($head, 150, 0, $file_name);
6674 my %latest_commit;
6675 my %latest_date;
6676 my $content_type = "application/$format+xml";
6677 if (defined $cgi->http('HTTP_ACCEPT') &&
6678 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6679 # browser (feed reader) prefers text/xml
6680 $content_type = 'text/xml';
6682 if (defined($commitlist[0])) {
6683 %latest_commit = %{$commitlist[0]};
6684 my $latest_epoch = $latest_commit{'committer_epoch'};
6685 %latest_date = parse_date($latest_epoch);
6686 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6687 if (defined $if_modified) {
6688 my $since;
6689 if (eval { require HTTP::Date; 1; }) {
6690 $since = HTTP::Date::str2time($if_modified);
6691 } elsif (eval { require Time::ParseDate; 1; }) {
6692 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6694 if (defined $since && $latest_epoch <= $since) {
6695 print {$out} $cgi->header(
6696 -type => $content_type,
6697 -charset => 'utf-8',
6698 -last_modified => $latest_date{'rfc2822'},
6699 -status => '304 Not Modified');
6700 return;
6703 print {$out} $cgi->header(
6704 -type => $content_type,
6705 -charset => 'utf-8',
6706 -last_modified => $latest_date{'rfc2822'});
6707 } else {
6708 print {$out} $cgi->header(
6709 -type => $content_type,
6710 -charset => 'utf-8');
6713 # Optimization: skip generating the body if client asks only
6714 # for Last-Modified date.
6715 return if ($cgi->request_method() eq 'HEAD');
6717 # header variables
6718 my $title = "$site_name - $project/$action";
6719 my $feed_type = 'log';
6720 if (defined $hash) {
6721 $title .= " - '$hash'";
6722 $feed_type = 'branch log';
6723 if (defined $file_name) {
6724 $title .= " :: $file_name";
6725 $feed_type = 'history';
6727 } elsif (defined $file_name) {
6728 $title .= " - $file_name";
6729 $feed_type = 'history';
6731 $title .= " $feed_type";
6732 my $descr = git_get_project_description($project);
6733 if (defined $descr) {
6734 $descr = esc_html($descr);
6735 } else {
6736 $descr = "$project " .
6737 ($format eq 'rss' ? 'RSS' : 'Atom') .
6738 " feed";
6740 my $owner = git_get_project_owner($project);
6741 $owner = esc_html($owner);
6743 #header
6744 my $alt_url;
6745 if (defined $file_name) {
6746 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6747 } elsif (defined $hash) {
6748 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6749 } else {
6750 $alt_url = href(-full=>1, action=>"summary");
6752 print {$out} qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6753 if ($format eq 'rss') {
6754 print {$out} <<XML;
6755 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6756 <channel>
6758 print {$out} "<title>$title</title>\n" .
6759 "<link>$alt_url</link>\n" .
6760 "<description>$descr</description>\n" .
6761 "<language>en</language>\n" .
6762 # project owner is responsible for 'editorial' content
6763 "<managingEditor>$owner</managingEditor>\n";
6764 if (defined $logo || defined $favicon) {
6765 # prefer the logo to the favicon, since RSS
6766 # doesn't allow both
6767 my $img = esc_url($logo || $favicon);
6768 print {$out} "<image>\n" .
6769 "<url>$img</url>\n" .
6770 "<title>$title</title>\n" .
6771 "<link>$alt_url</link>\n" .
6772 "</image>\n";
6774 if (%latest_date) {
6775 print {$out} "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6776 print {$out} "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6778 print {$out} "<generator>gitweb v.$version/$git_version</generator>\n";
6779 } elsif ($format eq 'atom') {
6780 print {$out} <<XML;
6781 <feed xmlns="http://www.w3.org/2005/Atom">
6783 print {$out} "<title>$title</title>\n" .
6784 "<subtitle>$descr</subtitle>\n" .
6785 '<link rel="alternate" type="text/html" href="' .
6786 $alt_url . '" />' . "\n" .
6787 '<link rel="self" type="' . $content_type . '" href="' .
6788 $cgi->self_url() . '" />' . "\n" .
6789 "<id>" . href(-full=>1) . "</id>\n" .
6790 # use project owner for feed author
6791 "<author><name>$owner</name></author>\n";
6792 if (defined $favicon) {
6793 print {$out} "<icon>" . esc_url($favicon) . "</icon>\n";
6795 if (defined $logo_url) {
6796 # not twice as wide as tall: 72 x 27 pixels
6797 print {$out} "<logo>" . esc_url($logo) . "</logo>\n";
6799 if (! %latest_date) {
6800 # dummy date to keep the feed valid until commits trickle in:
6801 print {$out} "<updated>1970-01-01T00:00:00Z</updated>\n";
6802 } else {
6803 print {$out} "<updated>$latest_date{'iso-8601'}</updated>\n";
6805 print {$out} "<generator version='$version/$git_version'>gitweb</generator>\n";
6808 # contents
6809 for (my $i = 0; $i <= $#commitlist; $i++) {
6810 my %co = %{$commitlist[$i]};
6811 my $commit = $co{'id'};
6812 # we read 150, we always show 30 and the ones more recent than 48 hours
6813 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6814 last;
6816 my %cd = parse_date($co{'author_epoch'});
6818 # get list of changed files
6819 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6820 $co{'parent'} || "--root",
6821 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6822 or next;
6823 my @difftree = map { chomp; $_ } <$fd>;
6824 close $fd
6825 or next;
6827 # print element (entry, item)
6828 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6829 if ($format eq 'rss') {
6830 print {$out} "<item>\n" .
6831 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6832 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6833 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6834 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6835 "<link>$co_url</link>\n" .
6836 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6837 "<content:encoded>" .
6838 "<![CDATA[\n";
6839 } elsif ($format eq 'atom') {
6840 print {$out} "<entry>\n" .
6841 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6842 "<updated>$cd{'iso-8601'}</updated>\n" .
6843 "<author>\n" .
6844 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6845 if ($co{'author_email'}) {
6846 print {$out} " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6848 print {$out} "</author>\n" .
6849 # use committer for contributor
6850 "<contributor>\n" .
6851 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6852 if ($co{'committer_email'}) {
6853 print {$out} " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6855 print {$out} "</contributor>\n" .
6856 "<published>$cd{'iso-8601'}</published>\n" .
6857 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6858 "<id>$co_url</id>\n" .
6859 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6860 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6862 my $comment = $co{'comment'};
6863 print {$out} "<pre>\n";
6864 foreach my $line (@$comment) {
6865 $line = esc_html($line);
6866 print {$out} "$line\n";
6868 print {$out} "</pre><ul>\n";
6869 foreach my $difftree_line (@difftree) {
6870 my %difftree = parse_difftree_raw_line($difftree_line);
6871 next if !$difftree{'from_id'};
6873 my $file = $difftree{'file'} || $difftree{'to_file'};
6875 print {$out} "<li>" .
6876 "[" .
6877 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6878 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6879 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6880 file_name=>$file, file_parent=>$difftree{'from_file'}),
6881 -title => "diff"}, 'D');
6882 if ($have_blame) {
6883 print {$out} $cgi->a({-href => href(-full=>1, action=>"blame",
6884 file_name=>$file, hash_base=>$commit),
6885 -title => "blame"}, 'B');
6887 # if this is not a feed of a file history
6888 if (!defined $file_name || $file_name ne $file) {
6889 print {$out} $cgi->a({-href => href(-full=>1, action=>"history",
6890 file_name=>$file, hash=>$commit),
6891 -title => "history"}, 'H');
6893 $file = esc_path($file);
6894 print {$out} "] ".
6895 "$file</li>\n";
6897 if ($format eq 'rss') {
6898 print {$out} "</ul>]]>\n" .
6899 "</content:encoded>\n" .
6900 "</item>\n";
6901 } elsif ($format eq 'atom') {
6902 print {$out} "</ul>\n</div>\n" .
6903 "</content>\n" .
6904 "</entry>\n";
6908 # end of feed
6909 if ($format eq 'rss') {
6910 print {$out} "</channel>\n</rss>\n";
6911 } elsif ($format eq 'atom') {
6912 print {$out} "</feed>\n";
6916 sub git_rss {
6917 git_feed('rss');
6920 sub git_atom {
6921 git_feed('atom');
6924 sub git_opml {
6925 my @list = git_get_projects_list();
6927 print {$out} $cgi->header(
6928 -type => 'text/xml',
6929 -charset => 'utf-8',
6930 -content_disposition => 'inline; filename="opml.xml"');
6932 print {$out} <<XML;
6933 <?xml version="1.0" encoding="utf-8"?>
6934 <opml version="1.0">
6935 <head>
6936 <title>$site_name OPML Export</title>
6937 </head>
6938 <body>
6939 <outline text="git RSS feeds">
6942 foreach my $pr (@list) {
6943 my %proj = %$pr;
6944 my $head = git_get_head_hash($proj{'path'});
6945 if (!defined $head) {
6946 next;
6948 $git_dir = "$projectroot/$proj{'path'}";
6949 my %co = parse_commit($head);
6950 if (!%co) {
6951 next;
6954 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6955 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6956 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6957 print {$out} "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6959 print {$out} <<XML;
6960 </outline>
6961 </body>
6962 </opml>