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