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