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