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