Code

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