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