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