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