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