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