Content tags: Point links to proper action
[git/gitweb.git] / gitweb / gitweb.perl
blob7be7f3e05346dc8c6e988a441cf136c940f7282d
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-scm.com/";
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)
164 # 'disabled' => boolean (optional)}
166 'tgz' => {
167 'display' => 'tar.gz',
168 'type' => 'application/x-gzip',
169 'suffix' => '.tar.gz',
170 'format' => 'tar',
171 'compressor' => ['gzip']},
173 'tbz2' => {
174 'display' => 'tar.bz2',
175 'type' => 'application/x-bzip2',
176 'suffix' => '.tar.bz2',
177 'format' => 'tar',
178 'compressor' => ['bzip2']},
180 'txz' => {
181 'display' => 'tar.xz',
182 'type' => 'application/x-xz',
183 'suffix' => '.tar.xz',
184 'format' => 'tar',
185 'compressor' => ['xz'],
186 'disabled' => 1},
188 'zip' => {
189 'display' => 'zip',
190 'type' => 'application/x-zip',
191 'suffix' => '.zip',
192 'format' => 'zip'},
195 # Aliases so we understand old gitweb.snapshot values in repository
196 # configuration.
197 our %known_snapshot_format_aliases = (
198 'gzip' => 'tgz',
199 'bzip2' => 'tbz2',
200 'xz' => 'txz',
202 # backward compatibility: legacy gitweb config support
203 'x-gzip' => undef, 'gz' => undef,
204 'x-bzip2' => undef, 'bz2' => undef,
205 'x-zip' => undef, '' => undef,
208 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
209 # are changed, it may be appropriate to change these values too via
210 # $GITWEB_CONFIG.
211 our %avatar_size = (
212 'default' => 16,
213 'double' => 32
216 # You define site-wide feature defaults here; override them with
217 # $GITWEB_CONFIG as necessary.
218 our %feature = (
219 # feature => {
220 # 'sub' => feature-sub (subroutine),
221 # 'override' => allow-override (boolean),
222 # 'default' => [ default options...] (array reference)}
224 # if feature is overridable (it means that allow-override has true value),
225 # then feature-sub will be called with default options as parameters;
226 # return value of feature-sub indicates if to enable specified feature
228 # if there is no 'sub' key (no feature-sub), then feature cannot be
229 # overriden
231 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
232 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
233 # is enabled
235 # Enable the 'blame' blob view, showing the last commit that modified
236 # each line in the file. This can be very CPU-intensive.
238 # To enable system wide have in $GITWEB_CONFIG
239 # $feature{'blame'}{'default'} = [1];
240 # To have project specific config enable override in $GITWEB_CONFIG
241 # $feature{'blame'}{'override'} = 1;
242 # and in project config gitweb.blame = 0|1;
243 'blame' => {
244 'sub' => sub { feature_bool('blame', @_) },
245 'override' => 0,
246 'default' => [0]},
248 # Enable the 'snapshot' link, providing a compressed archive of any
249 # tree. This can potentially generate high traffic if you have large
250 # project.
252 # Value is a list of formats defined in %known_snapshot_formats that
253 # you wish to offer.
254 # To disable system wide have in $GITWEB_CONFIG
255 # $feature{'snapshot'}{'default'} = [];
256 # To have project specific config enable override in $GITWEB_CONFIG
257 # $feature{'snapshot'}{'override'} = 1;
258 # and in project config, a comma-separated list of formats or "none"
259 # to disable. Example: gitweb.snapshot = tbz2,zip;
260 'snapshot' => {
261 'sub' => \&feature_snapshot,
262 'override' => 0,
263 'default' => ['tgz']},
265 # Enable text search, which will list the commits which match author,
266 # committer or commit text to a given string. Enabled by default.
267 # Project specific override is not supported.
268 'search' => {
269 'override' => 0,
270 'default' => [1]},
272 # Enable grep search, which will list the files in currently selected
273 # tree containing the given string. Enabled by default. This can be
274 # potentially CPU-intensive, of course.
276 # To enable system wide have in $GITWEB_CONFIG
277 # $feature{'grep'}{'default'} = [1];
278 # To have project specific config enable override in $GITWEB_CONFIG
279 # $feature{'grep'}{'override'} = 1;
280 # and in project config gitweb.grep = 0|1;
281 'grep' => {
282 'sub' => sub { feature_bool('grep', @_) },
283 'override' => 0,
284 'default' => [1]},
286 # Enable the pickaxe search, which will list the commits that modified
287 # a given string in a file. This can be practical and quite faster
288 # alternative to 'blame', but still potentially CPU-intensive.
290 # To enable system wide have in $GITWEB_CONFIG
291 # $feature{'pickaxe'}{'default'} = [1];
292 # To have project specific config enable override in $GITWEB_CONFIG
293 # $feature{'pickaxe'}{'override'} = 1;
294 # and in project config gitweb.pickaxe = 0|1;
295 'pickaxe' => {
296 'sub' => sub { feature_bool('pickaxe', @_) },
297 'override' => 0,
298 'default' => [1]},
300 # Enable showing size of blobs in a 'tree' view, in a separate
301 # column, similar to what 'ls -l' does. This cost a bit of IO.
303 # To disable system wide have in $GITWEB_CONFIG
304 # $feature{'show-sizes'}{'default'} = [0];
305 # To have project specific config enable override in $GITWEB_CONFIG
306 # $feature{'show-sizes'}{'override'} = 1;
307 # and in project config gitweb.showsizes = 0|1;
308 'show-sizes' => {
309 'sub' => sub { feature_bool('showsizes', @_) },
310 'override' => 0,
311 'default' => [1]},
313 # Make gitweb use an alternative format of the URLs which can be
314 # more readable and natural-looking: project name is embedded
315 # directly in the path and the query string contains other
316 # auxiliary information. All gitweb installations recognize
317 # URL in either format; this configures in which formats gitweb
318 # generates links.
320 # To enable system wide have in $GITWEB_CONFIG
321 # $feature{'pathinfo'}{'default'} = [1];
322 # Project specific override is not supported.
324 # Note that you will need to change the default location of CSS,
325 # favicon, logo and possibly other files to an absolute URL. Also,
326 # if gitweb.cgi serves as your indexfile, you will need to force
327 # $my_uri to contain the script name in your $GITWEB_CONFIG.
328 'pathinfo' => {
329 'override' => 0,
330 'default' => [0]},
332 # Make gitweb consider projects in project root subdirectories
333 # to be forks of existing projects. Given project $projname.git,
334 # projects matching $projname/*.git will not be shown in the main
335 # projects list, instead a '+' mark will be added to $projname
336 # there and a 'forks' view will be enabled for the project, listing
337 # all the forks. If project list is taken from a file, forks have
338 # to be listed after the main project.
340 # To enable system wide have in $GITWEB_CONFIG
341 # $feature{'forks'}{'default'} = [1];
342 # Project specific override is not supported.
343 'forks' => {
344 'override' => 0,
345 'default' => [0]},
347 # Insert custom links to the action bar of all project pages.
348 # This enables you mainly to link to third-party scripts integrating
349 # into gitweb; e.g. git-browser for graphical history representation
350 # or custom web-based repository administration interface.
352 # The 'default' value consists of a list of triplets in the form
353 # (label, link, position) where position is the label after which
354 # to insert the link and link is a format string where %n expands
355 # to the project name, %f to the project path within the filesystem,
356 # %h to the current hash (h gitweb parameter) and %b to the current
357 # hash base (hb gitweb parameter); %% expands to %.
359 # To enable system wide have in $GITWEB_CONFIG e.g.
360 # $feature{'actions'}{'default'} = [('graphiclog',
361 # '/git-browser/by-commit.html?r=%n', 'summary')];
362 # Project specific override is not supported.
363 'actions' => {
364 'override' => 0,
365 'default' => []},
367 # Allow gitweb scan project content tags described in ctags/
368 # of project repository, and display the popular Web 2.0-ish
369 # "tag cloud" near the project list. Note that this is something
370 # COMPLETELY different from the normal Git tags.
372 # gitweb by itself can show existing tags, but it does not handle
373 # tagging itself; you need an external application for that.
374 # For an example script, check Girocco's cgi/tagproj.cgi.
375 # You may want to install the HTML::TagCloud Perl module to get
376 # a pretty tag cloud instead of just a list of tags.
378 # To enable system wide have in $GITWEB_CONFIG
379 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
380 # Project specific override is not supported.
381 'ctags' => {
382 'override' => 0,
383 'default' => [0]},
385 # The maximum number of patches in a patchset generated in patch
386 # view. Set this to 0 or undef to disable patch view, or to a
387 # negative number to remove any limit.
389 # To disable system wide have in $GITWEB_CONFIG
390 # $feature{'patches'}{'default'} = [0];
391 # To have project specific config enable override in $GITWEB_CONFIG
392 # $feature{'patches'}{'override'} = 1;
393 # and in project config gitweb.patches = 0|n;
394 # where n is the maximum number of patches allowed in a patchset.
395 'patches' => {
396 'sub' => \&feature_patches,
397 'override' => 0,
398 'default' => [16]},
400 # Avatar support. When this feature is enabled, views such as
401 # shortlog or commit will display an avatar associated with
402 # the email of the committer(s) and/or author(s).
404 # Currently available providers are gravatar and picon.
405 # If an unknown provider is specified, the feature is disabled.
407 # Gravatar depends on Digest::MD5.
408 # Picon currently relies on the indiana.edu database.
410 # To enable system wide have in $GITWEB_CONFIG
411 # $feature{'avatar'}{'default'} = ['<provider>'];
412 # where <provider> is either gravatar or picon.
413 # To have project specific config enable override in $GITWEB_CONFIG
414 # $feature{'avatar'}{'override'} = 1;
415 # and in project config gitweb.avatar = <provider>;
416 'avatar' => {
417 'sub' => \&feature_avatar,
418 'override' => 0,
419 'default' => ['']},
422 sub gitweb_get_feature {
423 my ($name) = @_;
424 return unless exists $feature{$name};
425 my ($sub, $override, @defaults) = (
426 $feature{$name}{'sub'},
427 $feature{$name}{'override'},
428 @{$feature{$name}{'default'}});
429 if (!$override) { return @defaults; }
430 if (!defined $sub) {
431 warn "feature $name is not overridable";
432 return @defaults;
434 return $sub->(@defaults);
437 # A wrapper to check if a given feature is enabled.
438 # With this, you can say
440 # my $bool_feat = gitweb_check_feature('bool_feat');
441 # gitweb_check_feature('bool_feat') or somecode;
443 # instead of
445 # my ($bool_feat) = gitweb_get_feature('bool_feat');
446 # (gitweb_get_feature('bool_feat'))[0] or somecode;
448 sub gitweb_check_feature {
449 return (gitweb_get_feature(@_))[0];
453 sub feature_bool {
454 my $key = shift;
455 my ($val) = git_get_project_config($key, '--bool');
457 if (!defined $val) {
458 return ($_[0]);
459 } elsif ($val eq 'true') {
460 return (1);
461 } elsif ($val eq 'false') {
462 return (0);
466 sub feature_snapshot {
467 my (@fmts) = @_;
469 my ($val) = git_get_project_config('snapshot');
471 if ($val) {
472 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
475 return @fmts;
478 sub feature_patches {
479 my @val = (git_get_project_config('patches', '--int'));
481 if (@val) {
482 return @val;
485 return ($_[0]);
488 sub feature_avatar {
489 my @val = (git_get_project_config('avatar'));
491 return @val ? @val : @_;
494 # checking HEAD file with -e is fragile if the repository was
495 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
496 # and then pruned.
497 sub check_head_link {
498 my ($dir) = @_;
499 my $headfile = "$dir/HEAD";
500 return ((-e $headfile) ||
501 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
504 sub check_export_ok {
505 my ($dir) = @_;
506 return (check_head_link($dir) &&
507 (!$export_ok || -e "$dir/$export_ok") &&
508 (!$export_auth_hook || $export_auth_hook->($dir)));
511 # process alternate names for backward compatibility
512 # filter out unsupported (unknown) snapshot formats
513 sub filter_snapshot_fmts {
514 my @fmts = @_;
516 @fmts = map {
517 exists $known_snapshot_format_aliases{$_} ?
518 $known_snapshot_format_aliases{$_} : $_} @fmts;
519 @fmts = grep {
520 exists $known_snapshot_formats{$_} &&
521 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
524 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
525 if (-e $GITWEB_CONFIG) {
526 do $GITWEB_CONFIG;
527 } else {
528 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
529 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
532 # version of the core git binary
533 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
535 $projects_list ||= $projectroot;
537 # ======================================================================
538 # input validation and dispatch
540 # input parameters can be collected from a variety of sources (presently, CGI
541 # and PATH_INFO), so we define an %input_params hash that collects them all
542 # together during validation: this allows subsequent uses (e.g. href()) to be
543 # agnostic of the parameter origin
545 our %input_params = ();
547 # input parameters are stored with the long parameter name as key. This will
548 # also be used in the href subroutine to convert parameters to their CGI
549 # equivalent, and since the href() usage is the most frequent one, we store
550 # the name -> CGI key mapping here, instead of the reverse.
552 # XXX: Warning: If you touch this, check the search form for updating,
553 # too.
555 our @cgi_param_mapping = (
556 project => "p",
557 action => "a",
558 file_name => "f",
559 file_parent => "fp",
560 hash => "h",
561 hash_parent => "hp",
562 hash_base => "hb",
563 hash_parent_base => "hpb",
564 page => "pg",
565 order => "o",
566 searchtext => "s",
567 searchtype => "st",
568 snapshot_format => "sf",
569 ctag_filter => 't',
570 extra_options => "opt",
571 search_use_regexp => "sr",
573 our %cgi_param_mapping = @cgi_param_mapping;
575 # we will also need to know the possible actions, for validation
576 our %actions = (
577 "blame" => \&git_blame,
578 "blobdiff" => \&git_blobdiff,
579 "blobdiff_plain" => \&git_blobdiff_plain,
580 "blob" => \&git_blob,
581 "blob_plain" => \&git_blob_plain,
582 "commitdiff" => \&git_commitdiff,
583 "commitdiff_plain" => \&git_commitdiff_plain,
584 "commit" => \&git_commit,
585 "forks" => \&git_forks,
586 "heads" => \&git_heads,
587 "history" => \&git_history,
588 "log" => \&git_log,
589 "patch" => \&git_patch,
590 "patches" => \&git_patches,
591 "rss" => \&git_rss,
592 "atom" => \&git_atom,
593 "search" => \&git_search,
594 "search_help" => \&git_search_help,
595 "shortlog" => \&git_shortlog,
596 "summary" => \&git_summary,
597 "tag" => \&git_tag,
598 "tags" => \&git_tags,
599 "tree" => \&git_tree,
600 "snapshot" => \&git_snapshot,
601 "object" => \&git_object,
602 # those below don't need $project
603 "opml" => \&git_opml,
604 "project_list" => \&git_project_list,
605 "project_index" => \&git_project_index,
608 # finally, we have the hash of allowed extra_options for the commands that
609 # allow them
610 our %allowed_options = (
611 "--no-merges" => [ qw(rss atom log shortlog history) ],
614 # fill %input_params with the CGI parameters. All values except for 'opt'
615 # should be single values, but opt can be an array. We should probably
616 # build an array of parameters that can be multi-valued, but since for the time
617 # being it's only this one, we just single it out
618 while (my ($name, $symbol) = each %cgi_param_mapping) {
619 if ($symbol eq 'opt') {
620 $input_params{$name} = [ $cgi->param($symbol) ];
621 } else {
622 $input_params{$name} = $cgi->param($symbol);
626 # Backwards compatibility - by_tag= <=> t=
627 if ($cgi->param('by_tag')) {
628 $input_params{'ctag_filter'} = $cgi->param('by_tag');
631 # now read PATH_INFO and update the parameter list for missing parameters
632 sub evaluate_path_info {
633 return if defined $input_params{'project'};
634 return if !$path_info;
635 $path_info =~ s,^/+,,;
636 return if !$path_info;
638 # find which part of PATH_INFO is project
639 my $project = $path_info;
640 $project =~ s,/+$,,;
641 while ($project && !check_head_link("$projectroot/$project")) {
642 $project =~ s,/*[^/]*$,,;
644 return unless $project;
645 $input_params{'project'} = $project;
647 # do not change any parameters if an action is given using the query string
648 return if $input_params{'action'};
649 $path_info =~ s,^\Q$project\E/*,,;
651 # next, check if we have an action
652 my $action = $path_info;
653 $action =~ s,/.*$,,;
654 if (exists $actions{$action}) {
655 $path_info =~ s,^$action/*,,;
656 $input_params{'action'} = $action;
659 # list of actions that want hash_base instead of hash, but can have no
660 # pathname (f) parameter
661 my @wants_base = (
662 'tree',
663 'history',
666 # we want to catch
667 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
668 my ($parentrefname, $parentpathname, $refname, $pathname) =
669 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
671 # first, analyze the 'current' part
672 if (defined $pathname) {
673 # we got "branch:filename" or "branch:dir/"
674 # we could use git_get_type(branch:pathname), but:
675 # - it needs $git_dir
676 # - it does a git() call
677 # - the convention of terminating directories with a slash
678 # makes it superfluous
679 # - embedding the action in the PATH_INFO would make it even
680 # more superfluous
681 $pathname =~ s,^/+,,;
682 if (!$pathname || substr($pathname, -1) eq "/") {
683 $input_params{'action'} ||= "tree";
684 $pathname =~ s,/$,,;
685 } else {
686 # the default action depends on whether we had parent info
687 # or not
688 if ($parentrefname) {
689 $input_params{'action'} ||= "blobdiff_plain";
690 } else {
691 $input_params{'action'} ||= "blob_plain";
694 $input_params{'hash_base'} ||= $refname;
695 $input_params{'file_name'} ||= $pathname;
696 } elsif (defined $refname) {
697 # we got "branch". In this case we have to choose if we have to
698 # set hash or hash_base.
700 # Most of the actions without a pathname only want hash to be
701 # set, except for the ones specified in @wants_base that want
702 # hash_base instead. It should also be noted that hand-crafted
703 # links having 'history' as an action and no pathname or hash
704 # set will fail, but that happens regardless of PATH_INFO.
705 $input_params{'action'} ||= "shortlog";
706 if (grep { $_ eq $input_params{'action'} } @wants_base) {
707 $input_params{'hash_base'} ||= $refname;
708 } else {
709 $input_params{'hash'} ||= $refname;
713 # next, handle the 'parent' part, if present
714 if (defined $parentrefname) {
715 # a missing pathspec defaults to the 'current' filename, allowing e.g.
716 # someproject/blobdiff/oldrev..newrev:/filename
717 if ($parentpathname) {
718 $parentpathname =~ s,^/+,,;
719 $parentpathname =~ s,/$,,;
720 $input_params{'file_parent'} ||= $parentpathname;
721 } else {
722 $input_params{'file_parent'} ||= $input_params{'file_name'};
724 # we assume that hash_parent_base is wanted if a path was specified,
725 # or if the action wants hash_base instead of hash
726 if (defined $input_params{'file_parent'} ||
727 grep { $_ eq $input_params{'action'} } @wants_base) {
728 $input_params{'hash_parent_base'} ||= $parentrefname;
729 } else {
730 $input_params{'hash_parent'} ||= $parentrefname;
734 # for the snapshot action, we allow URLs in the form
735 # $project/snapshot/$hash.ext
736 # where .ext determines the snapshot and gets removed from the
737 # passed $refname to provide the $hash.
739 # To be able to tell that $refname includes the format extension, we
740 # require the following two conditions to be satisfied:
741 # - the hash input parameter MUST have been set from the $refname part
742 # of the URL (i.e. they must be equal)
743 # - the snapshot format MUST NOT have been defined already (e.g. from
744 # CGI parameter sf)
745 # It's also useless to try any matching unless $refname has a dot,
746 # so we check for that too
747 if (defined $input_params{'action'} &&
748 $input_params{'action'} eq 'snapshot' &&
749 defined $refname && index($refname, '.') != -1 &&
750 $refname eq $input_params{'hash'} &&
751 !defined $input_params{'snapshot_format'}) {
752 # We loop over the known snapshot formats, checking for
753 # extensions. Allowed extensions are both the defined suffix
754 # (which includes the initial dot already) and the snapshot
755 # format key itself, with a prepended dot
756 while (my ($fmt, $opt) = each %known_snapshot_formats) {
757 my $hash = $refname;
758 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
759 next;
761 my $sfx = $1;
762 # a valid suffix was found, so set the snapshot format
763 # and reset the hash parameter
764 $input_params{'snapshot_format'} = $fmt;
765 $input_params{'hash'} = $hash;
766 # we also set the format suffix to the one requested
767 # in the URL: this way a request for e.g. .tgz returns
768 # a .tgz instead of a .tar.gz
769 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
770 last;
774 evaluate_path_info();
776 our $action = $input_params{'action'};
777 if (defined $action) {
778 if (!validate_action($action)) {
779 die_error(400, "Invalid action parameter");
783 # parameters which are pathnames
784 our $project = $input_params{'project'};
785 if (defined $project) {
786 if (!validate_project($project)) {
787 undef $project;
788 die_error(404, "No such project");
792 our $file_name = $input_params{'file_name'};
793 if (defined $file_name) {
794 if (!validate_pathname($file_name)) {
795 die_error(400, "Invalid file parameter");
799 our $file_parent = $input_params{'file_parent'};
800 if (defined $file_parent) {
801 if (!validate_pathname($file_parent)) {
802 die_error(400, "Invalid file parent parameter");
806 # parameters which are refnames
807 our $hash = $input_params{'hash'};
808 if (defined $hash) {
809 if (!validate_refname($hash)) {
810 die_error(400, "Invalid hash parameter");
814 our $hash_parent = $input_params{'hash_parent'};
815 if (defined $hash_parent) {
816 if (!validate_refname($hash_parent)) {
817 die_error(400, "Invalid hash parent parameter");
821 our $hash_base = $input_params{'hash_base'};
822 if (defined $hash_base) {
823 if (!validate_refname($hash_base)) {
824 die_error(400, "Invalid hash base parameter");
828 our @extra_options = @{$input_params{'extra_options'}};
829 # @extra_options is always defined, since it can only be (currently) set from
830 # CGI, and $cgi->param() returns the empty array in array context if the param
831 # is not set
832 foreach my $opt (@extra_options) {
833 if (not exists $allowed_options{$opt}) {
834 die_error(400, "Invalid option parameter");
836 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
837 die_error(400, "Invalid option parameter for this action");
841 our $hash_parent_base = $input_params{'hash_parent_base'};
842 if (defined $hash_parent_base) {
843 if (!validate_refname($hash_parent_base)) {
844 die_error(400, "Invalid hash parent base parameter");
848 # other parameters
849 our $page = $input_params{'page'};
850 if (defined $page) {
851 if ($page =~ m/[^0-9]/) {
852 die_error(400, "Invalid page parameter");
856 our $searchtype = $input_params{'searchtype'};
857 if (defined $searchtype) {
858 if ($searchtype =~ m/[^a-z]/) {
859 die_error(400, "Invalid searchtype parameter");
863 our $search_use_regexp = $input_params{'search_use_regexp'};
865 our $searchtext = $input_params{'searchtext'};
866 our $search_regexp;
867 if (defined $searchtext) {
868 if (length($searchtext) < 2) {
869 die_error(403, "At least two characters are required for search parameter");
871 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
874 # path to the current git repository
875 our $git_dir;
876 $git_dir = "$projectroot/$project" if $project;
878 # list of supported snapshot formats
879 our @snapshot_fmts = gitweb_get_feature('snapshot');
880 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
882 # check that the avatar feature is set to a known provider name,
883 # and for each provider check if the dependencies are satisfied.
884 # if the provider name is invalid or the dependencies are not met,
885 # reset $git_avatar to the empty string.
886 our ($git_avatar) = gitweb_get_feature('avatar');
887 if ($git_avatar eq 'gravatar') {
888 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
889 } elsif ($git_avatar eq 'picon') {
890 # no dependencies
891 } else {
892 $git_avatar = '';
895 # dispatch
896 if (!defined $action) {
897 if (defined $hash) {
898 $action = git_get_type($hash);
899 } elsif (defined $hash_base && defined $file_name) {
900 $action = git_get_type("$hash_base:$file_name");
901 } elsif (defined $project) {
902 $action = 'summary';
903 } else {
904 $action = 'project_list';
907 if (!defined($actions{$action})) {
908 die_error(400, "Unknown action");
910 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
911 !$project) {
912 die_error(400, "Project needed");
914 $actions{$action}->();
915 exit;
917 ## ======================================================================
918 ## action links
920 sub href {
921 my %params = @_;
922 # default is to use -absolute url() i.e. $my_uri
923 my $href = $params{-full} ? $my_url : $my_uri;
925 $params{'project'} = $project unless exists $params{'project'};
927 if ($params{-replay}) {
928 while (my ($name, $symbol) = each %cgi_param_mapping) {
929 if (!exists $params{$name}) {
930 $params{$name} = $input_params{$name};
935 my $use_pathinfo = gitweb_check_feature('pathinfo');
936 if ($use_pathinfo and defined $params{'project'}) {
937 # try to put as many parameters as possible in PATH_INFO:
938 # - project name
939 # - action
940 # - hash_parent or hash_parent_base:/file_parent
941 # - hash or hash_base:/filename
942 # - the snapshot_format as an appropriate suffix
944 # When the script is the root DirectoryIndex for the domain,
945 # $href here would be something like http://gitweb.example.com/
946 # Thus, we strip any trailing / from $href, to spare us double
947 # slashes in the final URL
948 $href =~ s,/$,,;
950 # Then add the project name, if present
951 $href .= "/".esc_url($params{'project'});
952 delete $params{'project'};
954 # since we destructively absorb parameters, we keep this
955 # boolean that remembers if we're handling a snapshot
956 my $is_snapshot = $params{'action'} eq 'snapshot';
958 # Summary just uses the project path URL, any other action is
959 # added to the URL
960 if (defined $params{'action'}) {
961 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
962 delete $params{'action'};
965 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
966 # stripping nonexistent or useless pieces
967 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
968 || $params{'hash_parent'} || $params{'hash'});
969 if (defined $params{'hash_base'}) {
970 if (defined $params{'hash_parent_base'}) {
971 $href .= esc_url($params{'hash_parent_base'});
972 # skip the file_parent if it's the same as the file_name
973 if (defined $params{'file_parent'}) {
974 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
975 delete $params{'file_parent'};
976 } elsif ($params{'file_parent'} !~ /\.\./) {
977 $href .= ":/".esc_url($params{'file_parent'});
978 delete $params{'file_parent'};
981 $href .= "..";
982 delete $params{'hash_parent'};
983 delete $params{'hash_parent_base'};
984 } elsif (defined $params{'hash_parent'}) {
985 $href .= esc_url($params{'hash_parent'}). "..";
986 delete $params{'hash_parent'};
989 $href .= esc_url($params{'hash_base'});
990 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
991 $href .= ":/".esc_url($params{'file_name'});
992 delete $params{'file_name'};
994 delete $params{'hash'};
995 delete $params{'hash_base'};
996 } elsif (defined $params{'hash'}) {
997 $href .= esc_url($params{'hash'});
998 delete $params{'hash'};
1001 # If the action was a snapshot, we can absorb the
1002 # snapshot_format parameter too
1003 if ($is_snapshot) {
1004 my $fmt = $params{'snapshot_format'};
1005 # snapshot_format should always be defined when href()
1006 # is called, but just in case some code forgets, we
1007 # fall back to the default
1008 $fmt ||= $snapshot_fmts[0];
1009 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1010 delete $params{'snapshot_format'};
1014 # now encode the parameters explicitly
1015 my @result = ();
1016 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1017 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1018 if (defined $params{$name}) {
1019 if (ref($params{$name}) eq "ARRAY") {
1020 foreach my $par (@{$params{$name}}) {
1021 push @result, $symbol . "=" . esc_param($par);
1023 } else {
1024 push @result, $symbol . "=" . esc_param($params{$name});
1028 $href .= "?" . join(';', @result) if scalar @result;
1030 return $href;
1034 ## ======================================================================
1035 ## validation, quoting/unquoting and escaping
1037 sub validate_action {
1038 my $input = shift || return undef;
1039 return undef unless exists $actions{$input};
1040 return $input;
1043 sub validate_project {
1044 my $input = shift || return undef;
1045 if (!validate_pathname($input) ||
1046 !(-d "$projectroot/$input") ||
1047 !check_export_ok("$projectroot/$input") ||
1048 ($strict_export && !project_in_list($input))) {
1049 return undef;
1050 } else {
1051 return $input;
1055 sub validate_pathname {
1056 my $input = shift || return undef;
1058 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1059 # at the beginning, at the end, and between slashes.
1060 # also this catches doubled slashes
1061 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1062 return undef;
1064 # no null characters
1065 if ($input =~ m!\0!) {
1066 return undef;
1068 return $input;
1071 sub validate_refname {
1072 my $input = shift || return undef;
1074 # textual hashes are O.K.
1075 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1076 return $input;
1078 # it must be correct pathname
1079 $input = validate_pathname($input)
1080 or return undef;
1081 # restrictions on ref name according to git-check-ref-format
1082 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1083 return undef;
1085 return $input;
1088 # decode sequences of octets in utf8 into Perl's internal form,
1089 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1090 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1091 sub to_utf8 {
1092 my $str = shift;
1093 if (utf8::valid($str)) {
1094 utf8::decode($str);
1095 return $str;
1096 } else {
1097 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1101 # quote unsafe chars, but keep the slash, even when it's not
1102 # correct, but quoted slashes look too horrible in bookmarks
1103 sub esc_param {
1104 my $str = shift;
1105 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1106 $str =~ s/ /\+/g;
1107 return $str;
1110 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1111 sub esc_url {
1112 my $str = shift;
1113 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1114 $str =~ s/\+/%2B/g;
1115 $str =~ s/ /\+/g;
1116 return $str;
1119 # replace invalid utf8 character with SUBSTITUTION sequence
1120 sub esc_html {
1121 my $str = shift;
1122 my %opts = @_;
1124 $str = to_utf8($str);
1125 $str = $cgi->escapeHTML($str);
1126 if ($opts{'-nbsp'}) {
1127 $str =~ s/ /&nbsp;/g;
1129 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1130 return $str;
1133 # quote control characters and escape filename to HTML
1134 sub esc_path {
1135 my $str = shift;
1136 my %opts = @_;
1138 $str = to_utf8($str);
1139 $str = $cgi->escapeHTML($str);
1140 if ($opts{'-nbsp'}) {
1141 $str =~ s/ /&nbsp;/g;
1143 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1144 return $str;
1147 # Make control characters "printable", using character escape codes (CEC)
1148 sub quot_cec {
1149 my $cntrl = shift;
1150 my %opts = @_;
1151 my %es = ( # character escape codes, aka escape sequences
1152 "\t" => '\t', # tab (HT)
1153 "\n" => '\n', # line feed (LF)
1154 "\r" => '\r', # carrige return (CR)
1155 "\f" => '\f', # form feed (FF)
1156 "\b" => '\b', # backspace (BS)
1157 "\a" => '\a', # alarm (bell) (BEL)
1158 "\e" => '\e', # escape (ESC)
1159 "\013" => '\v', # vertical tab (VT)
1160 "\000" => '\0', # nul character (NUL)
1162 my $chr = ( (exists $es{$cntrl})
1163 ? $es{$cntrl}
1164 : sprintf('\%2x', ord($cntrl)) );
1165 if ($opts{-nohtml}) {
1166 return $chr;
1167 } else {
1168 return "<span class=\"cntrl\">$chr</span>";
1172 # Alternatively use unicode control pictures codepoints,
1173 # Unicode "printable representation" (PR)
1174 sub quot_upr {
1175 my $cntrl = shift;
1176 my %opts = @_;
1178 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1179 if ($opts{-nohtml}) {
1180 return $chr;
1181 } else {
1182 return "<span class=\"cntrl\">$chr</span>";
1186 # git may return quoted and escaped filenames
1187 sub unquote {
1188 my $str = shift;
1190 sub unq {
1191 my $seq = shift;
1192 my %es = ( # character escape codes, aka escape sequences
1193 't' => "\t", # tab (HT, TAB)
1194 'n' => "\n", # newline (NL)
1195 'r' => "\r", # return (CR)
1196 'f' => "\f", # form feed (FF)
1197 'b' => "\b", # backspace (BS)
1198 'a' => "\a", # alarm (bell) (BEL)
1199 'e' => "\e", # escape (ESC)
1200 'v' => "\013", # vertical tab (VT)
1203 if ($seq =~ m/^[0-7]{1,3}$/) {
1204 # octal char sequence
1205 return chr(oct($seq));
1206 } elsif (exists $es{$seq}) {
1207 # C escape sequence, aka character escape code
1208 return $es{$seq};
1210 # quoted ordinary character
1211 return $seq;
1214 if ($str =~ m/^"(.*)"$/) {
1215 # needs unquoting
1216 $str = $1;
1217 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1219 return $str;
1222 # escape tabs (convert tabs to spaces)
1223 sub untabify {
1224 my $line = shift;
1226 while ((my $pos = index($line, "\t")) != -1) {
1227 if (my $count = (8 - ($pos % 8))) {
1228 my $spaces = ' ' x $count;
1229 $line =~ s/\t/$spaces/;
1233 return $line;
1236 sub project_in_list {
1237 my $project = shift;
1238 my @list = git_get_projects_list();
1239 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1242 ## ----------------------------------------------------------------------
1243 ## HTML aware string manipulation
1245 # Try to chop given string on a word boundary between position
1246 # $len and $len+$add_len. If there is no word boundary there,
1247 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1248 # (marking chopped part) would be longer than given string.
1249 sub chop_str {
1250 my $str = shift;
1251 my $len = shift;
1252 my $add_len = shift || 10;
1253 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1255 # Make sure perl knows it is utf8 encoded so we don't
1256 # cut in the middle of a utf8 multibyte char.
1257 $str = to_utf8($str);
1259 # allow only $len chars, but don't cut a word if it would fit in $add_len
1260 # if it doesn't fit, cut it if it's still longer than the dots we would add
1261 # remove chopped character entities entirely
1263 # when chopping in the middle, distribute $len into left and right part
1264 # return early if chopping wouldn't make string shorter
1265 if ($where eq 'center') {
1266 return $str if ($len + 5 >= length($str)); # filler is length 5
1267 $len = int($len/2);
1268 } else {
1269 return $str if ($len + 4 >= length($str)); # filler is length 4
1272 # regexps: ending and beginning with word part up to $add_len
1273 my $endre = qr/.{$len}\w{0,$add_len}/;
1274 my $begre = qr/\w{0,$add_len}.{$len}/;
1276 if ($where eq 'left') {
1277 $str =~ m/^(.*?)($begre)$/;
1278 my ($lead, $body) = ($1, $2);
1279 if (length($lead) > 4) {
1280 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1281 $lead = " ...";
1283 return "$lead$body";
1285 } elsif ($where eq 'center') {
1286 $str =~ m/^($endre)(.*)$/;
1287 my ($left, $str) = ($1, $2);
1288 $str =~ m/^(.*?)($begre)$/;
1289 my ($mid, $right) = ($1, $2);
1290 if (length($mid) > 5) {
1291 $left =~ s/&[^;]*$//;
1292 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1293 $mid = " ... ";
1295 return "$left$mid$right";
1297 } else {
1298 $str =~ m/^($endre)(.*)$/;
1299 my $body = $1;
1300 my $tail = $2;
1301 if (length($tail) > 4) {
1302 $body =~ s/&[^;]*$//;
1303 $tail = "... ";
1305 return "$body$tail";
1309 # takes the same arguments as chop_str, but also wraps a <span> around the
1310 # result with a title attribute if it does get chopped. Additionally, the
1311 # string is HTML-escaped.
1312 sub chop_and_escape_str {
1313 my ($str) = @_;
1315 my $chopped = chop_str(@_);
1316 if ($chopped eq $str) {
1317 return esc_html($chopped);
1318 } else {
1319 $str =~ s/[[:cntrl:]]/?/g;
1320 return $cgi->span({-title=>$str}, esc_html($chopped));
1324 ## ----------------------------------------------------------------------
1325 ## functions returning short strings
1327 # CSS class for given age value (in seconds)
1328 sub age_class {
1329 my $age = shift;
1331 if (!defined $age) {
1332 return "noage";
1333 } elsif ($age < 60*60*2) {
1334 return "age0";
1335 } elsif ($age < 60*60*24*2) {
1336 return "age1";
1337 } else {
1338 return "age2";
1342 # convert age in seconds to "nn units ago" string
1343 sub age_string {
1344 my $age = shift;
1345 my $age_str;
1347 if ($age > 60*60*24*365*2) {
1348 $age_str = (int $age/60/60/24/365);
1349 $age_str .= " years ago";
1350 } elsif ($age > 60*60*24*(365/12)*2) {
1351 $age_str = int $age/60/60/24/(365/12);
1352 $age_str .= " months ago";
1353 } elsif ($age > 60*60*24*7*2) {
1354 $age_str = int $age/60/60/24/7;
1355 $age_str .= " weeks ago";
1356 } elsif ($age > 60*60*24*2) {
1357 $age_str = int $age/60/60/24;
1358 $age_str .= " days ago";
1359 } elsif ($age > 60*60*2) {
1360 $age_str = int $age/60/60;
1361 $age_str .= " hours ago";
1362 } elsif ($age > 60*2) {
1363 $age_str = int $age/60;
1364 $age_str .= " min ago";
1365 } elsif ($age > 2) {
1366 $age_str = int $age;
1367 $age_str .= " sec ago";
1368 } else {
1369 $age_str .= " right now";
1371 return $age_str;
1374 use constant {
1375 S_IFINVALID => 0030000,
1376 S_IFGITLINK => 0160000,
1379 # submodule/subproject, a commit object reference
1380 sub S_ISGITLINK {
1381 my $mode = shift;
1383 return (($mode & S_IFMT) == S_IFGITLINK)
1386 # convert file mode in octal to symbolic file mode string
1387 sub mode_str {
1388 my $mode = oct shift;
1390 if (S_ISGITLINK($mode)) {
1391 return 'm---------';
1392 } elsif (S_ISDIR($mode & S_IFMT)) {
1393 return 'drwxr-xr-x';
1394 } elsif (S_ISLNK($mode)) {
1395 return 'lrwxrwxrwx';
1396 } elsif (S_ISREG($mode)) {
1397 # git cares only about the executable bit
1398 if ($mode & S_IXUSR) {
1399 return '-rwxr-xr-x';
1400 } else {
1401 return '-rw-r--r--';
1403 } else {
1404 return '----------';
1408 # convert file mode in octal to file type string
1409 sub file_type {
1410 my $mode = shift;
1412 if ($mode !~ m/^[0-7]+$/) {
1413 return $mode;
1414 } else {
1415 $mode = oct $mode;
1418 if (S_ISGITLINK($mode)) {
1419 return "submodule";
1420 } elsif (S_ISDIR($mode & S_IFMT)) {
1421 return "directory";
1422 } elsif (S_ISLNK($mode)) {
1423 return "symlink";
1424 } elsif (S_ISREG($mode)) {
1425 return "file";
1426 } else {
1427 return "unknown";
1431 # convert file mode in octal to file type description string
1432 sub file_type_long {
1433 my $mode = shift;
1435 if ($mode !~ m/^[0-7]+$/) {
1436 return $mode;
1437 } else {
1438 $mode = oct $mode;
1441 if (S_ISGITLINK($mode)) {
1442 return "submodule";
1443 } elsif (S_ISDIR($mode & S_IFMT)) {
1444 return "directory";
1445 } elsif (S_ISLNK($mode)) {
1446 return "symlink";
1447 } elsif (S_ISREG($mode)) {
1448 if ($mode & S_IXUSR) {
1449 return "executable";
1450 } else {
1451 return "file";
1453 } else {
1454 return "unknown";
1459 ## ----------------------------------------------------------------------
1460 ## functions returning short HTML fragments, or transforming HTML fragments
1461 ## which don't belong to other sections
1463 # format line of commit message.
1464 sub format_log_line_html {
1465 my $line = shift;
1467 $line = esc_html($line, -nbsp=>1);
1468 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1469 $cgi->a({-href => href(action=>"object", hash=>$1),
1470 -class => "text"}, $1);
1471 }eg;
1473 return $line;
1476 # format marker of refs pointing to given object
1478 # the destination action is chosen based on object type and current context:
1479 # - for annotated tags, we choose the tag view unless it's the current view
1480 # already, in which case we go to shortlog view
1481 # - for other refs, we keep the current view if we're in history, shortlog or
1482 # log view, and select shortlog otherwise
1483 sub format_ref_marker {
1484 my ($refs, $id) = @_;
1485 my $markers = '';
1487 if (defined $refs->{$id}) {
1488 foreach my $ref (@{$refs->{$id}}) {
1489 # this code exploits the fact that non-lightweight tags are the
1490 # only indirect objects, and that they are the only objects for which
1491 # we want to use tag instead of shortlog as action
1492 my ($type, $name) = qw();
1493 my $indirect = ($ref =~ s/\^\{\}$//);
1494 # e.g. tags/v2.6.11 or heads/next
1495 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1496 $type = $1;
1497 $name = $2;
1498 } else {
1499 $type = "ref";
1500 $name = $ref;
1503 my $class = $type;
1504 $class .= " indirect" if $indirect;
1506 my $dest_action = "shortlog";
1508 if ($indirect) {
1509 $dest_action = "tag" unless $action eq "tag";
1510 } elsif ($action =~ /^(history|(short)?log)$/) {
1511 $dest_action = $action;
1514 my $dest = "";
1515 $dest .= "refs/" unless $ref =~ m!^refs/!;
1516 $dest .= $ref;
1518 my $link = $cgi->a({
1519 -href => href(
1520 action=>$dest_action,
1521 hash=>$dest
1522 )}, $name);
1524 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1525 $link . "</span>";
1529 if ($markers) {
1530 return ' <span class="refs">'. $markers . '</span>';
1531 } else {
1532 return "";
1536 # format, perhaps shortened and with markers, title line
1537 sub format_subject_html {
1538 my ($long, $short, $href, $extra) = @_;
1539 $extra = '' unless defined($extra);
1541 if (length($short) < length($long)) {
1542 $long =~ s/[[:cntrl:]]/?/g;
1543 return $cgi->a({-href => $href, -class => "list subject",
1544 -title => to_utf8($long)},
1545 esc_html($short)) . $extra;
1546 } else {
1547 return $cgi->a({-href => $href, -class => "list subject"},
1548 esc_html($long)) . $extra;
1552 # Rather than recomputing the url for an email multiple times, we cache it
1553 # after the first hit. This gives a visible benefit in views where the avatar
1554 # for the same email is used repeatedly (e.g. shortlog).
1555 # The cache is shared by all avatar engines (currently gravatar only), which
1556 # are free to use it as preferred. Since only one avatar engine is used for any
1557 # given page, there's no risk for cache conflicts.
1558 our %avatar_cache = ();
1560 # Compute the picon url for a given email, by using the picon search service over at
1561 # http://www.cs.indiana.edu/picons/search.html
1562 sub picon_url {
1563 my $email = lc shift;
1564 if (!$avatar_cache{$email}) {
1565 my ($user, $domain) = split('@', $email);
1566 $avatar_cache{$email} =
1567 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1568 "$domain/$user/" .
1569 "users+domains+unknown/up/single";
1571 return $avatar_cache{$email};
1574 # Compute the gravatar url for a given email, if it's not in the cache already.
1575 # Gravatar stores only the part of the URL before the size, since that's the
1576 # one computationally more expensive. This also allows reuse of the cache for
1577 # different sizes (for this particular engine).
1578 sub gravatar_url {
1579 my $email = lc shift;
1580 my $size = shift;
1581 $avatar_cache{$email} ||=
1582 "http://www.gravatar.com/avatar/" .
1583 Digest::MD5::md5_hex($email) . "?s=";
1584 return $avatar_cache{$email} . $size;
1587 # Insert an avatar for the given $email at the given $size if the feature
1588 # is enabled.
1589 sub git_get_avatar {
1590 my ($email, %opts) = @_;
1591 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1592 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1593 $opts{-size} ||= 'default';
1594 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1595 my $url = "";
1596 if ($git_avatar eq 'gravatar') {
1597 $url = gravatar_url($email, $size);
1598 } elsif ($git_avatar eq 'picon') {
1599 $url = picon_url($email);
1601 # Other providers can be added by extending the if chain, defining $url
1602 # as needed. If no variant puts something in $url, we assume avatars
1603 # are completely disabled/unavailable.
1604 if ($url) {
1605 return $pre_white .
1606 "<img width=\"$size\" " .
1607 "class=\"avatar\" " .
1608 "src=\"$url\" " .
1609 "alt=\"\" " .
1610 "/>" . $post_white;
1611 } else {
1612 return "";
1616 sub format_search_author {
1617 my ($author, $searchtype, $displaytext) = @_;
1618 my $have_search = gitweb_check_feature('search');
1620 if ($have_search) {
1621 my $performed = "";
1622 if ($searchtype eq 'author') {
1623 $performed = "authored";
1624 } elsif ($searchtype eq 'committer') {
1625 $performed = "committed";
1628 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1629 searchtext=>$author,
1630 searchtype=>$searchtype), class=>"list",
1631 title=>"Search for commits $performed by $author"},
1632 $displaytext);
1634 } else {
1635 return $displaytext;
1639 # format the author name of the given commit with the given tag
1640 # the author name is chopped and escaped according to the other
1641 # optional parameters (see chop_str).
1642 sub format_author_html {
1643 my $tag = shift;
1644 my $co = shift;
1645 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1646 return "<$tag class=\"author\">" .
1647 format_search_author($co->{'author_name'}, "author",
1648 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1649 $author) .
1650 "</$tag>";
1653 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1654 sub format_git_diff_header_line {
1655 my $line = shift;
1656 my $diffinfo = shift;
1657 my ($from, $to) = @_;
1659 if ($diffinfo->{'nparents'}) {
1660 # combined diff
1661 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1662 if ($to->{'href'}) {
1663 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1664 esc_path($to->{'file'}));
1665 } else { # file was deleted (no href)
1666 $line .= esc_path($to->{'file'});
1668 } else {
1669 # "ordinary" diff
1670 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1671 if ($from->{'href'}) {
1672 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1673 'a/' . esc_path($from->{'file'}));
1674 } else { # file was added (no href)
1675 $line .= 'a/' . esc_path($from->{'file'});
1677 $line .= ' ';
1678 if ($to->{'href'}) {
1679 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1680 'b/' . esc_path($to->{'file'}));
1681 } else { # file was deleted
1682 $line .= 'b/' . esc_path($to->{'file'});
1686 return "<div class=\"diff header\">$line</div>\n";
1689 # format extended diff header line, before patch itself
1690 sub format_extended_diff_header_line {
1691 my $line = shift;
1692 my $diffinfo = shift;
1693 my ($from, $to) = @_;
1695 # match <path>
1696 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1697 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1698 esc_path($from->{'file'}));
1700 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1701 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1702 esc_path($to->{'file'}));
1704 # match single <mode>
1705 if ($line =~ m/\s(\d{6})$/) {
1706 $line .= '<span class="info"> (' .
1707 file_type_long($1) .
1708 ')</span>';
1710 # match <hash>
1711 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1712 # can match only for combined diff
1713 $line = 'index ';
1714 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1715 if ($from->{'href'}[$i]) {
1716 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1717 -class=>"hash"},
1718 substr($diffinfo->{'from_id'}[$i],0,7));
1719 } else {
1720 $line .= '0' x 7;
1722 # separator
1723 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1725 $line .= '..';
1726 if ($to->{'href'}) {
1727 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1728 substr($diffinfo->{'to_id'},0,7));
1729 } else {
1730 $line .= '0' x 7;
1733 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1734 # can match only for ordinary diff
1735 my ($from_link, $to_link);
1736 if ($from->{'href'}) {
1737 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1738 substr($diffinfo->{'from_id'},0,7));
1739 } else {
1740 $from_link = '0' x 7;
1742 if ($to->{'href'}) {
1743 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1744 substr($diffinfo->{'to_id'},0,7));
1745 } else {
1746 $to_link = '0' x 7;
1748 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1749 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1752 return $line . "<br/>\n";
1755 # format from-file/to-file diff header
1756 sub format_diff_from_to_header {
1757 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1758 my $line;
1759 my $result = '';
1761 $line = $from_line;
1762 #assert($line =~ m/^---/) if DEBUG;
1763 # no extra formatting for "^--- /dev/null"
1764 if (! $diffinfo->{'nparents'}) {
1765 # ordinary (single parent) diff
1766 if ($line =~ m!^--- "?a/!) {
1767 if ($from->{'href'}) {
1768 $line = '--- a/' .
1769 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1770 esc_path($from->{'file'}));
1771 } else {
1772 $line = '--- a/' .
1773 esc_path($from->{'file'});
1776 $result .= qq!<div class="diff from_file">$line</div>\n!;
1778 } else {
1779 # combined diff (merge commit)
1780 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1781 if ($from->{'href'}[$i]) {
1782 $line = '--- ' .
1783 $cgi->a({-href=>href(action=>"blobdiff",
1784 hash_parent=>$diffinfo->{'from_id'}[$i],
1785 hash_parent_base=>$parents[$i],
1786 file_parent=>$from->{'file'}[$i],
1787 hash=>$diffinfo->{'to_id'},
1788 hash_base=>$hash,
1789 file_name=>$to->{'file'}),
1790 -class=>"path",
1791 -title=>"diff" . ($i+1)},
1792 $i+1) .
1793 '/' .
1794 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1795 esc_path($from->{'file'}[$i]));
1796 } else {
1797 $line = '--- /dev/null';
1799 $result .= qq!<div class="diff from_file">$line</div>\n!;
1803 $line = $to_line;
1804 #assert($line =~ m/^\+\+\+/) if DEBUG;
1805 # no extra formatting for "^+++ /dev/null"
1806 if ($line =~ m!^\+\+\+ "?b/!) {
1807 if ($to->{'href'}) {
1808 $line = '+++ b/' .
1809 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1810 esc_path($to->{'file'}));
1811 } else {
1812 $line = '+++ b/' .
1813 esc_path($to->{'file'});
1816 $result .= qq!<div class="diff to_file">$line</div>\n!;
1818 return $result;
1821 # create note for patch simplified by combined diff
1822 sub format_diff_cc_simplified {
1823 my ($diffinfo, @parents) = @_;
1824 my $result = '';
1826 $result .= "<div class=\"diff header\">" .
1827 "diff --cc ";
1828 if (!is_deleted($diffinfo)) {
1829 $result .= $cgi->a({-href => href(action=>"blob",
1830 hash_base=>$hash,
1831 hash=>$diffinfo->{'to_id'},
1832 file_name=>$diffinfo->{'to_file'}),
1833 -class => "path"},
1834 esc_path($diffinfo->{'to_file'}));
1835 } else {
1836 $result .= esc_path($diffinfo->{'to_file'});
1838 $result .= "</div>\n" . # class="diff header"
1839 "<div class=\"diff nodifferences\">" .
1840 "Simple merge" .
1841 "</div>\n"; # class="diff nodifferences"
1843 return $result;
1846 # format patch (diff) line (not to be used for diff headers)
1847 sub format_diff_line {
1848 my $line = shift;
1849 my ($from, $to) = @_;
1850 my $diff_class = "";
1852 chomp $line;
1854 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1855 # combined diff
1856 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1857 if ($line =~ m/^\@{3}/) {
1858 $diff_class = " chunk_header";
1859 } elsif ($line =~ m/^\\/) {
1860 $diff_class = " incomplete";
1861 } elsif ($prefix =~ tr/+/+/) {
1862 $diff_class = " add";
1863 } elsif ($prefix =~ tr/-/-/) {
1864 $diff_class = " rem";
1866 } else {
1867 # assume ordinary diff
1868 my $char = substr($line, 0, 1);
1869 if ($char eq '+') {
1870 $diff_class = " add";
1871 } elsif ($char eq '-') {
1872 $diff_class = " rem";
1873 } elsif ($char eq '@') {
1874 $diff_class = " chunk_header";
1875 } elsif ($char eq "\\") {
1876 $diff_class = " incomplete";
1879 $line = untabify($line);
1880 if ($from && $to && $line =~ m/^\@{2} /) {
1881 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1882 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1884 $from_lines = 0 unless defined $from_lines;
1885 $to_lines = 0 unless defined $to_lines;
1887 if ($from->{'href'}) {
1888 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1889 -class=>"list"}, $from_text);
1891 if ($to->{'href'}) {
1892 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1893 -class=>"list"}, $to_text);
1895 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1896 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1897 return "<div class=\"diff$diff_class\">$line</div>\n";
1898 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1899 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1900 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1902 @from_text = split(' ', $ranges);
1903 for (my $i = 0; $i < @from_text; ++$i) {
1904 ($from_start[$i], $from_nlines[$i]) =
1905 (split(',', substr($from_text[$i], 1)), 0);
1908 $to_text = pop @from_text;
1909 $to_start = pop @from_start;
1910 $to_nlines = pop @from_nlines;
1912 $line = "<span class=\"chunk_info\">$prefix ";
1913 for (my $i = 0; $i < @from_text; ++$i) {
1914 if ($from->{'href'}[$i]) {
1915 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1916 -class=>"list"}, $from_text[$i]);
1917 } else {
1918 $line .= $from_text[$i];
1920 $line .= " ";
1922 if ($to->{'href'}) {
1923 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1924 -class=>"list"}, $to_text);
1925 } else {
1926 $line .= $to_text;
1928 $line .= " $prefix</span>" .
1929 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1930 return "<div class=\"diff$diff_class\">$line</div>\n";
1932 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1935 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1936 # linked. Pass the hash of the tree/commit to snapshot.
1937 sub format_snapshot_links {
1938 my ($hash) = @_;
1939 my $num_fmts = @snapshot_fmts;
1940 if ($num_fmts > 1) {
1941 # A parenthesized list of links bearing format names.
1942 # e.g. "snapshot (_tar.gz_ _zip_)"
1943 return "snapshot (" . join(' ', map
1944 $cgi->a({
1945 -href => href(
1946 action=>"snapshot",
1947 hash=>$hash,
1948 snapshot_format=>$_
1950 }, $known_snapshot_formats{$_}{'display'})
1951 , @snapshot_fmts) . ")";
1952 } elsif ($num_fmts == 1) {
1953 # A single "snapshot" link whose tooltip bears the format name.
1954 # i.e. "_snapshot_"
1955 my ($fmt) = @snapshot_fmts;
1956 return
1957 $cgi->a({
1958 -href => href(
1959 action=>"snapshot",
1960 hash=>$hash,
1961 snapshot_format=>$fmt
1963 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1964 }, "snapshot");
1965 } else { # $num_fmts == 0
1966 return undef;
1970 ## ......................................................................
1971 ## functions returning values to be passed, perhaps after some
1972 ## transformation, to other functions; e.g. returning arguments to href()
1974 # returns hash to be passed to href to generate gitweb URL
1975 # in -title key it returns description of link
1976 sub get_feed_info {
1977 my $format = shift || 'Atom';
1978 my %res = (action => lc($format));
1980 # feed links are possible only for project views
1981 return unless (defined $project);
1982 # some views should link to OPML, or to generic project feed,
1983 # or don't have specific feed yet (so they should use generic)
1984 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1986 my $branch;
1987 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1988 # from tag links; this also makes possible to detect branch links
1989 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1990 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1991 $branch = $1;
1993 # find log type for feed description (title)
1994 my $type = 'log';
1995 if (defined $file_name) {
1996 $type = "history of $file_name";
1997 $type .= "/" if ($action eq 'tree');
1998 $type .= " on '$branch'" if (defined $branch);
1999 } else {
2000 $type = "log of $branch" if (defined $branch);
2003 $res{-title} = $type;
2004 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2005 $res{'file_name'} = $file_name;
2007 return %res;
2010 ## ----------------------------------------------------------------------
2011 ## git utility subroutines, invoking git commands
2013 # returns path to the core git executable and the --git-dir parameter as list
2014 sub git_cmd {
2015 return $GIT, '--git-dir='.$git_dir;
2018 # quote the given arguments for passing them to the shell
2019 # quote_command("command", "arg 1", "arg with ' and ! characters")
2020 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2021 # Try to avoid using this function wherever possible.
2022 sub quote_command {
2023 return join(' ',
2024 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2027 # get HEAD ref of given project as hash
2028 sub git_get_head_hash {
2029 my $project = shift;
2030 my $o_git_dir = $git_dir;
2031 my $retval = undef;
2032 $git_dir = "$projectroot/$project";
2033 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
2034 my $head = <$fd>;
2035 close $fd;
2036 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
2037 $retval = $1;
2040 if (defined $o_git_dir) {
2041 $git_dir = $o_git_dir;
2043 return $retval;
2046 # get type of given object
2047 sub git_get_type {
2048 my $hash = shift;
2050 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2051 my $type = <$fd>;
2052 close $fd or return;
2053 chomp $type;
2054 return $type;
2057 # repository configuration
2058 our $config_file = '';
2059 our %config;
2061 # store multiple values for single key as anonymous array reference
2062 # single values stored directly in the hash, not as [ <value> ]
2063 sub hash_set_multi {
2064 my ($hash, $key, $value) = @_;
2066 if (!exists $hash->{$key}) {
2067 $hash->{$key} = $value;
2068 } elsif (!ref $hash->{$key}) {
2069 $hash->{$key} = [ $hash->{$key}, $value ];
2070 } else {
2071 push @{$hash->{$key}}, $value;
2075 # return hash of git project configuration
2076 # optionally limited to some section, e.g. 'gitweb'
2077 sub git_parse_project_config {
2078 my $section_regexp = shift;
2079 my %config;
2081 local $/ = "\0";
2083 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2084 or return;
2086 while (my $keyval = <$fh>) {
2087 chomp $keyval;
2088 my ($key, $value) = split(/\n/, $keyval, 2);
2090 hash_set_multi(\%config, $key, $value)
2091 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2093 close $fh;
2095 return %config;
2098 # convert config value to boolean: 'true' or 'false'
2099 # no value, number > 0, 'true' and 'yes' values are true
2100 # rest of values are treated as false (never as error)
2101 sub config_to_bool {
2102 my $val = shift;
2104 return 1 if !defined $val; # section.key
2106 # strip leading and trailing whitespace
2107 $val =~ s/^\s+//;
2108 $val =~ s/\s+$//;
2110 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2111 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2114 # convert config value to simple decimal number
2115 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2116 # to be multiplied by 1024, 1048576, or 1073741824
2117 sub config_to_int {
2118 my $val = shift;
2120 # strip leading and trailing whitespace
2121 $val =~ s/^\s+//;
2122 $val =~ s/\s+$//;
2124 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2125 $unit = lc($unit);
2126 # unknown unit is treated as 1
2127 return $num * ($unit eq 'g' ? 1073741824 :
2128 $unit eq 'm' ? 1048576 :
2129 $unit eq 'k' ? 1024 : 1);
2131 return $val;
2134 # convert config value to array reference, if needed
2135 sub config_to_multi {
2136 my $val = shift;
2138 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2141 sub git_get_project_config {
2142 my ($key, $type) = @_;
2144 # key sanity check
2145 return unless ($key);
2146 $key =~ s/^gitweb\.//;
2147 return if ($key =~ m/\W/);
2149 # type sanity check
2150 if (defined $type) {
2151 $type =~ s/^--//;
2152 $type = undef
2153 unless ($type eq 'bool' || $type eq 'int');
2156 # get config
2157 if (!defined $config_file ||
2158 $config_file ne "$git_dir/config") {
2159 %config = git_parse_project_config('gitweb');
2160 $config_file = "$git_dir/config";
2163 # check if config variable (key) exists
2164 return unless exists $config{"gitweb.$key"};
2166 # ensure given type
2167 if (!defined $type) {
2168 return $config{"gitweb.$key"};
2169 } elsif ($type eq 'bool') {
2170 # backward compatibility: 'git config --bool' returns true/false
2171 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2172 } elsif ($type eq 'int') {
2173 return config_to_int($config{"gitweb.$key"});
2175 return $config{"gitweb.$key"};
2178 # get hash of given path at given ref
2179 sub git_get_hash_by_path {
2180 my $base = shift;
2181 my $path = shift || return undef;
2182 my $type = shift;
2184 $path =~ s,/+$,,;
2186 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2187 or die_error(500, "Open git-ls-tree failed");
2188 my $line = <$fd>;
2189 close $fd or return undef;
2191 if (!defined $line) {
2192 # there is no tree or hash given by $path at $base
2193 return undef;
2196 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2197 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2198 if (defined $type && $type ne $2) {
2199 # type doesn't match
2200 return undef;
2202 return $3;
2205 # get path of entry with given hash at given tree-ish (ref)
2206 # used to get 'from' filename for combined diff (merge commit) for renames
2207 sub git_get_path_by_hash {
2208 my $base = shift || return;
2209 my $hash = shift || return;
2211 local $/ = "\0";
2213 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2214 or return undef;
2215 while (my $line = <$fd>) {
2216 chomp $line;
2218 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2219 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2220 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2221 close $fd;
2222 return $1;
2225 close $fd;
2226 return undef;
2229 ## ......................................................................
2230 ## git utility functions, directly accessing git repository
2232 sub git_get_project_description {
2233 my $path = shift;
2235 $git_dir = "$projectroot/$path";
2236 open my $fd, '<', "$git_dir/description"
2237 or return git_get_project_config('description');
2238 my $descr = <$fd>;
2239 close $fd;
2240 if (defined $descr) {
2241 chomp $descr;
2243 return $descr;
2246 sub git_get_project_ctags {
2247 my $path = shift;
2248 my $ctags = {};
2250 $git_dir = "$projectroot/$path";
2251 opendir my $dh, "$git_dir/ctags"
2252 or return $ctags;
2253 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2254 open my $ct, '<', $_ or next;
2255 my $val = <$ct>;
2256 chomp $val;
2257 close $ct;
2258 my $ctag = $_; $ctag =~ s#.*/##;
2259 $ctags->{$ctag} = $val;
2261 closedir $dh;
2262 $ctags;
2265 sub git_populate_project_tagcloud {
2266 my ($ctags, $action) = @_;
2268 # First, merge different-cased tags; tags vote on casing
2269 my %ctags_lc;
2270 foreach (keys %$ctags) {
2271 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2272 if (not $ctags_lc{lc $_}->{topcount}
2273 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2274 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2275 $ctags_lc{lc $_}->{topname} = $_;
2279 my $cloud;
2280 if (eval { require HTML::TagCloud; 1; }) {
2281 $cloud = HTML::TagCloud->new;
2282 foreach (sort keys %ctags_lc) {
2283 # Pad the title with spaces so that the cloud looks
2284 # less crammed.
2285 my $title = $ctags_lc{$_}->{topname};
2286 $title =~ s/ /&nbsp;/g;
2287 $title =~ s/^/&nbsp;/g;
2288 $title =~ s/$/&nbsp;/g;
2289 $cloud->add($title, href(action=>$action, ctag_filter=>$_),
2290 $ctags_lc{$_}->{count});
2292 } else {
2293 $cloud = \%ctags_lc;
2295 $cloud;
2298 sub git_show_project_tagcloud {
2299 my ($cloud, $count, $action) = @_;
2300 print STDERR ref($cloud)."..\n";
2301 if (ref $cloud eq 'HTML::TagCloud') {
2302 return $cloud->html_and_css($count);
2303 } else {
2304 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2305 return '<p align="center">' . join (', ', map {
2306 $cgi->a({-href => href(action=>$action, ctag_filter=>$_)},
2307 $cloud->{$_}->{topname});
2308 } splice(@tags, 0, $count)) . '</p>';
2312 sub git_get_project_url_list {
2313 my $path = shift;
2315 $git_dir = "$projectroot/$path";
2316 open my $fd, '<', "$git_dir/cloneurl"
2317 or return wantarray ?
2318 @{ config_to_multi(git_get_project_config('url')) } :
2319 config_to_multi(git_get_project_config('url'));
2320 my @git_project_url_list = map { chomp; $_ } <$fd>;
2321 close $fd;
2323 return wantarray ? @git_project_url_list : \@git_project_url_list;
2326 sub git_get_projects_list {
2327 my ($filter) = @_;
2328 my @list;
2330 $filter ||= '';
2331 $filter =~ s/\.git$//;
2333 my $check_forks = gitweb_check_feature('forks');
2335 if (-d $projects_list) {
2336 # search in directory
2337 my $dir = $projects_list . ($filter ? "/$filter" : '');
2338 # remove the trailing "/"
2339 $dir =~ s!/+$!!;
2340 my $pfxlen = length("$dir");
2341 my $pfxdepth = ($dir =~ tr!/!!);
2343 File::Find::find({
2344 follow_fast => 1, # follow symbolic links
2345 follow_skip => 2, # ignore duplicates
2346 dangling_symlinks => 0, # ignore dangling symlinks, silently
2347 wanted => sub {
2348 # skip project-list toplevel, if we get it.
2349 return if (m!^[/.]$!);
2350 # only directories can be git repositories
2351 return unless (-d $_);
2352 # don't traverse too deep (Find is super slow on os x)
2353 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2354 $File::Find::prune = 1;
2355 return;
2358 my $subdir = substr($File::Find::name, $pfxlen + 1);
2359 # we check related file in $projectroot
2360 my $path = ($filter ? "$filter/" : '') . $subdir;
2361 if (check_export_ok("$projectroot/$path")) {
2362 push @list, { path => $path };
2363 $File::Find::prune = 1;
2366 }, "$dir");
2368 } elsif (-f $projects_list) {
2369 # read from file(url-encoded):
2370 # 'git%2Fgit.git Linus+Torvalds'
2371 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2372 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2373 my %paths;
2374 open my $fd, '<', $projects_list or return;
2375 PROJECT:
2376 while (my $line = <$fd>) {
2377 chomp $line;
2378 my ($path, $owner) = split ' ', $line;
2379 $path = unescape($path);
2380 $owner = unescape($owner);
2381 if (!defined $path) {
2382 next;
2384 if ($filter ne '') {
2385 # looking for forks;
2386 my $pfx = substr($path, 0, length($filter));
2387 if ($pfx ne $filter) {
2388 next PROJECT;
2390 my $sfx = substr($path, length($filter));
2391 if ($sfx !~ /^\/.*\.git$/) {
2392 next PROJECT;
2394 } elsif ($check_forks) {
2395 PATH:
2396 foreach my $filter (keys %paths) {
2397 # looking for forks;
2398 my $pfx = substr($path, 0, length($filter));
2399 if ($pfx ne $filter) {
2400 next PATH;
2402 my $sfx = substr($path, length($filter));
2403 if ($sfx !~ /^\/.*\.git$/) {
2404 next PATH;
2406 # is a fork, don't include it in
2407 # the list
2408 next PROJECT;
2411 if (check_export_ok("$projectroot/$path")) {
2412 my $pr = {
2413 path => $path,
2414 owner => to_utf8($owner),
2416 push @list, $pr;
2417 (my $forks_path = $path) =~ s/\.git$//;
2418 $paths{$forks_path}++;
2421 close $fd;
2423 return @list;
2426 our $gitweb_project_owner = undef;
2427 sub git_get_project_list_from_file {
2429 return if (defined $gitweb_project_owner);
2431 $gitweb_project_owner = {};
2432 # read from file (url-encoded):
2433 # 'git%2Fgit.git Linus+Torvalds'
2434 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2435 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2436 if (-f $projects_list) {
2437 open(my $fd, '<', $projects_list);
2438 while (my $line = <$fd>) {
2439 chomp $line;
2440 my ($pr, $ow) = split ' ', $line;
2441 $pr = unescape($pr);
2442 $ow = unescape($ow);
2443 $gitweb_project_owner->{$pr} = to_utf8($ow);
2445 close $fd;
2449 sub git_get_project_owner {
2450 my $project = shift;
2451 my $owner;
2453 return undef unless $project;
2454 $git_dir = "$projectroot/$project";
2456 if (!defined $gitweb_project_owner) {
2457 git_get_project_list_from_file();
2460 if (exists $gitweb_project_owner->{$project}) {
2461 $owner = $gitweb_project_owner->{$project};
2463 if (!defined $owner){
2464 $owner = git_get_project_config('owner');
2466 if (!defined $owner) {
2467 $owner = get_file_owner("$git_dir");
2470 return $owner;
2473 sub git_get_last_activity {
2474 my ($path) = @_;
2475 my $fd;
2477 $git_dir = "$projectroot/$path";
2478 open($fd, "-|", git_cmd(), 'for-each-ref',
2479 '--format=%(committer)',
2480 '--sort=-committerdate',
2481 '--count=1',
2482 'refs/heads') or return;
2483 my $most_recent = <$fd>;
2484 close $fd or return;
2485 if (defined $most_recent &&
2486 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2487 my $timestamp = $1;
2488 my $age = time - $timestamp;
2489 return ($age, age_string($age));
2491 return (undef, undef);
2494 sub git_get_references {
2495 my $type = shift || "";
2496 my %refs;
2497 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2498 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2499 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2500 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2501 or return;
2503 while (my $line = <$fd>) {
2504 chomp $line;
2505 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2506 if (defined $refs{$1}) {
2507 push @{$refs{$1}}, $2;
2508 } else {
2509 $refs{$1} = [ $2 ];
2513 close $fd or return;
2514 return \%refs;
2517 sub git_get_rev_name_tags {
2518 my $hash = shift || return undef;
2520 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2521 or return;
2522 my $name_rev = <$fd>;
2523 close $fd;
2525 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2526 return $1;
2527 } else {
2528 # catches also '$hash undefined' output
2529 return undef;
2533 ## ----------------------------------------------------------------------
2534 ## parse to hash functions
2536 sub parse_date {
2537 my $epoch = shift;
2538 my $tz = shift || "-0000";
2540 my %date;
2541 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2542 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2543 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2544 $date{'hour'} = $hour;
2545 $date{'minute'} = $min;
2546 $date{'mday'} = $mday;
2547 $date{'day'} = $days[$wday];
2548 $date{'month'} = $months[$mon];
2549 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2550 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2551 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2552 $mday, $months[$mon], $hour ,$min;
2553 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2554 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2556 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2557 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2558 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2559 $date{'hour_local'} = $hour;
2560 $date{'minute_local'} = $min;
2561 $date{'tz_local'} = $tz;
2562 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2563 1900+$year, $mon+1, $mday,
2564 $hour, $min, $sec, $tz);
2565 return %date;
2568 sub parse_tag {
2569 my $tag_id = shift;
2570 my %tag;
2571 my @comment;
2573 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2574 $tag{'id'} = $tag_id;
2575 while (my $line = <$fd>) {
2576 chomp $line;
2577 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2578 $tag{'object'} = $1;
2579 } elsif ($line =~ m/^type (.+)$/) {
2580 $tag{'type'} = $1;
2581 } elsif ($line =~ m/^tag (.+)$/) {
2582 $tag{'name'} = $1;
2583 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2584 $tag{'author'} = $1;
2585 $tag{'author_epoch'} = $2;
2586 $tag{'author_tz'} = $3;
2587 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2588 $tag{'author_name'} = $1;
2589 $tag{'author_email'} = $2;
2590 } else {
2591 $tag{'author_name'} = $tag{'author'};
2593 } elsif ($line =~ m/--BEGIN/) {
2594 push @comment, $line;
2595 last;
2596 } elsif ($line eq "") {
2597 last;
2600 push @comment, <$fd>;
2601 $tag{'comment'} = \@comment;
2602 close $fd or return;
2603 if (!defined $tag{'name'}) {
2604 return
2606 return %tag
2609 sub parse_commit_text {
2610 my ($commit_text, $withparents) = @_;
2611 my @commit_lines = split '\n', $commit_text;
2612 my %co;
2614 pop @commit_lines; # Remove '\0'
2616 if (! @commit_lines) {
2617 return;
2620 my $header = shift @commit_lines;
2621 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2622 return;
2624 ($co{'id'}, my @parents) = split ' ', $header;
2625 while (my $line = shift @commit_lines) {
2626 last if $line eq "\n";
2627 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2628 $co{'tree'} = $1;
2629 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2630 push @parents, $1;
2631 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2632 $co{'author'} = to_utf8($1);
2633 $co{'author_epoch'} = $2;
2634 $co{'author_tz'} = $3;
2635 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2636 $co{'author_name'} = $1;
2637 $co{'author_email'} = $2;
2638 } else {
2639 $co{'author_name'} = $co{'author'};
2641 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2642 $co{'committer'} = to_utf8($1);
2643 $co{'committer_epoch'} = $2;
2644 $co{'committer_tz'} = $3;
2645 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2646 $co{'committer_name'} = $1;
2647 $co{'committer_email'} = $2;
2648 } else {
2649 $co{'committer_name'} = $co{'committer'};
2653 if (!defined $co{'tree'}) {
2654 return;
2656 $co{'parents'} = \@parents;
2657 $co{'parent'} = $parents[0];
2659 foreach my $title (@commit_lines) {
2660 $title =~ s/^ //;
2661 if ($title ne "") {
2662 $co{'title'} = chop_str($title, 80, 5);
2663 # remove leading stuff of merges to make the interesting part visible
2664 if (length($title) > 50) {
2665 $title =~ s/^Automatic //;
2666 $title =~ s/^merge (of|with) /Merge ... /i;
2667 if (length($title) > 50) {
2668 $title =~ s/(http|rsync):\/\///;
2670 if (length($title) > 50) {
2671 $title =~ s/(master|www|rsync)\.//;
2673 if (length($title) > 50) {
2674 $title =~ s/kernel.org:?//;
2676 if (length($title) > 50) {
2677 $title =~ s/\/pub\/scm//;
2680 $co{'title_short'} = chop_str($title, 50, 5);
2681 last;
2684 if (! defined $co{'title'} || $co{'title'} eq "") {
2685 $co{'title'} = $co{'title_short'} = '(no commit message)';
2687 # remove added spaces
2688 foreach my $line (@commit_lines) {
2689 $line =~ s/^ //;
2691 $co{'comment'} = \@commit_lines;
2693 my $age = time - $co{'committer_epoch'};
2694 $co{'age'} = $age;
2695 $co{'age_string'} = age_string($age);
2696 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2697 if ($age > 60*60*24*7*2) {
2698 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2699 $co{'age_string_age'} = $co{'age_string'};
2700 } else {
2701 $co{'age_string_date'} = $co{'age_string'};
2702 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2704 return %co;
2707 sub parse_commit {
2708 my ($commit_id) = @_;
2709 my %co;
2711 local $/ = "\0";
2713 open my $fd, "-|", git_cmd(), "rev-list",
2714 "--parents",
2715 "--header",
2716 "--max-count=1",
2717 $commit_id,
2718 "--",
2719 or die_error(500, "Open git-rev-list failed");
2720 %co = parse_commit_text(<$fd>, 1);
2721 close $fd;
2723 return %co;
2726 sub parse_commits {
2727 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2728 my @cos;
2730 $maxcount ||= 1;
2731 $skip ||= 0;
2733 local $/ = "\0";
2735 open my $fd, "-|", git_cmd(), "rev-list",
2736 "--header",
2737 @args,
2738 ("--max-count=" . $maxcount),
2739 ("--skip=" . $skip),
2740 @extra_options,
2741 $commit_id,
2742 "--",
2743 ($filename ? ($filename) : ())
2744 or die_error(500, "Open git-rev-list failed");
2745 while (my $line = <$fd>) {
2746 my %co = parse_commit_text($line);
2747 push @cos, \%co;
2749 close $fd;
2751 return wantarray ? @cos : \@cos;
2754 # parse line of git-diff-tree "raw" output
2755 sub parse_difftree_raw_line {
2756 my $line = shift;
2757 my %res;
2759 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2760 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2761 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2762 $res{'from_mode'} = $1;
2763 $res{'to_mode'} = $2;
2764 $res{'from_id'} = $3;
2765 $res{'to_id'} = $4;
2766 $res{'status'} = $5;
2767 $res{'similarity'} = $6;
2768 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2769 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2770 } else {
2771 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2774 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2775 # combined diff (for merge commit)
2776 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2777 $res{'nparents'} = length($1);
2778 $res{'from_mode'} = [ split(' ', $2) ];
2779 $res{'to_mode'} = pop @{$res{'from_mode'}};
2780 $res{'from_id'} = [ split(' ', $3) ];
2781 $res{'to_id'} = pop @{$res{'from_id'}};
2782 $res{'status'} = [ split('', $4) ];
2783 $res{'to_file'} = unquote($5);
2785 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2786 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2787 $res{'commit'} = $1;
2790 return wantarray ? %res : \%res;
2793 # wrapper: return parsed line of git-diff-tree "raw" output
2794 # (the argument might be raw line, or parsed info)
2795 sub parsed_difftree_line {
2796 my $line_or_ref = shift;
2798 if (ref($line_or_ref) eq "HASH") {
2799 # pre-parsed (or generated by hand)
2800 return $line_or_ref;
2801 } else {
2802 return parse_difftree_raw_line($line_or_ref);
2806 # parse line of git-ls-tree output
2807 sub parse_ls_tree_line {
2808 my $line = shift;
2809 my %opts = @_;
2810 my %res;
2812 if ($opts{'-l'}) {
2813 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
2814 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
2816 $res{'mode'} = $1;
2817 $res{'type'} = $2;
2818 $res{'hash'} = $3;
2819 $res{'size'} = $4;
2820 if ($opts{'-z'}) {
2821 $res{'name'} = $5;
2822 } else {
2823 $res{'name'} = unquote($5);
2825 } else {
2826 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2827 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2829 $res{'mode'} = $1;
2830 $res{'type'} = $2;
2831 $res{'hash'} = $3;
2832 if ($opts{'-z'}) {
2833 $res{'name'} = $4;
2834 } else {
2835 $res{'name'} = unquote($4);
2839 return wantarray ? %res : \%res;
2842 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2843 sub parse_from_to_diffinfo {
2844 my ($diffinfo, $from, $to, @parents) = @_;
2846 if ($diffinfo->{'nparents'}) {
2847 # combined diff
2848 $from->{'file'} = [];
2849 $from->{'href'} = [];
2850 fill_from_file_info($diffinfo, @parents)
2851 unless exists $diffinfo->{'from_file'};
2852 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2853 $from->{'file'}[$i] =
2854 defined $diffinfo->{'from_file'}[$i] ?
2855 $diffinfo->{'from_file'}[$i] :
2856 $diffinfo->{'to_file'};
2857 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2858 $from->{'href'}[$i] = href(action=>"blob",
2859 hash_base=>$parents[$i],
2860 hash=>$diffinfo->{'from_id'}[$i],
2861 file_name=>$from->{'file'}[$i]);
2862 } else {
2863 $from->{'href'}[$i] = undef;
2866 } else {
2867 # ordinary (not combined) diff
2868 $from->{'file'} = $diffinfo->{'from_file'};
2869 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2870 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2871 hash=>$diffinfo->{'from_id'},
2872 file_name=>$from->{'file'});
2873 } else {
2874 delete $from->{'href'};
2878 $to->{'file'} = $diffinfo->{'to_file'};
2879 if (!is_deleted($diffinfo)) { # file exists in result
2880 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2881 hash=>$diffinfo->{'to_id'},
2882 file_name=>$to->{'file'});
2883 } else {
2884 delete $to->{'href'};
2888 ## ......................................................................
2889 ## parse to array of hashes functions
2891 sub git_get_heads_list {
2892 my $limit = shift;
2893 my @headslist;
2895 open my $fd, '-|', git_cmd(), 'for-each-ref',
2896 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2897 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2898 'refs/heads'
2899 or return;
2900 while (my $line = <$fd>) {
2901 my %ref_item;
2903 chomp $line;
2904 my ($refinfo, $committerinfo) = split(/\0/, $line);
2905 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2906 my ($committer, $epoch, $tz) =
2907 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2908 $ref_item{'fullname'} = $name;
2909 $name =~ s!^refs/heads/!!;
2911 $ref_item{'name'} = $name;
2912 $ref_item{'id'} = $hash;
2913 $ref_item{'title'} = $title || '(no commit message)';
2914 $ref_item{'epoch'} = $epoch;
2915 if ($epoch) {
2916 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2917 } else {
2918 $ref_item{'age'} = "unknown";
2921 push @headslist, \%ref_item;
2923 close $fd;
2925 return wantarray ? @headslist : \@headslist;
2928 sub git_get_tags_list {
2929 my $limit = shift;
2930 my @tagslist;
2932 open my $fd, '-|', git_cmd(), 'for-each-ref',
2933 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2934 '--format=%(objectname) %(objecttype) %(refname) '.
2935 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2936 'refs/tags'
2937 or return;
2938 while (my $line = <$fd>) {
2939 my %ref_item;
2941 chomp $line;
2942 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2943 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2944 my ($creator, $epoch, $tz) =
2945 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2946 $ref_item{'fullname'} = $name;
2947 $name =~ s!^refs/tags/!!;
2949 $ref_item{'type'} = $type;
2950 $ref_item{'id'} = $id;
2951 $ref_item{'name'} = $name;
2952 if ($type eq "tag") {
2953 $ref_item{'subject'} = $title;
2954 $ref_item{'reftype'} = $reftype;
2955 $ref_item{'refid'} = $refid;
2956 } else {
2957 $ref_item{'reftype'} = $type;
2958 $ref_item{'refid'} = $id;
2961 if ($type eq "tag" || $type eq "commit") {
2962 $ref_item{'epoch'} = $epoch;
2963 if ($epoch) {
2964 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2965 } else {
2966 $ref_item{'age'} = "unknown";
2970 push @tagslist, \%ref_item;
2972 close $fd;
2974 return wantarray ? @tagslist : \@tagslist;
2977 ## ----------------------------------------------------------------------
2978 ## filesystem-related functions
2980 sub get_file_owner {
2981 my $path = shift;
2983 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2984 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2985 if (!defined $gcos) {
2986 return undef;
2988 my $owner = $gcos;
2989 $owner =~ s/[,;].*$//;
2990 return to_utf8($owner);
2993 # assume that file exists
2994 sub insert_file {
2995 my $filename = shift;
2997 open my $fd, '<', $filename;
2998 print map { to_utf8($_) } <$fd>;
2999 close $fd;
3002 ## ......................................................................
3003 ## mimetype related functions
3005 sub mimetype_guess_file {
3006 my $filename = shift;
3007 my $mimemap = shift;
3008 -r $mimemap or return undef;
3010 my %mimemap;
3011 open(my $mh, '<', $mimemap) or return undef;
3012 while (<$mh>) {
3013 next if m/^#/; # skip comments
3014 my ($mimetype, $exts) = split(/\t+/);
3015 if (defined $exts) {
3016 my @exts = split(/\s+/, $exts);
3017 foreach my $ext (@exts) {
3018 $mimemap{$ext} = $mimetype;
3022 close($mh);
3024 $filename =~ /\.([^.]*)$/;
3025 return $mimemap{$1};
3028 sub mimetype_guess {
3029 my $filename = shift;
3030 my $mime;
3031 $filename =~ /\./ or return undef;
3033 if ($mimetypes_file) {
3034 my $file = $mimetypes_file;
3035 if ($file !~ m!^/!) { # if it is relative path
3036 # it is relative to project
3037 $file = "$projectroot/$project/$file";
3039 $mime = mimetype_guess_file($filename, $file);
3041 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3042 return $mime;
3045 sub blob_mimetype {
3046 my $fd = shift;
3047 my $filename = shift;
3049 if ($filename) {
3050 my $mime = mimetype_guess($filename);
3051 $mime and return $mime;
3054 # just in case
3055 return $default_blob_plain_mimetype unless $fd;
3057 if (-T $fd) {
3058 return 'text/plain';
3059 } elsif (! $filename) {
3060 return 'application/octet-stream';
3061 } elsif ($filename =~ m/\.png$/i) {
3062 return 'image/png';
3063 } elsif ($filename =~ m/\.gif$/i) {
3064 return 'image/gif';
3065 } elsif ($filename =~ m/\.jpe?g$/i) {
3066 return 'image/jpeg';
3067 } else {
3068 return 'application/octet-stream';
3072 sub blob_contenttype {
3073 my ($fd, $file_name, $type) = @_;
3075 $type ||= blob_mimetype($fd, $file_name);
3076 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3077 $type .= "; charset=$default_text_plain_charset";
3080 return $type;
3083 ## ======================================================================
3084 ## functions printing HTML: header, footer, error page
3086 sub git_header_html {
3087 my $status = shift || "200 OK";
3088 my $expires = shift;
3090 my $title = "$site_name";
3091 if (defined $project) {
3092 $title .= " - " . to_utf8($project);
3093 if (defined $action) {
3094 $title .= "/$action";
3095 if (defined $file_name) {
3096 $title .= " - " . esc_path($file_name);
3097 if ($action eq "tree" && $file_name !~ m|/$|) {
3098 $title .= "/";
3103 my $content_type;
3104 # require explicit support from the UA if we are to send the page as
3105 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3106 # we have to do this because MSIE sometimes globs '*/*', pretending to
3107 # support xhtml+xml but choking when it gets what it asked for.
3108 if (defined $cgi->http('HTTP_ACCEPT') &&
3109 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3110 $cgi->Accept('application/xhtml+xml') != 0) {
3111 $content_type = 'application/xhtml+xml';
3112 } else {
3113 $content_type = 'text/html';
3115 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3116 -status=> $status, -expires => $expires);
3117 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3118 print <<EOF;
3119 <?xml version="1.0" encoding="utf-8"?>
3120 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3121 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3122 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3123 <!-- git core binaries version $git_version -->
3124 <head>
3125 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3126 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3127 <meta name="robots" content="index, nofollow"/>
3128 <title>$title</title>
3130 # the stylesheet, favicon etc urls won't work correctly with path_info
3131 # unless we set the appropriate base URL
3132 if ($ENV{'PATH_INFO'}) {
3133 print "<base href=\"".esc_url($base_url)."\" />\n";
3135 # print out each stylesheet that exist, providing backwards capability
3136 # for those people who defined $stylesheet in a config file
3137 if (defined $stylesheet) {
3138 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3139 } else {
3140 foreach my $stylesheet (@stylesheets) {
3141 next unless $stylesheet;
3142 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3145 if (defined $project) {
3146 my %href_params = get_feed_info();
3147 if (!exists $href_params{'-title'}) {
3148 $href_params{'-title'} = 'log';
3151 foreach my $format qw(RSS Atom) {
3152 my $type = lc($format);
3153 my %link_attr = (
3154 '-rel' => 'alternate',
3155 '-title' => "$project - $href_params{'-title'} - $format feed",
3156 '-type' => "application/$type+xml"
3159 $href_params{'action'} = $type;
3160 $link_attr{'-href'} = href(%href_params);
3161 print "<link ".
3162 "rel=\"$link_attr{'-rel'}\" ".
3163 "title=\"$link_attr{'-title'}\" ".
3164 "href=\"$link_attr{'-href'}\" ".
3165 "type=\"$link_attr{'-type'}\" ".
3166 "/>\n";
3168 $href_params{'extra_options'} = '--no-merges';
3169 $link_attr{'-href'} = href(%href_params);
3170 $link_attr{'-title'} .= ' (no merges)';
3171 print "<link ".
3172 "rel=\"$link_attr{'-rel'}\" ".
3173 "title=\"$link_attr{'-title'}\" ".
3174 "href=\"$link_attr{'-href'}\" ".
3175 "type=\"$link_attr{'-type'}\" ".
3176 "/>\n";
3179 } else {
3180 printf('<link rel="alternate" title="%s projects list" '.
3181 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3182 $site_name, href(project=>undef, action=>"project_index"));
3183 printf('<link rel="alternate" title="%s projects feeds" '.
3184 'href="%s" type="text/x-opml" />'."\n",
3185 $site_name, href(project=>undef, action=>"opml"));
3187 if (defined $favicon) {
3188 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3191 print "</head>\n" .
3192 "<body>\n";
3194 if (-f $site_header) {
3195 insert_file($site_header);
3198 print "<div class=\"page_header\">\n" .
3199 $cgi->a({-href => esc_url($logo_url),
3200 -title => $logo_label},
3201 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3202 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3203 if (defined $project) {
3204 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3205 if (defined $action) {
3206 print " / $action";
3208 print "\n";
3210 print "</div>\n";
3212 my $have_search = gitweb_check_feature('search');
3213 if (defined $project && $have_search) {
3214 if (!defined $searchtext) {
3215 $searchtext = "";
3217 my $search_hash;
3218 if (defined $hash_base) {
3219 $search_hash = $hash_base;
3220 } elsif (defined $hash) {
3221 $search_hash = $hash;
3222 } else {
3223 $search_hash = "HEAD";
3225 my $action = $my_uri;
3226 my $use_pathinfo = gitweb_check_feature('pathinfo');
3227 if ($use_pathinfo) {
3228 $action .= "/".esc_url($project);
3230 print $cgi->startform(-method => "get", -action => $action) .
3231 "<div class=\"search\">\n" .
3232 (!$use_pathinfo &&
3233 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3234 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3235 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3236 $cgi->popup_menu(-name => 'st', -default => 'commit',
3237 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3238 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3239 " search:\n",
3240 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3241 "<span title=\"Extended regular expression\">" .
3242 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3243 -checked => $search_use_regexp) .
3244 "</span>" .
3245 "</div>" .
3246 $cgi->end_form() . "\n";
3250 sub git_footer_html {
3251 my $feed_class = 'rss_logo';
3253 print "<div class=\"page_footer\">\n";
3254 if (defined $project) {
3255 my $descr = git_get_project_description($project);
3256 if (defined $descr) {
3257 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3260 my %href_params = get_feed_info();
3261 if (!%href_params) {
3262 $feed_class .= ' generic';
3264 $href_params{'-title'} ||= 'log';
3266 foreach my $format qw(RSS Atom) {
3267 $href_params{'action'} = lc($format);
3268 print $cgi->a({-href => href(%href_params),
3269 -title => "$href_params{'-title'} $format feed",
3270 -class => $feed_class}, $format)."\n";
3273 } else {
3274 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3275 -class => $feed_class}, "OPML") . " ";
3276 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3277 -class => $feed_class}, "TXT") . "\n";
3279 print "</div>\n"; # class="page_footer"
3281 if (-f $site_footer) {
3282 insert_file($site_footer);
3285 print "</body>\n" .
3286 "</html>";
3289 # die_error(<http_status_code>, <error_message>)
3290 # Example: die_error(404, 'Hash not found')
3291 # By convention, use the following status codes (as defined in RFC 2616):
3292 # 400: Invalid or missing CGI parameters, or
3293 # requested object exists but has wrong type.
3294 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3295 # this server or project.
3296 # 404: Requested object/revision/project doesn't exist.
3297 # 500: The server isn't configured properly, or
3298 # an internal error occurred (e.g. failed assertions caused by bugs), or
3299 # an unknown error occurred (e.g. the git binary died unexpectedly).
3300 sub die_error {
3301 my $status = shift || 500;
3302 my $error = shift || "Internal server error";
3304 my %http_responses = (400 => '400 Bad Request',
3305 403 => '403 Forbidden',
3306 404 => '404 Not Found',
3307 500 => '500 Internal Server Error');
3308 git_header_html($http_responses{$status});
3309 print <<EOF;
3310 <div class="page_body">
3311 <br /><br />
3312 $status - $error
3313 <br />
3314 </div>
3316 git_footer_html();
3317 exit;
3320 ## ----------------------------------------------------------------------
3321 ## functions printing or outputting HTML: navigation
3323 sub git_print_page_nav {
3324 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3325 $extra = '' if !defined $extra; # pager or formats
3327 my @navs = qw(summary shortlog log commit commitdiff tree);
3328 if ($suppress) {
3329 @navs = grep { $_ ne $suppress } @navs;
3332 my %arg = map { $_ => {action=>$_} } @navs;
3333 if (defined $head) {
3334 for (qw(commit commitdiff)) {
3335 $arg{$_}{'hash'} = $head;
3337 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3338 for (qw(shortlog log)) {
3339 $arg{$_}{'hash'} = $head;
3344 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3345 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3347 my @actions = gitweb_get_feature('actions');
3348 my %repl = (
3349 '%' => '%',
3350 'n' => $project, # project name
3351 'f' => $git_dir, # project path within filesystem
3352 'h' => $treehead || '', # current hash ('h' parameter)
3353 'b' => $treebase || '', # hash base ('hb' parameter)
3355 while (@actions) {
3356 my ($label, $link, $pos) = splice(@actions,0,3);
3357 # insert
3358 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3359 # munch munch
3360 $link =~ s/%([%nfhb])/$repl{$1}/g;
3361 $arg{$label}{'_href'} = $link;
3364 print "<div class=\"page_nav\">\n" .
3365 (join " | ",
3366 map { $_ eq $current ?
3367 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3368 } @navs);
3369 print "<br/>\n$extra<br/>\n" .
3370 "</div>\n";
3373 sub format_paging_nav {
3374 my ($action, $hash, $head, $page, $has_next_link) = @_;
3375 my $paging_nav;
3378 if ($hash ne $head || $page) {
3379 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3380 } else {
3381 $paging_nav .= "HEAD";
3384 if ($page > 0) {
3385 $paging_nav .= " &sdot; " .
3386 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3387 -accesskey => "p", -title => "Alt-p"}, "prev");
3388 } else {
3389 $paging_nav .= " &sdot; prev";
3392 if ($has_next_link) {
3393 $paging_nav .= " &sdot; " .
3394 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3395 -accesskey => "n", -title => "Alt-n"}, "next");
3396 } else {
3397 $paging_nav .= " &sdot; next";
3400 return $paging_nav;
3403 ## ......................................................................
3404 ## functions printing or outputting HTML: div
3406 sub git_print_header_div {
3407 my ($action, $title, $hash, $hash_base) = @_;
3408 my %args = ();
3410 $args{'action'} = $action;
3411 $args{'hash'} = $hash if $hash;
3412 $args{'hash_base'} = $hash_base if $hash_base;
3414 print "<div class=\"header\">\n" .
3415 $cgi->a({-href => href(%args), -class => "title"},
3416 $title ? $title : $action) .
3417 "\n</div>\n";
3420 sub print_local_time {
3421 my %date = @_;
3422 if ($date{'hour_local'} < 6) {
3423 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3424 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3425 } else {
3426 printf(" (%02d:%02d %s)",
3427 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3431 # Outputs the author name and date in long form
3432 sub git_print_authorship {
3433 my $co = shift;
3434 my %opts = @_;
3435 my $tag = $opts{-tag} || 'div';
3436 my $author = $co->{'author_name'};
3438 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3439 print "<$tag class=\"author_date\">" .
3440 format_search_author($author, "author", esc_html($author)) .
3441 " [$ad{'rfc2822'}";
3442 print_local_time(%ad) if ($opts{-localtime});
3443 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3444 . "</$tag>\n";
3447 # Outputs table rows containing the full author or committer information,
3448 # in the format expected for 'commit' view (& similia).
3449 # Parameters are a commit hash reference, followed by the list of people
3450 # to output information for. If the list is empty it defalts to both
3451 # author and committer.
3452 sub git_print_authorship_rows {
3453 my $co = shift;
3454 # too bad we can't use @people = @_ || ('author', 'committer')
3455 my @people = @_;
3456 @people = ('author', 'committer') unless @people;
3457 foreach my $who (@people) {
3458 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3459 print "<tr><td>$who</td><td>" .
3460 format_search_author($co->{"${who}_name"}, $who,
3461 esc_html($co->{"${who}_name"})) . " " .
3462 format_search_author($co->{"${who}_email"}, $who,
3463 esc_html("<" . $co->{"${who}_email"} . ">")) .
3464 "</td><td rowspan=\"2\">" .
3465 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3466 "</td></tr>\n" .
3467 "<tr>" .
3468 "<td></td><td> $wd{'rfc2822'}";
3469 print_local_time(%wd);
3470 print "</td>" .
3471 "</tr>\n";
3475 sub git_print_page_path {
3476 my $name = shift;
3477 my $type = shift;
3478 my $hb = shift;
3481 print "<div class=\"page_path\">";
3482 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3483 -title => 'tree root'}, to_utf8("[$project]"));
3484 print " / ";
3485 if (defined $name) {
3486 my @dirname = split '/', $name;
3487 my $basename = pop @dirname;
3488 my $fullname = '';
3490 foreach my $dir (@dirname) {
3491 $fullname .= ($fullname ? '/' : '') . $dir;
3492 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3493 hash_base=>$hb),
3494 -title => $fullname}, esc_path($dir));
3495 print " / ";
3497 if (defined $type && $type eq 'blob') {
3498 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3499 hash_base=>$hb),
3500 -title => $name}, esc_path($basename));
3501 } elsif (defined $type && $type eq 'tree') {
3502 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3503 hash_base=>$hb),
3504 -title => $name}, esc_path($basename));
3505 print " / ";
3506 } else {
3507 print esc_path($basename);
3510 print "<br/></div>\n";
3513 sub git_print_log {
3514 my $log = shift;
3515 my %opts = @_;
3517 if ($opts{'-remove_title'}) {
3518 # remove title, i.e. first line of log
3519 shift @$log;
3521 # remove leading empty lines
3522 while (defined $log->[0] && $log->[0] eq "") {
3523 shift @$log;
3526 # print log
3527 my $signoff = 0;
3528 my $empty = 0;
3529 foreach my $line (@$log) {
3530 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3531 $signoff = 1;
3532 $empty = 0;
3533 if (! $opts{'-remove_signoff'}) {
3534 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3535 next;
3536 } else {
3537 # remove signoff lines
3538 next;
3540 } else {
3541 $signoff = 0;
3544 # print only one empty line
3545 # do not print empty line after signoff
3546 if ($line eq "") {
3547 next if ($empty || $signoff);
3548 $empty = 1;
3549 } else {
3550 $empty = 0;
3553 print format_log_line_html($line) . "<br/>\n";
3556 if ($opts{'-final_empty_line'}) {
3557 # end with single empty line
3558 print "<br/>\n" unless $empty;
3562 # return link target (what link points to)
3563 sub git_get_link_target {
3564 my $hash = shift;
3565 my $link_target;
3567 # read link
3568 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3569 or return;
3571 local $/ = undef;
3572 $link_target = <$fd>;
3574 close $fd
3575 or return;
3577 return $link_target;
3580 # given link target, and the directory (basedir) the link is in,
3581 # return target of link relative to top directory (top tree);
3582 # return undef if it is not possible (including absolute links).
3583 sub normalize_link_target {
3584 my ($link_target, $basedir) = @_;
3586 # absolute symlinks (beginning with '/') cannot be normalized
3587 return if (substr($link_target, 0, 1) eq '/');
3589 # normalize link target to path from top (root) tree (dir)
3590 my $path;
3591 if ($basedir) {
3592 $path = $basedir . '/' . $link_target;
3593 } else {
3594 # we are in top (root) tree (dir)
3595 $path = $link_target;
3598 # remove //, /./, and /../
3599 my @path_parts;
3600 foreach my $part (split('/', $path)) {
3601 # discard '.' and ''
3602 next if (!$part || $part eq '.');
3603 # handle '..'
3604 if ($part eq '..') {
3605 if (@path_parts) {
3606 pop @path_parts;
3607 } else {
3608 # link leads outside repository (outside top dir)
3609 return;
3611 } else {
3612 push @path_parts, $part;
3615 $path = join('/', @path_parts);
3617 return $path;
3620 # print tree entry (row of git_tree), but without encompassing <tr> element
3621 sub git_print_tree_entry {
3622 my ($t, $basedir, $hash_base, $have_blame) = @_;
3624 my %base_key = ();
3625 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3627 # The format of a table row is: mode list link. Where mode is
3628 # the mode of the entry, list is the name of the entry, an href,
3629 # and link is the action links of the entry.
3631 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3632 if (exists $t->{'size'}) {
3633 print "<td class=\"size\">$t->{'size'}</td>\n";
3635 if ($t->{'type'} eq "blob") {
3636 print "<td class=\"list\">" .
3637 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3638 file_name=>"$basedir$t->{'name'}", %base_key),
3639 -class => "list"}, esc_path($t->{'name'}));
3640 if (S_ISLNK(oct $t->{'mode'})) {
3641 my $link_target = git_get_link_target($t->{'hash'});
3642 if ($link_target) {
3643 my $norm_target = normalize_link_target($link_target, $basedir);
3644 if (defined $norm_target) {
3645 print " -> " .
3646 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3647 file_name=>$norm_target),
3648 -title => $norm_target}, esc_path($link_target));
3649 } else {
3650 print " -> " . esc_path($link_target);
3654 print "</td>\n";
3655 print "<td class=\"link\">";
3656 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3657 file_name=>"$basedir$t->{'name'}", %base_key)},
3658 "blob");
3659 if ($have_blame) {
3660 print " | " .
3661 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3662 file_name=>"$basedir$t->{'name'}", %base_key)},
3663 "blame");
3665 if (defined $hash_base) {
3666 print " | " .
3667 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3668 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3669 "history");
3671 print " | " .
3672 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3673 file_name=>"$basedir$t->{'name'}")},
3674 "raw");
3675 print "</td>\n";
3677 } elsif ($t->{'type'} eq "tree") {
3678 print "<td class=\"list\">";
3679 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3680 file_name=>"$basedir$t->{'name'}",
3681 %base_key)},
3682 esc_path($t->{'name'}));
3683 print "</td>\n";
3684 print "<td class=\"link\">";
3685 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3686 file_name=>"$basedir$t->{'name'}",
3687 %base_key)},
3688 "tree");
3689 if (defined $hash_base) {
3690 print " | " .
3691 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3692 file_name=>"$basedir$t->{'name'}")},
3693 "history");
3695 print "</td>\n";
3696 } else {
3697 # unknown object: we can only present history for it
3698 # (this includes 'commit' object, i.e. submodule support)
3699 print "<td class=\"list\">" .
3700 esc_path($t->{'name'}) .
3701 "</td>\n";
3702 print "<td class=\"link\">";
3703 if (defined $hash_base) {
3704 print $cgi->a({-href => href(action=>"history",
3705 hash_base=>$hash_base,
3706 file_name=>"$basedir$t->{'name'}")},
3707 "history");
3709 print "</td>\n";
3713 ## ......................................................................
3714 ## functions printing large fragments of HTML
3716 # get pre-image filenames for merge (combined) diff
3717 sub fill_from_file_info {
3718 my ($diff, @parents) = @_;
3720 $diff->{'from_file'} = [ ];
3721 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3722 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3723 if ($diff->{'status'}[$i] eq 'R' ||
3724 $diff->{'status'}[$i] eq 'C') {
3725 $diff->{'from_file'}[$i] =
3726 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3730 return $diff;
3733 # is current raw difftree line of file deletion
3734 sub is_deleted {
3735 my $diffinfo = shift;
3737 return $diffinfo->{'to_id'} eq ('0' x 40);
3740 # does patch correspond to [previous] difftree raw line
3741 # $diffinfo - hashref of parsed raw diff format
3742 # $patchinfo - hashref of parsed patch diff format
3743 # (the same keys as in $diffinfo)
3744 sub is_patch_split {
3745 my ($diffinfo, $patchinfo) = @_;
3747 return defined $diffinfo && defined $patchinfo
3748 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3752 sub git_difftree_body {
3753 my ($difftree, $hash, @parents) = @_;
3754 my ($parent) = $parents[0];
3755 my $have_blame = gitweb_check_feature('blame');
3756 print "<div class=\"list_head\">\n";
3757 if ($#{$difftree} > 10) {
3758 print(($#{$difftree} + 1) . " files changed:\n");
3760 print "</div>\n";
3762 print "<table class=\"" .
3763 (@parents > 1 ? "combined " : "") .
3764 "diff_tree\">\n";
3766 # header only for combined diff in 'commitdiff' view
3767 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3768 if ($has_header) {
3769 # table header
3770 print "<thead><tr>\n" .
3771 "<th></th><th></th>\n"; # filename, patchN link
3772 for (my $i = 0; $i < @parents; $i++) {
3773 my $par = $parents[$i];
3774 print "<th>" .
3775 $cgi->a({-href => href(action=>"commitdiff",
3776 hash=>$hash, hash_parent=>$par),
3777 -title => 'commitdiff to parent number ' .
3778 ($i+1) . ': ' . substr($par,0,7)},
3779 $i+1) .
3780 "&nbsp;</th>\n";
3782 print "</tr></thead>\n<tbody>\n";
3785 my $alternate = 1;
3786 my $patchno = 0;
3787 foreach my $line (@{$difftree}) {
3788 my $diff = parsed_difftree_line($line);
3790 if ($alternate) {
3791 print "<tr class=\"dark\">\n";
3792 } else {
3793 print "<tr class=\"light\">\n";
3795 $alternate ^= 1;
3797 if (exists $diff->{'nparents'}) { # combined diff
3799 fill_from_file_info($diff, @parents)
3800 unless exists $diff->{'from_file'};
3802 if (!is_deleted($diff)) {
3803 # file exists in the result (child) commit
3804 print "<td>" .
3805 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3806 file_name=>$diff->{'to_file'},
3807 hash_base=>$hash),
3808 -class => "list"}, esc_path($diff->{'to_file'})) .
3809 "</td>\n";
3810 } else {
3811 print "<td>" .
3812 esc_path($diff->{'to_file'}) .
3813 "</td>\n";
3816 if ($action eq 'commitdiff') {
3817 # link to patch
3818 $patchno++;
3819 print "<td class=\"link\">" .
3820 $cgi->a({-href => "#patch$patchno"}, "patch") .
3821 " | " .
3822 "</td>\n";
3825 my $has_history = 0;
3826 my $not_deleted = 0;
3827 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3828 my $hash_parent = $parents[$i];
3829 my $from_hash = $diff->{'from_id'}[$i];
3830 my $from_path = $diff->{'from_file'}[$i];
3831 my $status = $diff->{'status'}[$i];
3833 $has_history ||= ($status ne 'A');
3834 $not_deleted ||= ($status ne 'D');
3836 if ($status eq 'A') {
3837 print "<td class=\"link\" align=\"right\"> | </td>\n";
3838 } elsif ($status eq 'D') {
3839 print "<td class=\"link\">" .
3840 $cgi->a({-href => href(action=>"blob",
3841 hash_base=>$hash,
3842 hash=>$from_hash,
3843 file_name=>$from_path)},
3844 "blob" . ($i+1)) .
3845 " | </td>\n";
3846 } else {
3847 if ($diff->{'to_id'} eq $from_hash) {
3848 print "<td class=\"link nochange\">";
3849 } else {
3850 print "<td class=\"link\">";
3852 print $cgi->a({-href => href(action=>"blobdiff",
3853 hash=>$diff->{'to_id'},
3854 hash_parent=>$from_hash,
3855 hash_base=>$hash,
3856 hash_parent_base=>$hash_parent,
3857 file_name=>$diff->{'to_file'},
3858 file_parent=>$from_path)},
3859 "diff" . ($i+1)) .
3860 " | </td>\n";
3864 print "<td class=\"link\">";
3865 if ($not_deleted) {
3866 print $cgi->a({-href => href(action=>"blob",
3867 hash=>$diff->{'to_id'},
3868 file_name=>$diff->{'to_file'},
3869 hash_base=>$hash)},
3870 "blob");
3871 print " | " if ($has_history);
3873 if ($has_history) {
3874 print $cgi->a({-href => href(action=>"history",
3875 file_name=>$diff->{'to_file'},
3876 hash_base=>$hash)},
3877 "history");
3879 print "</td>\n";
3881 print "</tr>\n";
3882 next; # instead of 'else' clause, to avoid extra indent
3884 # else ordinary diff
3886 my ($to_mode_oct, $to_mode_str, $to_file_type);
3887 my ($from_mode_oct, $from_mode_str, $from_file_type);
3888 if ($diff->{'to_mode'} ne ('0' x 6)) {
3889 $to_mode_oct = oct $diff->{'to_mode'};
3890 if (S_ISREG($to_mode_oct)) { # only for regular file
3891 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3893 $to_file_type = file_type($diff->{'to_mode'});
3895 if ($diff->{'from_mode'} ne ('0' x 6)) {
3896 $from_mode_oct = oct $diff->{'from_mode'};
3897 if (S_ISREG($to_mode_oct)) { # only for regular file
3898 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3900 $from_file_type = file_type($diff->{'from_mode'});
3903 if ($diff->{'status'} eq "A") { # created
3904 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3905 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3906 $mode_chng .= "]</span>";
3907 print "<td>";
3908 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3909 hash_base=>$hash, file_name=>$diff->{'file'}),
3910 -class => "list"}, esc_path($diff->{'file'}));
3911 print "</td>\n";
3912 print "<td>$mode_chng</td>\n";
3913 print "<td class=\"link\">";
3914 if ($action eq 'commitdiff') {
3915 # link to patch
3916 $patchno++;
3917 print $cgi->a({-href => "#patch$patchno"}, "patch");
3918 print " | ";
3920 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3921 hash_base=>$hash, file_name=>$diff->{'file'})},
3922 "blob");
3923 print "</td>\n";
3925 } elsif ($diff->{'status'} eq "D") { # deleted
3926 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3927 print "<td>";
3928 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3929 hash_base=>$parent, file_name=>$diff->{'file'}),
3930 -class => "list"}, esc_path($diff->{'file'}));
3931 print "</td>\n";
3932 print "<td>$mode_chng</td>\n";
3933 print "<td class=\"link\">";
3934 if ($action eq 'commitdiff') {
3935 # link to patch
3936 $patchno++;
3937 print $cgi->a({-href => "#patch$patchno"}, "patch");
3938 print " | ";
3940 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3941 hash_base=>$parent, file_name=>$diff->{'file'})},
3942 "blob") . " | ";
3943 if ($have_blame) {
3944 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3945 file_name=>$diff->{'file'})},
3946 "blame") . " | ";
3948 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3949 file_name=>$diff->{'file'})},
3950 "history");
3951 print "</td>\n";
3953 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3954 my $mode_chnge = "";
3955 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3956 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3957 if ($from_file_type ne $to_file_type) {
3958 $mode_chnge .= " from $from_file_type to $to_file_type";
3960 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3961 if ($from_mode_str && $to_mode_str) {
3962 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3963 } elsif ($to_mode_str) {
3964 $mode_chnge .= " mode: $to_mode_str";
3967 $mode_chnge .= "]</span>\n";
3969 print "<td>";
3970 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3971 hash_base=>$hash, file_name=>$diff->{'file'}),
3972 -class => "list"}, esc_path($diff->{'file'}));
3973 print "</td>\n";
3974 print "<td>$mode_chnge</td>\n";
3975 print "<td class=\"link\">";
3976 if ($action eq 'commitdiff') {
3977 # link to patch
3978 $patchno++;
3979 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3980 " | ";
3981 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3982 # "commit" view and modified file (not onlu mode changed)
3983 print $cgi->a({-href => href(action=>"blobdiff",
3984 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3985 hash_base=>$hash, hash_parent_base=>$parent,
3986 file_name=>$diff->{'file'})},
3987 "diff") .
3988 " | ";
3990 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3991 hash_base=>$hash, file_name=>$diff->{'file'})},
3992 "blob") . " | ";
3993 if ($have_blame) {
3994 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3995 file_name=>$diff->{'file'})},
3996 "blame") . " | ";
3998 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3999 file_name=>$diff->{'file'})},
4000 "history");
4001 print "</td>\n";
4003 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4004 my %status_name = ('R' => 'moved', 'C' => 'copied');
4005 my $nstatus = $status_name{$diff->{'status'}};
4006 my $mode_chng = "";
4007 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4008 # mode also for directories, so we cannot use $to_mode_str
4009 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4011 print "<td>" .
4012 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4013 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4014 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4015 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4016 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4017 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4018 -class => "list"}, esc_path($diff->{'from_file'})) .
4019 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4020 "<td class=\"link\">";
4021 if ($action eq 'commitdiff') {
4022 # link to patch
4023 $patchno++;
4024 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4025 " | ";
4026 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4027 # "commit" view and modified file (not only pure rename or copy)
4028 print $cgi->a({-href => href(action=>"blobdiff",
4029 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4030 hash_base=>$hash, hash_parent_base=>$parent,
4031 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4032 "diff") .
4033 " | ";
4035 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4036 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4037 "blob") . " | ";
4038 if ($have_blame) {
4039 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4040 file_name=>$diff->{'to_file'})},
4041 "blame") . " | ";
4043 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4044 file_name=>$diff->{'to_file'})},
4045 "history");
4046 print "</td>\n";
4048 } # we should not encounter Unmerged (U) or Unknown (X) status
4049 print "</tr>\n";
4051 print "</tbody>" if $has_header;
4052 print "</table>\n";
4055 sub git_patchset_body {
4056 my ($fd, $difftree, $hash, @hash_parents) = @_;
4057 my ($hash_parent) = $hash_parents[0];
4059 my $is_combined = (@hash_parents > 1);
4060 my $patch_idx = 0;
4061 my $patch_number = 0;
4062 my $patch_line;
4063 my $diffinfo;
4064 my $to_name;
4065 my (%from, %to);
4067 print "<div class=\"patchset\">\n";
4069 # skip to first patch
4070 while ($patch_line = <$fd>) {
4071 chomp $patch_line;
4073 last if ($patch_line =~ m/^diff /);
4076 PATCH:
4077 while ($patch_line) {
4079 # parse "git diff" header line
4080 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4081 # $1 is from_name, which we do not use
4082 $to_name = unquote($2);
4083 $to_name =~ s!^b/!!;
4084 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4085 # $1 is 'cc' or 'combined', which we do not use
4086 $to_name = unquote($2);
4087 } else {
4088 $to_name = undef;
4091 # check if current patch belong to current raw line
4092 # and parse raw git-diff line if needed
4093 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4094 # this is continuation of a split patch
4095 print "<div class=\"patch cont\">\n";
4096 } else {
4097 # advance raw git-diff output if needed
4098 $patch_idx++ if defined $diffinfo;
4100 # read and prepare patch information
4101 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4103 # compact combined diff output can have some patches skipped
4104 # find which patch (using pathname of result) we are at now;
4105 if ($is_combined) {
4106 while ($to_name ne $diffinfo->{'to_file'}) {
4107 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4108 format_diff_cc_simplified($diffinfo, @hash_parents) .
4109 "</div>\n"; # class="patch"
4111 $patch_idx++;
4112 $patch_number++;
4114 last if $patch_idx > $#$difftree;
4115 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4119 # modifies %from, %to hashes
4120 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4122 # this is first patch for raw difftree line with $patch_idx index
4123 # we index @$difftree array from 0, but number patches from 1
4124 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4127 # git diff header
4128 #assert($patch_line =~ m/^diff /) if DEBUG;
4129 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4130 $patch_number++;
4131 # print "git diff" header
4132 print format_git_diff_header_line($patch_line, $diffinfo,
4133 \%from, \%to);
4135 # print extended diff header
4136 print "<div class=\"diff extended_header\">\n";
4137 EXTENDED_HEADER:
4138 while ($patch_line = <$fd>) {
4139 chomp $patch_line;
4141 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4143 print format_extended_diff_header_line($patch_line, $diffinfo,
4144 \%from, \%to);
4146 print "</div>\n"; # class="diff extended_header"
4148 # from-file/to-file diff header
4149 if (! $patch_line) {
4150 print "</div>\n"; # class="patch"
4151 last PATCH;
4153 next PATCH if ($patch_line =~ m/^diff /);
4154 #assert($patch_line =~ m/^---/) if DEBUG;
4156 my $last_patch_line = $patch_line;
4157 $patch_line = <$fd>;
4158 chomp $patch_line;
4159 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4161 print format_diff_from_to_header($last_patch_line, $patch_line,
4162 $diffinfo, \%from, \%to,
4163 @hash_parents);
4165 # the patch itself
4166 LINE:
4167 while ($patch_line = <$fd>) {
4168 chomp $patch_line;
4170 next PATCH if ($patch_line =~ m/^diff /);
4172 print format_diff_line($patch_line, \%from, \%to);
4175 } continue {
4176 print "</div>\n"; # class="patch"
4179 # for compact combined (--cc) format, with chunk and patch simpliciaction
4180 # patchset might be empty, but there might be unprocessed raw lines
4181 for (++$patch_idx if $patch_number > 0;
4182 $patch_idx < @$difftree;
4183 ++$patch_idx) {
4184 # read and prepare patch information
4185 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4187 # generate anchor for "patch" links in difftree / whatchanged part
4188 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4189 format_diff_cc_simplified($diffinfo, @hash_parents) .
4190 "</div>\n"; # class="patch"
4192 $patch_number++;
4195 if ($patch_number == 0) {
4196 if (@hash_parents > 1) {
4197 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4198 } else {
4199 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4203 print "</div>\n"; # class="patchset"
4206 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4208 # fills project list info (age, description, owner, forks) for each
4209 # project in the list, removing invalid projects from returned list
4210 # NOTE: modifies $projlist, but does not remove entries from it
4211 sub fill_project_list_info {
4212 my ($projlist, $check_forks, $show_ctags) = @_;
4213 my @projects;
4215 PROJECT:
4216 foreach my $pr (@$projlist) {
4217 my (@activity) = git_get_last_activity($pr->{'path'});
4218 unless (@activity) {
4219 next PROJECT;
4221 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4222 if (!defined $pr->{'descr'}) {
4223 my $descr = git_get_project_description($pr->{'path'}) || "";
4224 $descr = to_utf8($descr);
4225 $pr->{'descr_long'} = $descr;
4226 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4228 if (!defined $pr->{'owner'}) {
4229 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4231 if ($check_forks) {
4232 my $pname = $pr->{'path'};
4233 if (($pname =~ s/\.git$//) &&
4234 ($pname !~ /\/$/) &&
4235 (-d "$projectroot/$pname")) {
4236 $pr->{'forks'} = "-d $projectroot/$pname";
4237 } else {
4238 $pr->{'forks'} = 0;
4241 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4242 push @projects, $pr;
4245 return @projects;
4248 # print 'sort by' <th> element, generating 'sort by $name' replay link
4249 # if that order is not selected
4250 sub print_sort_th {
4251 my ($name, $order, $header) = @_;
4252 $header ||= ucfirst($name);
4254 if ($order eq $name) {
4255 print "<th>$header</th>\n";
4256 } else {
4257 print "<th>" .
4258 $cgi->a({-href => href(-replay=>1, order=>$name),
4259 -class => "header"}, $header) .
4260 "</th>\n";
4264 sub git_project_list_ctags {
4265 my ($projects, $action) = @_;
4266 $action ||= 'project_list';
4268 my %ctags;
4269 foreach my $p (@$projects) {
4270 foreach my $ct (keys %{$p->{'ctags'}}) {
4271 $ctags{$ct} += $p->{'ctags'}->{$ct};
4274 my $cloud = git_populate_project_tagcloud(\%ctags, $action);
4275 print git_show_project_tagcloud($cloud, 64, $action);
4278 sub git_project_list_body {
4279 # actually uses global variable $project
4280 my ($projlist, $order, $from, $to, $extra, $no_header, $ctags_action) = @_;
4282 my $check_forks = gitweb_check_feature('forks');
4283 my $show_ctags = gitweb_check_feature('ctags');
4284 my @projects = fill_project_list_info($projlist, $check_forks, $show_ctags);
4286 $order ||= $default_projects_order;
4287 $from = 0 unless defined $from;
4288 $to = $#projects if (!defined $to || $#projects < $to);
4290 my %order_info = (
4291 project => { key => 'path', type => 'str' },
4292 descr => { key => 'descr_long', type => 'str' },
4293 owner => { key => 'owner', type => 'str' },
4294 age => { key => 'age', type => 'num' }
4296 my $oi = $order_info{$order};
4297 if ($oi->{'type'} eq 'str') {
4298 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4299 } else {
4300 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4303 if ($show_ctags) {
4304 git_project_list_ctags(\@projects, $ctags_action);
4307 print "<table class=\"project_list\">\n";
4308 unless ($no_header) {
4309 print "<tr>\n";
4310 if ($check_forks) {
4311 print "<th></th>\n";
4313 print_sort_th('project', $order, 'Project');
4314 print_sort_th('descr', $order, 'Description');
4315 print_sort_th('owner', $order, 'Owner');
4316 print_sort_th('age', $order, 'Last Change');
4317 print "<th></th>\n" . # for links
4318 "</tr>\n";
4320 my $alternate = 1;
4321 my $tagfilter = $input_params{'ctag_filter'};
4322 for (my $i = $from; $i <= $to; $i++) {
4323 my $pr = $projects[$i];
4325 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4326 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4327 and not $pr->{'descr_long'} =~ /$searchtext/;
4328 # Weed out forks or non-matching entries of search
4329 if ($check_forks) {
4330 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4331 $forkbase="^$forkbase" if $forkbase;
4332 next if not $searchtext and not $tagfilter and $show_ctags
4333 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4336 if ($alternate) {
4337 print "<tr class=\"dark\">\n";
4338 } else {
4339 print "<tr class=\"light\">\n";
4341 $alternate ^= 1;
4342 if ($check_forks) {
4343 print "<td>";
4344 if ($pr->{'forks'}) {
4345 print "<!-- $pr->{'forks'} -->\n";
4346 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4348 print "</td>\n";
4350 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4351 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4352 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4353 -class => "list", -title => $pr->{'descr_long'}},
4354 esc_html($pr->{'descr'})) . "</td>\n" .
4355 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4356 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4357 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4358 "<td class=\"link\">" .
4359 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4360 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4361 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4362 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4363 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4364 "</td>\n" .
4365 "</tr>\n";
4367 if (defined $extra) {
4368 print "<tr>\n";
4369 if ($check_forks) {
4370 print "<td></td>\n";
4372 print "<td colspan=\"5\">$extra</td>\n" .
4373 "</tr>\n";
4375 print "</table>\n";
4378 sub git_project_search_form {
4379 print $cgi->startform(-method => "get") .
4380 "<p class=\"projsearch\">Search:\n" .
4381 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4382 "</p>" .
4383 $cgi->end_form() . "\n";
4386 sub git_project_list_all {
4387 my $order = $input_params{'order'};
4388 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4389 die_error(400, "Unknown order parameter");
4392 my @list = git_get_projects_list();
4393 if (!@list) {
4394 die_error(404, "No projects found");
4397 git_project_list_body(\@list, $order);
4400 sub git_shortlog_body {
4401 # uses global variable $project
4402 my ($commitlist, $from, $to, $refs, $extra) = @_;
4404 $from = 0 unless defined $from;
4405 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4407 print "<table class=\"shortlog\">\n";
4408 my $alternate = 1;
4409 for (my $i = $from; $i <= $to; $i++) {
4410 my %co = %{$commitlist->[$i]};
4411 my $commit = $co{'id'};
4412 my $ref = format_ref_marker($refs, $commit);
4413 if ($alternate) {
4414 print "<tr class=\"dark\">\n";
4415 } else {
4416 print "<tr class=\"light\">\n";
4418 $alternate ^= 1;
4419 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4420 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4421 format_author_html('td', \%co, 10) . "<td>";
4422 print format_subject_html($co{'title'}, $co{'title_short'},
4423 href(action=>"commit", hash=>$commit), $ref);
4424 print "</td>\n" .
4425 "<td class=\"link\">" .
4426 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4427 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4428 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4429 my $snapshot_links = format_snapshot_links($commit);
4430 if (defined $snapshot_links) {
4431 print " | " . $snapshot_links;
4433 print "</td>\n" .
4434 "</tr>\n";
4436 if (defined $extra) {
4437 print "<tr>\n" .
4438 "<td colspan=\"4\">$extra</td>\n" .
4439 "</tr>\n";
4441 print "</table>\n";
4444 sub git_history_body {
4445 # Warning: assumes constant type (blob or tree) during history
4446 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4448 $from = 0 unless defined $from;
4449 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4451 print "<table class=\"history\">\n";
4452 my $alternate = 1;
4453 for (my $i = $from; $i <= $to; $i++) {
4454 my %co = %{$commitlist->[$i]};
4455 if (!%co) {
4456 next;
4458 my $commit = $co{'id'};
4460 my $ref = format_ref_marker($refs, $commit);
4462 if ($alternate) {
4463 print "<tr class=\"dark\">\n";
4464 } else {
4465 print "<tr class=\"light\">\n";
4467 $alternate ^= 1;
4468 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4469 # shortlog: format_author_html('td', \%co, 10)
4470 format_author_html('td', \%co, 15, 3) . "<td>";
4471 # originally git_history used chop_str($co{'title'}, 50)
4472 print format_subject_html($co{'title'}, $co{'title_short'},
4473 href(action=>"commit", hash=>$commit), $ref);
4474 print "</td>\n" .
4475 "<td class=\"link\">" .
4476 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4477 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4479 if ($ftype eq 'blob') {
4480 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4481 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4482 if (defined $blob_current && defined $blob_parent &&
4483 $blob_current ne $blob_parent) {
4484 print " | " .
4485 $cgi->a({-href => href(action=>"blobdiff",
4486 hash=>$blob_current, hash_parent=>$blob_parent,
4487 hash_base=>$hash_base, hash_parent_base=>$commit,
4488 file_name=>$file_name)},
4489 "diff to current");
4492 print "</td>\n" .
4493 "</tr>\n";
4495 if (defined $extra) {
4496 print "<tr>\n" .
4497 "<td colspan=\"4\">$extra</td>\n" .
4498 "</tr>\n";
4500 print "</table>\n";
4503 sub git_tags_body {
4504 # uses global variable $project
4505 my ($taglist, $from, $to, $extra) = @_;
4506 $from = 0 unless defined $from;
4507 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4509 print "<table class=\"tags\">\n";
4510 my $alternate = 1;
4511 for (my $i = $from; $i <= $to; $i++) {
4512 my $entry = $taglist->[$i];
4513 my %tag = %$entry;
4514 my $comment = $tag{'subject'};
4515 my $comment_short;
4516 if (defined $comment) {
4517 $comment_short = chop_str($comment, 30, 5);
4519 if ($alternate) {
4520 print "<tr class=\"dark\">\n";
4521 } else {
4522 print "<tr class=\"light\">\n";
4524 $alternate ^= 1;
4525 if (defined $tag{'age'}) {
4526 print "<td><i>$tag{'age'}</i></td>\n";
4527 } else {
4528 print "<td></td>\n";
4530 print "<td>" .
4531 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4532 -class => "list name"}, esc_html($tag{'name'})) .
4533 "</td>\n" .
4534 "<td>";
4535 if (defined $comment) {
4536 print format_subject_html($comment, $comment_short,
4537 href(action=>"tag", hash=>$tag{'id'}));
4539 print "</td>\n" .
4540 "<td class=\"selflink\">";
4541 if ($tag{'type'} eq "tag") {
4542 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4543 } else {
4544 print "&nbsp;";
4546 print "</td>\n" .
4547 "<td class=\"link\">" . " | " .
4548 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4549 if ($tag{'reftype'} eq "commit") {
4550 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4551 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4552 } elsif ($tag{'reftype'} eq "blob") {
4553 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4555 print "</td>\n" .
4556 "</tr>";
4558 if (defined $extra) {
4559 print "<tr>\n" .
4560 "<td colspan=\"5\">$extra</td>\n" .
4561 "</tr>\n";
4563 print "</table>\n";
4566 sub git_heads_body {
4567 # uses global variable $project
4568 my ($headlist, $head, $from, $to, $extra) = @_;
4569 $from = 0 unless defined $from;
4570 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4572 print "<table class=\"heads\">\n";
4573 my $alternate = 1;
4574 for (my $i = $from; $i <= $to; $i++) {
4575 my $entry = $headlist->[$i];
4576 my %ref = %$entry;
4577 my $curr = $ref{'id'} eq $head;
4578 if ($alternate) {
4579 print "<tr class=\"dark\">\n";
4580 } else {
4581 print "<tr class=\"light\">\n";
4583 $alternate ^= 1;
4584 print "<td><i>$ref{'age'}</i></td>\n" .
4585 ($curr ? "<td class=\"current_head\">" : "<td>") .
4586 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4587 -class => "list name"},esc_html($ref{'name'})) .
4588 "</td>\n" .
4589 "<td class=\"link\">" .
4590 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4591 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4592 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4593 "</td>\n" .
4594 "</tr>";
4596 if (defined $extra) {
4597 print "<tr>\n" .
4598 "<td colspan=\"3\">$extra</td>\n" .
4599 "</tr>\n";
4601 print "</table>\n";
4604 sub git_search_grep_body {
4605 my ($commitlist, $from, $to, $extra) = @_;
4606 $from = 0 unless defined $from;
4607 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4609 print "<table class=\"commit_search\">\n";
4610 my $alternate = 1;
4611 for (my $i = $from; $i <= $to; $i++) {
4612 my %co = %{$commitlist->[$i]};
4613 if (!%co) {
4614 next;
4616 my $commit = $co{'id'};
4617 if ($alternate) {
4618 print "<tr class=\"dark\">\n";
4619 } else {
4620 print "<tr class=\"light\">\n";
4622 $alternate ^= 1;
4623 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4624 format_author_html('td', \%co, 15, 5) .
4625 "<td>" .
4626 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4627 -class => "list subject"},
4628 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4629 my $comment = $co{'comment'};
4630 foreach my $line (@$comment) {
4631 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4632 my ($lead, $match, $trail) = ($1, $2, $3);
4633 $match = chop_str($match, 70, 5, 'center');
4634 my $contextlen = int((80 - length($match))/2);
4635 $contextlen = 30 if ($contextlen > 30);
4636 $lead = chop_str($lead, $contextlen, 10, 'left');
4637 $trail = chop_str($trail, $contextlen, 10, 'right');
4639 $lead = esc_html($lead);
4640 $match = esc_html($match);
4641 $trail = esc_html($trail);
4643 print "$lead<span class=\"match\">$match</span>$trail<br />";
4646 print "</td>\n" .
4647 "<td class=\"link\">" .
4648 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4649 " | " .
4650 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4651 " | " .
4652 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4653 print "</td>\n" .
4654 "</tr>\n";
4656 if (defined $extra) {
4657 print "<tr>\n" .
4658 "<td colspan=\"3\">$extra</td>\n" .
4659 "</tr>\n";
4661 print "</table>\n";
4664 ## ======================================================================
4665 ## ======================================================================
4666 ## actions
4668 sub git_project_list {
4669 git_header_html();
4670 if (-f $home_text) {
4671 print "<div class=\"index_include\">\n";
4672 insert_file($home_text);
4673 print "</div>\n";
4675 git_project_search_form();
4676 git_project_list_all();
4677 git_footer_html();
4680 sub git_forks {
4681 my $order = $input_params{'order'};
4682 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4683 die_error(400, "Unknown order parameter");
4686 my @list = git_get_projects_list($project);
4687 if (!@list) {
4688 die_error(404, "No forks found");
4691 git_header_html();
4692 git_print_page_nav('','');
4693 git_print_header_div('summary', "$project forks");
4694 git_project_list_body(\@list, $order, undef, undef, undef, undef, 'forks');
4695 git_footer_html();
4698 sub git_project_index {
4699 my @projects = git_get_projects_list($project);
4701 print $cgi->header(
4702 -type => 'text/plain',
4703 -charset => 'utf-8',
4704 -content_disposition => 'inline; filename="index.aux"');
4706 foreach my $pr (@projects) {
4707 if (!exists $pr->{'owner'}) {
4708 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4711 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4712 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4713 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4714 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4715 $path =~ s/ /\+/g;
4716 $owner =~ s/ /\+/g;
4718 print "$path $owner\n";
4722 sub git_summary {
4723 my $descr = git_get_project_description($project) || "none";
4724 my %co = parse_commit("HEAD");
4725 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4726 my $head = $co{'id'};
4728 my $owner = git_get_project_owner($project);
4730 my $refs = git_get_references();
4731 # These get_*_list functions return one more to allow us to see if
4732 # there are more ...
4733 my @taglist = git_get_tags_list(16);
4734 my @headlist = git_get_heads_list(16);
4735 my @forklist;
4736 my $check_forks = gitweb_check_feature('forks');
4738 if ($check_forks) {
4739 @forklist = git_get_projects_list($project);
4742 git_header_html();
4743 git_print_page_nav('summary','', $head);
4745 print "<div class=\"title\">&nbsp;</div>\n";
4746 print "<table class=\"projects_list\">\n" .
4747 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4748 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4749 if (defined $cd{'rfc2822'}) {
4750 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4753 # use per project git URL list in $projectroot/$project/cloneurl
4754 # or make project git URL from git base URL and project name
4755 my $url_tag = "URL";
4756 my @url_list = git_get_project_url_list($project);
4757 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4758 foreach my $git_url (@url_list) {
4759 next unless $git_url;
4760 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4761 $url_tag = "";
4764 # Tag cloud
4765 my $show_ctags = gitweb_check_feature('ctags');
4766 if ($show_ctags) {
4767 my $ctags = git_get_project_ctags($project);
4768 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
4769 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4770 print "</td>\n<td>" unless %$ctags;
4771 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4772 print "</td>\n<td>" if %$ctags;
4773 print git_show_project_tagcloud($cloud, 48, 'project_list');
4774 print "</td></tr>";
4777 print "</table>\n";
4779 # If XSS prevention is on, we don't include README.html.
4780 # TODO: Allow a readme in some safe format.
4781 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4782 print "<div class=\"title\">readme</div>\n" .
4783 "<div class=\"readme\">\n";
4784 insert_file("$projectroot/$project/README.html");
4785 print "\n</div>\n"; # class="readme"
4788 # we need to request one more than 16 (0..15) to check if
4789 # those 16 are all
4790 my @commitlist = $head ? parse_commits($head, 17) : ();
4791 if (@commitlist) {
4792 git_print_header_div('shortlog');
4793 git_shortlog_body(\@commitlist, 0, 15, $refs,
4794 $#commitlist <= 15 ? undef :
4795 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4798 if (@taglist) {
4799 git_print_header_div('tags');
4800 git_tags_body(\@taglist, 0, 15,
4801 $#taglist <= 15 ? undef :
4802 $cgi->a({-href => href(action=>"tags")}, "..."));
4805 if (@headlist) {
4806 git_print_header_div('heads');
4807 git_heads_body(\@headlist, $head, 0, 15,
4808 $#headlist <= 15 ? undef :
4809 $cgi->a({-href => href(action=>"heads")}, "..."));
4812 if (@forklist) {
4813 git_print_header_div('forks');
4814 git_project_list_body(\@forklist, 'age', 0, 15,
4815 $#forklist <= 15 ? undef :
4816 $cgi->a({-href => href(action=>"forks")}, "..."),
4817 'no_header', 'forks');
4820 git_footer_html();
4823 sub git_tag {
4824 my $head = git_get_head_hash($project);
4825 git_header_html();
4826 git_print_page_nav('','', $head,undef,$head);
4827 my %tag = parse_tag($hash);
4829 if (! %tag) {
4830 die_error(404, "Unknown tag object");
4833 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4834 print "<div class=\"title_text\">\n" .
4835 "<table class=\"object_header\">\n" .
4836 "<tr>\n" .
4837 "<td>object</td>\n" .
4838 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4839 $tag{'object'}) . "</td>\n" .
4840 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4841 $tag{'type'}) . "</td>\n" .
4842 "</tr>\n";
4843 if (defined($tag{'author'})) {
4844 git_print_authorship_rows(\%tag, 'author');
4846 print "</table>\n\n" .
4847 "</div>\n";
4848 print "<div class=\"page_body\">";
4849 my $comment = $tag{'comment'};
4850 foreach my $line (@$comment) {
4851 chomp $line;
4852 print esc_html($line, -nbsp=>1) . "<br/>\n";
4854 print "</div>\n";
4855 git_footer_html();
4858 sub git_blame {
4859 # permissions
4860 gitweb_check_feature('blame')
4861 or die_error(403, "Blame view not allowed");
4863 # error checking
4864 die_error(400, "No file name given") unless $file_name;
4865 $hash_base ||= git_get_head_hash($project);
4866 die_error(404, "Couldn't find base commit") unless $hash_base;
4867 my %co = parse_commit($hash_base)
4868 or die_error(404, "Commit not found");
4869 my $ftype = "blob";
4870 if (!defined $hash) {
4871 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4872 or die_error(404, "Error looking up file");
4873 } else {
4874 $ftype = git_get_type($hash);
4875 if ($ftype !~ "blob") {
4876 die_error(400, "Object is not a blob");
4880 # run git-blame --porcelain
4881 open my $fd, "-|", git_cmd(), "blame", '-p',
4882 $hash_base, '--', $file_name
4883 or die_error(500, "Open git-blame failed");
4885 # page header
4886 git_header_html();
4887 my $formats_nav =
4888 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4889 "blob") .
4890 " | " .
4891 $cgi->a({-href => href(action=>"history", -replay=>1)},
4892 "history") .
4893 " | " .
4894 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4895 "HEAD");
4896 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4897 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4898 git_print_page_path($file_name, $ftype, $hash_base);
4900 # page body
4901 my @rev_color = qw(light dark);
4902 my $num_colors = scalar(@rev_color);
4903 my $current_color = 0;
4904 my %metainfo = ();
4906 print <<HTML;
4907 <div class="page_body">
4908 <table class="blame">
4909 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4910 HTML
4911 LINE:
4912 while (my $line = <$fd>) {
4913 chomp $line;
4914 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4915 # no <lines in group> for subsequent lines in group of lines
4916 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4917 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
4918 if (!exists $metainfo{$full_rev}) {
4919 $metainfo{$full_rev} = { 'nprevious' => 0 };
4921 my $meta = $metainfo{$full_rev};
4922 my $data;
4923 while ($data = <$fd>) {
4924 chomp $data;
4925 last if ($data =~ s/^\t//); # contents of line
4926 if ($data =~ /^(\S+)(?: (.*))?$/) {
4927 $meta->{$1} = $2 unless exists $meta->{$1};
4929 if ($data =~ /^previous /) {
4930 $meta->{'nprevious'}++;
4933 my $short_rev = substr($full_rev, 0, 8);
4934 my $author = $meta->{'author'};
4935 my %date =
4936 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
4937 my $date = $date{'iso-tz'};
4938 if ($group_size) {
4939 $current_color = ($current_color + 1) % $num_colors;
4941 my $tr_class = $rev_color[$current_color];
4942 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
4943 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
4944 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
4945 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
4946 if ($group_size) {
4947 print "<td class=\"sha1\"";
4948 print " title=\"". esc_html($author) . ", $date\"";
4949 print " rowspan=\"$group_size\"" if ($group_size > 1);
4950 print ">";
4951 print $cgi->a({-href => href(action=>"commit",
4952 hash=>$full_rev,
4953 file_name=>$file_name)},
4954 esc_html($short_rev));
4955 if ($group_size >= 2) {
4956 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
4957 if (@author_initials) {
4958 print "<br />" .
4959 esc_html(join('', @author_initials));
4960 # or join('.', ...)
4963 print "</td>\n";
4965 # 'previous' <sha1 of parent commit> <filename at commit>
4966 if (exists $meta->{'previous'} &&
4967 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
4968 $meta->{'parent'} = $1;
4969 $meta->{'file_parent'} = unquote($2);
4971 my $linenr_commit =
4972 exists($meta->{'parent'}) ?
4973 $meta->{'parent'} : $full_rev;
4974 my $linenr_filename =
4975 exists($meta->{'file_parent'}) ?
4976 $meta->{'file_parent'} : unquote($meta->{'filename'});
4977 my $blamed = href(action => 'blame',
4978 file_name => $linenr_filename,
4979 hash_base => $linenr_commit);
4980 print "<td class=\"linenr\">";
4981 print $cgi->a({ -href => "$blamed#l$orig_lineno",
4982 -class => "linenr" },
4983 esc_html($lineno));
4984 print "</td>";
4985 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4986 print "</tr>\n";
4988 print "</table>\n";
4989 print "</div>";
4990 close $fd
4991 or print "Reading blob failed\n";
4993 # page footer
4994 git_footer_html();
4997 sub git_tags {
4998 my $head = git_get_head_hash($project);
4999 git_header_html();
5000 git_print_page_nav('','', $head,undef,$head);
5001 git_print_header_div('summary', $project);
5003 my @tagslist = git_get_tags_list();
5004 if (@tagslist) {
5005 git_tags_body(\@tagslist);
5007 git_footer_html();
5010 sub git_heads {
5011 my $head = git_get_head_hash($project);
5012 git_header_html();
5013 git_print_page_nav('','', $head,undef,$head);
5014 git_print_header_div('summary', $project);
5016 my @headslist = git_get_heads_list();
5017 if (@headslist) {
5018 git_heads_body(\@headslist, $head);
5020 git_footer_html();
5023 sub git_blob_plain {
5024 my $type = shift;
5025 my $expires;
5027 if (!defined $hash) {
5028 if (defined $file_name) {
5029 my $base = $hash_base || git_get_head_hash($project);
5030 $hash = git_get_hash_by_path($base, $file_name, "blob")
5031 or die_error(404, "Cannot find file");
5032 } else {
5033 die_error(400, "No file name defined");
5035 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5036 # blobs defined by non-textual hash id's can be cached
5037 $expires = "+1d";
5040 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5041 or die_error(500, "Open git-cat-file blob '$hash' failed");
5043 # content-type (can include charset)
5044 $type = blob_contenttype($fd, $file_name, $type);
5046 # "save as" filename, even when no $file_name is given
5047 my $save_as = "$hash";
5048 if (defined $file_name) {
5049 $save_as = $file_name;
5050 } elsif ($type =~ m/^text\//) {
5051 $save_as .= '.txt';
5054 # With XSS prevention on, blobs of all types except a few known safe
5055 # ones are served with "Content-Disposition: attachment" to make sure
5056 # they don't run in our security domain. For certain image types,
5057 # blob view writes an <img> tag referring to blob_plain view, and we
5058 # want to be sure not to break that by serving the image as an
5059 # attachment (though Firefox 3 doesn't seem to care).
5060 my $sandbox = $prevent_xss &&
5061 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5063 print $cgi->header(
5064 -type => $type,
5065 -expires => $expires,
5066 -content_disposition =>
5067 ($sandbox ? 'attachment' : 'inline')
5068 . '; filename="' . $save_as . '"');
5069 local $/ = undef;
5070 binmode STDOUT, ':raw';
5071 print <$fd>;
5072 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5073 close $fd;
5076 sub git_blob {
5077 my $expires;
5079 if (!defined $hash) {
5080 if (defined $file_name) {
5081 my $base = $hash_base || git_get_head_hash($project);
5082 $hash = git_get_hash_by_path($base, $file_name, "blob")
5083 or die_error(404, "Cannot find file");
5084 } else {
5085 die_error(400, "No file name defined");
5087 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5088 # blobs defined by non-textual hash id's can be cached
5089 $expires = "+1d";
5092 my $have_blame = gitweb_check_feature('blame');
5093 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5094 or die_error(500, "Couldn't cat $file_name, $hash");
5095 my $mimetype = blob_mimetype($fd, $file_name);
5096 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5097 close $fd;
5098 return git_blob_plain($mimetype);
5100 # we can have blame only for text/* mimetype
5101 $have_blame &&= ($mimetype =~ m!^text/!);
5103 git_header_html(undef, $expires);
5104 my $formats_nav = '';
5105 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5106 if (defined $file_name) {
5107 if ($have_blame) {
5108 $formats_nav .=
5109 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5110 "blame") .
5111 " | ";
5113 $formats_nav .=
5114 $cgi->a({-href => href(action=>"history", -replay=>1)},
5115 "history") .
5116 " | " .
5117 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5118 "raw") .
5119 " | " .
5120 $cgi->a({-href => href(action=>"blob",
5121 hash_base=>"HEAD", file_name=>$file_name)},
5122 "HEAD");
5123 } else {
5124 $formats_nav .=
5125 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5126 "raw");
5128 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5129 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5130 } else {
5131 print "<div class=\"page_nav\">\n" .
5132 "<br/><br/></div>\n" .
5133 "<div class=\"title\">$hash</div>\n";
5135 git_print_page_path($file_name, "blob", $hash_base);
5136 print "<div class=\"page_body\">\n";
5137 if ($mimetype =~ m!^image/!) {
5138 print qq!<img type="$mimetype"!;
5139 if ($file_name) {
5140 print qq! alt="$file_name" title="$file_name"!;
5142 print qq! src="! .
5143 href(action=>"blob_plain", hash=>$hash,
5144 hash_base=>$hash_base, file_name=>$file_name) .
5145 qq!" />\n!;
5146 } else {
5147 my $nr;
5148 while (my $line = <$fd>) {
5149 chomp $line;
5150 $nr++;
5151 $line = untabify($line);
5152 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5153 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5156 close $fd
5157 or print "Reading blob failed.\n";
5158 print "</div>";
5159 git_footer_html();
5162 sub git_tree {
5163 if (!defined $hash_base) {
5164 $hash_base = "HEAD";
5166 if (!defined $hash) {
5167 if (defined $file_name) {
5168 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5169 } else {
5170 $hash = $hash_base;
5173 die_error(404, "No such tree") unless defined($hash);
5175 my $show_sizes = gitweb_check_feature('show-sizes');
5176 my $have_blame = gitweb_check_feature('blame');
5178 my @entries = ();
5180 local $/ = "\0";
5181 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5182 ($show_sizes ? '-l' : ()), @extra_options, $hash
5183 or die_error(500, "Open git-ls-tree failed");
5184 @entries = map { chomp; $_ } <$fd>;
5185 close $fd
5186 or die_error(404, "Reading tree failed");
5189 my $refs = git_get_references();
5190 my $ref = format_ref_marker($refs, $hash_base);
5191 git_header_html();
5192 my $basedir = '';
5193 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5194 my @views_nav = ();
5195 if (defined $file_name) {
5196 push @views_nav,
5197 $cgi->a({-href => href(action=>"history", -replay=>1)},
5198 "history"),
5199 $cgi->a({-href => href(action=>"tree",
5200 hash_base=>"HEAD", file_name=>$file_name)},
5201 "HEAD"),
5203 my $snapshot_links = format_snapshot_links($hash);
5204 if (defined $snapshot_links) {
5205 # FIXME: Should be available when we have no hash base as well.
5206 push @views_nav, $snapshot_links;
5208 git_print_page_nav('tree','', $hash_base, undef, undef,
5209 join(' | ', @views_nav));
5210 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5211 } else {
5212 undef $hash_base;
5213 print "<div class=\"page_nav\">\n";
5214 print "<br/><br/></div>\n";
5215 print "<div class=\"title\">$hash</div>\n";
5217 if (defined $file_name) {
5218 $basedir = $file_name;
5219 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5220 $basedir .= '/';
5222 git_print_page_path($file_name, 'tree', $hash_base);
5224 print "<div class=\"page_body\">\n";
5225 print "<table class=\"tree\">\n";
5226 my $alternate = 1;
5227 # '..' (top directory) link if possible
5228 if (defined $hash_base &&
5229 defined $file_name && $file_name =~ m![^/]+$!) {
5230 if ($alternate) {
5231 print "<tr class=\"dark\">\n";
5232 } else {
5233 print "<tr class=\"light\">\n";
5235 $alternate ^= 1;
5237 my $up = $file_name;
5238 $up =~ s!/?[^/]+$!!;
5239 undef $up unless $up;
5240 # based on git_print_tree_entry
5241 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5242 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5243 print '<td class="list">';
5244 print $cgi->a({-href => href(action=>"tree",
5245 hash_base=>$hash_base,
5246 file_name=>$up)},
5247 "..");
5248 print "</td>\n";
5249 print "<td class=\"link\"></td>\n";
5251 print "</tr>\n";
5253 foreach my $line (@entries) {
5254 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5256 if ($alternate) {
5257 print "<tr class=\"dark\">\n";
5258 } else {
5259 print "<tr class=\"light\">\n";
5261 $alternate ^= 1;
5263 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5265 print "</tr>\n";
5267 print "</table>\n" .
5268 "</div>";
5269 git_footer_html();
5272 sub git_snapshot {
5273 my $format = $input_params{'snapshot_format'};
5274 if (!@snapshot_fmts) {
5275 die_error(403, "Snapshots not allowed");
5277 # default to first supported snapshot format
5278 $format ||= $snapshot_fmts[0];
5279 if ($format !~ m/^[a-z0-9]+$/) {
5280 die_error(400, "Invalid snapshot format parameter");
5281 } elsif (!exists($known_snapshot_formats{$format})) {
5282 die_error(400, "Unknown snapshot format");
5283 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5284 die_error(403, "Snapshot format not allowed");
5285 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5286 die_error(403, "Unsupported snapshot format");
5289 if (!defined $hash) {
5290 $hash = git_get_head_hash($project);
5293 my $name = $project;
5294 $name =~ s,([^/])/*\.git$,$1,;
5295 $name = basename($name);
5296 my $filename = to_utf8($name);
5297 $name =~ s/\047/\047\\\047\047/g;
5298 my $cmd;
5299 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5300 $cmd = quote_command(
5301 git_cmd(), 'archive',
5302 "--format=$known_snapshot_formats{$format}{'format'}",
5303 "--prefix=$name/", $hash);
5304 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5305 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5308 print $cgi->header(
5309 -type => $known_snapshot_formats{$format}{'type'},
5310 -content_disposition => 'inline; filename="' . "$filename" . '"',
5311 -status => '200 OK');
5313 open my $fd, "-|", $cmd
5314 or die_error(500, "Execute git-archive failed");
5315 binmode STDOUT, ':raw';
5316 print <$fd>;
5317 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5318 close $fd;
5321 sub git_log {
5322 my $head = git_get_head_hash($project);
5323 if (!defined $hash) {
5324 $hash = $head;
5326 if (!defined $page) {
5327 $page = 0;
5329 my $refs = git_get_references();
5331 my @commitlist = parse_commits($hash, 101, (100 * $page));
5333 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
5335 my ($patch_max) = gitweb_get_feature('patches');
5336 if ($patch_max) {
5337 if ($patch_max < 0 || @commitlist <= $patch_max) {
5338 $paging_nav .= " &sdot; " .
5339 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5340 "patches");
5344 git_header_html();
5345 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5347 if (!@commitlist) {
5348 my %co = parse_commit($hash);
5350 git_print_header_div('summary', $project);
5351 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5353 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5354 for (my $i = 0; $i <= $to; $i++) {
5355 my %co = %{$commitlist[$i]};
5356 next if !%co;
5357 my $commit = $co{'id'};
5358 my $ref = format_ref_marker($refs, $commit);
5359 my %ad = parse_date($co{'author_epoch'});
5360 git_print_header_div('commit',
5361 "<span class=\"age\">$co{'age_string'}</span>" .
5362 esc_html($co{'title'}) . $ref,
5363 $commit);
5364 print "<div class=\"title_text\">\n" .
5365 "<div class=\"log_link\">\n" .
5366 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5367 " | " .
5368 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5369 " | " .
5370 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5371 "<br/>\n" .
5372 "</div>\n";
5373 git_print_authorship(\%co, -tag => 'span');
5374 print "<br/>\n</div>\n";
5376 print "<div class=\"log_body\">\n";
5377 git_print_log($co{'comment'}, -final_empty_line=> 1);
5378 print "</div>\n";
5380 if ($#commitlist >= 100) {
5381 print "<div class=\"page_nav\">\n";
5382 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5383 -accesskey => "n", -title => "Alt-n"}, "next");
5384 print "</div>\n";
5386 git_footer_html();
5389 sub git_commit {
5390 $hash ||= $hash_base || "HEAD";
5391 my %co = parse_commit($hash)
5392 or die_error(404, "Unknown commit object");
5394 my $parent = $co{'parent'};
5395 my $parents = $co{'parents'}; # listref
5397 # we need to prepare $formats_nav before any parameter munging
5398 my $formats_nav;
5399 if (!defined $parent) {
5400 # --root commitdiff
5401 $formats_nav .= '(initial)';
5402 } elsif (@$parents == 1) {
5403 # single parent commit
5404 $formats_nav .=
5405 '(parent: ' .
5406 $cgi->a({-href => href(action=>"commit",
5407 hash=>$parent)},
5408 esc_html(substr($parent, 0, 7))) .
5409 ')';
5410 } else {
5411 # merge commit
5412 $formats_nav .=
5413 '(merge: ' .
5414 join(' ', map {
5415 $cgi->a({-href => href(action=>"commit",
5416 hash=>$_)},
5417 esc_html(substr($_, 0, 7)));
5418 } @$parents ) .
5419 ')';
5421 if (gitweb_check_feature('patches') && @$parents <= 1) {
5422 $formats_nav .= " | " .
5423 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5424 "patch");
5427 if (!defined $parent) {
5428 $parent = "--root";
5430 my @difftree;
5431 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5432 @diff_opts,
5433 (@$parents <= 1 ? $parent : '-c'),
5434 $hash, "--"
5435 or die_error(500, "Open git-diff-tree failed");
5436 @difftree = map { chomp; $_ } <$fd>;
5437 close $fd or die_error(404, "Reading git-diff-tree failed");
5439 # non-textual hash id's can be cached
5440 my $expires;
5441 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5442 $expires = "+1d";
5444 my $refs = git_get_references();
5445 my $ref = format_ref_marker($refs, $co{'id'});
5447 git_header_html(undef, $expires);
5448 git_print_page_nav('commit', '',
5449 $hash, $co{'tree'}, $hash,
5450 $formats_nav);
5452 if (defined $co{'parent'}) {
5453 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5454 } else {
5455 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5457 print "<div class=\"title_text\">\n" .
5458 "<table class=\"object_header\">\n";
5459 git_print_authorship_rows(\%co);
5460 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5461 print "<tr>" .
5462 "<td>tree</td>" .
5463 "<td class=\"sha1\">" .
5464 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5465 class => "list"}, $co{'tree'}) .
5466 "</td>" .
5467 "<td class=\"link\">" .
5468 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5469 "tree");
5470 my $snapshot_links = format_snapshot_links($hash);
5471 if (defined $snapshot_links) {
5472 print " | " . $snapshot_links;
5474 print "</td>" .
5475 "</tr>\n";
5477 foreach my $par (@$parents) {
5478 print "<tr>" .
5479 "<td>parent</td>" .
5480 "<td class=\"sha1\">" .
5481 $cgi->a({-href => href(action=>"commit", hash=>$par),
5482 class => "list"}, $par) .
5483 "</td>" .
5484 "<td class=\"link\">" .
5485 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5486 " | " .
5487 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5488 "</td>" .
5489 "</tr>\n";
5491 print "</table>".
5492 "</div>\n";
5494 print "<div class=\"page_body\">\n";
5495 git_print_log($co{'comment'});
5496 print "</div>\n";
5498 git_difftree_body(\@difftree, $hash, @$parents);
5500 git_footer_html();
5503 sub git_object {
5504 # object is defined by:
5505 # - hash or hash_base alone
5506 # - hash_base and file_name
5507 my $type;
5509 # - hash or hash_base alone
5510 if ($hash || ($hash_base && !defined $file_name)) {
5511 my $object_id = $hash || $hash_base;
5513 open my $fd, "-|", quote_command(
5514 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5515 or die_error(404, "Object does not exist");
5516 $type = <$fd>;
5517 chomp $type;
5518 close $fd
5519 or die_error(404, "Object does not exist");
5521 # - hash_base and file_name
5522 } elsif ($hash_base && defined $file_name) {
5523 $file_name =~ s,/+$,,;
5525 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5526 or die_error(404, "Base object does not exist");
5528 # here errors should not hapen
5529 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5530 or die_error(500, "Open git-ls-tree failed");
5531 my $line = <$fd>;
5532 close $fd;
5534 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5535 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5536 die_error(404, "File or directory for given base does not exist");
5538 $type = $2;
5539 $hash = $3;
5540 } else {
5541 die_error(400, "Not enough information to find object");
5544 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5545 hash=>$hash, hash_base=>$hash_base,
5546 file_name=>$file_name),
5547 -status => '302 Found');
5550 sub git_blobdiff {
5551 my $format = shift || 'html';
5553 my $fd;
5554 my @difftree;
5555 my %diffinfo;
5556 my $expires;
5558 # preparing $fd and %diffinfo for git_patchset_body
5559 # new style URI
5560 if (defined $hash_base && defined $hash_parent_base) {
5561 if (defined $file_name) {
5562 # read raw output
5563 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5564 $hash_parent_base, $hash_base,
5565 "--", (defined $file_parent ? $file_parent : ()), $file_name
5566 or die_error(500, "Open git-diff-tree failed");
5567 @difftree = map { chomp; $_ } <$fd>;
5568 close $fd
5569 or die_error(404, "Reading git-diff-tree failed");
5570 @difftree
5571 or die_error(404, "Blob diff not found");
5573 } elsif (defined $hash &&
5574 $hash =~ /[0-9a-fA-F]{40}/) {
5575 # try to find filename from $hash
5577 # read filtered raw output
5578 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5579 $hash_parent_base, $hash_base, "--"
5580 or die_error(500, "Open git-diff-tree failed");
5581 @difftree =
5582 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5583 # $hash == to_id
5584 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5585 map { chomp; $_ } <$fd>;
5586 close $fd
5587 or die_error(404, "Reading git-diff-tree failed");
5588 @difftree
5589 or die_error(404, "Blob diff not found");
5591 } else {
5592 die_error(400, "Missing one of the blob diff parameters");
5595 if (@difftree > 1) {
5596 die_error(400, "Ambiguous blob diff specification");
5599 %diffinfo = parse_difftree_raw_line($difftree[0]);
5600 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5601 $file_name ||= $diffinfo{'to_file'};
5603 $hash_parent ||= $diffinfo{'from_id'};
5604 $hash ||= $diffinfo{'to_id'};
5606 # non-textual hash id's can be cached
5607 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5608 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5609 $expires = '+1d';
5612 # open patch output
5613 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5614 '-p', ($format eq 'html' ? "--full-index" : ()),
5615 $hash_parent_base, $hash_base,
5616 "--", (defined $file_parent ? $file_parent : ()), $file_name
5617 or die_error(500, "Open git-diff-tree failed");
5620 # old/legacy style URI -- not generated anymore since 1.4.3.
5621 if (!%diffinfo) {
5622 die_error('404 Not Found', "Missing one of the blob diff parameters")
5625 # header
5626 if ($format eq 'html') {
5627 my $formats_nav =
5628 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5629 "raw");
5630 git_header_html(undef, $expires);
5631 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5632 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5633 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5634 } else {
5635 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5636 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5638 if (defined $file_name) {
5639 git_print_page_path($file_name, "blob", $hash_base);
5640 } else {
5641 print "<div class=\"page_path\"></div>\n";
5644 } elsif ($format eq 'plain') {
5645 print $cgi->header(
5646 -type => 'text/plain',
5647 -charset => 'utf-8',
5648 -expires => $expires,
5649 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5651 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5653 } else {
5654 die_error(400, "Unknown blobdiff format");
5657 # patch
5658 if ($format eq 'html') {
5659 print "<div class=\"page_body\">\n";
5661 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5662 close $fd;
5664 print "</div>\n"; # class="page_body"
5665 git_footer_html();
5667 } else {
5668 while (my $line = <$fd>) {
5669 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5670 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5672 print $line;
5674 last if $line =~ m!^\+\+\+!;
5676 local $/ = undef;
5677 print <$fd>;
5678 close $fd;
5682 sub git_blobdiff_plain {
5683 git_blobdiff('plain');
5686 sub git_commitdiff {
5687 my %params = @_;
5688 my $format = $params{-format} || 'html';
5690 my ($patch_max) = gitweb_get_feature('patches');
5691 if ($format eq 'patch') {
5692 die_error(403, "Patch view not allowed") unless $patch_max;
5695 $hash ||= $hash_base || "HEAD";
5696 my %co = parse_commit($hash)
5697 or die_error(404, "Unknown commit object");
5699 # choose format for commitdiff for merge
5700 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5701 $hash_parent = '--cc';
5703 # we need to prepare $formats_nav before almost any parameter munging
5704 my $formats_nav;
5705 if ($format eq 'html') {
5706 $formats_nav =
5707 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5708 "raw");
5709 if ($patch_max && @{$co{'parents'}} <= 1) {
5710 $formats_nav .= " | " .
5711 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5712 "patch");
5715 if (defined $hash_parent &&
5716 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5717 # commitdiff with two commits given
5718 my $hash_parent_short = $hash_parent;
5719 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5720 $hash_parent_short = substr($hash_parent, 0, 7);
5722 $formats_nav .=
5723 ' (from';
5724 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5725 if ($co{'parents'}[$i] eq $hash_parent) {
5726 $formats_nav .= ' parent ' . ($i+1);
5727 last;
5730 $formats_nav .= ': ' .
5731 $cgi->a({-href => href(action=>"commitdiff",
5732 hash=>$hash_parent)},
5733 esc_html($hash_parent_short)) .
5734 ')';
5735 } elsif (!$co{'parent'}) {
5736 # --root commitdiff
5737 $formats_nav .= ' (initial)';
5738 } elsif (scalar @{$co{'parents'}} == 1) {
5739 # single parent commit
5740 $formats_nav .=
5741 ' (parent: ' .
5742 $cgi->a({-href => href(action=>"commitdiff",
5743 hash=>$co{'parent'})},
5744 esc_html(substr($co{'parent'}, 0, 7))) .
5745 ')';
5746 } else {
5747 # merge commit
5748 if ($hash_parent eq '--cc') {
5749 $formats_nav .= ' | ' .
5750 $cgi->a({-href => href(action=>"commitdiff",
5751 hash=>$hash, hash_parent=>'-c')},
5752 'combined');
5753 } else { # $hash_parent eq '-c'
5754 $formats_nav .= ' | ' .
5755 $cgi->a({-href => href(action=>"commitdiff",
5756 hash=>$hash, hash_parent=>'--cc')},
5757 'compact');
5759 $formats_nav .=
5760 ' (merge: ' .
5761 join(' ', map {
5762 $cgi->a({-href => href(action=>"commitdiff",
5763 hash=>$_)},
5764 esc_html(substr($_, 0, 7)));
5765 } @{$co{'parents'}} ) .
5766 ')';
5770 my $hash_parent_param = $hash_parent;
5771 if (!defined $hash_parent_param) {
5772 # --cc for multiple parents, --root for parentless
5773 $hash_parent_param =
5774 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5777 # read commitdiff
5778 my $fd;
5779 my @difftree;
5780 if ($format eq 'html') {
5781 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5782 "--no-commit-id", "--patch-with-raw", "--full-index",
5783 $hash_parent_param, $hash, "--"
5784 or die_error(500, "Open git-diff-tree failed");
5786 while (my $line = <$fd>) {
5787 chomp $line;
5788 # empty line ends raw part of diff-tree output
5789 last unless $line;
5790 push @difftree, scalar parse_difftree_raw_line($line);
5793 } elsif ($format eq 'plain') {
5794 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5795 '-p', $hash_parent_param, $hash, "--"
5796 or die_error(500, "Open git-diff-tree failed");
5797 } elsif ($format eq 'patch') {
5798 # For commit ranges, we limit the output to the number of
5799 # patches specified in the 'patches' feature.
5800 # For single commits, we limit the output to a single patch,
5801 # diverging from the git-format-patch default.
5802 my @commit_spec = ();
5803 if ($hash_parent) {
5804 if ($patch_max > 0) {
5805 push @commit_spec, "-$patch_max";
5807 push @commit_spec, '-n', "$hash_parent..$hash";
5808 } else {
5809 if ($params{-single}) {
5810 push @commit_spec, '-1';
5811 } else {
5812 if ($patch_max > 0) {
5813 push @commit_spec, "-$patch_max";
5815 push @commit_spec, "-n";
5817 push @commit_spec, '--root', $hash;
5819 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5820 '--stdout', @commit_spec
5821 or die_error(500, "Open git-format-patch failed");
5822 } else {
5823 die_error(400, "Unknown commitdiff format");
5826 # non-textual hash id's can be cached
5827 my $expires;
5828 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5829 $expires = "+1d";
5832 # write commit message
5833 if ($format eq 'html') {
5834 my $refs = git_get_references();
5835 my $ref = format_ref_marker($refs, $co{'id'});
5837 git_header_html(undef, $expires);
5838 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5839 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5840 print "<div class=\"title_text\">\n" .
5841 "<table class=\"object_header\">\n";
5842 git_print_authorship_rows(\%co);
5843 print "</table>".
5844 "</div>\n";
5845 print "<div class=\"page_body\">\n";
5846 if (@{$co{'comment'}} > 1) {
5847 print "<div class=\"log\">\n";
5848 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5849 print "</div>\n"; # class="log"
5852 } elsif ($format eq 'plain') {
5853 my $refs = git_get_references("tags");
5854 my $tagname = git_get_rev_name_tags($hash);
5855 my $filename = basename($project) . "-$hash.patch";
5857 print $cgi->header(
5858 -type => 'text/plain',
5859 -charset => 'utf-8',
5860 -expires => $expires,
5861 -content_disposition => 'inline; filename="' . "$filename" . '"');
5862 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5863 print "From: " . to_utf8($co{'author'}) . "\n";
5864 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5865 print "Subject: " . to_utf8($co{'title'}) . "\n";
5867 print "X-Git-Tag: $tagname\n" if $tagname;
5868 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5870 foreach my $line (@{$co{'comment'}}) {
5871 print to_utf8($line) . "\n";
5873 print "---\n\n";
5874 } elsif ($format eq 'patch') {
5875 my $filename = basename($project) . "-$hash.patch";
5877 print $cgi->header(
5878 -type => 'text/plain',
5879 -charset => 'utf-8',
5880 -expires => $expires,
5881 -content_disposition => 'inline; filename="' . "$filename" . '"');
5884 # write patch
5885 if ($format eq 'html') {
5886 my $use_parents = !defined $hash_parent ||
5887 $hash_parent eq '-c' || $hash_parent eq '--cc';
5888 git_difftree_body(\@difftree, $hash,
5889 $use_parents ? @{$co{'parents'}} : $hash_parent);
5890 print "<br/>\n";
5892 git_patchset_body($fd, \@difftree, $hash,
5893 $use_parents ? @{$co{'parents'}} : $hash_parent);
5894 close $fd;
5895 print "</div>\n"; # class="page_body"
5896 git_footer_html();
5898 } elsif ($format eq 'plain') {
5899 local $/ = undef;
5900 print <$fd>;
5901 close $fd
5902 or print "Reading git-diff-tree failed\n";
5903 } elsif ($format eq 'patch') {
5904 local $/ = undef;
5905 print <$fd>;
5906 close $fd
5907 or print "Reading git-format-patch failed\n";
5911 sub git_commitdiff_plain {
5912 git_commitdiff(-format => 'plain');
5915 # format-patch-style patches
5916 sub git_patch {
5917 git_commitdiff(-format => 'patch', -single => 1);
5920 sub git_patches {
5921 git_commitdiff(-format => 'patch');
5924 sub git_history {
5925 if (!defined $hash_base) {
5926 $hash_base = git_get_head_hash($project);
5928 if (!defined $page) {
5929 $page = 0;
5931 my $ftype;
5932 my %co = parse_commit($hash_base)
5933 or die_error(404, "Unknown commit object");
5935 my $refs = git_get_references();
5936 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5938 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5939 $file_name, "--full-history")
5940 or die_error(404, "No such file or directory on given branch");
5942 if (!defined $hash && defined $file_name) {
5943 # some commits could have deleted file in question,
5944 # and not have it in tree, but one of them has to have it
5945 for (my $i = 0; $i <= @commitlist; $i++) {
5946 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5947 last if defined $hash;
5950 if (defined $hash) {
5951 $ftype = git_get_type($hash);
5953 if (!defined $ftype) {
5954 die_error(500, "Unknown type of object");
5957 my $paging_nav = '';
5958 if ($page > 0) {
5959 $paging_nav .=
5960 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5961 file_name=>$file_name)},
5962 "first");
5963 $paging_nav .= " &sdot; " .
5964 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5965 -accesskey => "p", -title => "Alt-p"}, "prev");
5966 } else {
5967 $paging_nav .= "first";
5968 $paging_nav .= " &sdot; prev";
5970 my $next_link = '';
5971 if ($#commitlist >= 100) {
5972 $next_link =
5973 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5974 -accesskey => "n", -title => "Alt-n"}, "next");
5975 $paging_nav .= " &sdot; $next_link";
5976 } else {
5977 $paging_nav .= " &sdot; next";
5980 git_header_html();
5981 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5982 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5983 git_print_page_path($file_name, $ftype, $hash_base);
5985 git_history_body(\@commitlist, 0, 99,
5986 $refs, $hash_base, $ftype, $next_link);
5988 git_footer_html();
5991 sub git_search {
5992 gitweb_check_feature('search') or die_error(403, "Search is disabled");
5993 if (!defined $searchtext) {
5994 die_error(400, "Text field is empty");
5996 if (!defined $hash) {
5997 $hash = git_get_head_hash($project);
5999 my %co = parse_commit($hash);
6000 if (!%co) {
6001 die_error(404, "Unknown commit object");
6003 if (!defined $page) {
6004 $page = 0;
6007 $searchtype ||= 'commit';
6008 if ($searchtype eq 'pickaxe') {
6009 # pickaxe may take all resources of your box and run for several minutes
6010 # with every query - so decide by yourself how public you make this feature
6011 gitweb_check_feature('pickaxe')
6012 or die_error(403, "Pickaxe is disabled");
6014 if ($searchtype eq 'grep') {
6015 gitweb_check_feature('grep')
6016 or die_error(403, "Grep is disabled");
6019 git_header_html();
6021 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6022 my $greptype;
6023 if ($searchtype eq 'commit') {
6024 $greptype = "--grep=";
6025 } elsif ($searchtype eq 'author') {
6026 $greptype = "--author=";
6027 } elsif ($searchtype eq 'committer') {
6028 $greptype = "--committer=";
6030 $greptype .= $searchtext;
6031 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6032 $greptype, '--regexp-ignore-case',
6033 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6035 my $paging_nav = '';
6036 if ($page > 0) {
6037 $paging_nav .=
6038 $cgi->a({-href => href(action=>"search", hash=>$hash,
6039 searchtext=>$searchtext,
6040 searchtype=>$searchtype)},
6041 "first");
6042 $paging_nav .= " &sdot; " .
6043 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6044 -accesskey => "p", -title => "Alt-p"}, "prev");
6045 } else {
6046 $paging_nav .= "first";
6047 $paging_nav .= " &sdot; prev";
6049 my $next_link = '';
6050 if ($#commitlist >= 100) {
6051 $next_link =
6052 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6053 -accesskey => "n", -title => "Alt-n"}, "next");
6054 $paging_nav .= " &sdot; $next_link";
6055 } else {
6056 $paging_nav .= " &sdot; next";
6059 if ($#commitlist >= 100) {
6062 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6063 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6064 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6067 if ($searchtype eq 'pickaxe') {
6068 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6069 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6071 print "<table class=\"pickaxe search\">\n";
6072 my $alternate = 1;
6073 local $/ = "\n";
6074 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6075 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6076 ($search_use_regexp ? '--pickaxe-regex' : ());
6077 undef %co;
6078 my @files;
6079 while (my $line = <$fd>) {
6080 chomp $line;
6081 next unless $line;
6083 my %set = parse_difftree_raw_line($line);
6084 if (defined $set{'commit'}) {
6085 # finish previous commit
6086 if (%co) {
6087 print "</td>\n" .
6088 "<td class=\"link\">" .
6089 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6090 " | " .
6091 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6092 print "</td>\n" .
6093 "</tr>\n";
6096 if ($alternate) {
6097 print "<tr class=\"dark\">\n";
6098 } else {
6099 print "<tr class=\"light\">\n";
6101 $alternate ^= 1;
6102 %co = parse_commit($set{'commit'});
6103 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6104 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6105 "<td><i>$author</i></td>\n" .
6106 "<td>" .
6107 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6108 -class => "list subject"},
6109 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6110 } elsif (defined $set{'to_id'}) {
6111 next if ($set{'to_id'} =~ m/^0{40}$/);
6113 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6114 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6115 -class => "list"},
6116 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6117 "<br/>\n";
6120 close $fd;
6122 # finish last commit (warning: repetition!)
6123 if (%co) {
6124 print "</td>\n" .
6125 "<td class=\"link\">" .
6126 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6127 " | " .
6128 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6129 print "</td>\n" .
6130 "</tr>\n";
6133 print "</table>\n";
6136 if ($searchtype eq 'grep') {
6137 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6138 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6140 print "<table class=\"grep_search\">\n";
6141 my $alternate = 1;
6142 my $matches = 0;
6143 local $/ = "\n";
6144 open my $fd, "-|", git_cmd(), 'grep', '-n',
6145 $search_use_regexp ? ('-E', '-i') : '-F',
6146 $searchtext, $co{'tree'};
6147 my $lastfile = '';
6148 while (my $line = <$fd>) {
6149 chomp $line;
6150 my ($file, $lno, $ltext, $binary);
6151 last if ($matches++ > 1000);
6152 if ($line =~ /^Binary file (.+) matches$/) {
6153 $file = $1;
6154 $binary = 1;
6155 } else {
6156 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6158 if ($file ne $lastfile) {
6159 $lastfile and print "</td></tr>\n";
6160 if ($alternate++) {
6161 print "<tr class=\"dark\">\n";
6162 } else {
6163 print "<tr class=\"light\">\n";
6165 print "<td class=\"list\">".
6166 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6167 file_name=>"$file"),
6168 -class => "list"}, esc_path($file));
6169 print "</td><td>\n";
6170 $lastfile = $file;
6172 if ($binary) {
6173 print "<div class=\"binary\">Binary file</div>\n";
6174 } else {
6175 $ltext = untabify($ltext);
6176 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6177 $ltext = esc_html($1, -nbsp=>1);
6178 $ltext .= '<span class="match">';
6179 $ltext .= esc_html($2, -nbsp=>1);
6180 $ltext .= '</span>';
6181 $ltext .= esc_html($3, -nbsp=>1);
6182 } else {
6183 $ltext = esc_html($ltext, -nbsp=>1);
6185 print "<div class=\"pre\">" .
6186 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6187 file_name=>"$file").'#l'.$lno,
6188 -class => "linenr"}, sprintf('%4i', $lno))
6189 . ' ' . $ltext . "</div>\n";
6192 if ($lastfile) {
6193 print "</td></tr>\n";
6194 if ($matches > 1000) {
6195 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6197 } else {
6198 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6200 close $fd;
6202 print "</table>\n";
6204 git_footer_html();
6207 sub git_search_help {
6208 git_header_html();
6209 git_print_page_nav('','', $hash,$hash,$hash);
6210 print <<EOT;
6211 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6212 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6213 the pattern entered is recognized as the POSIX extended
6214 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6215 insensitive).</p>
6216 <dl>
6217 <dt><b>commit</b></dt>
6218 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6220 my $have_grep = gitweb_check_feature('grep');
6221 if ($have_grep) {
6222 print <<EOT;
6223 <dt><b>grep</b></dt>
6224 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6225 a different one) are searched for the given pattern. On large trees, this search can take
6226 a while and put some strain on the server, so please use it with some consideration. Note that
6227 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6228 case-sensitive.</dd>
6231 print <<EOT;
6232 <dt><b>author</b></dt>
6233 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6234 <dt><b>committer</b></dt>
6235 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6237 my $have_pickaxe = gitweb_check_feature('pickaxe');
6238 if ($have_pickaxe) {
6239 print <<EOT;
6240 <dt><b>pickaxe</b></dt>
6241 <dd>All commits that caused the string to appear or disappear from any file (changes that
6242 added, removed or "modified" the string) will be listed. This search can take a while and
6243 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6244 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6247 print "</dl>\n";
6248 git_footer_html();
6251 sub git_shortlog {
6252 my $head = git_get_head_hash($project);
6253 if (!defined $hash) {
6254 $hash = $head;
6256 if (!defined $page) {
6257 $page = 0;
6259 my $refs = git_get_references();
6261 my $commit_hash = $hash;
6262 if (defined $hash_parent) {
6263 $commit_hash = "$hash_parent..$hash";
6265 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6267 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6268 my $next_link = '';
6269 if ($#commitlist >= 100) {
6270 $next_link =
6271 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6272 -accesskey => "n", -title => "Alt-n"}, "next");
6274 my $patch_max = gitweb_check_feature('patches');
6275 if ($patch_max) {
6276 if ($patch_max < 0 || @commitlist <= $patch_max) {
6277 $paging_nav .= " &sdot; " .
6278 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6279 "patches");
6283 git_header_html();
6284 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6285 git_print_header_div('summary', $project);
6287 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6289 git_footer_html();
6292 ## ......................................................................
6293 ## feeds (RSS, Atom; OPML)
6295 sub git_feed {
6296 my $format = shift || 'atom';
6297 my $have_blame = gitweb_check_feature('blame');
6299 # Atom: http://www.atomenabled.org/developers/syndication/
6300 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6301 if ($format ne 'rss' && $format ne 'atom') {
6302 die_error(400, "Unknown web feed format");
6305 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6306 my $head = $hash || 'HEAD';
6307 my @commitlist = parse_commits($head, 150, 0, $file_name);
6309 my %latest_commit;
6310 my %latest_date;
6311 my $content_type = "application/$format+xml";
6312 if (defined $cgi->http('HTTP_ACCEPT') &&
6313 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6314 # browser (feed reader) prefers text/xml
6315 $content_type = 'text/xml';
6317 if (defined($commitlist[0])) {
6318 %latest_commit = %{$commitlist[0]};
6319 my $latest_epoch = $latest_commit{'committer_epoch'};
6320 %latest_date = parse_date($latest_epoch);
6321 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6322 if (defined $if_modified) {
6323 my $since;
6324 if (eval { require HTTP::Date; 1; }) {
6325 $since = HTTP::Date::str2time($if_modified);
6326 } elsif (eval { require Time::ParseDate; 1; }) {
6327 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6329 if (defined $since && $latest_epoch <= $since) {
6330 print $cgi->header(
6331 -type => $content_type,
6332 -charset => 'utf-8',
6333 -last_modified => $latest_date{'rfc2822'},
6334 -status => '304 Not Modified');
6335 return;
6338 print $cgi->header(
6339 -type => $content_type,
6340 -charset => 'utf-8',
6341 -last_modified => $latest_date{'rfc2822'});
6342 } else {
6343 print $cgi->header(
6344 -type => $content_type,
6345 -charset => 'utf-8');
6348 # Optimization: skip generating the body if client asks only
6349 # for Last-Modified date.
6350 return if ($cgi->request_method() eq 'HEAD');
6352 # header variables
6353 my $title = "$site_name - $project/$action";
6354 my $feed_type = 'log';
6355 if (defined $hash) {
6356 $title .= " - '$hash'";
6357 $feed_type = 'branch log';
6358 if (defined $file_name) {
6359 $title .= " :: $file_name";
6360 $feed_type = 'history';
6362 } elsif (defined $file_name) {
6363 $title .= " - $file_name";
6364 $feed_type = 'history';
6366 $title .= " $feed_type";
6367 my $descr = git_get_project_description($project);
6368 if (defined $descr) {
6369 $descr = esc_html($descr);
6370 } else {
6371 $descr = "$project " .
6372 ($format eq 'rss' ? 'RSS' : 'Atom') .
6373 " feed";
6375 my $owner = git_get_project_owner($project);
6376 $owner = esc_html($owner);
6378 #header
6379 my $alt_url;
6380 if (defined $file_name) {
6381 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6382 } elsif (defined $hash) {
6383 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6384 } else {
6385 $alt_url = href(-full=>1, action=>"summary");
6387 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6388 if ($format eq 'rss') {
6389 print <<XML;
6390 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6391 <channel>
6393 print "<title>$title</title>\n" .
6394 "<link>$alt_url</link>\n" .
6395 "<description>$descr</description>\n" .
6396 "<language>en</language>\n" .
6397 # project owner is responsible for 'editorial' content
6398 "<managingEditor>$owner</managingEditor>\n";
6399 if (defined $logo || defined $favicon) {
6400 # prefer the logo to the favicon, since RSS
6401 # doesn't allow both
6402 my $img = esc_url($logo || $favicon);
6403 print "<image>\n" .
6404 "<url>$img</url>\n" .
6405 "<title>$title</title>\n" .
6406 "<link>$alt_url</link>\n" .
6407 "</image>\n";
6409 if (%latest_date) {
6410 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6411 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6413 print "<generator>gitweb v.$version/$git_version</generator>\n";
6414 } elsif ($format eq 'atom') {
6415 print <<XML;
6416 <feed xmlns="http://www.w3.org/2005/Atom">
6418 print "<title>$title</title>\n" .
6419 "<subtitle>$descr</subtitle>\n" .
6420 '<link rel="alternate" type="text/html" href="' .
6421 $alt_url . '" />' . "\n" .
6422 '<link rel="self" type="' . $content_type . '" href="' .
6423 $cgi->self_url() . '" />' . "\n" .
6424 "<id>" . href(-full=>1) . "</id>\n" .
6425 # use project owner for feed author
6426 "<author><name>$owner</name></author>\n";
6427 if (defined $favicon) {
6428 print "<icon>" . esc_url($favicon) . "</icon>\n";
6430 if (defined $logo_url) {
6431 # not twice as wide as tall: 72 x 27 pixels
6432 print "<logo>" . esc_url($logo) . "</logo>\n";
6434 if (! %latest_date) {
6435 # dummy date to keep the feed valid until commits trickle in:
6436 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6437 } else {
6438 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6440 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6443 # contents
6444 for (my $i = 0; $i <= $#commitlist; $i++) {
6445 my %co = %{$commitlist[$i]};
6446 my $commit = $co{'id'};
6447 # we read 150, we always show 30 and the ones more recent than 48 hours
6448 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6449 last;
6451 my %cd = parse_date($co{'author_epoch'});
6453 # get list of changed files
6454 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6455 $co{'parent'} || "--root",
6456 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6457 or next;
6458 my @difftree = map { chomp; $_ } <$fd>;
6459 close $fd
6460 or next;
6462 # print element (entry, item)
6463 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6464 if ($format eq 'rss') {
6465 print "<item>\n" .
6466 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6467 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6468 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6469 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6470 "<link>$co_url</link>\n" .
6471 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6472 "<content:encoded>" .
6473 "<![CDATA[\n";
6474 } elsif ($format eq 'atom') {
6475 print "<entry>\n" .
6476 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6477 "<updated>$cd{'iso-8601'}</updated>\n" .
6478 "<author>\n" .
6479 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6480 if ($co{'author_email'}) {
6481 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6483 print "</author>\n" .
6484 # use committer for contributor
6485 "<contributor>\n" .
6486 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6487 if ($co{'committer_email'}) {
6488 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6490 print "</contributor>\n" .
6491 "<published>$cd{'iso-8601'}</published>\n" .
6492 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6493 "<id>$co_url</id>\n" .
6494 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6495 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6497 my $comment = $co{'comment'};
6498 print "<pre>\n";
6499 foreach my $line (@$comment) {
6500 $line = esc_html($line);
6501 print "$line\n";
6503 print "</pre><ul>\n";
6504 foreach my $difftree_line (@difftree) {
6505 my %difftree = parse_difftree_raw_line($difftree_line);
6506 next if !$difftree{'from_id'};
6508 my $file = $difftree{'file'} || $difftree{'to_file'};
6510 print "<li>" .
6511 "[" .
6512 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6513 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6514 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6515 file_name=>$file, file_parent=>$difftree{'from_file'}),
6516 -title => "diff"}, 'D');
6517 if ($have_blame) {
6518 print $cgi->a({-href => href(-full=>1, action=>"blame",
6519 file_name=>$file, hash_base=>$commit),
6520 -title => "blame"}, 'B');
6522 # if this is not a feed of a file history
6523 if (!defined $file_name || $file_name ne $file) {
6524 print $cgi->a({-href => href(-full=>1, action=>"history",
6525 file_name=>$file, hash=>$commit),
6526 -title => "history"}, 'H');
6528 $file = esc_path($file);
6529 print "] ".
6530 "$file</li>\n";
6532 if ($format eq 'rss') {
6533 print "</ul>]]>\n" .
6534 "</content:encoded>\n" .
6535 "</item>\n";
6536 } elsif ($format eq 'atom') {
6537 print "</ul>\n</div>\n" .
6538 "</content>\n" .
6539 "</entry>\n";
6543 # end of feed
6544 if ($format eq 'rss') {
6545 print "</channel>\n</rss>\n";
6546 } elsif ($format eq 'atom') {
6547 print "</feed>\n";
6551 sub git_rss {
6552 git_feed('rss');
6555 sub git_atom {
6556 git_feed('atom');
6559 sub git_opml {
6560 my @list = git_get_projects_list();
6562 print $cgi->header(
6563 -type => 'text/xml',
6564 -charset => 'utf-8',
6565 -content_disposition => 'inline; filename="opml.xml"');
6567 print <<XML;
6568 <?xml version="1.0" encoding="utf-8"?>
6569 <opml version="1.0">
6570 <head>
6571 <title>$site_name OPML Export</title>
6572 </head>
6573 <body>
6574 <outline text="git RSS feeds">
6577 foreach my $pr (@list) {
6578 my %proj = %$pr;
6579 my $head = git_get_head_hash($proj{'path'});
6580 if (!defined $head) {
6581 next;
6583 $git_dir = "$projectroot/$proj{'path'}";
6584 my %co = parse_commit($head);
6585 if (!%co) {
6586 next;
6589 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6590 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6591 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6592 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6594 print <<XML;
6595 </outline>
6596 </body>
6597 </opml>