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