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