gitweb: Use light/dark class also in 'blame' view
[git/dscho.git] / gitweb / gitweb.perl
blobbb7a5a91ec6a72de0d2e267404cad91c6a57f52c
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 ':mode';
17 use File::Find qw();
18 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
21 BEGIN {
22 CGI->compile() if $ENV{'MOD_PERL'};
25 our $cgi = new CGI;
26 our $version = "++GIT_VERSION++";
27 our $my_url = $cgi->url();
28 our $my_uri = $cgi->url(-absolute => 1);
30 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
31 # needed and used only for URLs with nonempty PATH_INFO
32 our $base_url = $my_url;
34 # When the script is used as DirectoryIndex, the URL does not contain the name
35 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
36 # have to do it ourselves. We make $path_info global because it's also used
37 # later on.
39 # Another issue with the script being the DirectoryIndex is that the resulting
40 # $my_url data is not the full script URL: this is good, because we want
41 # generated links to keep implying the script name if it wasn't explicitly
42 # indicated in the URL we're handling, but it means that $my_url cannot be used
43 # as base URL.
44 # Therefore, if we needed to strip PATH_INFO, then we know that we have
45 # to build the base URL ourselves:
46 our $path_info = $ENV{"PATH_INFO"};
47 if ($path_info) {
48 if ($my_url =~ s,\Q$path_info\E$,, &&
49 $my_uri =~ s,\Q$path_info\E$,, &&
50 defined $ENV{'SCRIPT_NAME'}) {
51 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
55 # core git executable to use
56 # this can just be "git" if your webserver has a sensible PATH
57 our $GIT = "++GIT_BINDIR++/git";
59 # absolute fs-path which will be prepended to the project path
60 #our $projectroot = "/pub/scm";
61 our $projectroot = "++GITWEB_PROJECTROOT++";
63 # fs traversing limit for getting project list
64 # the number is relative to the projectroot
65 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
67 # target of the home link on top of all pages
68 our $home_link = $my_uri || "/";
70 # string of the home link on top of all pages
71 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
73 # name of your site or organization to appear in page titles
74 # replace this with something more descriptive for clearer bookmarks
75 our $site_name = "++GITWEB_SITENAME++"
76 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
78 # filename of html text to include at top of each page
79 our $site_header = "++GITWEB_SITE_HEADER++";
80 # html text to include at home page
81 our $home_text = "++GITWEB_HOMETEXT++";
82 # filename of html text to include at bottom of each page
83 our $site_footer = "++GITWEB_SITE_FOOTER++";
85 # URI of stylesheets
86 our @stylesheets = ("++GITWEB_CSS++");
87 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
88 our $stylesheet = undef;
89 # URI of GIT logo (72x27 size)
90 our $logo = "++GITWEB_LOGO++";
91 # URI of GIT favicon, assumed to be image/png type
92 our $favicon = "++GITWEB_FAVICON++";
94 # URI and label (title) of GIT logo link
95 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
96 #our $logo_label = "git documentation";
97 our $logo_url = "http://git.or.cz/";
98 our $logo_label = "git homepage";
100 # source of projects list
101 our $projects_list = "++GITWEB_LIST++";
103 # the width (in characters) of the projects list "Description" column
104 our $projects_list_description_width = 25;
106 # default order of projects list
107 # valid values are none, project, descr, owner, and age
108 our $default_projects_order = "project";
110 # show repository only if this file exists
111 # (only effective if this variable evaluates to true)
112 our $export_ok = "++GITWEB_EXPORT_OK++";
114 # show repository only if this subroutine returns true
115 # when given the path to the project, for example:
116 # sub { return -e "$_[0]/git-daemon-export-ok"; }
117 our $export_auth_hook = undef;
119 # only allow viewing of repositories also shown on the overview page
120 our $strict_export = "++GITWEB_STRICT_EXPORT++";
122 # list of git base URLs used for URL to where fetch project from,
123 # i.e. full URL is "$git_base_url/$project"
124 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
126 # default blob_plain mimetype and default charset for text/plain blob
127 our $default_blob_plain_mimetype = 'text/plain';
128 our $default_text_plain_charset = undef;
130 # file to use for guessing MIME types before trying /etc/mime.types
131 # (relative to the current git repository)
132 our $mimetypes_file = undef;
134 # assume this charset if line contains non-UTF-8 characters;
135 # it should be valid encoding (see Encoding::Supported(3pm) for list),
136 # for which encoding all byte sequences are valid, for example
137 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
138 # could be even 'utf-8' for the old behavior)
139 our $fallback_encoding = 'latin1';
141 # rename detection options for git-diff and git-diff-tree
142 # - default is '-M', with the cost proportional to
143 # (number of removed files) * (number of new files).
144 # - more costly is '-C' (which implies '-M'), with the cost proportional to
145 # (number of changed files + number of removed files) * (number of new files)
146 # - even more costly is '-C', '--find-copies-harder' with cost
147 # (number of files in the original tree) * (number of new files)
148 # - one might want to include '-B' option, e.g. '-B', '-M'
149 our @diff_opts = ('-M'); # taken from git_commit
151 # Disables features that would allow repository owners to inject script into
152 # the gitweb domain.
153 our $prevent_xss = 0;
155 # information about snapshot formats that gitweb is capable of serving
156 our %known_snapshot_formats = (
157 # name => {
158 # 'display' => display name,
159 # 'type' => mime type,
160 # 'suffix' => filename suffix,
161 # 'format' => --format for git-archive,
162 # 'compressor' => [compressor command and arguments]
163 # (array reference, optional)}
165 'tgz' => {
166 'display' => 'tar.gz',
167 'type' => 'application/x-gzip',
168 'suffix' => '.tar.gz',
169 'format' => 'tar',
170 'compressor' => ['gzip']},
172 'tbz2' => {
173 'display' => 'tar.bz2',
174 'type' => 'application/x-bzip2',
175 'suffix' => '.tar.bz2',
176 'format' => 'tar',
177 'compressor' => ['bzip2']},
179 'zip' => {
180 'display' => 'zip',
181 'type' => 'application/x-zip',
182 'suffix' => '.zip',
183 'format' => 'zip'},
186 # Aliases so we understand old gitweb.snapshot values in repository
187 # configuration.
188 our %known_snapshot_format_aliases = (
189 'gzip' => 'tgz',
190 'bzip2' => 'tbz2',
192 # backward compatibility: legacy gitweb config support
193 'x-gzip' => undef, 'gz' => undef,
194 'x-bzip2' => undef, 'bz2' => undef,
195 'x-zip' => undef, '' => undef,
198 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
199 # are changed, it may be appropriate to change these values too via
200 # $GITWEB_CONFIG.
201 our %avatar_size = (
202 'default' => 16,
203 'double' => 32
206 # You define site-wide feature defaults here; override them with
207 # $GITWEB_CONFIG as necessary.
208 our %feature = (
209 # feature => {
210 # 'sub' => feature-sub (subroutine),
211 # 'override' => allow-override (boolean),
212 # 'default' => [ default options...] (array reference)}
214 # if feature is overridable (it means that allow-override has true value),
215 # then feature-sub will be called with default options as parameters;
216 # return value of feature-sub indicates if to enable specified feature
218 # if there is no 'sub' key (no feature-sub), then feature cannot be
219 # overriden
221 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
222 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
223 # is enabled
225 # Enable the 'blame' blob view, showing the last commit that modified
226 # each line in the file. This can be very CPU-intensive.
228 # To enable system wide have in $GITWEB_CONFIG
229 # $feature{'blame'}{'default'} = [1];
230 # To have project specific config enable override in $GITWEB_CONFIG
231 # $feature{'blame'}{'override'} = 1;
232 # and in project config gitweb.blame = 0|1;
233 'blame' => {
234 'sub' => sub { feature_bool('blame', @_) },
235 'override' => 0,
236 'default' => [0]},
238 # Enable the 'snapshot' link, providing a compressed archive of any
239 # tree. This can potentially generate high traffic if you have large
240 # project.
242 # Value is a list of formats defined in %known_snapshot_formats that
243 # you wish to offer.
244 # To disable system wide have in $GITWEB_CONFIG
245 # $feature{'snapshot'}{'default'} = [];
246 # To have project specific config enable override in $GITWEB_CONFIG
247 # $feature{'snapshot'}{'override'} = 1;
248 # and in project config, a comma-separated list of formats or "none"
249 # to disable. Example: gitweb.snapshot = tbz2,zip;
250 'snapshot' => {
251 'sub' => \&feature_snapshot,
252 'override' => 0,
253 'default' => ['tgz']},
255 # Enable text search, which will list the commits which match author,
256 # committer or commit text to a given string. Enabled by default.
257 # Project specific override is not supported.
258 'search' => {
259 'override' => 0,
260 'default' => [1]},
262 # Enable grep search, which will list the files in currently selected
263 # tree containing the given string. Enabled by default. This can be
264 # potentially CPU-intensive, of course.
266 # To enable system wide have in $GITWEB_CONFIG
267 # $feature{'grep'}{'default'} = [1];
268 # To have project specific config enable override in $GITWEB_CONFIG
269 # $feature{'grep'}{'override'} = 1;
270 # and in project config gitweb.grep = 0|1;
271 'grep' => {
272 'sub' => sub { feature_bool('grep', @_) },
273 'override' => 0,
274 'default' => [1]},
276 # Enable the pickaxe search, which will list the commits that modified
277 # a given string in a file. This can be practical and quite faster
278 # alternative to 'blame', but still potentially CPU-intensive.
280 # To enable system wide have in $GITWEB_CONFIG
281 # $feature{'pickaxe'}{'default'} = [1];
282 # To have project specific config enable override in $GITWEB_CONFIG
283 # $feature{'pickaxe'}{'override'} = 1;
284 # and in project config gitweb.pickaxe = 0|1;
285 'pickaxe' => {
286 'sub' => sub { feature_bool('pickaxe', @_) },
287 'override' => 0,
288 'default' => [1]},
290 # Make gitweb use an alternative format of the URLs which can be
291 # more readable and natural-looking: project name is embedded
292 # directly in the path and the query string contains other
293 # auxiliary information. All gitweb installations recognize
294 # URL in either format; this configures in which formats gitweb
295 # generates links.
297 # To enable system wide have in $GITWEB_CONFIG
298 # $feature{'pathinfo'}{'default'} = [1];
299 # Project specific override is not supported.
301 # Note that you will need to change the default location of CSS,
302 # favicon, logo and possibly other files to an absolute URL. Also,
303 # if gitweb.cgi serves as your indexfile, you will need to force
304 # $my_uri to contain the script name in your $GITWEB_CONFIG.
305 'pathinfo' => {
306 'override' => 0,
307 'default' => [0]},
309 # Make gitweb consider projects in project root subdirectories
310 # to be forks of existing projects. Given project $projname.git,
311 # projects matching $projname/*.git will not be shown in the main
312 # projects list, instead a '+' mark will be added to $projname
313 # there and a 'forks' view will be enabled for the project, listing
314 # all the forks. If project list is taken from a file, forks have
315 # to be listed after the main project.
317 # To enable system wide have in $GITWEB_CONFIG
318 # $feature{'forks'}{'default'} = [1];
319 # Project specific override is not supported.
320 'forks' => {
321 'override' => 0,
322 'default' => [0]},
324 # Insert custom links to the action bar of all project pages.
325 # This enables you mainly to link to third-party scripts integrating
326 # into gitweb; e.g. git-browser for graphical history representation
327 # or custom web-based repository administration interface.
329 # The 'default' value consists of a list of triplets in the form
330 # (label, link, position) where position is the label after which
331 # to insert the link and link is a format string where %n expands
332 # to the project name, %f to the project path within the filesystem,
333 # %h to the current hash (h gitweb parameter) and %b to the current
334 # hash base (hb gitweb parameter); %% expands to %.
336 # To enable system wide have in $GITWEB_CONFIG e.g.
337 # $feature{'actions'}{'default'} = [('graphiclog',
338 # '/git-browser/by-commit.html?r=%n', 'summary')];
339 # Project specific override is not supported.
340 'actions' => {
341 'override' => 0,
342 'default' => []},
344 # Allow gitweb scan project content tags described in ctags/
345 # of project repository, and display the popular Web 2.0-ish
346 # "tag cloud" near the project list. Note that this is something
347 # COMPLETELY different from the normal Git tags.
349 # gitweb by itself can show existing tags, but it does not handle
350 # tagging itself; you need an external application for that.
351 # For an example script, check Girocco's cgi/tagproj.cgi.
352 # You may want to install the HTML::TagCloud Perl module to get
353 # a pretty tag cloud instead of just a list of tags.
355 # To enable system wide have in $GITWEB_CONFIG
356 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
357 # Project specific override is not supported.
358 'ctags' => {
359 'override' => 0,
360 'default' => [0]},
362 # The maximum number of patches in a patchset generated in patch
363 # view. Set this to 0 or undef to disable patch view, or to a
364 # negative number to remove any limit.
366 # To disable system wide have in $GITWEB_CONFIG
367 # $feature{'patches'}{'default'} = [0];
368 # To have project specific config enable override in $GITWEB_CONFIG
369 # $feature{'patches'}{'override'} = 1;
370 # and in project config gitweb.patches = 0|n;
371 # where n is the maximum number of patches allowed in a patchset.
372 'patches' => {
373 'sub' => \&feature_patches,
374 'override' => 0,
375 'default' => [16]},
377 # Avatar support. When this feature is enabled, views such as
378 # shortlog or commit will display an avatar associated with
379 # the email of the committer(s) and/or author(s).
381 # Currently available providers are gravatar and picon.
382 # If an unknown provider is specified, the feature is disabled.
384 # Gravatar depends on Digest::MD5.
385 # Picon currently relies on the indiana.edu database.
387 # To enable system wide have in $GITWEB_CONFIG
388 # $feature{'avatar'}{'default'} = ['<provider>'];
389 # where <provider> is either gravatar or picon.
390 # To have project specific config enable override in $GITWEB_CONFIG
391 # $feature{'avatar'}{'override'} = 1;
392 # and in project config gitweb.avatar = <provider>;
393 'avatar' => {
394 'sub' => \&feature_avatar,
395 'override' => 0,
396 'default' => ['']},
399 sub gitweb_get_feature {
400 my ($name) = @_;
401 return unless exists $feature{$name};
402 my ($sub, $override, @defaults) = (
403 $feature{$name}{'sub'},
404 $feature{$name}{'override'},
405 @{$feature{$name}{'default'}});
406 if (!$override) { return @defaults; }
407 if (!defined $sub) {
408 warn "feature $name is not overrideable";
409 return @defaults;
411 return $sub->(@defaults);
414 # A wrapper to check if a given feature is enabled.
415 # With this, you can say
417 # my $bool_feat = gitweb_check_feature('bool_feat');
418 # gitweb_check_feature('bool_feat') or somecode;
420 # instead of
422 # my ($bool_feat) = gitweb_get_feature('bool_feat');
423 # (gitweb_get_feature('bool_feat'))[0] or somecode;
425 sub gitweb_check_feature {
426 return (gitweb_get_feature(@_))[0];
430 sub feature_bool {
431 my $key = shift;
432 my ($val) = git_get_project_config($key, '--bool');
434 if (!defined $val) {
435 return ($_[0]);
436 } elsif ($val eq 'true') {
437 return (1);
438 } elsif ($val eq 'false') {
439 return (0);
443 sub feature_snapshot {
444 my (@fmts) = @_;
446 my ($val) = git_get_project_config('snapshot');
448 if ($val) {
449 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
452 return @fmts;
455 sub feature_patches {
456 my @val = (git_get_project_config('patches', '--int'));
458 if (@val) {
459 return @val;
462 return ($_[0]);
465 sub feature_avatar {
466 my @val = (git_get_project_config('avatar'));
468 return @val ? @val : @_;
471 # checking HEAD file with -e is fragile if the repository was
472 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
473 # and then pruned.
474 sub check_head_link {
475 my ($dir) = @_;
476 my $headfile = "$dir/HEAD";
477 return ((-e $headfile) ||
478 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
481 sub check_export_ok {
482 my ($dir) = @_;
483 return (check_head_link($dir) &&
484 (!$export_ok || -e "$dir/$export_ok") &&
485 (!$export_auth_hook || $export_auth_hook->($dir)));
488 # process alternate names for backward compatibility
489 # filter out unsupported (unknown) snapshot formats
490 sub filter_snapshot_fmts {
491 my @fmts = @_;
493 @fmts = map {
494 exists $known_snapshot_format_aliases{$_} ?
495 $known_snapshot_format_aliases{$_} : $_} @fmts;
496 @fmts = grep {
497 exists $known_snapshot_formats{$_} } @fmts;
500 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
501 if (-e $GITWEB_CONFIG) {
502 do $GITWEB_CONFIG;
503 } else {
504 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
505 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
508 # version of the core git binary
509 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
511 $projects_list ||= $projectroot;
513 # ======================================================================
514 # input validation and dispatch
516 # input parameters can be collected from a variety of sources (presently, CGI
517 # and PATH_INFO), so we define an %input_params hash that collects them all
518 # together during validation: this allows subsequent uses (e.g. href()) to be
519 # agnostic of the parameter origin
521 our %input_params = ();
523 # input parameters are stored with the long parameter name as key. This will
524 # also be used in the href subroutine to convert parameters to their CGI
525 # equivalent, and since the href() usage is the most frequent one, we store
526 # the name -> CGI key mapping here, instead of the reverse.
528 # XXX: Warning: If you touch this, check the search form for updating,
529 # too.
531 our @cgi_param_mapping = (
532 project => "p",
533 action => "a",
534 file_name => "f",
535 file_parent => "fp",
536 hash => "h",
537 hash_parent => "hp",
538 hash_base => "hb",
539 hash_parent_base => "hpb",
540 page => "pg",
541 order => "o",
542 searchtext => "s",
543 searchtype => "st",
544 snapshot_format => "sf",
545 extra_options => "opt",
546 search_use_regexp => "sr",
548 our %cgi_param_mapping = @cgi_param_mapping;
550 # we will also need to know the possible actions, for validation
551 our %actions = (
552 "blame" => \&git_blame,
553 "blobdiff" => \&git_blobdiff,
554 "blobdiff_plain" => \&git_blobdiff_plain,
555 "blob" => \&git_blob,
556 "blob_plain" => \&git_blob_plain,
557 "commitdiff" => \&git_commitdiff,
558 "commitdiff_plain" => \&git_commitdiff_plain,
559 "commit" => \&git_commit,
560 "forks" => \&git_forks,
561 "heads" => \&git_heads,
562 "history" => \&git_history,
563 "log" => \&git_log,
564 "patch" => \&git_patch,
565 "patches" => \&git_patches,
566 "rss" => \&git_rss,
567 "atom" => \&git_atom,
568 "search" => \&git_search,
569 "search_help" => \&git_search_help,
570 "shortlog" => \&git_shortlog,
571 "summary" => \&git_summary,
572 "tag" => \&git_tag,
573 "tags" => \&git_tags,
574 "tree" => \&git_tree,
575 "snapshot" => \&git_snapshot,
576 "object" => \&git_object,
577 # those below don't need $project
578 "opml" => \&git_opml,
579 "project_list" => \&git_project_list,
580 "project_index" => \&git_project_index,
583 # finally, we have the hash of allowed extra_options for the commands that
584 # allow them
585 our %allowed_options = (
586 "--no-merges" => [ qw(rss atom log shortlog history) ],
589 # fill %input_params with the CGI parameters. All values except for 'opt'
590 # should be single values, but opt can be an array. We should probably
591 # build an array of parameters that can be multi-valued, but since for the time
592 # being it's only this one, we just single it out
593 while (my ($name, $symbol) = each %cgi_param_mapping) {
594 if ($symbol eq 'opt') {
595 $input_params{$name} = [ $cgi->param($symbol) ];
596 } else {
597 $input_params{$name} = $cgi->param($symbol);
601 # now read PATH_INFO and update the parameter list for missing parameters
602 sub evaluate_path_info {
603 return if defined $input_params{'project'};
604 return if !$path_info;
605 $path_info =~ s,^/+,,;
606 return if !$path_info;
608 # find which part of PATH_INFO is project
609 my $project = $path_info;
610 $project =~ s,/+$,,;
611 while ($project && !check_head_link("$projectroot/$project")) {
612 $project =~ s,/*[^/]*$,,;
614 return unless $project;
615 $input_params{'project'} = $project;
617 # do not change any parameters if an action is given using the query string
618 return if $input_params{'action'};
619 $path_info =~ s,^\Q$project\E/*,,;
621 # next, check if we have an action
622 my $action = $path_info;
623 $action =~ s,/.*$,,;
624 if (exists $actions{$action}) {
625 $path_info =~ s,^$action/*,,;
626 $input_params{'action'} = $action;
629 # list of actions that want hash_base instead of hash, but can have no
630 # pathname (f) parameter
631 my @wants_base = (
632 'tree',
633 'history',
636 # we want to catch
637 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
638 my ($parentrefname, $parentpathname, $refname, $pathname) =
639 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
641 # first, analyze the 'current' part
642 if (defined $pathname) {
643 # we got "branch:filename" or "branch:dir/"
644 # we could use git_get_type(branch:pathname), but:
645 # - it needs $git_dir
646 # - it does a git() call
647 # - the convention of terminating directories with a slash
648 # makes it superfluous
649 # - embedding the action in the PATH_INFO would make it even
650 # more superfluous
651 $pathname =~ s,^/+,,;
652 if (!$pathname || substr($pathname, -1) eq "/") {
653 $input_params{'action'} ||= "tree";
654 $pathname =~ s,/$,,;
655 } else {
656 # the default action depends on whether we had parent info
657 # or not
658 if ($parentrefname) {
659 $input_params{'action'} ||= "blobdiff_plain";
660 } else {
661 $input_params{'action'} ||= "blob_plain";
664 $input_params{'hash_base'} ||= $refname;
665 $input_params{'file_name'} ||= $pathname;
666 } elsif (defined $refname) {
667 # we got "branch". In this case we have to choose if we have to
668 # set hash or hash_base.
670 # Most of the actions without a pathname only want hash to be
671 # set, except for the ones specified in @wants_base that want
672 # hash_base instead. It should also be noted that hand-crafted
673 # links having 'history' as an action and no pathname or hash
674 # set will fail, but that happens regardless of PATH_INFO.
675 $input_params{'action'} ||= "shortlog";
676 if (grep { $_ eq $input_params{'action'} } @wants_base) {
677 $input_params{'hash_base'} ||= $refname;
678 } else {
679 $input_params{'hash'} ||= $refname;
683 # next, handle the 'parent' part, if present
684 if (defined $parentrefname) {
685 # a missing pathspec defaults to the 'current' filename, allowing e.g.
686 # someproject/blobdiff/oldrev..newrev:/filename
687 if ($parentpathname) {
688 $parentpathname =~ s,^/+,,;
689 $parentpathname =~ s,/$,,;
690 $input_params{'file_parent'} ||= $parentpathname;
691 } else {
692 $input_params{'file_parent'} ||= $input_params{'file_name'};
694 # we assume that hash_parent_base is wanted if a path was specified,
695 # or if the action wants hash_base instead of hash
696 if (defined $input_params{'file_parent'} ||
697 grep { $_ eq $input_params{'action'} } @wants_base) {
698 $input_params{'hash_parent_base'} ||= $parentrefname;
699 } else {
700 $input_params{'hash_parent'} ||= $parentrefname;
704 # for the snapshot action, we allow URLs in the form
705 # $project/snapshot/$hash.ext
706 # where .ext determines the snapshot and gets removed from the
707 # passed $refname to provide the $hash.
709 # To be able to tell that $refname includes the format extension, we
710 # require the following two conditions to be satisfied:
711 # - the hash input parameter MUST have been set from the $refname part
712 # of the URL (i.e. they must be equal)
713 # - the snapshot format MUST NOT have been defined already (e.g. from
714 # CGI parameter sf)
715 # It's also useless to try any matching unless $refname has a dot,
716 # so we check for that too
717 if (defined $input_params{'action'} &&
718 $input_params{'action'} eq 'snapshot' &&
719 defined $refname && index($refname, '.') != -1 &&
720 $refname eq $input_params{'hash'} &&
721 !defined $input_params{'snapshot_format'}) {
722 # We loop over the known snapshot formats, checking for
723 # extensions. Allowed extensions are both the defined suffix
724 # (which includes the initial dot already) and the snapshot
725 # format key itself, with a prepended dot
726 while (my ($fmt, $opt) = each %known_snapshot_formats) {
727 my $hash = $refname;
728 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
729 next;
731 my $sfx = $1;
732 # a valid suffix was found, so set the snapshot format
733 # and reset the hash parameter
734 $input_params{'snapshot_format'} = $fmt;
735 $input_params{'hash'} = $hash;
736 # we also set the format suffix to the one requested
737 # in the URL: this way a request for e.g. .tgz returns
738 # a .tgz instead of a .tar.gz
739 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
740 last;
744 evaluate_path_info();
746 our $action = $input_params{'action'};
747 if (defined $action) {
748 if (!validate_action($action)) {
749 die_error(400, "Invalid action parameter");
753 # parameters which are pathnames
754 our $project = $input_params{'project'};
755 if (defined $project) {
756 if (!validate_project($project)) {
757 undef $project;
758 die_error(404, "No such project");
762 our $file_name = $input_params{'file_name'};
763 if (defined $file_name) {
764 if (!validate_pathname($file_name)) {
765 die_error(400, "Invalid file parameter");
769 our $file_parent = $input_params{'file_parent'};
770 if (defined $file_parent) {
771 if (!validate_pathname($file_parent)) {
772 die_error(400, "Invalid file parent parameter");
776 # parameters which are refnames
777 our $hash = $input_params{'hash'};
778 if (defined $hash) {
779 if (!validate_refname($hash)) {
780 die_error(400, "Invalid hash parameter");
784 our $hash_parent = $input_params{'hash_parent'};
785 if (defined $hash_parent) {
786 if (!validate_refname($hash_parent)) {
787 die_error(400, "Invalid hash parent parameter");
791 our $hash_base = $input_params{'hash_base'};
792 if (defined $hash_base) {
793 if (!validate_refname($hash_base)) {
794 die_error(400, "Invalid hash base parameter");
798 our @extra_options = @{$input_params{'extra_options'}};
799 # @extra_options is always defined, since it can only be (currently) set from
800 # CGI, and $cgi->param() returns the empty array in array context if the param
801 # is not set
802 foreach my $opt (@extra_options) {
803 if (not exists $allowed_options{$opt}) {
804 die_error(400, "Invalid option parameter");
806 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
807 die_error(400, "Invalid option parameter for this action");
811 our $hash_parent_base = $input_params{'hash_parent_base'};
812 if (defined $hash_parent_base) {
813 if (!validate_refname($hash_parent_base)) {
814 die_error(400, "Invalid hash parent base parameter");
818 # other parameters
819 our $page = $input_params{'page'};
820 if (defined $page) {
821 if ($page =~ m/[^0-9]/) {
822 die_error(400, "Invalid page parameter");
826 our $searchtype = $input_params{'searchtype'};
827 if (defined $searchtype) {
828 if ($searchtype =~ m/[^a-z]/) {
829 die_error(400, "Invalid searchtype parameter");
833 our $search_use_regexp = $input_params{'search_use_regexp'};
835 our $searchtext = $input_params{'searchtext'};
836 our $search_regexp;
837 if (defined $searchtext) {
838 if (length($searchtext) < 2) {
839 die_error(403, "At least two characters are required for search parameter");
841 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
844 # path to the current git repository
845 our $git_dir;
846 $git_dir = "$projectroot/$project" if $project;
848 # list of supported snapshot formats
849 our @snapshot_fmts = gitweb_get_feature('snapshot');
850 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
852 # check that the avatar feature is set to a known provider name,
853 # and for each provider check if the dependencies are satisfied.
854 # if the provider name is invalid or the dependencies are not met,
855 # reset $git_avatar to the empty string.
856 our ($git_avatar) = gitweb_get_feature('avatar');
857 if ($git_avatar eq 'gravatar') {
858 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
859 } elsif ($git_avatar eq 'picon') {
860 # no dependencies
861 } else {
862 $git_avatar = '';
865 # dispatch
866 if (!defined $action) {
867 if (defined $hash) {
868 $action = git_get_type($hash);
869 } elsif (defined $hash_base && defined $file_name) {
870 $action = git_get_type("$hash_base:$file_name");
871 } elsif (defined $project) {
872 $action = 'summary';
873 } else {
874 $action = 'project_list';
877 if (!defined($actions{$action})) {
878 die_error(400, "Unknown action");
880 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
881 !$project) {
882 die_error(400, "Project needed");
884 $actions{$action}->();
885 exit;
887 ## ======================================================================
888 ## action links
890 sub href {
891 my %params = @_;
892 # default is to use -absolute url() i.e. $my_uri
893 my $href = $params{-full} ? $my_url : $my_uri;
895 $params{'project'} = $project unless exists $params{'project'};
897 if ($params{-replay}) {
898 while (my ($name, $symbol) = each %cgi_param_mapping) {
899 if (!exists $params{$name}) {
900 $params{$name} = $input_params{$name};
905 my $use_pathinfo = gitweb_check_feature('pathinfo');
906 if ($use_pathinfo and defined $params{'project'}) {
907 # try to put as many parameters as possible in PATH_INFO:
908 # - project name
909 # - action
910 # - hash_parent or hash_parent_base:/file_parent
911 # - hash or hash_base:/filename
912 # - the snapshot_format as an appropriate suffix
914 # When the script is the root DirectoryIndex for the domain,
915 # $href here would be something like http://gitweb.example.com/
916 # Thus, we strip any trailing / from $href, to spare us double
917 # slashes in the final URL
918 $href =~ s,/$,,;
920 # Then add the project name, if present
921 $href .= "/".esc_url($params{'project'});
922 delete $params{'project'};
924 # since we destructively absorb parameters, we keep this
925 # boolean that remembers if we're handling a snapshot
926 my $is_snapshot = $params{'action'} eq 'snapshot';
928 # Summary just uses the project path URL, any other action is
929 # added to the URL
930 if (defined $params{'action'}) {
931 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
932 delete $params{'action'};
935 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
936 # stripping nonexistent or useless pieces
937 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
938 || $params{'hash_parent'} || $params{'hash'});
939 if (defined $params{'hash_base'}) {
940 if (defined $params{'hash_parent_base'}) {
941 $href .= esc_url($params{'hash_parent_base'});
942 # skip the file_parent if it's the same as the file_name
943 delete $params{'file_parent'} if $params{'file_parent'} eq $params{'file_name'};
944 if (defined $params{'file_parent'} && $params{'file_parent'} !~ /\.\./) {
945 $href .= ":/".esc_url($params{'file_parent'});
946 delete $params{'file_parent'};
948 $href .= "..";
949 delete $params{'hash_parent'};
950 delete $params{'hash_parent_base'};
951 } elsif (defined $params{'hash_parent'}) {
952 $href .= esc_url($params{'hash_parent'}). "..";
953 delete $params{'hash_parent'};
956 $href .= esc_url($params{'hash_base'});
957 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
958 $href .= ":/".esc_url($params{'file_name'});
959 delete $params{'file_name'};
961 delete $params{'hash'};
962 delete $params{'hash_base'};
963 } elsif (defined $params{'hash'}) {
964 $href .= esc_url($params{'hash'});
965 delete $params{'hash'};
968 # If the action was a snapshot, we can absorb the
969 # snapshot_format parameter too
970 if ($is_snapshot) {
971 my $fmt = $params{'snapshot_format'};
972 # snapshot_format should always be defined when href()
973 # is called, but just in case some code forgets, we
974 # fall back to the default
975 $fmt ||= $snapshot_fmts[0];
976 $href .= $known_snapshot_formats{$fmt}{'suffix'};
977 delete $params{'snapshot_format'};
981 # now encode the parameters explicitly
982 my @result = ();
983 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
984 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
985 if (defined $params{$name}) {
986 if (ref($params{$name}) eq "ARRAY") {
987 foreach my $par (@{$params{$name}}) {
988 push @result, $symbol . "=" . esc_param($par);
990 } else {
991 push @result, $symbol . "=" . esc_param($params{$name});
995 $href .= "?" . join(';', @result) if scalar @result;
997 return $href;
1001 ## ======================================================================
1002 ## validation, quoting/unquoting and escaping
1004 sub validate_action {
1005 my $input = shift || return undef;
1006 return undef unless exists $actions{$input};
1007 return $input;
1010 sub validate_project {
1011 my $input = shift || return undef;
1012 if (!validate_pathname($input) ||
1013 !(-d "$projectroot/$input") ||
1014 !check_export_ok("$projectroot/$input") ||
1015 ($strict_export && !project_in_list($input))) {
1016 return undef;
1017 } else {
1018 return $input;
1022 sub validate_pathname {
1023 my $input = shift || return undef;
1025 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1026 # at the beginning, at the end, and between slashes.
1027 # also this catches doubled slashes
1028 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1029 return undef;
1031 # no null characters
1032 if ($input =~ m!\0!) {
1033 return undef;
1035 return $input;
1038 sub validate_refname {
1039 my $input = shift || return undef;
1041 # textual hashes are O.K.
1042 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1043 return $input;
1045 # it must be correct pathname
1046 $input = validate_pathname($input)
1047 or return undef;
1048 # restrictions on ref name according to git-check-ref-format
1049 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1050 return undef;
1052 return $input;
1055 # decode sequences of octets in utf8 into Perl's internal form,
1056 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1057 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1058 sub to_utf8 {
1059 my $str = shift;
1060 if (utf8::valid($str)) {
1061 utf8::decode($str);
1062 return $str;
1063 } else {
1064 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1068 # quote unsafe chars, but keep the slash, even when it's not
1069 # correct, but quoted slashes look too horrible in bookmarks
1070 sub esc_param {
1071 my $str = shift;
1072 $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
1073 $str =~ s/\+/%2B/g;
1074 $str =~ s/ /\+/g;
1075 return $str;
1078 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1079 sub esc_url {
1080 my $str = shift;
1081 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1082 $str =~ s/\+/%2B/g;
1083 $str =~ s/ /\+/g;
1084 return $str;
1087 # replace invalid utf8 character with SUBSTITUTION sequence
1088 sub esc_html {
1089 my $str = shift;
1090 my %opts = @_;
1092 $str = to_utf8($str);
1093 $str = $cgi->escapeHTML($str);
1094 if ($opts{'-nbsp'}) {
1095 $str =~ s/ /&nbsp;/g;
1097 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1098 return $str;
1101 # quote control characters and escape filename to HTML
1102 sub esc_path {
1103 my $str = shift;
1104 my %opts = @_;
1106 $str = to_utf8($str);
1107 $str = $cgi->escapeHTML($str);
1108 if ($opts{'-nbsp'}) {
1109 $str =~ s/ /&nbsp;/g;
1111 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1112 return $str;
1115 # Make control characters "printable", using character escape codes (CEC)
1116 sub quot_cec {
1117 my $cntrl = shift;
1118 my %opts = @_;
1119 my %es = ( # character escape codes, aka escape sequences
1120 "\t" => '\t', # tab (HT)
1121 "\n" => '\n', # line feed (LF)
1122 "\r" => '\r', # carrige return (CR)
1123 "\f" => '\f', # form feed (FF)
1124 "\b" => '\b', # backspace (BS)
1125 "\a" => '\a', # alarm (bell) (BEL)
1126 "\e" => '\e', # escape (ESC)
1127 "\013" => '\v', # vertical tab (VT)
1128 "\000" => '\0', # nul character (NUL)
1130 my $chr = ( (exists $es{$cntrl})
1131 ? $es{$cntrl}
1132 : sprintf('\%2x', ord($cntrl)) );
1133 if ($opts{-nohtml}) {
1134 return $chr;
1135 } else {
1136 return "<span class=\"cntrl\">$chr</span>";
1140 # Alternatively use unicode control pictures codepoints,
1141 # Unicode "printable representation" (PR)
1142 sub quot_upr {
1143 my $cntrl = shift;
1144 my %opts = @_;
1146 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1147 if ($opts{-nohtml}) {
1148 return $chr;
1149 } else {
1150 return "<span class=\"cntrl\">$chr</span>";
1154 # git may return quoted and escaped filenames
1155 sub unquote {
1156 my $str = shift;
1158 sub unq {
1159 my $seq = shift;
1160 my %es = ( # character escape codes, aka escape sequences
1161 't' => "\t", # tab (HT, TAB)
1162 'n' => "\n", # newline (NL)
1163 'r' => "\r", # return (CR)
1164 'f' => "\f", # form feed (FF)
1165 'b' => "\b", # backspace (BS)
1166 'a' => "\a", # alarm (bell) (BEL)
1167 'e' => "\e", # escape (ESC)
1168 'v' => "\013", # vertical tab (VT)
1171 if ($seq =~ m/^[0-7]{1,3}$/) {
1172 # octal char sequence
1173 return chr(oct($seq));
1174 } elsif (exists $es{$seq}) {
1175 # C escape sequence, aka character escape code
1176 return $es{$seq};
1178 # quoted ordinary character
1179 return $seq;
1182 if ($str =~ m/^"(.*)"$/) {
1183 # needs unquoting
1184 $str = $1;
1185 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1187 return $str;
1190 # if filename is surrounded in double quotes, it need to be unquoted
1191 sub unquote_maybe {
1192 my $str = shift;
1194 if ($str =~ /^"(.*)"$/) {
1195 return unquote($1);
1197 return $str;
1200 # escape tabs (convert tabs to spaces)
1201 sub untabify {
1202 my $line = shift;
1204 while ((my $pos = index($line, "\t")) != -1) {
1205 if (my $count = (8 - ($pos % 8))) {
1206 my $spaces = ' ' x $count;
1207 $line =~ s/\t/$spaces/;
1211 return $line;
1214 sub project_in_list {
1215 my $project = shift;
1216 my @list = git_get_projects_list();
1217 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1220 ## ----------------------------------------------------------------------
1221 ## HTML aware string manipulation
1223 # Try to chop given string on a word boundary between position
1224 # $len and $len+$add_len. If there is no word boundary there,
1225 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1226 # (marking chopped part) would be longer than given string.
1227 sub chop_str {
1228 my $str = shift;
1229 my $len = shift;
1230 my $add_len = shift || 10;
1231 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1233 # Make sure perl knows it is utf8 encoded so we don't
1234 # cut in the middle of a utf8 multibyte char.
1235 $str = to_utf8($str);
1237 # allow only $len chars, but don't cut a word if it would fit in $add_len
1238 # if it doesn't fit, cut it if it's still longer than the dots we would add
1239 # remove chopped character entities entirely
1241 # when chopping in the middle, distribute $len into left and right part
1242 # return early if chopping wouldn't make string shorter
1243 if ($where eq 'center') {
1244 return $str if ($len + 5 >= length($str)); # filler is length 5
1245 $len = int($len/2);
1246 } else {
1247 return $str if ($len + 4 >= length($str)); # filler is length 4
1250 # regexps: ending and beginning with word part up to $add_len
1251 my $endre = qr/.{$len}\w{0,$add_len}/;
1252 my $begre = qr/\w{0,$add_len}.{$len}/;
1254 if ($where eq 'left') {
1255 $str =~ m/^(.*?)($begre)$/;
1256 my ($lead, $body) = ($1, $2);
1257 if (length($lead) > 4) {
1258 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1259 $lead = " ...";
1261 return "$lead$body";
1263 } elsif ($where eq 'center') {
1264 $str =~ m/^($endre)(.*)$/;
1265 my ($left, $str) = ($1, $2);
1266 $str =~ m/^(.*?)($begre)$/;
1267 my ($mid, $right) = ($1, $2);
1268 if (length($mid) > 5) {
1269 $left =~ s/&[^;]*$//;
1270 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1271 $mid = " ... ";
1273 return "$left$mid$right";
1275 } else {
1276 $str =~ m/^($endre)(.*)$/;
1277 my $body = $1;
1278 my $tail = $2;
1279 if (length($tail) > 4) {
1280 $body =~ s/&[^;]*$//;
1281 $tail = "... ";
1283 return "$body$tail";
1287 # takes the same arguments as chop_str, but also wraps a <span> around the
1288 # result with a title attribute if it does get chopped. Additionally, the
1289 # string is HTML-escaped.
1290 sub chop_and_escape_str {
1291 my ($str) = @_;
1293 my $chopped = chop_str(@_);
1294 if ($chopped eq $str) {
1295 return esc_html($chopped);
1296 } else {
1297 $str =~ s/[[:cntrl:]]/?/g;
1298 return $cgi->span({-title=>$str}, esc_html($chopped));
1302 ## ----------------------------------------------------------------------
1303 ## functions returning short strings
1305 # CSS class for given age value (in seconds)
1306 sub age_class {
1307 my $age = shift;
1309 if (!defined $age) {
1310 return "noage";
1311 } elsif ($age < 60*60*2) {
1312 return "age0";
1313 } elsif ($age < 60*60*24*2) {
1314 return "age1";
1315 } else {
1316 return "age2";
1320 # convert age in seconds to "nn units ago" string
1321 sub age_string {
1322 my $age = shift;
1323 my $age_str;
1325 if ($age > 60*60*24*365*2) {
1326 $age_str = (int $age/60/60/24/365);
1327 $age_str .= " years ago";
1328 } elsif ($age > 60*60*24*(365/12)*2) {
1329 $age_str = int $age/60/60/24/(365/12);
1330 $age_str .= " months ago";
1331 } elsif ($age > 60*60*24*7*2) {
1332 $age_str = int $age/60/60/24/7;
1333 $age_str .= " weeks ago";
1334 } elsif ($age > 60*60*24*2) {
1335 $age_str = int $age/60/60/24;
1336 $age_str .= " days ago";
1337 } elsif ($age > 60*60*2) {
1338 $age_str = int $age/60/60;
1339 $age_str .= " hours ago";
1340 } elsif ($age > 60*2) {
1341 $age_str = int $age/60;
1342 $age_str .= " min ago";
1343 } elsif ($age > 2) {
1344 $age_str = int $age;
1345 $age_str .= " sec ago";
1346 } else {
1347 $age_str .= " right now";
1349 return $age_str;
1352 use constant {
1353 S_IFINVALID => 0030000,
1354 S_IFGITLINK => 0160000,
1357 # submodule/subproject, a commit object reference
1358 sub S_ISGITLINK {
1359 my $mode = shift;
1361 return (($mode & S_IFMT) == S_IFGITLINK)
1364 # convert file mode in octal to symbolic file mode string
1365 sub mode_str {
1366 my $mode = oct shift;
1368 if (S_ISGITLINK($mode)) {
1369 return 'm---------';
1370 } elsif (S_ISDIR($mode & S_IFMT)) {
1371 return 'drwxr-xr-x';
1372 } elsif (S_ISLNK($mode)) {
1373 return 'lrwxrwxrwx';
1374 } elsif (S_ISREG($mode)) {
1375 # git cares only about the executable bit
1376 if ($mode & S_IXUSR) {
1377 return '-rwxr-xr-x';
1378 } else {
1379 return '-rw-r--r--';
1381 } else {
1382 return '----------';
1386 # convert file mode in octal to file type string
1387 sub file_type {
1388 my $mode = shift;
1390 if ($mode !~ m/^[0-7]+$/) {
1391 return $mode;
1392 } else {
1393 $mode = oct $mode;
1396 if (S_ISGITLINK($mode)) {
1397 return "submodule";
1398 } elsif (S_ISDIR($mode & S_IFMT)) {
1399 return "directory";
1400 } elsif (S_ISLNK($mode)) {
1401 return "symlink";
1402 } elsif (S_ISREG($mode)) {
1403 return "file";
1404 } else {
1405 return "unknown";
1409 # convert file mode in octal to file type description string
1410 sub file_type_long {
1411 my $mode = shift;
1413 if ($mode !~ m/^[0-7]+$/) {
1414 return $mode;
1415 } else {
1416 $mode = oct $mode;
1419 if (S_ISGITLINK($mode)) {
1420 return "submodule";
1421 } elsif (S_ISDIR($mode & S_IFMT)) {
1422 return "directory";
1423 } elsif (S_ISLNK($mode)) {
1424 return "symlink";
1425 } elsif (S_ISREG($mode)) {
1426 if ($mode & S_IXUSR) {
1427 return "executable";
1428 } else {
1429 return "file";
1431 } else {
1432 return "unknown";
1437 ## ----------------------------------------------------------------------
1438 ## functions returning short HTML fragments, or transforming HTML fragments
1439 ## which don't belong to other sections
1441 # format line of commit message.
1442 sub format_log_line_html {
1443 my $line = shift;
1445 $line = esc_html($line, -nbsp=>1);
1446 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1447 $cgi->a({-href => href(action=>"object", hash=>$1),
1448 -class => "text"}, $1);
1449 }eg;
1451 return $line;
1454 # format marker of refs pointing to given object
1456 # the destination action is chosen based on object type and current context:
1457 # - for annotated tags, we choose the tag view unless it's the current view
1458 # already, in which case we go to shortlog view
1459 # - for other refs, we keep the current view if we're in history, shortlog or
1460 # log view, and select shortlog otherwise
1461 sub format_ref_marker {
1462 my ($refs, $id) = @_;
1463 my $markers = '';
1465 if (defined $refs->{$id}) {
1466 foreach my $ref (@{$refs->{$id}}) {
1467 # this code exploits the fact that non-lightweight tags are the
1468 # only indirect objects, and that they are the only objects for which
1469 # we want to use tag instead of shortlog as action
1470 my ($type, $name) = qw();
1471 my $indirect = ($ref =~ s/\^\{\}$//);
1472 # e.g. tags/v2.6.11 or heads/next
1473 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1474 $type = $1;
1475 $name = $2;
1476 } else {
1477 $type = "ref";
1478 $name = $ref;
1481 my $class = $type;
1482 $class .= " indirect" if $indirect;
1484 my $dest_action = "shortlog";
1486 if ($indirect) {
1487 $dest_action = "tag" unless $action eq "tag";
1488 } elsif ($action =~ /^(history|(short)?log)$/) {
1489 $dest_action = $action;
1492 my $dest = "";
1493 $dest .= "refs/" unless $ref =~ m!^refs/!;
1494 $dest .= $ref;
1496 my $link = $cgi->a({
1497 -href => href(
1498 action=>$dest_action,
1499 hash=>$dest
1500 )}, $name);
1502 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1503 $link . "</span>";
1507 if ($markers) {
1508 return ' <span class="refs">'. $markers . '</span>';
1509 } else {
1510 return "";
1514 # format, perhaps shortened and with markers, title line
1515 sub format_subject_html {
1516 my ($long, $short, $href, $extra) = @_;
1517 $extra = '' unless defined($extra);
1519 if (length($short) < length($long)) {
1520 $long =~ s/[[:cntrl:]]/?/g;
1521 return $cgi->a({-href => $href, -class => "list subject",
1522 -title => to_utf8($long)},
1523 esc_html($short) . $extra);
1524 } else {
1525 return $cgi->a({-href => $href, -class => "list subject"},
1526 esc_html($long) . $extra);
1530 # Rather than recomputing the url for an email multiple times, we cache it
1531 # after the first hit. This gives a visible benefit in views where the avatar
1532 # for the same email is used repeatedly (e.g. shortlog).
1533 # The cache is shared by all avatar engines (currently gravatar only), which
1534 # are free to use it as preferred. Since only one avatar engine is used for any
1535 # given page, there's no risk for cache conflicts.
1536 our %avatar_cache = ();
1538 # Compute the picon url for a given email, by using the picon search service over at
1539 # http://www.cs.indiana.edu/picons/search.html
1540 sub picon_url {
1541 my $email = lc shift;
1542 if (!$avatar_cache{$email}) {
1543 my ($user, $domain) = split('@', $email);
1544 $avatar_cache{$email} =
1545 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1546 "$domain/$user/" .
1547 "users+domains+unknown/up/single";
1549 return $avatar_cache{$email};
1552 # Compute the gravatar url for a given email, if it's not in the cache already.
1553 # Gravatar stores only the part of the URL before the size, since that's the
1554 # one computationally more expensive. This also allows reuse of the cache for
1555 # different sizes (for this particular engine).
1556 sub gravatar_url {
1557 my $email = lc shift;
1558 my $size = shift;
1559 $avatar_cache{$email} ||=
1560 "http://www.gravatar.com/avatar/" .
1561 Digest::MD5::md5_hex($email) . "?s=";
1562 return $avatar_cache{$email} . $size;
1565 # Insert an avatar for the given $email at the given $size if the feature
1566 # is enabled.
1567 sub git_get_avatar {
1568 my ($email, %opts) = @_;
1569 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1570 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1571 $opts{-size} ||= 'default';
1572 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1573 my $url = "";
1574 if ($git_avatar eq 'gravatar') {
1575 $url = gravatar_url($email, $size);
1576 } elsif ($git_avatar eq 'picon') {
1577 $url = picon_url($email);
1579 # Other providers can be added by extending the if chain, defining $url
1580 # as needed. If no variant puts something in $url, we assume avatars
1581 # are completely disabled/unavailable.
1582 if ($url) {
1583 return $pre_white .
1584 "<img width=\"$size\" " .
1585 "class=\"avatar\" " .
1586 "src=\"$url\" " .
1587 "alt=\"\" " .
1588 "/>" . $post_white;
1589 } else {
1590 return "";
1594 # format the author name of the given commit with the given tag
1595 # the author name is chopped and escaped according to the other
1596 # optional parameters (see chop_str).
1597 sub format_author_html {
1598 my $tag = shift;
1599 my $co = shift;
1600 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1601 return "<$tag class=\"author\">" .
1602 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1603 $author . "</$tag>";
1606 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1607 sub format_git_diff_header_line {
1608 my $line = shift;
1609 my $diffinfo = shift;
1610 my ($from, $to) = @_;
1612 if ($diffinfo->{'nparents'}) {
1613 # combined diff
1614 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1615 if ($to->{'href'}) {
1616 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1617 esc_path($to->{'file'}));
1618 } else { # file was deleted (no href)
1619 $line .= esc_path($to->{'file'});
1621 } else {
1622 # "ordinary" diff
1623 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1624 if ($from->{'href'}) {
1625 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1626 'a/' . esc_path($from->{'file'}));
1627 } else { # file was added (no href)
1628 $line .= 'a/' . esc_path($from->{'file'});
1630 $line .= ' ';
1631 if ($to->{'href'}) {
1632 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1633 'b/' . esc_path($to->{'file'}));
1634 } else { # file was deleted
1635 $line .= 'b/' . esc_path($to->{'file'});
1639 return "<div class=\"diff header\">$line</div>\n";
1642 # format extended diff header line, before patch itself
1643 sub format_extended_diff_header_line {
1644 my $line = shift;
1645 my $diffinfo = shift;
1646 my ($from, $to) = @_;
1648 # match <path>
1649 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1650 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1651 esc_path($from->{'file'}));
1653 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1654 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1655 esc_path($to->{'file'}));
1657 # match single <mode>
1658 if ($line =~ m/\s(\d{6})$/) {
1659 $line .= '<span class="info"> (' .
1660 file_type_long($1) .
1661 ')</span>';
1663 # match <hash>
1664 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1665 # can match only for combined diff
1666 $line = 'index ';
1667 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1668 if ($from->{'href'}[$i]) {
1669 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1670 -class=>"hash"},
1671 substr($diffinfo->{'from_id'}[$i],0,7));
1672 } else {
1673 $line .= '0' x 7;
1675 # separator
1676 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1678 $line .= '..';
1679 if ($to->{'href'}) {
1680 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1681 substr($diffinfo->{'to_id'},0,7));
1682 } else {
1683 $line .= '0' x 7;
1686 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1687 # can match only for ordinary diff
1688 my ($from_link, $to_link);
1689 if ($from->{'href'}) {
1690 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1691 substr($diffinfo->{'from_id'},0,7));
1692 } else {
1693 $from_link = '0' x 7;
1695 if ($to->{'href'}) {
1696 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1697 substr($diffinfo->{'to_id'},0,7));
1698 } else {
1699 $to_link = '0' x 7;
1701 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1702 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1705 return $line . "<br/>\n";
1708 # format from-file/to-file diff header
1709 sub format_diff_from_to_header {
1710 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1711 my $line;
1712 my $result = '';
1714 $line = $from_line;
1715 #assert($line =~ m/^---/) if DEBUG;
1716 # no extra formatting for "^--- /dev/null"
1717 if (! $diffinfo->{'nparents'}) {
1718 # ordinary (single parent) diff
1719 if ($line =~ m!^--- "?a/!) {
1720 if ($from->{'href'}) {
1721 $line = '--- a/' .
1722 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1723 esc_path($from->{'file'}));
1724 } else {
1725 $line = '--- a/' .
1726 esc_path($from->{'file'});
1729 $result .= qq!<div class="diff from_file">$line</div>\n!;
1731 } else {
1732 # combined diff (merge commit)
1733 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1734 if ($from->{'href'}[$i]) {
1735 $line = '--- ' .
1736 $cgi->a({-href=>href(action=>"blobdiff",
1737 hash_parent=>$diffinfo->{'from_id'}[$i],
1738 hash_parent_base=>$parents[$i],
1739 file_parent=>$from->{'file'}[$i],
1740 hash=>$diffinfo->{'to_id'},
1741 hash_base=>$hash,
1742 file_name=>$to->{'file'}),
1743 -class=>"path",
1744 -title=>"diff" . ($i+1)},
1745 $i+1) .
1746 '/' .
1747 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1748 esc_path($from->{'file'}[$i]));
1749 } else {
1750 $line = '--- /dev/null';
1752 $result .= qq!<div class="diff from_file">$line</div>\n!;
1756 $line = $to_line;
1757 #assert($line =~ m/^\+\+\+/) if DEBUG;
1758 # no extra formatting for "^+++ /dev/null"
1759 if ($line =~ m!^\+\+\+ "?b/!) {
1760 if ($to->{'href'}) {
1761 $line = '+++ b/' .
1762 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1763 esc_path($to->{'file'}));
1764 } else {
1765 $line = '+++ b/' .
1766 esc_path($to->{'file'});
1769 $result .= qq!<div class="diff to_file">$line</div>\n!;
1771 return $result;
1774 # create note for patch simplified by combined diff
1775 sub format_diff_cc_simplified {
1776 my ($diffinfo, @parents) = @_;
1777 my $result = '';
1779 $result .= "<div class=\"diff header\">" .
1780 "diff --cc ";
1781 if (!is_deleted($diffinfo)) {
1782 $result .= $cgi->a({-href => href(action=>"blob",
1783 hash_base=>$hash,
1784 hash=>$diffinfo->{'to_id'},
1785 file_name=>$diffinfo->{'to_file'}),
1786 -class => "path"},
1787 esc_path($diffinfo->{'to_file'}));
1788 } else {
1789 $result .= esc_path($diffinfo->{'to_file'});
1791 $result .= "</div>\n" . # class="diff header"
1792 "<div class=\"diff nodifferences\">" .
1793 "Simple merge" .
1794 "</div>\n"; # class="diff nodifferences"
1796 return $result;
1799 # format patch (diff) line (not to be used for diff headers)
1800 sub format_diff_line {
1801 my $line = shift;
1802 my ($from, $to) = @_;
1803 my $diff_class = "";
1805 chomp $line;
1807 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1808 # combined diff
1809 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1810 if ($line =~ m/^\@{3}/) {
1811 $diff_class = " chunk_header";
1812 } elsif ($line =~ m/^\\/) {
1813 $diff_class = " incomplete";
1814 } elsif ($prefix =~ tr/+/+/) {
1815 $diff_class = " add";
1816 } elsif ($prefix =~ tr/-/-/) {
1817 $diff_class = " rem";
1819 } else {
1820 # assume ordinary diff
1821 my $char = substr($line, 0, 1);
1822 if ($char eq '+') {
1823 $diff_class = " add";
1824 } elsif ($char eq '-') {
1825 $diff_class = " rem";
1826 } elsif ($char eq '@') {
1827 $diff_class = " chunk_header";
1828 } elsif ($char eq "\\") {
1829 $diff_class = " incomplete";
1832 $line = untabify($line);
1833 if ($from && $to && $line =~ m/^\@{2} /) {
1834 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1835 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1837 $from_lines = 0 unless defined $from_lines;
1838 $to_lines = 0 unless defined $to_lines;
1840 if ($from->{'href'}) {
1841 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1842 -class=>"list"}, $from_text);
1844 if ($to->{'href'}) {
1845 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1846 -class=>"list"}, $to_text);
1848 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1849 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1850 return "<div class=\"diff$diff_class\">$line</div>\n";
1851 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1852 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1853 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1855 @from_text = split(' ', $ranges);
1856 for (my $i = 0; $i < @from_text; ++$i) {
1857 ($from_start[$i], $from_nlines[$i]) =
1858 (split(',', substr($from_text[$i], 1)), 0);
1861 $to_text = pop @from_text;
1862 $to_start = pop @from_start;
1863 $to_nlines = pop @from_nlines;
1865 $line = "<span class=\"chunk_info\">$prefix ";
1866 for (my $i = 0; $i < @from_text; ++$i) {
1867 if ($from->{'href'}[$i]) {
1868 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1869 -class=>"list"}, $from_text[$i]);
1870 } else {
1871 $line .= $from_text[$i];
1873 $line .= " ";
1875 if ($to->{'href'}) {
1876 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1877 -class=>"list"}, $to_text);
1878 } else {
1879 $line .= $to_text;
1881 $line .= " $prefix</span>" .
1882 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1883 return "<div class=\"diff$diff_class\">$line</div>\n";
1885 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1888 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1889 # linked. Pass the hash of the tree/commit to snapshot.
1890 sub format_snapshot_links {
1891 my ($hash) = @_;
1892 my $num_fmts = @snapshot_fmts;
1893 if ($num_fmts > 1) {
1894 # A parenthesized list of links bearing format names.
1895 # e.g. "snapshot (_tar.gz_ _zip_)"
1896 return "snapshot (" . join(' ', map
1897 $cgi->a({
1898 -href => href(
1899 action=>"snapshot",
1900 hash=>$hash,
1901 snapshot_format=>$_
1903 }, $known_snapshot_formats{$_}{'display'})
1904 , @snapshot_fmts) . ")";
1905 } elsif ($num_fmts == 1) {
1906 # A single "snapshot" link whose tooltip bears the format name.
1907 # i.e. "_snapshot_"
1908 my ($fmt) = @snapshot_fmts;
1909 return
1910 $cgi->a({
1911 -href => href(
1912 action=>"snapshot",
1913 hash=>$hash,
1914 snapshot_format=>$fmt
1916 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1917 }, "snapshot");
1918 } else { # $num_fmts == 0
1919 return undef;
1923 ## ......................................................................
1924 ## functions returning values to be passed, perhaps after some
1925 ## transformation, to other functions; e.g. returning arguments to href()
1927 # returns hash to be passed to href to generate gitweb URL
1928 # in -title key it returns description of link
1929 sub get_feed_info {
1930 my $format = shift || 'Atom';
1931 my %res = (action => lc($format));
1933 # feed links are possible only for project views
1934 return unless (defined $project);
1935 # some views should link to OPML, or to generic project feed,
1936 # or don't have specific feed yet (so they should use generic)
1937 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1939 my $branch;
1940 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1941 # from tag links; this also makes possible to detect branch links
1942 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1943 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1944 $branch = $1;
1946 # find log type for feed description (title)
1947 my $type = 'log';
1948 if (defined $file_name) {
1949 $type = "history of $file_name";
1950 $type .= "/" if ($action eq 'tree');
1951 $type .= " on '$branch'" if (defined $branch);
1952 } else {
1953 $type = "log of $branch" if (defined $branch);
1956 $res{-title} = $type;
1957 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
1958 $res{'file_name'} = $file_name;
1960 return %res;
1963 ## ----------------------------------------------------------------------
1964 ## git utility subroutines, invoking git commands
1966 # returns path to the core git executable and the --git-dir parameter as list
1967 sub git_cmd {
1968 return $GIT, '--git-dir='.$git_dir;
1971 # quote the given arguments for passing them to the shell
1972 # quote_command("command", "arg 1", "arg with ' and ! characters")
1973 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
1974 # Try to avoid using this function wherever possible.
1975 sub quote_command {
1976 return join(' ',
1977 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
1980 # get HEAD ref of given project as hash
1981 sub git_get_head_hash {
1982 my $project = shift;
1983 my $o_git_dir = $git_dir;
1984 my $retval = undef;
1985 $git_dir = "$projectroot/$project";
1986 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1987 my $head = <$fd>;
1988 close $fd;
1989 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1990 $retval = $1;
1993 if (defined $o_git_dir) {
1994 $git_dir = $o_git_dir;
1996 return $retval;
1999 # get type of given object
2000 sub git_get_type {
2001 my $hash = shift;
2003 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2004 my $type = <$fd>;
2005 close $fd or return;
2006 chomp $type;
2007 return $type;
2010 # repository configuration
2011 our $config_file = '';
2012 our %config;
2014 # store multiple values for single key as anonymous array reference
2015 # single values stored directly in the hash, not as [ <value> ]
2016 sub hash_set_multi {
2017 my ($hash, $key, $value) = @_;
2019 if (!exists $hash->{$key}) {
2020 $hash->{$key} = $value;
2021 } elsif (!ref $hash->{$key}) {
2022 $hash->{$key} = [ $hash->{$key}, $value ];
2023 } else {
2024 push @{$hash->{$key}}, $value;
2028 # return hash of git project configuration
2029 # optionally limited to some section, e.g. 'gitweb'
2030 sub git_parse_project_config {
2031 my $section_regexp = shift;
2032 my %config;
2034 local $/ = "\0";
2036 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2037 or return;
2039 while (my $keyval = <$fh>) {
2040 chomp $keyval;
2041 my ($key, $value) = split(/\n/, $keyval, 2);
2043 hash_set_multi(\%config, $key, $value)
2044 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2046 close $fh;
2048 return %config;
2051 # convert config value to boolean: 'true' or 'false'
2052 # no value, number > 0, 'true' and 'yes' values are true
2053 # rest of values are treated as false (never as error)
2054 sub config_to_bool {
2055 my $val = shift;
2057 return 1 if !defined $val; # section.key
2059 # strip leading and trailing whitespace
2060 $val =~ s/^\s+//;
2061 $val =~ s/\s+$//;
2063 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2064 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2067 # convert config value to simple decimal number
2068 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2069 # to be multiplied by 1024, 1048576, or 1073741824
2070 sub config_to_int {
2071 my $val = shift;
2073 # strip leading and trailing whitespace
2074 $val =~ s/^\s+//;
2075 $val =~ s/\s+$//;
2077 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2078 $unit = lc($unit);
2079 # unknown unit is treated as 1
2080 return $num * ($unit eq 'g' ? 1073741824 :
2081 $unit eq 'm' ? 1048576 :
2082 $unit eq 'k' ? 1024 : 1);
2084 return $val;
2087 # convert config value to array reference, if needed
2088 sub config_to_multi {
2089 my $val = shift;
2091 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2094 sub git_get_project_config {
2095 my ($key, $type) = @_;
2097 # key sanity check
2098 return unless ($key);
2099 $key =~ s/^gitweb\.//;
2100 return if ($key =~ m/\W/);
2102 # type sanity check
2103 if (defined $type) {
2104 $type =~ s/^--//;
2105 $type = undef
2106 unless ($type eq 'bool' || $type eq 'int');
2109 # get config
2110 if (!defined $config_file ||
2111 $config_file ne "$git_dir/config") {
2112 %config = git_parse_project_config('gitweb');
2113 $config_file = "$git_dir/config";
2116 # check if config variable (key) exists
2117 return unless exists $config{"gitweb.$key"};
2119 # ensure given type
2120 if (!defined $type) {
2121 return $config{"gitweb.$key"};
2122 } elsif ($type eq 'bool') {
2123 # backward compatibility: 'git config --bool' returns true/false
2124 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2125 } elsif ($type eq 'int') {
2126 return config_to_int($config{"gitweb.$key"});
2128 return $config{"gitweb.$key"};
2131 # get hash of given path at given ref
2132 sub git_get_hash_by_path {
2133 my $base = shift;
2134 my $path = shift || return undef;
2135 my $type = shift;
2137 $path =~ s,/+$,,;
2139 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2140 or die_error(500, "Open git-ls-tree failed");
2141 my $line = <$fd>;
2142 close $fd or return undef;
2144 if (!defined $line) {
2145 # there is no tree or hash given by $path at $base
2146 return undef;
2149 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2150 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2151 if (defined $type && $type ne $2) {
2152 # type doesn't match
2153 return undef;
2155 return $3;
2158 # get path of entry with given hash at given tree-ish (ref)
2159 # used to get 'from' filename for combined diff (merge commit) for renames
2160 sub git_get_path_by_hash {
2161 my $base = shift || return;
2162 my $hash = shift || return;
2164 local $/ = "\0";
2166 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2167 or return undef;
2168 while (my $line = <$fd>) {
2169 chomp $line;
2171 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2172 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2173 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2174 close $fd;
2175 return $1;
2178 close $fd;
2179 return undef;
2182 ## ......................................................................
2183 ## git utility functions, directly accessing git repository
2185 sub git_get_project_description {
2186 my $path = shift;
2188 $git_dir = "$projectroot/$path";
2189 open my $fd, '<', "$git_dir/description"
2190 or return git_get_project_config('description');
2191 my $descr = <$fd>;
2192 close $fd;
2193 if (defined $descr) {
2194 chomp $descr;
2196 return $descr;
2199 sub git_get_project_ctags {
2200 my $path = shift;
2201 my $ctags = {};
2203 $git_dir = "$projectroot/$path";
2204 opendir my $dh, "$git_dir/ctags"
2205 or return $ctags;
2206 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2207 open my $ct, '<', $_ or next;
2208 my $val = <$ct>;
2209 chomp $val;
2210 close $ct;
2211 my $ctag = $_; $ctag =~ s#.*/##;
2212 $ctags->{$ctag} = $val;
2214 closedir $dh;
2215 $ctags;
2218 sub git_populate_project_tagcloud {
2219 my $ctags = shift;
2221 # First, merge different-cased tags; tags vote on casing
2222 my %ctags_lc;
2223 foreach (keys %$ctags) {
2224 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2225 if (not $ctags_lc{lc $_}->{topcount}
2226 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2227 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2228 $ctags_lc{lc $_}->{topname} = $_;
2232 my $cloud;
2233 if (eval { require HTML::TagCloud; 1; }) {
2234 $cloud = HTML::TagCloud->new;
2235 foreach (sort keys %ctags_lc) {
2236 # Pad the title with spaces so that the cloud looks
2237 # less crammed.
2238 my $title = $ctags_lc{$_}->{topname};
2239 $title =~ s/ /&nbsp;/g;
2240 $title =~ s/^/&nbsp;/g;
2241 $title =~ s/$/&nbsp;/g;
2242 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2244 } else {
2245 $cloud = \%ctags_lc;
2247 $cloud;
2250 sub git_show_project_tagcloud {
2251 my ($cloud, $count) = @_;
2252 print STDERR ref($cloud)."..\n";
2253 if (ref $cloud eq 'HTML::TagCloud') {
2254 return $cloud->html_and_css($count);
2255 } else {
2256 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2257 return '<p align="center">' . join (', ', map {
2258 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2259 } splice(@tags, 0, $count)) . '</p>';
2263 sub git_get_project_url_list {
2264 my $path = shift;
2266 $git_dir = "$projectroot/$path";
2267 open my $fd, '<', "$git_dir/cloneurl"
2268 or return wantarray ?
2269 @{ config_to_multi(git_get_project_config('url')) } :
2270 config_to_multi(git_get_project_config('url'));
2271 my @git_project_url_list = map { chomp; $_ } <$fd>;
2272 close $fd;
2274 return wantarray ? @git_project_url_list : \@git_project_url_list;
2277 sub git_get_projects_list {
2278 my ($filter) = @_;
2279 my @list;
2281 $filter ||= '';
2282 $filter =~ s/\.git$//;
2284 my $check_forks = gitweb_check_feature('forks');
2286 if (-d $projects_list) {
2287 # search in directory
2288 my $dir = $projects_list . ($filter ? "/$filter" : '');
2289 # remove the trailing "/"
2290 $dir =~ s!/+$!!;
2291 my $pfxlen = length("$dir");
2292 my $pfxdepth = ($dir =~ tr!/!!);
2294 File::Find::find({
2295 follow_fast => 1, # follow symbolic links
2296 follow_skip => 2, # ignore duplicates
2297 dangling_symlinks => 0, # ignore dangling symlinks, silently
2298 wanted => sub {
2299 # skip project-list toplevel, if we get it.
2300 return if (m!^[/.]$!);
2301 # only directories can be git repositories
2302 return unless (-d $_);
2303 # don't traverse too deep (Find is super slow on os x)
2304 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2305 $File::Find::prune = 1;
2306 return;
2309 my $subdir = substr($File::Find::name, $pfxlen + 1);
2310 # we check related file in $projectroot
2311 my $path = ($filter ? "$filter/" : '') . $subdir;
2312 if (check_export_ok("$projectroot/$path")) {
2313 push @list, { path => $path };
2314 $File::Find::prune = 1;
2317 }, "$dir");
2319 } elsif (-f $projects_list) {
2320 # read from file(url-encoded):
2321 # 'git%2Fgit.git Linus+Torvalds'
2322 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2323 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2324 my %paths;
2325 open my $fd, '<', $projects_list or return;
2326 PROJECT:
2327 while (my $line = <$fd>) {
2328 chomp $line;
2329 my ($path, $owner) = split ' ', $line;
2330 $path = unescape($path);
2331 $owner = unescape($owner);
2332 if (!defined $path) {
2333 next;
2335 if ($filter ne '') {
2336 # looking for forks;
2337 my $pfx = substr($path, 0, length($filter));
2338 if ($pfx ne $filter) {
2339 next PROJECT;
2341 my $sfx = substr($path, length($filter));
2342 if ($sfx !~ /^\/.*\.git$/) {
2343 next PROJECT;
2345 } elsif ($check_forks) {
2346 PATH:
2347 foreach my $filter (keys %paths) {
2348 # looking for forks;
2349 my $pfx = substr($path, 0, length($filter));
2350 if ($pfx ne $filter) {
2351 next PATH;
2353 my $sfx = substr($path, length($filter));
2354 if ($sfx !~ /^\/.*\.git$/) {
2355 next PATH;
2357 # is a fork, don't include it in
2358 # the list
2359 next PROJECT;
2362 if (check_export_ok("$projectroot/$path")) {
2363 my $pr = {
2364 path => $path,
2365 owner => to_utf8($owner),
2367 push @list, $pr;
2368 (my $forks_path = $path) =~ s/\.git$//;
2369 $paths{$forks_path}++;
2372 close $fd;
2374 return @list;
2377 our $gitweb_project_owner = undef;
2378 sub git_get_project_list_from_file {
2380 return if (defined $gitweb_project_owner);
2382 $gitweb_project_owner = {};
2383 # read from file (url-encoded):
2384 # 'git%2Fgit.git Linus+Torvalds'
2385 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2386 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2387 if (-f $projects_list) {
2388 open(my $fd, '<', $projects_list);
2389 while (my $line = <$fd>) {
2390 chomp $line;
2391 my ($pr, $ow) = split ' ', $line;
2392 $pr = unescape($pr);
2393 $ow = unescape($ow);
2394 $gitweb_project_owner->{$pr} = to_utf8($ow);
2396 close $fd;
2400 sub git_get_project_owner {
2401 my $project = shift;
2402 my $owner;
2404 return undef unless $project;
2405 $git_dir = "$projectroot/$project";
2407 if (!defined $gitweb_project_owner) {
2408 git_get_project_list_from_file();
2411 if (exists $gitweb_project_owner->{$project}) {
2412 $owner = $gitweb_project_owner->{$project};
2414 if (!defined $owner){
2415 $owner = git_get_project_config('owner');
2417 if (!defined $owner) {
2418 $owner = get_file_owner("$git_dir");
2421 return $owner;
2424 sub git_get_last_activity {
2425 my ($path) = @_;
2426 my $fd;
2428 $git_dir = "$projectroot/$path";
2429 open($fd, "-|", git_cmd(), 'for-each-ref',
2430 '--format=%(committer)',
2431 '--sort=-committerdate',
2432 '--count=1',
2433 'refs/heads') or return;
2434 my $most_recent = <$fd>;
2435 close $fd or return;
2436 if (defined $most_recent &&
2437 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2438 my $timestamp = $1;
2439 my $age = time - $timestamp;
2440 return ($age, age_string($age));
2442 return (undef, undef);
2445 sub git_get_references {
2446 my $type = shift || "";
2447 my %refs;
2448 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2449 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2450 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2451 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2452 or return;
2454 while (my $line = <$fd>) {
2455 chomp $line;
2456 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2457 if (defined $refs{$1}) {
2458 push @{$refs{$1}}, $2;
2459 } else {
2460 $refs{$1} = [ $2 ];
2464 close $fd or return;
2465 return \%refs;
2468 sub git_get_rev_name_tags {
2469 my $hash = shift || return undef;
2471 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2472 or return;
2473 my $name_rev = <$fd>;
2474 close $fd;
2476 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2477 return $1;
2478 } else {
2479 # catches also '$hash undefined' output
2480 return undef;
2484 ## ----------------------------------------------------------------------
2485 ## parse to hash functions
2487 sub parse_date {
2488 my $epoch = shift;
2489 my $tz = shift || "-0000";
2491 my %date;
2492 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2493 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2494 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2495 $date{'hour'} = $hour;
2496 $date{'minute'} = $min;
2497 $date{'mday'} = $mday;
2498 $date{'day'} = $days[$wday];
2499 $date{'month'} = $months[$mon];
2500 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2501 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2502 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2503 $mday, $months[$mon], $hour ,$min;
2504 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2505 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2507 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2508 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2509 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2510 $date{'hour_local'} = $hour;
2511 $date{'minute_local'} = $min;
2512 $date{'tz_local'} = $tz;
2513 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2514 1900+$year, $mon+1, $mday,
2515 $hour, $min, $sec, $tz);
2516 return %date;
2519 sub parse_tag {
2520 my $tag_id = shift;
2521 my %tag;
2522 my @comment;
2524 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2525 $tag{'id'} = $tag_id;
2526 while (my $line = <$fd>) {
2527 chomp $line;
2528 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2529 $tag{'object'} = $1;
2530 } elsif ($line =~ m/^type (.+)$/) {
2531 $tag{'type'} = $1;
2532 } elsif ($line =~ m/^tag (.+)$/) {
2533 $tag{'name'} = $1;
2534 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2535 $tag{'author'} = $1;
2536 $tag{'author_epoch'} = $2;
2537 $tag{'author_tz'} = $3;
2538 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2539 $tag{'author_name'} = $1;
2540 $tag{'author_email'} = $2;
2541 } else {
2542 $tag{'author_name'} = $tag{'author'};
2544 } elsif ($line =~ m/--BEGIN/) {
2545 push @comment, $line;
2546 last;
2547 } elsif ($line eq "") {
2548 last;
2551 push @comment, <$fd>;
2552 $tag{'comment'} = \@comment;
2553 close $fd or return;
2554 if (!defined $tag{'name'}) {
2555 return
2557 return %tag
2560 sub parse_commit_text {
2561 my ($commit_text, $withparents) = @_;
2562 my @commit_lines = split '\n', $commit_text;
2563 my %co;
2565 pop @commit_lines; # Remove '\0'
2567 if (! @commit_lines) {
2568 return;
2571 my $header = shift @commit_lines;
2572 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2573 return;
2575 ($co{'id'}, my @parents) = split ' ', $header;
2576 while (my $line = shift @commit_lines) {
2577 last if $line eq "\n";
2578 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2579 $co{'tree'} = $1;
2580 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2581 push @parents, $1;
2582 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2583 $co{'author'} = $1;
2584 $co{'author_epoch'} = $2;
2585 $co{'author_tz'} = $3;
2586 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2587 $co{'author_name'} = $1;
2588 $co{'author_email'} = $2;
2589 } else {
2590 $co{'author_name'} = $co{'author'};
2592 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2593 $co{'committer'} = $1;
2594 $co{'committer_epoch'} = $2;
2595 $co{'committer_tz'} = $3;
2596 $co{'committer_name'} = $co{'committer'};
2597 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2598 $co{'committer_name'} = $1;
2599 $co{'committer_email'} = $2;
2600 } else {
2601 $co{'committer_name'} = $co{'committer'};
2605 if (!defined $co{'tree'}) {
2606 return;
2608 $co{'parents'} = \@parents;
2609 $co{'parent'} = $parents[0];
2611 foreach my $title (@commit_lines) {
2612 $title =~ s/^ //;
2613 if ($title ne "") {
2614 $co{'title'} = chop_str($title, 80, 5);
2615 # remove leading stuff of merges to make the interesting part visible
2616 if (length($title) > 50) {
2617 $title =~ s/^Automatic //;
2618 $title =~ s/^merge (of|with) /Merge ... /i;
2619 if (length($title) > 50) {
2620 $title =~ s/(http|rsync):\/\///;
2622 if (length($title) > 50) {
2623 $title =~ s/(master|www|rsync)\.//;
2625 if (length($title) > 50) {
2626 $title =~ s/kernel.org:?//;
2628 if (length($title) > 50) {
2629 $title =~ s/\/pub\/scm//;
2632 $co{'title_short'} = chop_str($title, 50, 5);
2633 last;
2636 if (! defined $co{'title'} || $co{'title'} eq "") {
2637 $co{'title'} = $co{'title_short'} = '(no commit message)';
2639 # remove added spaces
2640 foreach my $line (@commit_lines) {
2641 $line =~ s/^ //;
2643 $co{'comment'} = \@commit_lines;
2645 my $age = time - $co{'committer_epoch'};
2646 $co{'age'} = $age;
2647 $co{'age_string'} = age_string($age);
2648 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2649 if ($age > 60*60*24*7*2) {
2650 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2651 $co{'age_string_age'} = $co{'age_string'};
2652 } else {
2653 $co{'age_string_date'} = $co{'age_string'};
2654 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2656 return %co;
2659 sub parse_commit {
2660 my ($commit_id) = @_;
2661 my %co;
2663 local $/ = "\0";
2665 open my $fd, "-|", git_cmd(), "rev-list",
2666 "--parents",
2667 "--header",
2668 "--max-count=1",
2669 $commit_id,
2670 "--",
2671 or die_error(500, "Open git-rev-list failed");
2672 %co = parse_commit_text(<$fd>, 1);
2673 close $fd;
2675 return %co;
2678 sub parse_commits {
2679 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2680 my @cos;
2682 $maxcount ||= 1;
2683 $skip ||= 0;
2685 local $/ = "\0";
2687 open my $fd, "-|", git_cmd(), "rev-list",
2688 "--header",
2689 @args,
2690 ("--max-count=" . $maxcount),
2691 ("--skip=" . $skip),
2692 @extra_options,
2693 $commit_id,
2694 "--",
2695 ($filename ? ($filename) : ())
2696 or die_error(500, "Open git-rev-list failed");
2697 while (my $line = <$fd>) {
2698 my %co = parse_commit_text($line);
2699 push @cos, \%co;
2701 close $fd;
2703 return wantarray ? @cos : \@cos;
2706 # parse line of git-diff-tree "raw" output
2707 sub parse_difftree_raw_line {
2708 my $line = shift;
2709 my %res;
2711 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2712 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2713 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2714 $res{'from_mode'} = $1;
2715 $res{'to_mode'} = $2;
2716 $res{'from_id'} = $3;
2717 $res{'to_id'} = $4;
2718 $res{'status'} = $5;
2719 $res{'similarity'} = $6;
2720 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2721 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2722 } else {
2723 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2726 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2727 # combined diff (for merge commit)
2728 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2729 $res{'nparents'} = length($1);
2730 $res{'from_mode'} = [ split(' ', $2) ];
2731 $res{'to_mode'} = pop @{$res{'from_mode'}};
2732 $res{'from_id'} = [ split(' ', $3) ];
2733 $res{'to_id'} = pop @{$res{'from_id'}};
2734 $res{'status'} = [ split('', $4) ];
2735 $res{'to_file'} = unquote($5);
2737 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2738 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2739 $res{'commit'} = $1;
2742 return wantarray ? %res : \%res;
2745 # wrapper: return parsed line of git-diff-tree "raw" output
2746 # (the argument might be raw line, or parsed info)
2747 sub parsed_difftree_line {
2748 my $line_or_ref = shift;
2750 if (ref($line_or_ref) eq "HASH") {
2751 # pre-parsed (or generated by hand)
2752 return $line_or_ref;
2753 } else {
2754 return parse_difftree_raw_line($line_or_ref);
2758 # parse line of git-ls-tree output
2759 sub parse_ls_tree_line {
2760 my $line = shift;
2761 my %opts = @_;
2762 my %res;
2764 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2765 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2767 $res{'mode'} = $1;
2768 $res{'type'} = $2;
2769 $res{'hash'} = $3;
2770 if ($opts{'-z'}) {
2771 $res{'name'} = $4;
2772 } else {
2773 $res{'name'} = unquote($4);
2776 return wantarray ? %res : \%res;
2779 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2780 sub parse_from_to_diffinfo {
2781 my ($diffinfo, $from, $to, @parents) = @_;
2783 if ($diffinfo->{'nparents'}) {
2784 # combined diff
2785 $from->{'file'} = [];
2786 $from->{'href'} = [];
2787 fill_from_file_info($diffinfo, @parents)
2788 unless exists $diffinfo->{'from_file'};
2789 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2790 $from->{'file'}[$i] =
2791 defined $diffinfo->{'from_file'}[$i] ?
2792 $diffinfo->{'from_file'}[$i] :
2793 $diffinfo->{'to_file'};
2794 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2795 $from->{'href'}[$i] = href(action=>"blob",
2796 hash_base=>$parents[$i],
2797 hash=>$diffinfo->{'from_id'}[$i],
2798 file_name=>$from->{'file'}[$i]);
2799 } else {
2800 $from->{'href'}[$i] = undef;
2803 } else {
2804 # ordinary (not combined) diff
2805 $from->{'file'} = $diffinfo->{'from_file'};
2806 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2807 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2808 hash=>$diffinfo->{'from_id'},
2809 file_name=>$from->{'file'});
2810 } else {
2811 delete $from->{'href'};
2815 $to->{'file'} = $diffinfo->{'to_file'};
2816 if (!is_deleted($diffinfo)) { # file exists in result
2817 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2818 hash=>$diffinfo->{'to_id'},
2819 file_name=>$to->{'file'});
2820 } else {
2821 delete $to->{'href'};
2825 ## ......................................................................
2826 ## parse to array of hashes functions
2828 sub git_get_heads_list {
2829 my $limit = shift;
2830 my @headslist;
2832 open my $fd, '-|', git_cmd(), 'for-each-ref',
2833 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2834 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2835 'refs/heads'
2836 or return;
2837 while (my $line = <$fd>) {
2838 my %ref_item;
2840 chomp $line;
2841 my ($refinfo, $committerinfo) = split(/\0/, $line);
2842 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2843 my ($committer, $epoch, $tz) =
2844 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2845 $ref_item{'fullname'} = $name;
2846 $name =~ s!^refs/heads/!!;
2848 $ref_item{'name'} = $name;
2849 $ref_item{'id'} = $hash;
2850 $ref_item{'title'} = $title || '(no commit message)';
2851 $ref_item{'epoch'} = $epoch;
2852 if ($epoch) {
2853 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2854 } else {
2855 $ref_item{'age'} = "unknown";
2858 push @headslist, \%ref_item;
2860 close $fd;
2862 return wantarray ? @headslist : \@headslist;
2865 sub git_get_tags_list {
2866 my $limit = shift;
2867 my @tagslist;
2869 open my $fd, '-|', git_cmd(), 'for-each-ref',
2870 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2871 '--format=%(objectname) %(objecttype) %(refname) '.
2872 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2873 'refs/tags'
2874 or return;
2875 while (my $line = <$fd>) {
2876 my %ref_item;
2878 chomp $line;
2879 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2880 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2881 my ($creator, $epoch, $tz) =
2882 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2883 $ref_item{'fullname'} = $name;
2884 $name =~ s!^refs/tags/!!;
2886 $ref_item{'type'} = $type;
2887 $ref_item{'id'} = $id;
2888 $ref_item{'name'} = $name;
2889 if ($type eq "tag") {
2890 $ref_item{'subject'} = $title;
2891 $ref_item{'reftype'} = $reftype;
2892 $ref_item{'refid'} = $refid;
2893 } else {
2894 $ref_item{'reftype'} = $type;
2895 $ref_item{'refid'} = $id;
2898 if ($type eq "tag" || $type eq "commit") {
2899 $ref_item{'epoch'} = $epoch;
2900 if ($epoch) {
2901 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2902 } else {
2903 $ref_item{'age'} = "unknown";
2907 push @tagslist, \%ref_item;
2909 close $fd;
2911 return wantarray ? @tagslist : \@tagslist;
2914 ## ----------------------------------------------------------------------
2915 ## filesystem-related functions
2917 sub get_file_owner {
2918 my $path = shift;
2920 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2921 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2922 if (!defined $gcos) {
2923 return undef;
2925 my $owner = $gcos;
2926 $owner =~ s/[,;].*$//;
2927 return to_utf8($owner);
2930 # assume that file exists
2931 sub insert_file {
2932 my $filename = shift;
2934 open my $fd, '<', $filename;
2935 print map { to_utf8($_) } <$fd>;
2936 close $fd;
2939 ## ......................................................................
2940 ## mimetype related functions
2942 sub mimetype_guess_file {
2943 my $filename = shift;
2944 my $mimemap = shift;
2945 -r $mimemap or return undef;
2947 my %mimemap;
2948 open(my $mh, '<', $mimemap) or return undef;
2949 while (<$mh>) {
2950 next if m/^#/; # skip comments
2951 my ($mimetype, $exts) = split(/\t+/);
2952 if (defined $exts) {
2953 my @exts = split(/\s+/, $exts);
2954 foreach my $ext (@exts) {
2955 $mimemap{$ext} = $mimetype;
2959 close($mh);
2961 $filename =~ /\.([^.]*)$/;
2962 return $mimemap{$1};
2965 sub mimetype_guess {
2966 my $filename = shift;
2967 my $mime;
2968 $filename =~ /\./ or return undef;
2970 if ($mimetypes_file) {
2971 my $file = $mimetypes_file;
2972 if ($file !~ m!^/!) { # if it is relative path
2973 # it is relative to project
2974 $file = "$projectroot/$project/$file";
2976 $mime = mimetype_guess_file($filename, $file);
2978 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2979 return $mime;
2982 sub blob_mimetype {
2983 my $fd = shift;
2984 my $filename = shift;
2986 if ($filename) {
2987 my $mime = mimetype_guess($filename);
2988 $mime and return $mime;
2991 # just in case
2992 return $default_blob_plain_mimetype unless $fd;
2994 if (-T $fd) {
2995 return 'text/plain';
2996 } elsif (! $filename) {
2997 return 'application/octet-stream';
2998 } elsif ($filename =~ m/\.png$/i) {
2999 return 'image/png';
3000 } elsif ($filename =~ m/\.gif$/i) {
3001 return 'image/gif';
3002 } elsif ($filename =~ m/\.jpe?g$/i) {
3003 return 'image/jpeg';
3004 } else {
3005 return 'application/octet-stream';
3009 sub blob_contenttype {
3010 my ($fd, $file_name, $type) = @_;
3012 $type ||= blob_mimetype($fd, $file_name);
3013 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3014 $type .= "; charset=$default_text_plain_charset";
3017 return $type;
3020 ## ======================================================================
3021 ## functions printing HTML: header, footer, error page
3023 sub git_header_html {
3024 my $status = shift || "200 OK";
3025 my $expires = shift;
3027 my $title = "$site_name";
3028 if (defined $project) {
3029 $title .= " - " . to_utf8($project);
3030 if (defined $action) {
3031 $title .= "/$action";
3032 if (defined $file_name) {
3033 $title .= " - " . esc_path($file_name);
3034 if ($action eq "tree" && $file_name !~ m|/$|) {
3035 $title .= "/";
3040 my $content_type;
3041 # require explicit support from the UA if we are to send the page as
3042 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3043 # we have to do this because MSIE sometimes globs '*/*', pretending to
3044 # support xhtml+xml but choking when it gets what it asked for.
3045 if (defined $cgi->http('HTTP_ACCEPT') &&
3046 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3047 $cgi->Accept('application/xhtml+xml') != 0) {
3048 $content_type = 'application/xhtml+xml';
3049 } else {
3050 $content_type = 'text/html';
3052 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3053 -status=> $status, -expires => $expires);
3054 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3055 print <<EOF;
3056 <?xml version="1.0" encoding="utf-8"?>
3057 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3058 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3059 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3060 <!-- git core binaries version $git_version -->
3061 <head>
3062 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3063 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3064 <meta name="robots" content="index, nofollow"/>
3065 <title>$title</title>
3067 # the stylesheet, favicon etc urls won't work correctly with path_info
3068 # unless we set the appropriate base URL
3069 if ($ENV{'PATH_INFO'}) {
3070 print "<base href=\"".esc_url($base_url)."\" />\n";
3072 # print out each stylesheet that exist, providing backwards capability
3073 # for those people who defined $stylesheet in a config file
3074 if (defined $stylesheet) {
3075 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3076 } else {
3077 foreach my $stylesheet (@stylesheets) {
3078 next unless $stylesheet;
3079 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3082 if (defined $project) {
3083 my %href_params = get_feed_info();
3084 if (!exists $href_params{'-title'}) {
3085 $href_params{'-title'} = 'log';
3088 foreach my $format qw(RSS Atom) {
3089 my $type = lc($format);
3090 my %link_attr = (
3091 '-rel' => 'alternate',
3092 '-title' => "$project - $href_params{'-title'} - $format feed",
3093 '-type' => "application/$type+xml"
3096 $href_params{'action'} = $type;
3097 $link_attr{'-href'} = href(%href_params);
3098 print "<link ".
3099 "rel=\"$link_attr{'-rel'}\" ".
3100 "title=\"$link_attr{'-title'}\" ".
3101 "href=\"$link_attr{'-href'}\" ".
3102 "type=\"$link_attr{'-type'}\" ".
3103 "/>\n";
3105 $href_params{'extra_options'} = '--no-merges';
3106 $link_attr{'-href'} = href(%href_params);
3107 $link_attr{'-title'} .= ' (no merges)';
3108 print "<link ".
3109 "rel=\"$link_attr{'-rel'}\" ".
3110 "title=\"$link_attr{'-title'}\" ".
3111 "href=\"$link_attr{'-href'}\" ".
3112 "type=\"$link_attr{'-type'}\" ".
3113 "/>\n";
3116 } else {
3117 printf('<link rel="alternate" title="%s projects list" '.
3118 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3119 $site_name, href(project=>undef, action=>"project_index"));
3120 printf('<link rel="alternate" title="%s projects feeds" '.
3121 'href="%s" type="text/x-opml" />'."\n",
3122 $site_name, href(project=>undef, action=>"opml"));
3124 if (defined $favicon) {
3125 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3128 print "</head>\n" .
3129 "<body>\n";
3131 if (-f $site_header) {
3132 insert_file($site_header);
3135 print "<div class=\"page_header\">\n" .
3136 $cgi->a({-href => esc_url($logo_url),
3137 -title => $logo_label},
3138 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3139 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3140 if (defined $project) {
3141 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3142 if (defined $action) {
3143 print " / $action";
3145 print "\n";
3147 print "</div>\n";
3149 my $have_search = gitweb_check_feature('search');
3150 if (defined $project && $have_search) {
3151 if (!defined $searchtext) {
3152 $searchtext = "";
3154 my $search_hash;
3155 if (defined $hash_base) {
3156 $search_hash = $hash_base;
3157 } elsif (defined $hash) {
3158 $search_hash = $hash;
3159 } else {
3160 $search_hash = "HEAD";
3162 my $action = $my_uri;
3163 my $use_pathinfo = gitweb_check_feature('pathinfo');
3164 if ($use_pathinfo) {
3165 $action .= "/".esc_url($project);
3167 print $cgi->startform(-method => "get", -action => $action) .
3168 "<div class=\"search\">\n" .
3169 (!$use_pathinfo &&
3170 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3171 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3172 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3173 $cgi->popup_menu(-name => 'st', -default => 'commit',
3174 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3175 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3176 " search:\n",
3177 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3178 "<span title=\"Extended regular expression\">" .
3179 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3180 -checked => $search_use_regexp) .
3181 "</span>" .
3182 "</div>" .
3183 $cgi->end_form() . "\n";
3187 sub git_footer_html {
3188 my $feed_class = 'rss_logo';
3190 print "<div class=\"page_footer\">\n";
3191 if (defined $project) {
3192 my $descr = git_get_project_description($project);
3193 if (defined $descr) {
3194 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3197 my %href_params = get_feed_info();
3198 if (!%href_params) {
3199 $feed_class .= ' generic';
3201 $href_params{'-title'} ||= 'log';
3203 foreach my $format qw(RSS Atom) {
3204 $href_params{'action'} = lc($format);
3205 print $cgi->a({-href => href(%href_params),
3206 -title => "$href_params{'-title'} $format feed",
3207 -class => $feed_class}, $format)."\n";
3210 } else {
3211 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3212 -class => $feed_class}, "OPML") . " ";
3213 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3214 -class => $feed_class}, "TXT") . "\n";
3216 print "</div>\n"; # class="page_footer"
3218 if (-f $site_footer) {
3219 insert_file($site_footer);
3222 print "</body>\n" .
3223 "</html>";
3226 # die_error(<http_status_code>, <error_message>)
3227 # Example: die_error(404, 'Hash not found')
3228 # By convention, use the following status codes (as defined in RFC 2616):
3229 # 400: Invalid or missing CGI parameters, or
3230 # requested object exists but has wrong type.
3231 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3232 # this server or project.
3233 # 404: Requested object/revision/project doesn't exist.
3234 # 500: The server isn't configured properly, or
3235 # an internal error occurred (e.g. failed assertions caused by bugs), or
3236 # an unknown error occurred (e.g. the git binary died unexpectedly).
3237 sub die_error {
3238 my $status = shift || 500;
3239 my $error = shift || "Internal server error";
3241 my %http_responses = (400 => '400 Bad Request',
3242 403 => '403 Forbidden',
3243 404 => '404 Not Found',
3244 500 => '500 Internal Server Error');
3245 git_header_html($http_responses{$status});
3246 print <<EOF;
3247 <div class="page_body">
3248 <br /><br />
3249 $status - $error
3250 <br />
3251 </div>
3253 git_footer_html();
3254 exit;
3257 ## ----------------------------------------------------------------------
3258 ## functions printing or outputting HTML: navigation
3260 sub git_print_page_nav {
3261 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3262 $extra = '' if !defined $extra; # pager or formats
3264 my @navs = qw(summary shortlog log commit commitdiff tree);
3265 if ($suppress) {
3266 @navs = grep { $_ ne $suppress } @navs;
3269 my %arg = map { $_ => {action=>$_} } @navs;
3270 if (defined $head) {
3271 for (qw(commit commitdiff)) {
3272 $arg{$_}{'hash'} = $head;
3274 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3275 for (qw(shortlog log)) {
3276 $arg{$_}{'hash'} = $head;
3281 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3282 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3284 my @actions = gitweb_get_feature('actions');
3285 my %repl = (
3286 '%' => '%',
3287 'n' => $project, # project name
3288 'f' => $git_dir, # project path within filesystem
3289 'h' => $treehead || '', # current hash ('h' parameter)
3290 'b' => $treebase || '', # hash base ('hb' parameter)
3292 while (@actions) {
3293 my ($label, $link, $pos) = splice(@actions,0,3);
3294 # insert
3295 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3296 # munch munch
3297 $link =~ s/%([%nfhb])/$repl{$1}/g;
3298 $arg{$label}{'_href'} = $link;
3301 print "<div class=\"page_nav\">\n" .
3302 (join " | ",
3303 map { $_ eq $current ?
3304 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3305 } @navs);
3306 print "<br/>\n$extra<br/>\n" .
3307 "</div>\n";
3310 sub format_paging_nav {
3311 my ($action, $hash, $head, $page, $has_next_link) = @_;
3312 my $paging_nav;
3315 if ($hash ne $head || $page) {
3316 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3317 } else {
3318 $paging_nav .= "HEAD";
3321 if ($page > 0) {
3322 $paging_nav .= " &sdot; " .
3323 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3324 -accesskey => "p", -title => "Alt-p"}, "prev");
3325 } else {
3326 $paging_nav .= " &sdot; prev";
3329 if ($has_next_link) {
3330 $paging_nav .= " &sdot; " .
3331 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3332 -accesskey => "n", -title => "Alt-n"}, "next");
3333 } else {
3334 $paging_nav .= " &sdot; next";
3337 return $paging_nav;
3340 ## ......................................................................
3341 ## functions printing or outputting HTML: div
3343 sub git_print_header_div {
3344 my ($action, $title, $hash, $hash_base) = @_;
3345 my %args = ();
3347 $args{'action'} = $action;
3348 $args{'hash'} = $hash if $hash;
3349 $args{'hash_base'} = $hash_base if $hash_base;
3351 print "<div class=\"header\">\n" .
3352 $cgi->a({-href => href(%args), -class => "title"},
3353 $title ? $title : $action) .
3354 "\n</div>\n";
3357 sub print_local_time {
3358 my %date = @_;
3359 if ($date{'hour_local'} < 6) {
3360 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3361 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3362 } else {
3363 printf(" (%02d:%02d %s)",
3364 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3368 # Outputs the author name and date in long form
3369 sub git_print_authorship {
3370 my $co = shift;
3371 my %opts = @_;
3372 my $tag = $opts{-tag} || 'div';
3374 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3375 print "<$tag class=\"author_date\">" .
3376 esc_html($co->{'author_name'}) .
3377 " [$ad{'rfc2822'}";
3378 print_local_time(%ad) if ($opts{-localtime});
3379 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3380 . "</$tag>\n";
3383 # Outputs table rows containing the full author or committer information,
3384 # in the format expected for 'commit' view (& similia).
3385 # Parameters are a commit hash reference, followed by the list of people
3386 # to output information for. If the list is empty it defalts to both
3387 # author and committer.
3388 sub git_print_authorship_rows {
3389 my $co = shift;
3390 # too bad we can't use @people = @_ || ('author', 'committer')
3391 my @people = @_;
3392 @people = ('author', 'committer') unless @people;
3393 foreach my $who (@people) {
3394 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3395 print "<tr><td>$who</td><td>" . esc_html($co->{$who}) . "</td>" .
3396 "<td rowspan=\"2\">" .
3397 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3398 "</td></tr>\n" .
3399 "<tr>" .
3400 "<td></td><td> $wd{'rfc2822'}";
3401 print_local_time(%wd);
3402 print "</td>" .
3403 "</tr>\n";
3407 sub git_print_page_path {
3408 my $name = shift;
3409 my $type = shift;
3410 my $hb = shift;
3413 print "<div class=\"page_path\">";
3414 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3415 -title => 'tree root'}, to_utf8("[$project]"));
3416 print " / ";
3417 if (defined $name) {
3418 my @dirname = split '/', $name;
3419 my $basename = pop @dirname;
3420 my $fullname = '';
3422 foreach my $dir (@dirname) {
3423 $fullname .= ($fullname ? '/' : '') . $dir;
3424 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3425 hash_base=>$hb),
3426 -title => $fullname}, esc_path($dir));
3427 print " / ";
3429 if (defined $type && $type eq 'blob') {
3430 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3431 hash_base=>$hb),
3432 -title => $name}, esc_path($basename));
3433 } elsif (defined $type && $type eq 'tree') {
3434 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3435 hash_base=>$hb),
3436 -title => $name}, esc_path($basename));
3437 print " / ";
3438 } else {
3439 print esc_path($basename);
3442 print "<br/></div>\n";
3445 sub git_print_log {
3446 my $log = shift;
3447 my %opts = @_;
3449 if ($opts{'-remove_title'}) {
3450 # remove title, i.e. first line of log
3451 shift @$log;
3453 # remove leading empty lines
3454 while (defined $log->[0] && $log->[0] eq "") {
3455 shift @$log;
3458 # print log
3459 my $signoff = 0;
3460 my $empty = 0;
3461 foreach my $line (@$log) {
3462 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3463 $signoff = 1;
3464 $empty = 0;
3465 if (! $opts{'-remove_signoff'}) {
3466 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3467 next;
3468 } else {
3469 # remove signoff lines
3470 next;
3472 } else {
3473 $signoff = 0;
3476 # print only one empty line
3477 # do not print empty line after signoff
3478 if ($line eq "") {
3479 next if ($empty || $signoff);
3480 $empty = 1;
3481 } else {
3482 $empty = 0;
3485 print format_log_line_html($line) . "<br/>\n";
3488 if ($opts{'-final_empty_line'}) {
3489 # end with single empty line
3490 print "<br/>\n" unless $empty;
3494 # return link target (what link points to)
3495 sub git_get_link_target {
3496 my $hash = shift;
3497 my $link_target;
3499 # read link
3500 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3501 or return;
3503 local $/ = undef;
3504 $link_target = <$fd>;
3506 close $fd
3507 or return;
3509 return $link_target;
3512 # given link target, and the directory (basedir) the link is in,
3513 # return target of link relative to top directory (top tree);
3514 # return undef if it is not possible (including absolute links).
3515 sub normalize_link_target {
3516 my ($link_target, $basedir) = @_;
3518 # absolute symlinks (beginning with '/') cannot be normalized
3519 return if (substr($link_target, 0, 1) eq '/');
3521 # normalize link target to path from top (root) tree (dir)
3522 my $path;
3523 if ($basedir) {
3524 $path = $basedir . '/' . $link_target;
3525 } else {
3526 # we are in top (root) tree (dir)
3527 $path = $link_target;
3530 # remove //, /./, and /../
3531 my @path_parts;
3532 foreach my $part (split('/', $path)) {
3533 # discard '.' and ''
3534 next if (!$part || $part eq '.');
3535 # handle '..'
3536 if ($part eq '..') {
3537 if (@path_parts) {
3538 pop @path_parts;
3539 } else {
3540 # link leads outside repository (outside top dir)
3541 return;
3543 } else {
3544 push @path_parts, $part;
3547 $path = join('/', @path_parts);
3549 return $path;
3552 # print tree entry (row of git_tree), but without encompassing <tr> element
3553 sub git_print_tree_entry {
3554 my ($t, $basedir, $hash_base, $have_blame) = @_;
3556 my %base_key = ();
3557 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3559 # The format of a table row is: mode list link. Where mode is
3560 # the mode of the entry, list is the name of the entry, an href,
3561 # and link is the action links of the entry.
3563 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3564 if ($t->{'type'} eq "blob") {
3565 print "<td class=\"list\">" .
3566 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3567 file_name=>"$basedir$t->{'name'}", %base_key),
3568 -class => "list"}, esc_path($t->{'name'}));
3569 if (S_ISLNK(oct $t->{'mode'})) {
3570 my $link_target = git_get_link_target($t->{'hash'});
3571 if ($link_target) {
3572 my $norm_target = normalize_link_target($link_target, $basedir);
3573 if (defined $norm_target) {
3574 print " -> " .
3575 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3576 file_name=>$norm_target),
3577 -title => $norm_target}, esc_path($link_target));
3578 } else {
3579 print " -> " . esc_path($link_target);
3583 print "</td>\n";
3584 print "<td class=\"link\">";
3585 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3586 file_name=>"$basedir$t->{'name'}", %base_key)},
3587 "blob");
3588 if ($have_blame) {
3589 print " | " .
3590 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3591 file_name=>"$basedir$t->{'name'}", %base_key)},
3592 "blame");
3594 if (defined $hash_base) {
3595 print " | " .
3596 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3597 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3598 "history");
3600 print " | " .
3601 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3602 file_name=>"$basedir$t->{'name'}")},
3603 "raw");
3604 print "</td>\n";
3606 } elsif ($t->{'type'} eq "tree") {
3607 print "<td class=\"list\">";
3608 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3609 file_name=>"$basedir$t->{'name'}", %base_key)},
3610 esc_path($t->{'name'}));
3611 print "</td>\n";
3612 print "<td class=\"link\">";
3613 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3614 file_name=>"$basedir$t->{'name'}", %base_key)},
3615 "tree");
3616 if (defined $hash_base) {
3617 print " | " .
3618 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3619 file_name=>"$basedir$t->{'name'}")},
3620 "history");
3622 print "</td>\n";
3623 } else {
3624 # unknown object: we can only present history for it
3625 # (this includes 'commit' object, i.e. submodule support)
3626 print "<td class=\"list\">" .
3627 esc_path($t->{'name'}) .
3628 "</td>\n";
3629 print "<td class=\"link\">";
3630 if (defined $hash_base) {
3631 print $cgi->a({-href => href(action=>"history",
3632 hash_base=>$hash_base,
3633 file_name=>"$basedir$t->{'name'}")},
3634 "history");
3636 print "</td>\n";
3640 ## ......................................................................
3641 ## functions printing large fragments of HTML
3643 # get pre-image filenames for merge (combined) diff
3644 sub fill_from_file_info {
3645 my ($diff, @parents) = @_;
3647 $diff->{'from_file'} = [ ];
3648 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3649 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3650 if ($diff->{'status'}[$i] eq 'R' ||
3651 $diff->{'status'}[$i] eq 'C') {
3652 $diff->{'from_file'}[$i] =
3653 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3657 return $diff;
3660 # is current raw difftree line of file deletion
3661 sub is_deleted {
3662 my $diffinfo = shift;
3664 return $diffinfo->{'to_id'} eq ('0' x 40);
3667 # does patch correspond to [previous] difftree raw line
3668 # $diffinfo - hashref of parsed raw diff format
3669 # $patchinfo - hashref of parsed patch diff format
3670 # (the same keys as in $diffinfo)
3671 sub is_patch_split {
3672 my ($diffinfo, $patchinfo) = @_;
3674 return defined $diffinfo && defined $patchinfo
3675 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3679 sub git_difftree_body {
3680 my ($difftree, $hash, @parents) = @_;
3681 my ($parent) = $parents[0];
3682 my $have_blame = gitweb_check_feature('blame');
3683 print "<div class=\"list_head\">\n";
3684 if ($#{$difftree} > 10) {
3685 print(($#{$difftree} + 1) . " files changed:\n");
3687 print "</div>\n";
3689 print "<table class=\"" .
3690 (@parents > 1 ? "combined " : "") .
3691 "diff_tree\">\n";
3693 # header only for combined diff in 'commitdiff' view
3694 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3695 if ($has_header) {
3696 # table header
3697 print "<thead><tr>\n" .
3698 "<th></th><th></th>\n"; # filename, patchN link
3699 for (my $i = 0; $i < @parents; $i++) {
3700 my $par = $parents[$i];
3701 print "<th>" .
3702 $cgi->a({-href => href(action=>"commitdiff",
3703 hash=>$hash, hash_parent=>$par),
3704 -title => 'commitdiff to parent number ' .
3705 ($i+1) . ': ' . substr($par,0,7)},
3706 $i+1) .
3707 "&nbsp;</th>\n";
3709 print "</tr></thead>\n<tbody>\n";
3712 my $alternate = 1;
3713 my $patchno = 0;
3714 foreach my $line (@{$difftree}) {
3715 my $diff = parsed_difftree_line($line);
3717 if ($alternate) {
3718 print "<tr class=\"dark\">\n";
3719 } else {
3720 print "<tr class=\"light\">\n";
3722 $alternate ^= 1;
3724 if (exists $diff->{'nparents'}) { # combined diff
3726 fill_from_file_info($diff, @parents)
3727 unless exists $diff->{'from_file'};
3729 if (!is_deleted($diff)) {
3730 # file exists in the result (child) commit
3731 print "<td>" .
3732 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3733 file_name=>$diff->{'to_file'},
3734 hash_base=>$hash),
3735 -class => "list"}, esc_path($diff->{'to_file'})) .
3736 "</td>\n";
3737 } else {
3738 print "<td>" .
3739 esc_path($diff->{'to_file'}) .
3740 "</td>\n";
3743 if ($action eq 'commitdiff') {
3744 # link to patch
3745 $patchno++;
3746 print "<td class=\"link\">" .
3747 $cgi->a({-href => "#patch$patchno"}, "patch") .
3748 " | " .
3749 "</td>\n";
3752 my $has_history = 0;
3753 my $not_deleted = 0;
3754 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3755 my $hash_parent = $parents[$i];
3756 my $from_hash = $diff->{'from_id'}[$i];
3757 my $from_path = $diff->{'from_file'}[$i];
3758 my $status = $diff->{'status'}[$i];
3760 $has_history ||= ($status ne 'A');
3761 $not_deleted ||= ($status ne 'D');
3763 if ($status eq 'A') {
3764 print "<td class=\"link\" align=\"right\"> | </td>\n";
3765 } elsif ($status eq 'D') {
3766 print "<td class=\"link\">" .
3767 $cgi->a({-href => href(action=>"blob",
3768 hash_base=>$hash,
3769 hash=>$from_hash,
3770 file_name=>$from_path)},
3771 "blob" . ($i+1)) .
3772 " | </td>\n";
3773 } else {
3774 if ($diff->{'to_id'} eq $from_hash) {
3775 print "<td class=\"link nochange\">";
3776 } else {
3777 print "<td class=\"link\">";
3779 print $cgi->a({-href => href(action=>"blobdiff",
3780 hash=>$diff->{'to_id'},
3781 hash_parent=>$from_hash,
3782 hash_base=>$hash,
3783 hash_parent_base=>$hash_parent,
3784 file_name=>$diff->{'to_file'},
3785 file_parent=>$from_path)},
3786 "diff" . ($i+1)) .
3787 " | </td>\n";
3791 print "<td class=\"link\">";
3792 if ($not_deleted) {
3793 print $cgi->a({-href => href(action=>"blob",
3794 hash=>$diff->{'to_id'},
3795 file_name=>$diff->{'to_file'},
3796 hash_base=>$hash)},
3797 "blob");
3798 print " | " if ($has_history);
3800 if ($has_history) {
3801 print $cgi->a({-href => href(action=>"history",
3802 file_name=>$diff->{'to_file'},
3803 hash_base=>$hash)},
3804 "history");
3806 print "</td>\n";
3808 print "</tr>\n";
3809 next; # instead of 'else' clause, to avoid extra indent
3811 # else ordinary diff
3813 my ($to_mode_oct, $to_mode_str, $to_file_type);
3814 my ($from_mode_oct, $from_mode_str, $from_file_type);
3815 if ($diff->{'to_mode'} ne ('0' x 6)) {
3816 $to_mode_oct = oct $diff->{'to_mode'};
3817 if (S_ISREG($to_mode_oct)) { # only for regular file
3818 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3820 $to_file_type = file_type($diff->{'to_mode'});
3822 if ($diff->{'from_mode'} ne ('0' x 6)) {
3823 $from_mode_oct = oct $diff->{'from_mode'};
3824 if (S_ISREG($to_mode_oct)) { # only for regular file
3825 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3827 $from_file_type = file_type($diff->{'from_mode'});
3830 if ($diff->{'status'} eq "A") { # created
3831 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3832 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3833 $mode_chng .= "]</span>";
3834 print "<td>";
3835 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3836 hash_base=>$hash, file_name=>$diff->{'file'}),
3837 -class => "list"}, esc_path($diff->{'file'}));
3838 print "</td>\n";
3839 print "<td>$mode_chng</td>\n";
3840 print "<td class=\"link\">";
3841 if ($action eq 'commitdiff') {
3842 # link to patch
3843 $patchno++;
3844 print $cgi->a({-href => "#patch$patchno"}, "patch");
3845 print " | ";
3847 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3848 hash_base=>$hash, file_name=>$diff->{'file'})},
3849 "blob");
3850 print "</td>\n";
3852 } elsif ($diff->{'status'} eq "D") { # deleted
3853 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3854 print "<td>";
3855 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3856 hash_base=>$parent, file_name=>$diff->{'file'}),
3857 -class => "list"}, esc_path($diff->{'file'}));
3858 print "</td>\n";
3859 print "<td>$mode_chng</td>\n";
3860 print "<td class=\"link\">";
3861 if ($action eq 'commitdiff') {
3862 # link to patch
3863 $patchno++;
3864 print $cgi->a({-href => "#patch$patchno"}, "patch");
3865 print " | ";
3867 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3868 hash_base=>$parent, file_name=>$diff->{'file'})},
3869 "blob") . " | ";
3870 if ($have_blame) {
3871 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3872 file_name=>$diff->{'file'})},
3873 "blame") . " | ";
3875 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3876 file_name=>$diff->{'file'})},
3877 "history");
3878 print "</td>\n";
3880 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3881 my $mode_chnge = "";
3882 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3883 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3884 if ($from_file_type ne $to_file_type) {
3885 $mode_chnge .= " from $from_file_type to $to_file_type";
3887 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3888 if ($from_mode_str && $to_mode_str) {
3889 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3890 } elsif ($to_mode_str) {
3891 $mode_chnge .= " mode: $to_mode_str";
3894 $mode_chnge .= "]</span>\n";
3896 print "<td>";
3897 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3898 hash_base=>$hash, file_name=>$diff->{'file'}),
3899 -class => "list"}, esc_path($diff->{'file'}));
3900 print "</td>\n";
3901 print "<td>$mode_chnge</td>\n";
3902 print "<td class=\"link\">";
3903 if ($action eq 'commitdiff') {
3904 # link to patch
3905 $patchno++;
3906 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3907 " | ";
3908 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3909 # "commit" view and modified file (not onlu mode changed)
3910 print $cgi->a({-href => href(action=>"blobdiff",
3911 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3912 hash_base=>$hash, hash_parent_base=>$parent,
3913 file_name=>$diff->{'file'})},
3914 "diff") .
3915 " | ";
3917 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3918 hash_base=>$hash, file_name=>$diff->{'file'})},
3919 "blob") . " | ";
3920 if ($have_blame) {
3921 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3922 file_name=>$diff->{'file'})},
3923 "blame") . " | ";
3925 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3926 file_name=>$diff->{'file'})},
3927 "history");
3928 print "</td>\n";
3930 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3931 my %status_name = ('R' => 'moved', 'C' => 'copied');
3932 my $nstatus = $status_name{$diff->{'status'}};
3933 my $mode_chng = "";
3934 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3935 # mode also for directories, so we cannot use $to_mode_str
3936 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3938 print "<td>" .
3939 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3940 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3941 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3942 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3943 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3944 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3945 -class => "list"}, esc_path($diff->{'from_file'})) .
3946 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3947 "<td class=\"link\">";
3948 if ($action eq 'commitdiff') {
3949 # link to patch
3950 $patchno++;
3951 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3952 " | ";
3953 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3954 # "commit" view and modified file (not only pure rename or copy)
3955 print $cgi->a({-href => href(action=>"blobdiff",
3956 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3957 hash_base=>$hash, hash_parent_base=>$parent,
3958 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3959 "diff") .
3960 " | ";
3962 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3963 hash_base=>$parent, file_name=>$diff->{'to_file'})},
3964 "blob") . " | ";
3965 if ($have_blame) {
3966 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3967 file_name=>$diff->{'to_file'})},
3968 "blame") . " | ";
3970 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3971 file_name=>$diff->{'to_file'})},
3972 "history");
3973 print "</td>\n";
3975 } # we should not encounter Unmerged (U) or Unknown (X) status
3976 print "</tr>\n";
3978 print "</tbody>" if $has_header;
3979 print "</table>\n";
3982 sub git_patchset_body {
3983 my ($fd, $difftree, $hash, @hash_parents) = @_;
3984 my ($hash_parent) = $hash_parents[0];
3986 my $is_combined = (@hash_parents > 1);
3987 my $patch_idx = 0;
3988 my $patch_number = 0;
3989 my $patch_line;
3990 my $diffinfo;
3991 my $to_name;
3992 my (%from, %to);
3994 print "<div class=\"patchset\">\n";
3996 # skip to first patch
3997 while ($patch_line = <$fd>) {
3998 chomp $patch_line;
4000 last if ($patch_line =~ m/^diff /);
4003 PATCH:
4004 while ($patch_line) {
4006 # parse "git diff" header line
4007 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4008 # $1 is from_name, which we do not use
4009 $to_name = unquote($2);
4010 $to_name =~ s!^b/!!;
4011 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4012 # $1 is 'cc' or 'combined', which we do not use
4013 $to_name = unquote($2);
4014 } else {
4015 $to_name = undef;
4018 # check if current patch belong to current raw line
4019 # and parse raw git-diff line if needed
4020 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4021 # this is continuation of a split patch
4022 print "<div class=\"patch cont\">\n";
4023 } else {
4024 # advance raw git-diff output if needed
4025 $patch_idx++ if defined $diffinfo;
4027 # read and prepare patch information
4028 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4030 # compact combined diff output can have some patches skipped
4031 # find which patch (using pathname of result) we are at now;
4032 if ($is_combined) {
4033 while ($to_name ne $diffinfo->{'to_file'}) {
4034 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4035 format_diff_cc_simplified($diffinfo, @hash_parents) .
4036 "</div>\n"; # class="patch"
4038 $patch_idx++;
4039 $patch_number++;
4041 last if $patch_idx > $#$difftree;
4042 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4046 # modifies %from, %to hashes
4047 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4049 # this is first patch for raw difftree line with $patch_idx index
4050 # we index @$difftree array from 0, but number patches from 1
4051 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4054 # git diff header
4055 #assert($patch_line =~ m/^diff /) if DEBUG;
4056 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4057 $patch_number++;
4058 # print "git diff" header
4059 print format_git_diff_header_line($patch_line, $diffinfo,
4060 \%from, \%to);
4062 # print extended diff header
4063 print "<div class=\"diff extended_header\">\n";
4064 EXTENDED_HEADER:
4065 while ($patch_line = <$fd>) {
4066 chomp $patch_line;
4068 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4070 print format_extended_diff_header_line($patch_line, $diffinfo,
4071 \%from, \%to);
4073 print "</div>\n"; # class="diff extended_header"
4075 # from-file/to-file diff header
4076 if (! $patch_line) {
4077 print "</div>\n"; # class="patch"
4078 last PATCH;
4080 next PATCH if ($patch_line =~ m/^diff /);
4081 #assert($patch_line =~ m/^---/) if DEBUG;
4083 my $last_patch_line = $patch_line;
4084 $patch_line = <$fd>;
4085 chomp $patch_line;
4086 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4088 print format_diff_from_to_header($last_patch_line, $patch_line,
4089 $diffinfo, \%from, \%to,
4090 @hash_parents);
4092 # the patch itself
4093 LINE:
4094 while ($patch_line = <$fd>) {
4095 chomp $patch_line;
4097 next PATCH if ($patch_line =~ m/^diff /);
4099 print format_diff_line($patch_line, \%from, \%to);
4102 } continue {
4103 print "</div>\n"; # class="patch"
4106 # for compact combined (--cc) format, with chunk and patch simpliciaction
4107 # patchset might be empty, but there might be unprocessed raw lines
4108 for (++$patch_idx if $patch_number > 0;
4109 $patch_idx < @$difftree;
4110 ++$patch_idx) {
4111 # read and prepare patch information
4112 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4114 # generate anchor for "patch" links in difftree / whatchanged part
4115 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4116 format_diff_cc_simplified($diffinfo, @hash_parents) .
4117 "</div>\n"; # class="patch"
4119 $patch_number++;
4122 if ($patch_number == 0) {
4123 if (@hash_parents > 1) {
4124 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4125 } else {
4126 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4130 print "</div>\n"; # class="patchset"
4133 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4135 # fills project list info (age, description, owner, forks) for each
4136 # project in the list, removing invalid projects from returned list
4137 # NOTE: modifies $projlist, but does not remove entries from it
4138 sub fill_project_list_info {
4139 my ($projlist, $check_forks) = @_;
4140 my @projects;
4142 my $show_ctags = gitweb_check_feature('ctags');
4143 PROJECT:
4144 foreach my $pr (@$projlist) {
4145 my (@activity) = git_get_last_activity($pr->{'path'});
4146 unless (@activity) {
4147 next PROJECT;
4149 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4150 if (!defined $pr->{'descr'}) {
4151 my $descr = git_get_project_description($pr->{'path'}) || "";
4152 $descr = to_utf8($descr);
4153 $pr->{'descr_long'} = $descr;
4154 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4156 if (!defined $pr->{'owner'}) {
4157 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4159 if ($check_forks) {
4160 my $pname = $pr->{'path'};
4161 if (($pname =~ s/\.git$//) &&
4162 ($pname !~ /\/$/) &&
4163 (-d "$projectroot/$pname")) {
4164 $pr->{'forks'} = "-d $projectroot/$pname";
4165 } else {
4166 $pr->{'forks'} = 0;
4169 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4170 push @projects, $pr;
4173 return @projects;
4176 # print 'sort by' <th> element, generating 'sort by $name' replay link
4177 # if that order is not selected
4178 sub print_sort_th {
4179 my ($name, $order, $header) = @_;
4180 $header ||= ucfirst($name);
4182 if ($order eq $name) {
4183 print "<th>$header</th>\n";
4184 } else {
4185 print "<th>" .
4186 $cgi->a({-href => href(-replay=>1, order=>$name),
4187 -class => "header"}, $header) .
4188 "</th>\n";
4192 sub git_project_list_body {
4193 # actually uses global variable $project
4194 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4196 my $check_forks = gitweb_check_feature('forks');
4197 my @projects = fill_project_list_info($projlist, $check_forks);
4199 $order ||= $default_projects_order;
4200 $from = 0 unless defined $from;
4201 $to = $#projects if (!defined $to || $#projects < $to);
4203 my %order_info = (
4204 project => { key => 'path', type => 'str' },
4205 descr => { key => 'descr_long', type => 'str' },
4206 owner => { key => 'owner', type => 'str' },
4207 age => { key => 'age', type => 'num' }
4209 my $oi = $order_info{$order};
4210 if ($oi->{'type'} eq 'str') {
4211 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4212 } else {
4213 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4216 my $show_ctags = gitweb_check_feature('ctags');
4217 if ($show_ctags) {
4218 my %ctags;
4219 foreach my $p (@projects) {
4220 foreach my $ct (keys %{$p->{'ctags'}}) {
4221 $ctags{$ct} += $p->{'ctags'}->{$ct};
4224 my $cloud = git_populate_project_tagcloud(\%ctags);
4225 print git_show_project_tagcloud($cloud, 64);
4228 print "<table class=\"project_list\">\n";
4229 unless ($no_header) {
4230 print "<tr>\n";
4231 if ($check_forks) {
4232 print "<th></th>\n";
4234 print_sort_th('project', $order, 'Project');
4235 print_sort_th('descr', $order, 'Description');
4236 print_sort_th('owner', $order, 'Owner');
4237 print_sort_th('age', $order, 'Last Change');
4238 print "<th></th>\n" . # for links
4239 "</tr>\n";
4241 my $alternate = 1;
4242 my $tagfilter = $cgi->param('by_tag');
4243 for (my $i = $from; $i <= $to; $i++) {
4244 my $pr = $projects[$i];
4246 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4247 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4248 and not $pr->{'descr_long'} =~ /$searchtext/;
4249 # Weed out forks or non-matching entries of search
4250 if ($check_forks) {
4251 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4252 $forkbase="^$forkbase" if $forkbase;
4253 next if not $searchtext and not $tagfilter and $show_ctags
4254 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4257 if ($alternate) {
4258 print "<tr class=\"dark\">\n";
4259 } else {
4260 print "<tr class=\"light\">\n";
4262 $alternate ^= 1;
4263 if ($check_forks) {
4264 print "<td>";
4265 if ($pr->{'forks'}) {
4266 print "<!-- $pr->{'forks'} -->\n";
4267 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4269 print "</td>\n";
4271 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4272 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4273 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4274 -class => "list", -title => $pr->{'descr_long'}},
4275 esc_html($pr->{'descr'})) . "</td>\n" .
4276 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4277 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4278 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4279 "<td class=\"link\">" .
4280 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4281 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4282 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4283 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4284 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4285 "</td>\n" .
4286 "</tr>\n";
4288 if (defined $extra) {
4289 print "<tr>\n";
4290 if ($check_forks) {
4291 print "<td></td>\n";
4293 print "<td colspan=\"5\">$extra</td>\n" .
4294 "</tr>\n";
4296 print "</table>\n";
4299 sub git_shortlog_body {
4300 # uses global variable $project
4301 my ($commitlist, $from, $to, $refs, $extra) = @_;
4303 $from = 0 unless defined $from;
4304 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4306 print "<table class=\"shortlog\">\n";
4307 my $alternate = 1;
4308 for (my $i = $from; $i <= $to; $i++) {
4309 my %co = %{$commitlist->[$i]};
4310 my $commit = $co{'id'};
4311 my $ref = format_ref_marker($refs, $commit);
4312 if ($alternate) {
4313 print "<tr class=\"dark\">\n";
4314 } else {
4315 print "<tr class=\"light\">\n";
4317 $alternate ^= 1;
4318 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4319 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4320 format_author_html('td', \%co, 10) . "<td>";
4321 print format_subject_html($co{'title'}, $co{'title_short'},
4322 href(action=>"commit", hash=>$commit), $ref);
4323 print "</td>\n" .
4324 "<td class=\"link\">" .
4325 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4326 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4327 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4328 my $snapshot_links = format_snapshot_links($commit);
4329 if (defined $snapshot_links) {
4330 print " | " . $snapshot_links;
4332 print "</td>\n" .
4333 "</tr>\n";
4335 if (defined $extra) {
4336 print "<tr>\n" .
4337 "<td colspan=\"4\">$extra</td>\n" .
4338 "</tr>\n";
4340 print "</table>\n";
4343 sub git_history_body {
4344 # Warning: assumes constant type (blob or tree) during history
4345 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4347 $from = 0 unless defined $from;
4348 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4350 print "<table class=\"history\">\n";
4351 my $alternate = 1;
4352 for (my $i = $from; $i <= $to; $i++) {
4353 my %co = %{$commitlist->[$i]};
4354 if (!%co) {
4355 next;
4357 my $commit = $co{'id'};
4359 my $ref = format_ref_marker($refs, $commit);
4361 if ($alternate) {
4362 print "<tr class=\"dark\">\n";
4363 } else {
4364 print "<tr class=\"light\">\n";
4366 $alternate ^= 1;
4367 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4368 # shortlog: format_author_html('td', \%co, 10)
4369 format_author_html('td', \%co, 15, 3) . "<td>";
4370 # originally git_history used chop_str($co{'title'}, 50)
4371 print format_subject_html($co{'title'}, $co{'title_short'},
4372 href(action=>"commit", hash=>$commit), $ref);
4373 print "</td>\n" .
4374 "<td class=\"link\">" .
4375 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4376 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4378 if ($ftype eq 'blob') {
4379 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4380 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4381 if (defined $blob_current && defined $blob_parent &&
4382 $blob_current ne $blob_parent) {
4383 print " | " .
4384 $cgi->a({-href => href(action=>"blobdiff",
4385 hash=>$blob_current, hash_parent=>$blob_parent,
4386 hash_base=>$hash_base, hash_parent_base=>$commit,
4387 file_name=>$file_name)},
4388 "diff to current");
4391 print "</td>\n" .
4392 "</tr>\n";
4394 if (defined $extra) {
4395 print "<tr>\n" .
4396 "<td colspan=\"4\">$extra</td>\n" .
4397 "</tr>\n";
4399 print "</table>\n";
4402 sub git_tags_body {
4403 # uses global variable $project
4404 my ($taglist, $from, $to, $extra) = @_;
4405 $from = 0 unless defined $from;
4406 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4408 print "<table class=\"tags\">\n";
4409 my $alternate = 1;
4410 for (my $i = $from; $i <= $to; $i++) {
4411 my $entry = $taglist->[$i];
4412 my %tag = %$entry;
4413 my $comment = $tag{'subject'};
4414 my $comment_short;
4415 if (defined $comment) {
4416 $comment_short = chop_str($comment, 30, 5);
4418 if ($alternate) {
4419 print "<tr class=\"dark\">\n";
4420 } else {
4421 print "<tr class=\"light\">\n";
4423 $alternate ^= 1;
4424 if (defined $tag{'age'}) {
4425 print "<td><i>$tag{'age'}</i></td>\n";
4426 } else {
4427 print "<td></td>\n";
4429 print "<td>" .
4430 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4431 -class => "list name"}, esc_html($tag{'name'})) .
4432 "</td>\n" .
4433 "<td>";
4434 if (defined $comment) {
4435 print format_subject_html($comment, $comment_short,
4436 href(action=>"tag", hash=>$tag{'id'}));
4438 print "</td>\n" .
4439 "<td class=\"selflink\">";
4440 if ($tag{'type'} eq "tag") {
4441 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4442 } else {
4443 print "&nbsp;";
4445 print "</td>\n" .
4446 "<td class=\"link\">" . " | " .
4447 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4448 if ($tag{'reftype'} eq "commit") {
4449 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4450 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4451 } elsif ($tag{'reftype'} eq "blob") {
4452 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4454 print "</td>\n" .
4455 "</tr>";
4457 if (defined $extra) {
4458 print "<tr>\n" .
4459 "<td colspan=\"5\">$extra</td>\n" .
4460 "</tr>\n";
4462 print "</table>\n";
4465 sub git_heads_body {
4466 # uses global variable $project
4467 my ($headlist, $head, $from, $to, $extra) = @_;
4468 $from = 0 unless defined $from;
4469 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4471 print "<table class=\"heads\">\n";
4472 my $alternate = 1;
4473 for (my $i = $from; $i <= $to; $i++) {
4474 my $entry = $headlist->[$i];
4475 my %ref = %$entry;
4476 my $curr = $ref{'id'} eq $head;
4477 if ($alternate) {
4478 print "<tr class=\"dark\">\n";
4479 } else {
4480 print "<tr class=\"light\">\n";
4482 $alternate ^= 1;
4483 print "<td><i>$ref{'age'}</i></td>\n" .
4484 ($curr ? "<td class=\"current_head\">" : "<td>") .
4485 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4486 -class => "list name"},esc_html($ref{'name'})) .
4487 "</td>\n" .
4488 "<td class=\"link\">" .
4489 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4490 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4491 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4492 "</td>\n" .
4493 "</tr>";
4495 if (defined $extra) {
4496 print "<tr>\n" .
4497 "<td colspan=\"3\">$extra</td>\n" .
4498 "</tr>\n";
4500 print "</table>\n";
4503 sub git_search_grep_body {
4504 my ($commitlist, $from, $to, $extra) = @_;
4505 $from = 0 unless defined $from;
4506 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4508 print "<table class=\"commit_search\">\n";
4509 my $alternate = 1;
4510 for (my $i = $from; $i <= $to; $i++) {
4511 my %co = %{$commitlist->[$i]};
4512 if (!%co) {
4513 next;
4515 my $commit = $co{'id'};
4516 if ($alternate) {
4517 print "<tr class=\"dark\">\n";
4518 } else {
4519 print "<tr class=\"light\">\n";
4521 $alternate ^= 1;
4522 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4523 format_author_html('td', \%co, 15, 5) .
4524 "<td>" .
4525 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4526 -class => "list subject"},
4527 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4528 my $comment = $co{'comment'};
4529 foreach my $line (@$comment) {
4530 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4531 my ($lead, $match, $trail) = ($1, $2, $3);
4532 $match = chop_str($match, 70, 5, 'center');
4533 my $contextlen = int((80 - length($match))/2);
4534 $contextlen = 30 if ($contextlen > 30);
4535 $lead = chop_str($lead, $contextlen, 10, 'left');
4536 $trail = chop_str($trail, $contextlen, 10, 'right');
4538 $lead = esc_html($lead);
4539 $match = esc_html($match);
4540 $trail = esc_html($trail);
4542 print "$lead<span class=\"match\">$match</span>$trail<br />";
4545 print "</td>\n" .
4546 "<td class=\"link\">" .
4547 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4548 " | " .
4549 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4550 " | " .
4551 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4552 print "</td>\n" .
4553 "</tr>\n";
4555 if (defined $extra) {
4556 print "<tr>\n" .
4557 "<td colspan=\"3\">$extra</td>\n" .
4558 "</tr>\n";
4560 print "</table>\n";
4563 ## ======================================================================
4564 ## ======================================================================
4565 ## actions
4567 sub git_project_list {
4568 my $order = $input_params{'order'};
4569 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4570 die_error(400, "Unknown order parameter");
4573 my @list = git_get_projects_list();
4574 if (!@list) {
4575 die_error(404, "No projects found");
4578 git_header_html();
4579 if (-f $home_text) {
4580 print "<div class=\"index_include\">\n";
4581 insert_file($home_text);
4582 print "</div>\n";
4584 print $cgi->startform(-method => "get") .
4585 "<p class=\"projsearch\">Search:\n" .
4586 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4587 "</p>" .
4588 $cgi->end_form() . "\n";
4589 git_project_list_body(\@list, $order);
4590 git_footer_html();
4593 sub git_forks {
4594 my $order = $input_params{'order'};
4595 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4596 die_error(400, "Unknown order parameter");
4599 my @list = git_get_projects_list($project);
4600 if (!@list) {
4601 die_error(404, "No forks found");
4604 git_header_html();
4605 git_print_page_nav('','');
4606 git_print_header_div('summary', "$project forks");
4607 git_project_list_body(\@list, $order);
4608 git_footer_html();
4611 sub git_project_index {
4612 my @projects = git_get_projects_list($project);
4614 print $cgi->header(
4615 -type => 'text/plain',
4616 -charset => 'utf-8',
4617 -content_disposition => 'inline; filename="index.aux"');
4619 foreach my $pr (@projects) {
4620 if (!exists $pr->{'owner'}) {
4621 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4624 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4625 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4626 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4627 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4628 $path =~ s/ /\+/g;
4629 $owner =~ s/ /\+/g;
4631 print "$path $owner\n";
4635 sub git_summary {
4636 my $descr = git_get_project_description($project) || "none";
4637 my %co = parse_commit("HEAD");
4638 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4639 my $head = $co{'id'};
4641 my $owner = git_get_project_owner($project);
4643 my $refs = git_get_references();
4644 # These get_*_list functions return one more to allow us to see if
4645 # there are more ...
4646 my @taglist = git_get_tags_list(16);
4647 my @headlist = git_get_heads_list(16);
4648 my @forklist;
4649 my $check_forks = gitweb_check_feature('forks');
4651 if ($check_forks) {
4652 @forklist = git_get_projects_list($project);
4655 git_header_html();
4656 git_print_page_nav('summary','', $head);
4658 print "<div class=\"title\">&nbsp;</div>\n";
4659 print "<table class=\"projects_list\">\n" .
4660 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4661 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4662 if (defined $cd{'rfc2822'}) {
4663 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4666 # use per project git URL list in $projectroot/$project/cloneurl
4667 # or make project git URL from git base URL and project name
4668 my $url_tag = "URL";
4669 my @url_list = git_get_project_url_list($project);
4670 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4671 foreach my $git_url (@url_list) {
4672 next unless $git_url;
4673 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4674 $url_tag = "";
4677 # Tag cloud
4678 my $show_ctags = gitweb_check_feature('ctags');
4679 if ($show_ctags) {
4680 my $ctags = git_get_project_ctags($project);
4681 my $cloud = git_populate_project_tagcloud($ctags);
4682 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4683 print "</td>\n<td>" unless %$ctags;
4684 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4685 print "</td>\n<td>" if %$ctags;
4686 print git_show_project_tagcloud($cloud, 48);
4687 print "</td></tr>";
4690 print "</table>\n";
4692 # If XSS prevention is on, we don't include README.html.
4693 # TODO: Allow a readme in some safe format.
4694 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4695 print "<div class=\"title\">readme</div>\n" .
4696 "<div class=\"readme\">\n";
4697 insert_file("$projectroot/$project/README.html");
4698 print "\n</div>\n"; # class="readme"
4701 # we need to request one more than 16 (0..15) to check if
4702 # those 16 are all
4703 my @commitlist = $head ? parse_commits($head, 17) : ();
4704 if (@commitlist) {
4705 git_print_header_div('shortlog');
4706 git_shortlog_body(\@commitlist, 0, 15, $refs,
4707 $#commitlist <= 15 ? undef :
4708 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4711 if (@taglist) {
4712 git_print_header_div('tags');
4713 git_tags_body(\@taglist, 0, 15,
4714 $#taglist <= 15 ? undef :
4715 $cgi->a({-href => href(action=>"tags")}, "..."));
4718 if (@headlist) {
4719 git_print_header_div('heads');
4720 git_heads_body(\@headlist, $head, 0, 15,
4721 $#headlist <= 15 ? undef :
4722 $cgi->a({-href => href(action=>"heads")}, "..."));
4725 if (@forklist) {
4726 git_print_header_div('forks');
4727 git_project_list_body(\@forklist, 'age', 0, 15,
4728 $#forklist <= 15 ? undef :
4729 $cgi->a({-href => href(action=>"forks")}, "..."),
4730 'no_header');
4733 git_footer_html();
4736 sub git_tag {
4737 my $head = git_get_head_hash($project);
4738 git_header_html();
4739 git_print_page_nav('','', $head,undef,$head);
4740 my %tag = parse_tag($hash);
4742 if (! %tag) {
4743 die_error(404, "Unknown tag object");
4746 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4747 print "<div class=\"title_text\">\n" .
4748 "<table class=\"object_header\">\n" .
4749 "<tr>\n" .
4750 "<td>object</td>\n" .
4751 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4752 $tag{'object'}) . "</td>\n" .
4753 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4754 $tag{'type'}) . "</td>\n" .
4755 "</tr>\n";
4756 if (defined($tag{'author'})) {
4757 git_print_authorship_rows(\%tag, 'author');
4759 print "</table>\n\n" .
4760 "</div>\n";
4761 print "<div class=\"page_body\">";
4762 my $comment = $tag{'comment'};
4763 foreach my $line (@$comment) {
4764 chomp $line;
4765 print esc_html($line, -nbsp=>1) . "<br/>\n";
4767 print "</div>\n";
4768 git_footer_html();
4771 sub git_blame {
4772 # permissions
4773 gitweb_check_feature('blame')
4774 or die_error(403, "Blame view not allowed");
4776 # error checking
4777 die_error(400, "No file name given") unless $file_name;
4778 $hash_base ||= git_get_head_hash($project);
4779 die_error(404, "Couldn't find base commit") unless $hash_base;
4780 my %co = parse_commit($hash_base)
4781 or die_error(404, "Commit not found");
4782 my $ftype = "blob";
4783 if (!defined $hash) {
4784 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4785 or die_error(404, "Error looking up file");
4786 } else {
4787 $ftype = git_get_type($hash);
4788 if ($ftype !~ "blob") {
4789 die_error(400, "Object is not a blob");
4793 # run git-blame --porcelain
4794 open my $fd, "-|", git_cmd(), "blame", '-p',
4795 $hash_base, '--', $file_name
4796 or die_error(500, "Open git-blame failed");
4798 # page header
4799 git_header_html();
4800 my $formats_nav =
4801 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4802 "blob") .
4803 " | " .
4804 $cgi->a({-href => href(action=>"history", -replay=>1)},
4805 "history") .
4806 " | " .
4807 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4808 "HEAD");
4809 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4810 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4811 git_print_page_path($file_name, $ftype, $hash_base);
4813 # page body
4814 my @rev_color = qw(light dark);
4815 my $num_colors = scalar(@rev_color);
4816 my $current_color = 0;
4817 my %metainfo = ();
4819 print <<HTML;
4820 <div class="page_body">
4821 <table class="blame">
4822 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4823 HTML
4824 LINE:
4825 while (my $line = <$fd>) {
4826 chomp $line;
4827 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4828 # no <lines in group> for subsequent lines in group of lines
4829 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4830 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
4831 if (!exists $metainfo{$full_rev}) {
4832 $metainfo{$full_rev} = {};
4834 my $meta = $metainfo{$full_rev};
4835 my $data;
4836 while ($data = <$fd>) {
4837 chomp $data;
4838 last if ($data =~ s/^\t//); # contents of line
4839 if ($data =~ /^(\S+)(?: (.*))?$/) {
4840 $meta->{$1} = $2 unless exists $meta->{$1};
4843 my $short_rev = substr($full_rev, 0, 8);
4844 my $author = $meta->{'author'};
4845 my %date =
4846 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
4847 my $date = $date{'iso-tz'};
4848 if ($group_size) {
4849 $current_color = ($current_color + 1) % $num_colors;
4851 my $tr_class = $rev_color[$current_color];
4852 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
4853 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
4854 if ($group_size) {
4855 print "<td class=\"sha1\"";
4856 print " title=\"". esc_html($author) . ", $date\"";
4857 print " rowspan=\"$group_size\"" if ($group_size > 1);
4858 print ">";
4859 print $cgi->a({-href => href(action=>"commit",
4860 hash=>$full_rev,
4861 file_name=>$file_name)},
4862 esc_html($short_rev));
4863 if ($group_size >= 2) {
4864 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
4865 if (@author_initials) {
4866 print "<br />" .
4867 esc_html(join('', @author_initials));
4868 # or join('.', ...)
4871 print "</td>\n";
4873 # 'previous' <sha1 of parent commit> <filename at commit>
4874 if (exists $meta->{'previous'} &&
4875 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
4876 $meta->{'parent'} = $1;
4877 $meta->{'file_parent'} = unquote_maybe($2);
4879 my $linenr_commit =
4880 exists($meta->{'parent'}) ?
4881 $meta->{'parent'} : $full_rev;
4882 my $linenr_filename =
4883 exists($meta->{'file_parent'}) ?
4884 $meta->{'file_parent'} : unquote_maybe($meta->{'filename'});
4885 my $blamed = href(action => 'blame',
4886 file_name => $linenr_filename,
4887 hash_base => $linenr_commit);
4888 print "<td class=\"linenr\">";
4889 print $cgi->a({ -href => "$blamed#l$orig_lineno",
4890 -class => "linenr" },
4891 esc_html($lineno));
4892 print "</td>";
4893 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4894 print "</tr>\n";
4896 print "</table>\n";
4897 print "</div>";
4898 close $fd
4899 or print "Reading blob failed\n";
4901 # page footer
4902 git_footer_html();
4905 sub git_tags {
4906 my $head = git_get_head_hash($project);
4907 git_header_html();
4908 git_print_page_nav('','', $head,undef,$head);
4909 git_print_header_div('summary', $project);
4911 my @tagslist = git_get_tags_list();
4912 if (@tagslist) {
4913 git_tags_body(\@tagslist);
4915 git_footer_html();
4918 sub git_heads {
4919 my $head = git_get_head_hash($project);
4920 git_header_html();
4921 git_print_page_nav('','', $head,undef,$head);
4922 git_print_header_div('summary', $project);
4924 my @headslist = git_get_heads_list();
4925 if (@headslist) {
4926 git_heads_body(\@headslist, $head);
4928 git_footer_html();
4931 sub git_blob_plain {
4932 my $type = shift;
4933 my $expires;
4935 if (!defined $hash) {
4936 if (defined $file_name) {
4937 my $base = $hash_base || git_get_head_hash($project);
4938 $hash = git_get_hash_by_path($base, $file_name, "blob")
4939 or die_error(404, "Cannot find file");
4940 } else {
4941 die_error(400, "No file name defined");
4943 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4944 # blobs defined by non-textual hash id's can be cached
4945 $expires = "+1d";
4948 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4949 or die_error(500, "Open git-cat-file blob '$hash' failed");
4951 # content-type (can include charset)
4952 $type = blob_contenttype($fd, $file_name, $type);
4954 # "save as" filename, even when no $file_name is given
4955 my $save_as = "$hash";
4956 if (defined $file_name) {
4957 $save_as = $file_name;
4958 } elsif ($type =~ m/^text\//) {
4959 $save_as .= '.txt';
4962 # With XSS prevention on, blobs of all types except a few known safe
4963 # ones are served with "Content-Disposition: attachment" to make sure
4964 # they don't run in our security domain. For certain image types,
4965 # blob view writes an <img> tag referring to blob_plain view, and we
4966 # want to be sure not to break that by serving the image as an
4967 # attachment (though Firefox 3 doesn't seem to care).
4968 my $sandbox = $prevent_xss &&
4969 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
4971 print $cgi->header(
4972 -type => $type,
4973 -expires => $expires,
4974 -content_disposition =>
4975 ($sandbox ? 'attachment' : 'inline')
4976 . '; filename="' . $save_as . '"');
4977 local $/ = undef;
4978 binmode STDOUT, ':raw';
4979 print <$fd>;
4980 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4981 close $fd;
4984 sub git_blob {
4985 my $expires;
4987 if (!defined $hash) {
4988 if (defined $file_name) {
4989 my $base = $hash_base || git_get_head_hash($project);
4990 $hash = git_get_hash_by_path($base, $file_name, "blob")
4991 or die_error(404, "Cannot find file");
4992 } else {
4993 die_error(400, "No file name defined");
4995 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4996 # blobs defined by non-textual hash id's can be cached
4997 $expires = "+1d";
5000 my $have_blame = gitweb_check_feature('blame');
5001 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5002 or die_error(500, "Couldn't cat $file_name, $hash");
5003 my $mimetype = blob_mimetype($fd, $file_name);
5004 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5005 close $fd;
5006 return git_blob_plain($mimetype);
5008 # we can have blame only for text/* mimetype
5009 $have_blame &&= ($mimetype =~ m!^text/!);
5011 git_header_html(undef, $expires);
5012 my $formats_nav = '';
5013 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5014 if (defined $file_name) {
5015 if ($have_blame) {
5016 $formats_nav .=
5017 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5018 "blame") .
5019 " | ";
5021 $formats_nav .=
5022 $cgi->a({-href => href(action=>"history", -replay=>1)},
5023 "history") .
5024 " | " .
5025 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5026 "raw") .
5027 " | " .
5028 $cgi->a({-href => href(action=>"blob",
5029 hash_base=>"HEAD", file_name=>$file_name)},
5030 "HEAD");
5031 } else {
5032 $formats_nav .=
5033 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5034 "raw");
5036 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5037 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5038 } else {
5039 print "<div class=\"page_nav\">\n" .
5040 "<br/><br/></div>\n" .
5041 "<div class=\"title\">$hash</div>\n";
5043 git_print_page_path($file_name, "blob", $hash_base);
5044 print "<div class=\"page_body\">\n";
5045 if ($mimetype =~ m!^image/!) {
5046 print qq!<img type="$mimetype"!;
5047 if ($file_name) {
5048 print qq! alt="$file_name" title="$file_name"!;
5050 print qq! src="! .
5051 href(action=>"blob_plain", hash=>$hash,
5052 hash_base=>$hash_base, file_name=>$file_name) .
5053 qq!" />\n!;
5054 } else {
5055 my $nr;
5056 while (my $line = <$fd>) {
5057 chomp $line;
5058 $nr++;
5059 $line = untabify($line);
5060 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5061 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5064 close $fd
5065 or print "Reading blob failed.\n";
5066 print "</div>";
5067 git_footer_html();
5070 sub git_tree {
5071 if (!defined $hash_base) {
5072 $hash_base = "HEAD";
5074 if (!defined $hash) {
5075 if (defined $file_name) {
5076 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5077 } else {
5078 $hash = $hash_base;
5081 die_error(404, "No such tree") unless defined($hash);
5083 my @entries = ();
5085 local $/ = "\0";
5086 open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
5087 or die_error(500, "Open git-ls-tree failed");
5088 @entries = map { chomp; $_ } <$fd>;
5089 close $fd
5090 or die_error(404, "Reading tree failed");
5093 my $refs = git_get_references();
5094 my $ref = format_ref_marker($refs, $hash_base);
5095 git_header_html();
5096 my $basedir = '';
5097 my $have_blame = gitweb_check_feature('blame');
5098 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5099 my @views_nav = ();
5100 if (defined $file_name) {
5101 push @views_nav,
5102 $cgi->a({-href => href(action=>"history", -replay=>1)},
5103 "history"),
5104 $cgi->a({-href => href(action=>"tree",
5105 hash_base=>"HEAD", file_name=>$file_name)},
5106 "HEAD"),
5108 my $snapshot_links = format_snapshot_links($hash);
5109 if (defined $snapshot_links) {
5110 # FIXME: Should be available when we have no hash base as well.
5111 push @views_nav, $snapshot_links;
5113 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
5114 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5115 } else {
5116 undef $hash_base;
5117 print "<div class=\"page_nav\">\n";
5118 print "<br/><br/></div>\n";
5119 print "<div class=\"title\">$hash</div>\n";
5121 if (defined $file_name) {
5122 $basedir = $file_name;
5123 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5124 $basedir .= '/';
5126 git_print_page_path($file_name, 'tree', $hash_base);
5128 print "<div class=\"page_body\">\n";
5129 print "<table class=\"tree\">\n";
5130 my $alternate = 1;
5131 # '..' (top directory) link if possible
5132 if (defined $hash_base &&
5133 defined $file_name && $file_name =~ m![^/]+$!) {
5134 if ($alternate) {
5135 print "<tr class=\"dark\">\n";
5136 } else {
5137 print "<tr class=\"light\">\n";
5139 $alternate ^= 1;
5141 my $up = $file_name;
5142 $up =~ s!/?[^/]+$!!;
5143 undef $up unless $up;
5144 # based on git_print_tree_entry
5145 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5146 print '<td class="list">';
5147 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
5148 file_name=>$up)},
5149 "..");
5150 print "</td>\n";
5151 print "<td class=\"link\"></td>\n";
5153 print "</tr>\n";
5155 foreach my $line (@entries) {
5156 my %t = parse_ls_tree_line($line, -z => 1);
5158 if ($alternate) {
5159 print "<tr class=\"dark\">\n";
5160 } else {
5161 print "<tr class=\"light\">\n";
5163 $alternate ^= 1;
5165 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5167 print "</tr>\n";
5169 print "</table>\n" .
5170 "</div>";
5171 git_footer_html();
5174 sub git_snapshot {
5175 my $format = $input_params{'snapshot_format'};
5176 if (!@snapshot_fmts) {
5177 die_error(403, "Snapshots not allowed");
5179 # default to first supported snapshot format
5180 $format ||= $snapshot_fmts[0];
5181 if ($format !~ m/^[a-z0-9]+$/) {
5182 die_error(400, "Invalid snapshot format parameter");
5183 } elsif (!exists($known_snapshot_formats{$format})) {
5184 die_error(400, "Unknown snapshot format");
5185 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5186 die_error(403, "Unsupported snapshot format");
5189 if (!defined $hash) {
5190 $hash = git_get_head_hash($project);
5193 my $name = $project;
5194 $name =~ s,([^/])/*\.git$,$1,;
5195 $name = basename($name);
5196 my $filename = to_utf8($name);
5197 $name =~ s/\047/\047\\\047\047/g;
5198 my $cmd;
5199 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5200 $cmd = quote_command(
5201 git_cmd(), 'archive',
5202 "--format=$known_snapshot_formats{$format}{'format'}",
5203 "--prefix=$name/", $hash);
5204 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5205 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5208 print $cgi->header(
5209 -type => $known_snapshot_formats{$format}{'type'},
5210 -content_disposition => 'inline; filename="' . "$filename" . '"',
5211 -status => '200 OK');
5213 open my $fd, "-|", $cmd
5214 or die_error(500, "Execute git-archive failed");
5215 binmode STDOUT, ':raw';
5216 print <$fd>;
5217 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5218 close $fd;
5221 sub git_log {
5222 my $head = git_get_head_hash($project);
5223 if (!defined $hash) {
5224 $hash = $head;
5226 if (!defined $page) {
5227 $page = 0;
5229 my $refs = git_get_references();
5231 my @commitlist = parse_commits($hash, 101, (100 * $page));
5233 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
5235 my ($patch_max) = gitweb_get_feature('patches');
5236 if ($patch_max) {
5237 if ($patch_max < 0 || @commitlist <= $patch_max) {
5238 $paging_nav .= " &sdot; " .
5239 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5240 "patches");
5244 git_header_html();
5245 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5247 if (!@commitlist) {
5248 my %co = parse_commit($hash);
5250 git_print_header_div('summary', $project);
5251 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5253 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5254 for (my $i = 0; $i <= $to; $i++) {
5255 my %co = %{$commitlist[$i]};
5256 next if !%co;
5257 my $commit = $co{'id'};
5258 my $ref = format_ref_marker($refs, $commit);
5259 my %ad = parse_date($co{'author_epoch'});
5260 git_print_header_div('commit',
5261 "<span class=\"age\">$co{'age_string'}</span>" .
5262 esc_html($co{'title'}) . $ref,
5263 $commit);
5264 print "<div class=\"title_text\">\n" .
5265 "<div class=\"log_link\">\n" .
5266 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5267 " | " .
5268 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5269 " | " .
5270 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5271 "<br/>\n" .
5272 "</div>\n";
5273 git_print_authorship(\%co, -tag => 'span');
5274 print "<br/>\n</div>\n";
5276 print "<div class=\"log_body\">\n";
5277 git_print_log($co{'comment'}, -final_empty_line=> 1);
5278 print "</div>\n";
5280 if ($#commitlist >= 100) {
5281 print "<div class=\"page_nav\">\n";
5282 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5283 -accesskey => "n", -title => "Alt-n"}, "next");
5284 print "</div>\n";
5286 git_footer_html();
5289 sub git_commit {
5290 $hash ||= $hash_base || "HEAD";
5291 my %co = parse_commit($hash)
5292 or die_error(404, "Unknown commit object");
5294 my $parent = $co{'parent'};
5295 my $parents = $co{'parents'}; # listref
5297 # we need to prepare $formats_nav before any parameter munging
5298 my $formats_nav;
5299 if (!defined $parent) {
5300 # --root commitdiff
5301 $formats_nav .= '(initial)';
5302 } elsif (@$parents == 1) {
5303 # single parent commit
5304 $formats_nav .=
5305 '(parent: ' .
5306 $cgi->a({-href => href(action=>"commit",
5307 hash=>$parent)},
5308 esc_html(substr($parent, 0, 7))) .
5309 ')';
5310 } else {
5311 # merge commit
5312 $formats_nav .=
5313 '(merge: ' .
5314 join(' ', map {
5315 $cgi->a({-href => href(action=>"commit",
5316 hash=>$_)},
5317 esc_html(substr($_, 0, 7)));
5318 } @$parents ) .
5319 ')';
5321 if (gitweb_check_feature('patches')) {
5322 $formats_nav .= " | " .
5323 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5324 "patch");
5327 if (!defined $parent) {
5328 $parent = "--root";
5330 my @difftree;
5331 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5332 @diff_opts,
5333 (@$parents <= 1 ? $parent : '-c'),
5334 $hash, "--"
5335 or die_error(500, "Open git-diff-tree failed");
5336 @difftree = map { chomp; $_ } <$fd>;
5337 close $fd or die_error(404, "Reading git-diff-tree failed");
5339 # non-textual hash id's can be cached
5340 my $expires;
5341 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5342 $expires = "+1d";
5344 my $refs = git_get_references();
5345 my $ref = format_ref_marker($refs, $co{'id'});
5347 git_header_html(undef, $expires);
5348 git_print_page_nav('commit', '',
5349 $hash, $co{'tree'}, $hash,
5350 $formats_nav);
5352 if (defined $co{'parent'}) {
5353 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5354 } else {
5355 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5357 print "<div class=\"title_text\">\n" .
5358 "<table class=\"object_header\">\n";
5359 git_print_authorship_rows(\%co);
5360 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5361 print "<tr>" .
5362 "<td>tree</td>" .
5363 "<td class=\"sha1\">" .
5364 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5365 class => "list"}, $co{'tree'}) .
5366 "</td>" .
5367 "<td class=\"link\">" .
5368 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5369 "tree");
5370 my $snapshot_links = format_snapshot_links($hash);
5371 if (defined $snapshot_links) {
5372 print " | " . $snapshot_links;
5374 print "</td>" .
5375 "</tr>\n";
5377 foreach my $par (@$parents) {
5378 print "<tr>" .
5379 "<td>parent</td>" .
5380 "<td class=\"sha1\">" .
5381 $cgi->a({-href => href(action=>"commit", hash=>$par),
5382 class => "list"}, $par) .
5383 "</td>" .
5384 "<td class=\"link\">" .
5385 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5386 " | " .
5387 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5388 "</td>" .
5389 "</tr>\n";
5391 print "</table>".
5392 "</div>\n";
5394 print "<div class=\"page_body\">\n";
5395 git_print_log($co{'comment'});
5396 print "</div>\n";
5398 git_difftree_body(\@difftree, $hash, @$parents);
5400 git_footer_html();
5403 sub git_object {
5404 # object is defined by:
5405 # - hash or hash_base alone
5406 # - hash_base and file_name
5407 my $type;
5409 # - hash or hash_base alone
5410 if ($hash || ($hash_base && !defined $file_name)) {
5411 my $object_id = $hash || $hash_base;
5413 open my $fd, "-|", quote_command(
5414 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5415 or die_error(404, "Object does not exist");
5416 $type = <$fd>;
5417 chomp $type;
5418 close $fd
5419 or die_error(404, "Object does not exist");
5421 # - hash_base and file_name
5422 } elsif ($hash_base && defined $file_name) {
5423 $file_name =~ s,/+$,,;
5425 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5426 or die_error(404, "Base object does not exist");
5428 # here errors should not hapen
5429 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5430 or die_error(500, "Open git-ls-tree failed");
5431 my $line = <$fd>;
5432 close $fd;
5434 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5435 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5436 die_error(404, "File or directory for given base does not exist");
5438 $type = $2;
5439 $hash = $3;
5440 } else {
5441 die_error(400, "Not enough information to find object");
5444 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5445 hash=>$hash, hash_base=>$hash_base,
5446 file_name=>$file_name),
5447 -status => '302 Found');
5450 sub git_blobdiff {
5451 my $format = shift || 'html';
5453 my $fd;
5454 my @difftree;
5455 my %diffinfo;
5456 my $expires;
5458 # preparing $fd and %diffinfo for git_patchset_body
5459 # new style URI
5460 if (defined $hash_base && defined $hash_parent_base) {
5461 if (defined $file_name) {
5462 # read raw output
5463 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5464 $hash_parent_base, $hash_base,
5465 "--", (defined $file_parent ? $file_parent : ()), $file_name
5466 or die_error(500, "Open git-diff-tree failed");
5467 @difftree = map { chomp; $_ } <$fd>;
5468 close $fd
5469 or die_error(404, "Reading git-diff-tree failed");
5470 @difftree
5471 or die_error(404, "Blob diff not found");
5473 } elsif (defined $hash &&
5474 $hash =~ /[0-9a-fA-F]{40}/) {
5475 # try to find filename from $hash
5477 # read filtered raw output
5478 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5479 $hash_parent_base, $hash_base, "--"
5480 or die_error(500, "Open git-diff-tree failed");
5481 @difftree =
5482 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5483 # $hash == to_id
5484 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5485 map { chomp; $_ } <$fd>;
5486 close $fd
5487 or die_error(404, "Reading git-diff-tree failed");
5488 @difftree
5489 or die_error(404, "Blob diff not found");
5491 } else {
5492 die_error(400, "Missing one of the blob diff parameters");
5495 if (@difftree > 1) {
5496 die_error(400, "Ambiguous blob diff specification");
5499 %diffinfo = parse_difftree_raw_line($difftree[0]);
5500 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5501 $file_name ||= $diffinfo{'to_file'};
5503 $hash_parent ||= $diffinfo{'from_id'};
5504 $hash ||= $diffinfo{'to_id'};
5506 # non-textual hash id's can be cached
5507 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5508 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5509 $expires = '+1d';
5512 # open patch output
5513 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5514 '-p', ($format eq 'html' ? "--full-index" : ()),
5515 $hash_parent_base, $hash_base,
5516 "--", (defined $file_parent ? $file_parent : ()), $file_name
5517 or die_error(500, "Open git-diff-tree failed");
5520 # old/legacy style URI -- not generated anymore since 1.4.3.
5521 if (!%diffinfo) {
5522 die_error('404 Not Found', "Missing one of the blob diff parameters")
5525 # header
5526 if ($format eq 'html') {
5527 my $formats_nav =
5528 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5529 "raw");
5530 git_header_html(undef, $expires);
5531 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5532 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5533 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5534 } else {
5535 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5536 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5538 if (defined $file_name) {
5539 git_print_page_path($file_name, "blob", $hash_base);
5540 } else {
5541 print "<div class=\"page_path\"></div>\n";
5544 } elsif ($format eq 'plain') {
5545 print $cgi->header(
5546 -type => 'text/plain',
5547 -charset => 'utf-8',
5548 -expires => $expires,
5549 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5551 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5553 } else {
5554 die_error(400, "Unknown blobdiff format");
5557 # patch
5558 if ($format eq 'html') {
5559 print "<div class=\"page_body\">\n";
5561 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5562 close $fd;
5564 print "</div>\n"; # class="page_body"
5565 git_footer_html();
5567 } else {
5568 while (my $line = <$fd>) {
5569 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5570 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5572 print $line;
5574 last if $line =~ m!^\+\+\+!;
5576 local $/ = undef;
5577 print <$fd>;
5578 close $fd;
5582 sub git_blobdiff_plain {
5583 git_blobdiff('plain');
5586 sub git_commitdiff {
5587 my %params = @_;
5588 my $format = $params{-format} || 'html';
5590 my ($patch_max) = gitweb_get_feature('patches');
5591 if ($format eq 'patch') {
5592 die_error(403, "Patch view not allowed") unless $patch_max;
5595 $hash ||= $hash_base || "HEAD";
5596 my %co = parse_commit($hash)
5597 or die_error(404, "Unknown commit object");
5599 # choose format for commitdiff for merge
5600 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5601 $hash_parent = '--cc';
5603 # we need to prepare $formats_nav before almost any parameter munging
5604 my $formats_nav;
5605 if ($format eq 'html') {
5606 $formats_nav =
5607 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5608 "raw");
5609 if ($patch_max) {
5610 $formats_nav .= " | " .
5611 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5612 "patch");
5615 if (defined $hash_parent &&
5616 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5617 # commitdiff with two commits given
5618 my $hash_parent_short = $hash_parent;
5619 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5620 $hash_parent_short = substr($hash_parent, 0, 7);
5622 $formats_nav .=
5623 ' (from';
5624 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5625 if ($co{'parents'}[$i] eq $hash_parent) {
5626 $formats_nav .= ' parent ' . ($i+1);
5627 last;
5630 $formats_nav .= ': ' .
5631 $cgi->a({-href => href(action=>"commitdiff",
5632 hash=>$hash_parent)},
5633 esc_html($hash_parent_short)) .
5634 ')';
5635 } elsif (!$co{'parent'}) {
5636 # --root commitdiff
5637 $formats_nav .= ' (initial)';
5638 } elsif (scalar @{$co{'parents'}} == 1) {
5639 # single parent commit
5640 $formats_nav .=
5641 ' (parent: ' .
5642 $cgi->a({-href => href(action=>"commitdiff",
5643 hash=>$co{'parent'})},
5644 esc_html(substr($co{'parent'}, 0, 7))) .
5645 ')';
5646 } else {
5647 # merge commit
5648 if ($hash_parent eq '--cc') {
5649 $formats_nav .= ' | ' .
5650 $cgi->a({-href => href(action=>"commitdiff",
5651 hash=>$hash, hash_parent=>'-c')},
5652 'combined');
5653 } else { # $hash_parent eq '-c'
5654 $formats_nav .= ' | ' .
5655 $cgi->a({-href => href(action=>"commitdiff",
5656 hash=>$hash, hash_parent=>'--cc')},
5657 'compact');
5659 $formats_nav .=
5660 ' (merge: ' .
5661 join(' ', map {
5662 $cgi->a({-href => href(action=>"commitdiff",
5663 hash=>$_)},
5664 esc_html(substr($_, 0, 7)));
5665 } @{$co{'parents'}} ) .
5666 ')';
5670 my $hash_parent_param = $hash_parent;
5671 if (!defined $hash_parent_param) {
5672 # --cc for multiple parents, --root for parentless
5673 $hash_parent_param =
5674 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5677 # read commitdiff
5678 my $fd;
5679 my @difftree;
5680 if ($format eq 'html') {
5681 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5682 "--no-commit-id", "--patch-with-raw", "--full-index",
5683 $hash_parent_param, $hash, "--"
5684 or die_error(500, "Open git-diff-tree failed");
5686 while (my $line = <$fd>) {
5687 chomp $line;
5688 # empty line ends raw part of diff-tree output
5689 last unless $line;
5690 push @difftree, scalar parse_difftree_raw_line($line);
5693 } elsif ($format eq 'plain') {
5694 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5695 '-p', $hash_parent_param, $hash, "--"
5696 or die_error(500, "Open git-diff-tree failed");
5697 } elsif ($format eq 'patch') {
5698 # For commit ranges, we limit the output to the number of
5699 # patches specified in the 'patches' feature.
5700 # For single commits, we limit the output to a single patch,
5701 # diverging from the git-format-patch default.
5702 my @commit_spec = ();
5703 if ($hash_parent) {
5704 if ($patch_max > 0) {
5705 push @commit_spec, "-$patch_max";
5707 push @commit_spec, '-n', "$hash_parent..$hash";
5708 } else {
5709 if ($params{-single}) {
5710 push @commit_spec, '-1';
5711 } else {
5712 if ($patch_max > 0) {
5713 push @commit_spec, "-$patch_max";
5715 push @commit_spec, "-n";
5717 push @commit_spec, '--root', $hash;
5719 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5720 '--stdout', @commit_spec
5721 or die_error(500, "Open git-format-patch failed");
5722 } else {
5723 die_error(400, "Unknown commitdiff format");
5726 # non-textual hash id's can be cached
5727 my $expires;
5728 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5729 $expires = "+1d";
5732 # write commit message
5733 if ($format eq 'html') {
5734 my $refs = git_get_references();
5735 my $ref = format_ref_marker($refs, $co{'id'});
5737 git_header_html(undef, $expires);
5738 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5739 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5740 print "<div class=\"title_text\">\n" .
5741 "<table class=\"object_header\">\n";
5742 git_print_authorship_rows(\%co);
5743 print "</table>".
5744 "</div>\n";
5745 print "<div class=\"page_body\">\n";
5746 if (@{$co{'comment'}} > 1) {
5747 print "<div class=\"log\">\n";
5748 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5749 print "</div>\n"; # class="log"
5752 } elsif ($format eq 'plain') {
5753 my $refs = git_get_references("tags");
5754 my $tagname = git_get_rev_name_tags($hash);
5755 my $filename = basename($project) . "-$hash.patch";
5757 print $cgi->header(
5758 -type => 'text/plain',
5759 -charset => 'utf-8',
5760 -expires => $expires,
5761 -content_disposition => 'inline; filename="' . "$filename" . '"');
5762 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5763 print "From: " . to_utf8($co{'author'}) . "\n";
5764 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5765 print "Subject: " . to_utf8($co{'title'}) . "\n";
5767 print "X-Git-Tag: $tagname\n" if $tagname;
5768 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5770 foreach my $line (@{$co{'comment'}}) {
5771 print to_utf8($line) . "\n";
5773 print "---\n\n";
5774 } elsif ($format eq 'patch') {
5775 my $filename = basename($project) . "-$hash.patch";
5777 print $cgi->header(
5778 -type => 'text/plain',
5779 -charset => 'utf-8',
5780 -expires => $expires,
5781 -content_disposition => 'inline; filename="' . "$filename" . '"');
5784 # write patch
5785 if ($format eq 'html') {
5786 my $use_parents = !defined $hash_parent ||
5787 $hash_parent eq '-c' || $hash_parent eq '--cc';
5788 git_difftree_body(\@difftree, $hash,
5789 $use_parents ? @{$co{'parents'}} : $hash_parent);
5790 print "<br/>\n";
5792 git_patchset_body($fd, \@difftree, $hash,
5793 $use_parents ? @{$co{'parents'}} : $hash_parent);
5794 close $fd;
5795 print "</div>\n"; # class="page_body"
5796 git_footer_html();
5798 } elsif ($format eq 'plain') {
5799 local $/ = undef;
5800 print <$fd>;
5801 close $fd
5802 or print "Reading git-diff-tree failed\n";
5803 } elsif ($format eq 'patch') {
5804 local $/ = undef;
5805 print <$fd>;
5806 close $fd
5807 or print "Reading git-format-patch failed\n";
5811 sub git_commitdiff_plain {
5812 git_commitdiff(-format => 'plain');
5815 # format-patch-style patches
5816 sub git_patch {
5817 git_commitdiff(-format => 'patch', -single=> 1);
5820 sub git_patches {
5821 git_commitdiff(-format => 'patch');
5824 sub git_history {
5825 if (!defined $hash_base) {
5826 $hash_base = git_get_head_hash($project);
5828 if (!defined $page) {
5829 $page = 0;
5831 my $ftype;
5832 my %co = parse_commit($hash_base)
5833 or die_error(404, "Unknown commit object");
5835 my $refs = git_get_references();
5836 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5838 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5839 $file_name, "--full-history")
5840 or die_error(404, "No such file or directory on given branch");
5842 if (!defined $hash && defined $file_name) {
5843 # some commits could have deleted file in question,
5844 # and not have it in tree, but one of them has to have it
5845 for (my $i = 0; $i <= @commitlist; $i++) {
5846 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5847 last if defined $hash;
5850 if (defined $hash) {
5851 $ftype = git_get_type($hash);
5853 if (!defined $ftype) {
5854 die_error(500, "Unknown type of object");
5857 my $paging_nav = '';
5858 if ($page > 0) {
5859 $paging_nav .=
5860 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5861 file_name=>$file_name)},
5862 "first");
5863 $paging_nav .= " &sdot; " .
5864 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5865 -accesskey => "p", -title => "Alt-p"}, "prev");
5866 } else {
5867 $paging_nav .= "first";
5868 $paging_nav .= " &sdot; prev";
5870 my $next_link = '';
5871 if ($#commitlist >= 100) {
5872 $next_link =
5873 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5874 -accesskey => "n", -title => "Alt-n"}, "next");
5875 $paging_nav .= " &sdot; $next_link";
5876 } else {
5877 $paging_nav .= " &sdot; next";
5880 git_header_html();
5881 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5882 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5883 git_print_page_path($file_name, $ftype, $hash_base);
5885 git_history_body(\@commitlist, 0, 99,
5886 $refs, $hash_base, $ftype, $next_link);
5888 git_footer_html();
5891 sub git_search {
5892 gitweb_check_feature('search') or die_error(403, "Search is disabled");
5893 if (!defined $searchtext) {
5894 die_error(400, "Text field is empty");
5896 if (!defined $hash) {
5897 $hash = git_get_head_hash($project);
5899 my %co = parse_commit($hash);
5900 if (!%co) {
5901 die_error(404, "Unknown commit object");
5903 if (!defined $page) {
5904 $page = 0;
5907 $searchtype ||= 'commit';
5908 if ($searchtype eq 'pickaxe') {
5909 # pickaxe may take all resources of your box and run for several minutes
5910 # with every query - so decide by yourself how public you make this feature
5911 gitweb_check_feature('pickaxe')
5912 or die_error(403, "Pickaxe is disabled");
5914 if ($searchtype eq 'grep') {
5915 gitweb_check_feature('grep')
5916 or die_error(403, "Grep is disabled");
5919 git_header_html();
5921 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5922 my $greptype;
5923 if ($searchtype eq 'commit') {
5924 $greptype = "--grep=";
5925 } elsif ($searchtype eq 'author') {
5926 $greptype = "--author=";
5927 } elsif ($searchtype eq 'committer') {
5928 $greptype = "--committer=";
5930 $greptype .= $searchtext;
5931 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5932 $greptype, '--regexp-ignore-case',
5933 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5935 my $paging_nav = '';
5936 if ($page > 0) {
5937 $paging_nav .=
5938 $cgi->a({-href => href(action=>"search", hash=>$hash,
5939 searchtext=>$searchtext,
5940 searchtype=>$searchtype)},
5941 "first");
5942 $paging_nav .= " &sdot; " .
5943 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5944 -accesskey => "p", -title => "Alt-p"}, "prev");
5945 } else {
5946 $paging_nav .= "first";
5947 $paging_nav .= " &sdot; prev";
5949 my $next_link = '';
5950 if ($#commitlist >= 100) {
5951 $next_link =
5952 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5953 -accesskey => "n", -title => "Alt-n"}, "next");
5954 $paging_nav .= " &sdot; $next_link";
5955 } else {
5956 $paging_nav .= " &sdot; next";
5959 if ($#commitlist >= 100) {
5962 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5963 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5964 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5967 if ($searchtype eq 'pickaxe') {
5968 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5969 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5971 print "<table class=\"pickaxe search\">\n";
5972 my $alternate = 1;
5973 local $/ = "\n";
5974 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5975 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5976 ($search_use_regexp ? '--pickaxe-regex' : ());
5977 undef %co;
5978 my @files;
5979 while (my $line = <$fd>) {
5980 chomp $line;
5981 next unless $line;
5983 my %set = parse_difftree_raw_line($line);
5984 if (defined $set{'commit'}) {
5985 # finish previous commit
5986 if (%co) {
5987 print "</td>\n" .
5988 "<td class=\"link\">" .
5989 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5990 " | " .
5991 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5992 print "</td>\n" .
5993 "</tr>\n";
5996 if ($alternate) {
5997 print "<tr class=\"dark\">\n";
5998 } else {
5999 print "<tr class=\"light\">\n";
6001 $alternate ^= 1;
6002 %co = parse_commit($set{'commit'});
6003 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6004 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6005 "<td><i>$author</i></td>\n" .
6006 "<td>" .
6007 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6008 -class => "list subject"},
6009 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6010 } elsif (defined $set{'to_id'}) {
6011 next if ($set{'to_id'} =~ m/^0{40}$/);
6013 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6014 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6015 -class => "list"},
6016 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6017 "<br/>\n";
6020 close $fd;
6022 # finish last commit (warning: repetition!)
6023 if (%co) {
6024 print "</td>\n" .
6025 "<td class=\"link\">" .
6026 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6027 " | " .
6028 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6029 print "</td>\n" .
6030 "</tr>\n";
6033 print "</table>\n";
6036 if ($searchtype eq 'grep') {
6037 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6038 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6040 print "<table class=\"grep_search\">\n";
6041 my $alternate = 1;
6042 my $matches = 0;
6043 local $/ = "\n";
6044 open my $fd, "-|", git_cmd(), 'grep', '-n',
6045 $search_use_regexp ? ('-E', '-i') : '-F',
6046 $searchtext, $co{'tree'};
6047 my $lastfile = '';
6048 while (my $line = <$fd>) {
6049 chomp $line;
6050 my ($file, $lno, $ltext, $binary);
6051 last if ($matches++ > 1000);
6052 if ($line =~ /^Binary file (.+) matches$/) {
6053 $file = $1;
6054 $binary = 1;
6055 } else {
6056 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6058 if ($file ne $lastfile) {
6059 $lastfile and print "</td></tr>\n";
6060 if ($alternate++) {
6061 print "<tr class=\"dark\">\n";
6062 } else {
6063 print "<tr class=\"light\">\n";
6065 print "<td class=\"list\">".
6066 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6067 file_name=>"$file"),
6068 -class => "list"}, esc_path($file));
6069 print "</td><td>\n";
6070 $lastfile = $file;
6072 if ($binary) {
6073 print "<div class=\"binary\">Binary file</div>\n";
6074 } else {
6075 $ltext = untabify($ltext);
6076 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6077 $ltext = esc_html($1, -nbsp=>1);
6078 $ltext .= '<span class="match">';
6079 $ltext .= esc_html($2, -nbsp=>1);
6080 $ltext .= '</span>';
6081 $ltext .= esc_html($3, -nbsp=>1);
6082 } else {
6083 $ltext = esc_html($ltext, -nbsp=>1);
6085 print "<div class=\"pre\">" .
6086 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6087 file_name=>"$file").'#l'.$lno,
6088 -class => "linenr"}, sprintf('%4i', $lno))
6089 . ' ' . $ltext . "</div>\n";
6092 if ($lastfile) {
6093 print "</td></tr>\n";
6094 if ($matches > 1000) {
6095 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6097 } else {
6098 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6100 close $fd;
6102 print "</table>\n";
6104 git_footer_html();
6107 sub git_search_help {
6108 git_header_html();
6109 git_print_page_nav('','', $hash,$hash,$hash);
6110 print <<EOT;
6111 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6112 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6113 the pattern entered is recognized as the POSIX extended
6114 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6115 insensitive).</p>
6116 <dl>
6117 <dt><b>commit</b></dt>
6118 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6120 my $have_grep = gitweb_check_feature('grep');
6121 if ($have_grep) {
6122 print <<EOT;
6123 <dt><b>grep</b></dt>
6124 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6125 a different one) are searched for the given pattern. On large trees, this search can take
6126 a while and put some strain on the server, so please use it with some consideration. Note that
6127 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6128 case-sensitive.</dd>
6131 print <<EOT;
6132 <dt><b>author</b></dt>
6133 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6134 <dt><b>committer</b></dt>
6135 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6137 my $have_pickaxe = gitweb_check_feature('pickaxe');
6138 if ($have_pickaxe) {
6139 print <<EOT;
6140 <dt><b>pickaxe</b></dt>
6141 <dd>All commits that caused the string to appear or disappear from any file (changes that
6142 added, removed or "modified" the string) will be listed. This search can take a while and
6143 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6144 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6147 print "</dl>\n";
6148 git_footer_html();
6151 sub git_shortlog {
6152 my $head = git_get_head_hash($project);
6153 if (!defined $hash) {
6154 $hash = $head;
6156 if (!defined $page) {
6157 $page = 0;
6159 my $refs = git_get_references();
6161 my $commit_hash = $hash;
6162 if (defined $hash_parent) {
6163 $commit_hash = "$hash_parent..$hash";
6165 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6167 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6168 my $next_link = '';
6169 if ($#commitlist >= 100) {
6170 $next_link =
6171 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6172 -accesskey => "n", -title => "Alt-n"}, "next");
6174 my $patch_max = gitweb_check_feature('patches');
6175 if ($patch_max) {
6176 if ($patch_max < 0 || @commitlist <= $patch_max) {
6177 $paging_nav .= " &sdot; " .
6178 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6179 "patches");
6183 git_header_html();
6184 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6185 git_print_header_div('summary', $project);
6187 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6189 git_footer_html();
6192 ## ......................................................................
6193 ## feeds (RSS, Atom; OPML)
6195 sub git_feed {
6196 my $format = shift || 'atom';
6197 my $have_blame = gitweb_check_feature('blame');
6199 # Atom: http://www.atomenabled.org/developers/syndication/
6200 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6201 if ($format ne 'rss' && $format ne 'atom') {
6202 die_error(400, "Unknown web feed format");
6205 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6206 my $head = $hash || 'HEAD';
6207 my @commitlist = parse_commits($head, 150, 0, $file_name);
6209 my %latest_commit;
6210 my %latest_date;
6211 my $content_type = "application/$format+xml";
6212 if (defined $cgi->http('HTTP_ACCEPT') &&
6213 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6214 # browser (feed reader) prefers text/xml
6215 $content_type = 'text/xml';
6217 if (defined($commitlist[0])) {
6218 %latest_commit = %{$commitlist[0]};
6219 my $latest_epoch = $latest_commit{'committer_epoch'};
6220 %latest_date = parse_date($latest_epoch);
6221 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6222 if (defined $if_modified) {
6223 my $since;
6224 if (eval { require HTTP::Date; 1; }) {
6225 $since = HTTP::Date::str2time($if_modified);
6226 } elsif (eval { require Time::ParseDate; 1; }) {
6227 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6229 if (defined $since && $latest_epoch <= $since) {
6230 print $cgi->header(
6231 -type => $content_type,
6232 -charset => 'utf-8',
6233 -last_modified => $latest_date{'rfc2822'},
6234 -status => '304 Not Modified');
6235 return;
6238 print $cgi->header(
6239 -type => $content_type,
6240 -charset => 'utf-8',
6241 -last_modified => $latest_date{'rfc2822'});
6242 } else {
6243 print $cgi->header(
6244 -type => $content_type,
6245 -charset => 'utf-8');
6248 # Optimization: skip generating the body if client asks only
6249 # for Last-Modified date.
6250 return if ($cgi->request_method() eq 'HEAD');
6252 # header variables
6253 my $title = "$site_name - $project/$action";
6254 my $feed_type = 'log';
6255 if (defined $hash) {
6256 $title .= " - '$hash'";
6257 $feed_type = 'branch log';
6258 if (defined $file_name) {
6259 $title .= " :: $file_name";
6260 $feed_type = 'history';
6262 } elsif (defined $file_name) {
6263 $title .= " - $file_name";
6264 $feed_type = 'history';
6266 $title .= " $feed_type";
6267 my $descr = git_get_project_description($project);
6268 if (defined $descr) {
6269 $descr = esc_html($descr);
6270 } else {
6271 $descr = "$project " .
6272 ($format eq 'rss' ? 'RSS' : 'Atom') .
6273 " feed";
6275 my $owner = git_get_project_owner($project);
6276 $owner = esc_html($owner);
6278 #header
6279 my $alt_url;
6280 if (defined $file_name) {
6281 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6282 } elsif (defined $hash) {
6283 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6284 } else {
6285 $alt_url = href(-full=>1, action=>"summary");
6287 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6288 if ($format eq 'rss') {
6289 print <<XML;
6290 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6291 <channel>
6293 print "<title>$title</title>\n" .
6294 "<link>$alt_url</link>\n" .
6295 "<description>$descr</description>\n" .
6296 "<language>en</language>\n" .
6297 # project owner is responsible for 'editorial' content
6298 "<managingEditor>$owner</managingEditor>\n";
6299 if (defined $logo || defined $favicon) {
6300 # prefer the logo to the favicon, since RSS
6301 # doesn't allow both
6302 my $img = esc_url($logo || $favicon);
6303 print "<image>\n" .
6304 "<url>$img</url>\n" .
6305 "<title>$title</title>\n" .
6306 "<link>$alt_url</link>\n" .
6307 "</image>\n";
6309 if (%latest_date) {
6310 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6311 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6313 print "<generator>gitweb v.$version/$git_version</generator>\n";
6314 } elsif ($format eq 'atom') {
6315 print <<XML;
6316 <feed xmlns="http://www.w3.org/2005/Atom">
6318 print "<title>$title</title>\n" .
6319 "<subtitle>$descr</subtitle>\n" .
6320 '<link rel="alternate" type="text/html" href="' .
6321 $alt_url . '" />' . "\n" .
6322 '<link rel="self" type="' . $content_type . '" href="' .
6323 $cgi->self_url() . '" />' . "\n" .
6324 "<id>" . href(-full=>1) . "</id>\n" .
6325 # use project owner for feed author
6326 "<author><name>$owner</name></author>\n";
6327 if (defined $favicon) {
6328 print "<icon>" . esc_url($favicon) . "</icon>\n";
6330 if (defined $logo_url) {
6331 # not twice as wide as tall: 72 x 27 pixels
6332 print "<logo>" . esc_url($logo) . "</logo>\n";
6334 if (! %latest_date) {
6335 # dummy date to keep the feed valid until commits trickle in:
6336 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6337 } else {
6338 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6340 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6343 # contents
6344 for (my $i = 0; $i <= $#commitlist; $i++) {
6345 my %co = %{$commitlist[$i]};
6346 my $commit = $co{'id'};
6347 # we read 150, we always show 30 and the ones more recent than 48 hours
6348 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6349 last;
6351 my %cd = parse_date($co{'author_epoch'});
6353 # get list of changed files
6354 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6355 $co{'parent'} || "--root",
6356 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6357 or next;
6358 my @difftree = map { chomp; $_ } <$fd>;
6359 close $fd
6360 or next;
6362 # print element (entry, item)
6363 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6364 if ($format eq 'rss') {
6365 print "<item>\n" .
6366 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6367 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6368 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6369 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6370 "<link>$co_url</link>\n" .
6371 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6372 "<content:encoded>" .
6373 "<![CDATA[\n";
6374 } elsif ($format eq 'atom') {
6375 print "<entry>\n" .
6376 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6377 "<updated>$cd{'iso-8601'}</updated>\n" .
6378 "<author>\n" .
6379 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6380 if ($co{'author_email'}) {
6381 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6383 print "</author>\n" .
6384 # use committer for contributor
6385 "<contributor>\n" .
6386 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6387 if ($co{'committer_email'}) {
6388 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6390 print "</contributor>\n" .
6391 "<published>$cd{'iso-8601'}</published>\n" .
6392 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6393 "<id>$co_url</id>\n" .
6394 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6395 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6397 my $comment = $co{'comment'};
6398 print "<pre>\n";
6399 foreach my $line (@$comment) {
6400 $line = esc_html($line);
6401 print "$line\n";
6403 print "</pre><ul>\n";
6404 foreach my $difftree_line (@difftree) {
6405 my %difftree = parse_difftree_raw_line($difftree_line);
6406 next if !$difftree{'from_id'};
6408 my $file = $difftree{'file'} || $difftree{'to_file'};
6410 print "<li>" .
6411 "[" .
6412 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6413 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6414 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6415 file_name=>$file, file_parent=>$difftree{'from_file'}),
6416 -title => "diff"}, 'D');
6417 if ($have_blame) {
6418 print $cgi->a({-href => href(-full=>1, action=>"blame",
6419 file_name=>$file, hash_base=>$commit),
6420 -title => "blame"}, 'B');
6422 # if this is not a feed of a file history
6423 if (!defined $file_name || $file_name ne $file) {
6424 print $cgi->a({-href => href(-full=>1, action=>"history",
6425 file_name=>$file, hash=>$commit),
6426 -title => "history"}, 'H');
6428 $file = esc_path($file);
6429 print "] ".
6430 "$file</li>\n";
6432 if ($format eq 'rss') {
6433 print "</ul>]]>\n" .
6434 "</content:encoded>\n" .
6435 "</item>\n";
6436 } elsif ($format eq 'atom') {
6437 print "</ul>\n</div>\n" .
6438 "</content>\n" .
6439 "</entry>\n";
6443 # end of feed
6444 if ($format eq 'rss') {
6445 print "</channel>\n</rss>\n";
6446 } elsif ($format eq 'atom') {
6447 print "</feed>\n";
6451 sub git_rss {
6452 git_feed('rss');
6455 sub git_atom {
6456 git_feed('atom');
6459 sub git_opml {
6460 my @list = git_get_projects_list();
6462 print $cgi->header(
6463 -type => 'text/xml',
6464 -charset => 'utf-8',
6465 -content_disposition => 'inline; filename="opml.xml"');
6467 print <<XML;
6468 <?xml version="1.0" encoding="utf-8"?>
6469 <opml version="1.0">
6470 <head>
6471 <title>$site_name OPML Export</title>
6472 </head>
6473 <body>
6474 <outline text="git RSS feeds">
6477 foreach my $pr (@list) {
6478 my %proj = %$pr;
6479 my $head = git_get_head_hash($proj{'path'});
6480 if (!defined $head) {
6481 next;
6483 $git_dir = "$projectroot/$proj{'path'}";
6484 my %co = parse_commit($head);
6485 if (!%co) {
6486 next;
6489 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6490 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6491 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6492 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6494 print <<XML;
6495 </outline>
6496 </body>
6497 </opml>