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