Merge branch 't/forks/sort-by-age' into refs/top-bases/master
[git/gitweb.git] / gitweb / gitweb.perl
blobb75b7ff179e5d89c8a8f16c0f938623c4f222ba5
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
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 BEGIN {
22 CGI->compile() if $ENV{'MOD_PERL'};
25 our $cgi = new CGI;
26 our $version = "++GIT_VERSION++";
27 our $my_url = $cgi->url();
28 our $my_uri = $cgi->url(-absolute => 1);
30 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
31 # needed and used only for URLs with nonempty PATH_INFO
32 our $base_url = $my_url;
34 # When the script is used as DirectoryIndex, the URL does not contain the name
35 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
36 # have to do it ourselves. We make $path_info global because it's also used
37 # later on.
39 # Another issue with the script being the DirectoryIndex is that the resulting
40 # $my_url data is not the full script URL: this is good, because we want
41 # generated links to keep implying the script name if it wasn't explicitly
42 # indicated in the URL we're handling, but it means that $my_url cannot be used
43 # as base URL.
44 # Therefore, if we needed to strip PATH_INFO, then we know that we have
45 # to build the base URL ourselves:
46 our $path_info = $ENV{"PATH_INFO"};
47 if ($path_info) {
48 if ($my_url =~ s,\Q$path_info\E$,, &&
49 $my_uri =~ s,\Q$path_info\E$,, &&
50 defined $ENV{'SCRIPT_NAME'}) {
51 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
55 # core git executable to use
56 # this can just be "git" if your webserver has a sensible PATH
57 our $GIT = "++GIT_BINDIR++/git";
59 # absolute fs-path which will be prepended to the project path
60 #our $projectroot = "/pub/scm";
61 our $projectroot = "++GITWEB_PROJECTROOT++";
63 # fs traversing limit for getting project list
64 # the number is relative to the projectroot
65 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
67 # target of the home link on top of all pages
68 our $home_link = $my_uri || "/";
70 # string of the home link on top of all pages
71 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
73 # name of your site or organization to appear in page titles
74 # replace this with something more descriptive for clearer bookmarks
75 our $site_name = "++GITWEB_SITENAME++"
76 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
78 # filename of html text to include at top of each page
79 our $site_header = "++GITWEB_SITE_HEADER++";
80 # html text to include at home page
81 our $home_text = "++GITWEB_HOMETEXT++";
82 # filename of html text to include at bottom of each page
83 our $site_footer = "++GITWEB_SITE_FOOTER++";
85 # URI of stylesheets
86 our @stylesheets = ("++GITWEB_CSS++");
87 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
88 our $stylesheet = undef;
89 # URI of GIT logo (72x27 size)
90 our $logo = "++GITWEB_LOGO++";
91 # URI of GIT favicon, assumed to be image/png type
92 our $favicon = "++GITWEB_FAVICON++";
94 # URI and label (title) of GIT logo link
95 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
96 #our $logo_label = "git documentation";
97 our $logo_url = "http://git.or.cz/";
98 our $logo_label = "git homepage";
100 # source of projects list
101 our $projects_list = "++GITWEB_LIST++";
103 # the width (in characters) of the projects list "Description" column
104 our $projects_list_description_width = 25;
106 # default order of projects list
107 # valid values are none, project, descr, owner, and age
108 our $default_projects_order = "project";
110 # show repository only if this file exists
111 # (only effective if this variable evaluates to true)
112 our $export_ok = "++GITWEB_EXPORT_OK++";
114 # show repository only if this subroutine returns true
115 # when given the path to the project, for example:
116 # sub { return -e "$_[0]/git-daemon-export-ok"; }
117 our $export_auth_hook = undef;
119 # only allow viewing of repositories also shown on the overview page
120 our $strict_export = "++GITWEB_STRICT_EXPORT++";
122 # list of git base URLs used for URL to where fetch project from,
123 # i.e. full URL is "$git_base_url/$project"
124 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
126 # default blob_plain mimetype and default charset for text/plain blob
127 our $default_blob_plain_mimetype = 'text/plain';
128 our $default_text_plain_charset = undef;
130 # file to use for guessing MIME types before trying /etc/mime.types
131 # (relative to the current git repository)
132 our $mimetypes_file = undef;
134 # assume this charset if line contains non-UTF-8 characters;
135 # it should be valid encoding (see Encoding::Supported(3pm) for list),
136 # for which encoding all byte sequences are valid, for example
137 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
138 # could be even 'utf-8' for the old behavior)
139 our $fallback_encoding = 'latin1';
141 # rename detection options for git-diff and git-diff-tree
142 # - default is '-M', with the cost proportional to
143 # (number of removed files) * (number of new files).
144 # - more costly is '-C' (which implies '-M'), with the cost proportional to
145 # (number of changed files + number of removed files) * (number of new files)
146 # - even more costly is '-C', '--find-copies-harder' with cost
147 # (number of files in the original tree) * (number of new files)
148 # - one might want to include '-B' option, e.g. '-B', '-M'
149 our @diff_opts = ('-M'); # taken from git_commit
151 # Disables features that would allow repository owners to inject script into
152 # the gitweb domain.
153 our $prevent_xss = 0;
155 # information about snapshot formats that gitweb is capable of serving
156 our %known_snapshot_formats = (
157 # name => {
158 # 'display' => display name,
159 # 'type' => mime type,
160 # 'suffix' => filename suffix,
161 # 'format' => --format for git-archive,
162 # 'compressor' => [compressor command and arguments]
163 # (array reference, optional)}
165 'tgz' => {
166 'display' => 'tar.gz',
167 'type' => 'application/x-gzip',
168 'suffix' => '.tar.gz',
169 'format' => 'tar',
170 'compressor' => ['gzip']},
172 'tbz2' => {
173 'display' => 'tar.bz2',
174 'type' => 'application/x-bzip2',
175 'suffix' => '.tar.bz2',
176 'format' => 'tar',
177 'compressor' => ['bzip2']},
179 'zip' => {
180 'display' => 'zip',
181 'type' => 'application/x-zip',
182 'suffix' => '.zip',
183 'format' => 'zip'},
186 # Aliases so we understand old gitweb.snapshot values in repository
187 # configuration.
188 our %known_snapshot_format_aliases = (
189 'gzip' => 'tgz',
190 'bzip2' => 'tbz2',
192 # backward compatibility: legacy gitweb config support
193 'x-gzip' => undef, 'gz' => undef,
194 'x-bzip2' => undef, 'bz2' => undef,
195 'x-zip' => undef, '' => undef,
198 # You define site-wide feature defaults here; override them with
199 # $GITWEB_CONFIG as necessary.
200 our %feature = (
201 # feature => {
202 # 'sub' => feature-sub (subroutine),
203 # 'override' => allow-override (boolean),
204 # 'default' => [ default options...] (array reference)}
206 # if feature is overridable (it means that allow-override has true value),
207 # then feature-sub will be called with default options as parameters;
208 # return value of feature-sub indicates if to enable specified feature
210 # if there is no 'sub' key (no feature-sub), then feature cannot be
211 # overriden
213 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
214 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
215 # is enabled
217 # Enable the 'blame' blob view, showing the last commit that modified
218 # each line in the file. This can be very CPU-intensive.
220 # To enable system wide have in $GITWEB_CONFIG
221 # $feature{'blame'}{'default'} = [1];
222 # To have project specific config enable override in $GITWEB_CONFIG
223 # $feature{'blame'}{'override'} = 1;
224 # and in project config gitweb.blame = 0|1;
225 'blame' => {
226 'sub' => sub { feature_bool('blame', @_) },
227 'override' => 0,
228 'default' => [0]},
230 # Enable the 'snapshot' link, providing a compressed archive of any
231 # tree. This can potentially generate high traffic if you have large
232 # project.
234 # Value is a list of formats defined in %known_snapshot_formats that
235 # you wish to offer.
236 # To disable system wide have in $GITWEB_CONFIG
237 # $feature{'snapshot'}{'default'} = [];
238 # To have project specific config enable override in $GITWEB_CONFIG
239 # $feature{'snapshot'}{'override'} = 1;
240 # and in project config, a comma-separated list of formats or "none"
241 # to disable. Example: gitweb.snapshot = tbz2,zip;
242 'snapshot' => {
243 'sub' => \&feature_snapshot,
244 'override' => 0,
245 'default' => ['tgz']},
247 # Enable text search, which will list the commits which match author,
248 # committer or commit text to a given string. Enabled by default.
249 # Project specific override is not supported.
250 'search' => {
251 'override' => 0,
252 'default' => [1]},
254 # Enable grep search, which will list the files in currently selected
255 # tree containing the given string. Enabled by default. This can be
256 # potentially CPU-intensive, of course.
258 # To enable system wide have in $GITWEB_CONFIG
259 # $feature{'grep'}{'default'} = [1];
260 # To have project specific config enable override in $GITWEB_CONFIG
261 # $feature{'grep'}{'override'} = 1;
262 # and in project config gitweb.grep = 0|1;
263 'grep' => {
264 'sub' => sub { feature_bool('grep', @_) },
265 'override' => 0,
266 'default' => [1]},
268 # Enable the pickaxe search, which will list the commits that modified
269 # a given string in a file. This can be practical and quite faster
270 # alternative to 'blame', but still potentially CPU-intensive.
272 # To enable system wide have in $GITWEB_CONFIG
273 # $feature{'pickaxe'}{'default'} = [1];
274 # To have project specific config enable override in $GITWEB_CONFIG
275 # $feature{'pickaxe'}{'override'} = 1;
276 # and in project config gitweb.pickaxe = 0|1;
277 'pickaxe' => {
278 'sub' => sub { feature_bool('pickaxe', @_) },
279 'override' => 0,
280 'default' => [1]},
282 # Make gitweb use an alternative format of the URLs which can be
283 # more readable and natural-looking: project name is embedded
284 # directly in the path and the query string contains other
285 # auxiliary information. All gitweb installations recognize
286 # URL in either format; this configures in which formats gitweb
287 # generates links.
289 # To enable system wide have in $GITWEB_CONFIG
290 # $feature{'pathinfo'}{'default'} = [1];
291 # Project specific override is not supported.
293 # Note that you will need to change the default location of CSS,
294 # favicon, logo and possibly other files to an absolute URL. Also,
295 # if gitweb.cgi serves as your indexfile, you will need to force
296 # $my_uri to contain the script name in your $GITWEB_CONFIG.
297 'pathinfo' => {
298 'override' => 0,
299 'default' => [0]},
301 # Make gitweb consider projects in project root subdirectories
302 # to be forks of existing projects. Given project $projname.git,
303 # projects matching $projname/*.git will not be shown in the main
304 # projects list, instead a '+' mark will be added to $projname
305 # there and a 'forks' view will be enabled for the project, listing
306 # all the forks. If project list is taken from a file, forks have
307 # to be listed after the main project.
309 # To enable system wide have in $GITWEB_CONFIG
310 # $feature{'forks'}{'default'} = [1];
311 # Project specific override is not supported.
312 'forks' => {
313 'override' => 0,
314 'default' => [0]},
316 # Insert custom links to the action bar of all project pages.
317 # This enables you mainly to link to third-party scripts integrating
318 # into gitweb; e.g. git-browser for graphical history representation
319 # or custom web-based repository administration interface.
321 # The 'default' value consists of a list of triplets in the form
322 # (label, link, position) where position is the label after which
323 # to insert the link and link is a format string where %n expands
324 # to the project name, %f to the project path within the filesystem,
325 # %h to the current hash (h gitweb parameter) and %b to the current
326 # hash base (hb gitweb parameter); %% expands to %.
328 # To enable system wide have in $GITWEB_CONFIG e.g.
329 # $feature{'actions'}{'default'} = [('graphiclog',
330 # '/git-browser/by-commit.html?r=%n', 'summary')];
331 # Project specific override is not supported.
332 'actions' => {
333 'override' => 0,
334 'default' => []},
336 # Allow gitweb scan project content tags described in ctags/
337 # of project repository, and display the popular Web 2.0-ish
338 # "tag cloud" near the project list. Note that this is something
339 # COMPLETELY different from the normal Git tags.
341 # gitweb by itself can show existing tags, but it does not handle
342 # tagging itself; you need an external application for that.
343 # For an example script, check Girocco's cgi/tagproj.cgi.
344 # You may want to install the HTML::TagCloud Perl module to get
345 # a pretty tag cloud instead of just a list of tags.
347 # To enable system wide have in $GITWEB_CONFIG
348 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
349 # Project specific override is not supported.
350 'ctags' => {
351 'override' => 0,
352 'default' => [0]},
354 # The maximum number of patches in a patchset generated in patch
355 # view. Set this to 0 or undef to disable patch view, or to a
356 # negative number to remove any limit.
358 # To disable system wide have in $GITWEB_CONFIG
359 # $feature{'patches'}{'default'} = [0];
360 # To have project specific config enable override in $GITWEB_CONFIG
361 # $feature{'patches'}{'override'} = 1;
362 # and in project config gitweb.patches = 0|n;
363 # where n is the maximum number of patches allowed in a patchset.
364 'patches' => {
365 'sub' => \&feature_patches,
366 'override' => 0,
367 'default' => [16]},
370 sub gitweb_get_feature {
371 my ($name) = @_;
372 return unless exists $feature{$name};
373 my ($sub, $override, @defaults) = (
374 $feature{$name}{'sub'},
375 $feature{$name}{'override'},
376 @{$feature{$name}{'default'}});
377 if (!$override) { return @defaults; }
378 if (!defined $sub) {
379 warn "feature $name is not overrideable";
380 return @defaults;
382 return $sub->(@defaults);
385 # A wrapper to check if a given feature is enabled.
386 # With this, you can say
388 # my $bool_feat = gitweb_check_feature('bool_feat');
389 # gitweb_check_feature('bool_feat') or somecode;
391 # instead of
393 # my ($bool_feat) = gitweb_get_feature('bool_feat');
394 # (gitweb_get_feature('bool_feat'))[0] or somecode;
396 sub gitweb_check_feature {
397 return (gitweb_get_feature(@_))[0];
401 sub feature_bool {
402 my $key = shift;
403 my ($val) = git_get_project_config($key, '--bool');
405 if (!defined $val) {
406 return ($_[0]);
407 } elsif ($val eq 'true') {
408 return (1);
409 } elsif ($val eq 'false') {
410 return (0);
414 sub feature_snapshot {
415 my (@fmts) = @_;
417 my ($val) = git_get_project_config('snapshot');
419 if ($val) {
420 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
423 return @fmts;
426 sub feature_patches {
427 my @val = (git_get_project_config('patches', '--int'));
429 if (@val) {
430 return @val;
433 return ($_[0]);
436 # checking HEAD file with -e is fragile if the repository was
437 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
438 # and then pruned.
439 sub check_head_link {
440 my ($dir) = @_;
441 my $headfile = "$dir/HEAD";
442 return ((-e $headfile) ||
443 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
446 sub check_export_ok {
447 my ($dir) = @_;
448 return (check_head_link($dir) &&
449 (!$export_ok || -e "$dir/$export_ok") &&
450 (!$export_auth_hook || $export_auth_hook->($dir)));
453 # process alternate names for backward compatibility
454 # filter out unsupported (unknown) snapshot formats
455 sub filter_snapshot_fmts {
456 my @fmts = @_;
458 @fmts = map {
459 exists $known_snapshot_format_aliases{$_} ?
460 $known_snapshot_format_aliases{$_} : $_} @fmts;
461 @fmts = grep {
462 exists $known_snapshot_formats{$_} } @fmts;
465 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
466 if (-e $GITWEB_CONFIG) {
467 do $GITWEB_CONFIG;
468 } else {
469 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
470 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
473 # version of the core git binary
474 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
476 $projects_list ||= $projectroot;
478 # ======================================================================
479 # input validation and dispatch
481 # input parameters can be collected from a variety of sources (presently, CGI
482 # and PATH_INFO), so we define an %input_params hash that collects them all
483 # together during validation: this allows subsequent uses (e.g. href()) to be
484 # agnostic of the parameter origin
486 our %input_params = ();
488 # input parameters are stored with the long parameter name as key. This will
489 # also be used in the href subroutine to convert parameters to their CGI
490 # equivalent, and since the href() usage is the most frequent one, we store
491 # the name -> CGI key mapping here, instead of the reverse.
493 # XXX: Warning: If you touch this, check the search form for updating,
494 # too.
496 our @cgi_param_mapping = (
497 project => "p",
498 action => "a",
499 file_name => "f",
500 file_parent => "fp",
501 hash => "h",
502 hash_parent => "hp",
503 hash_base => "hb",
504 hash_parent_base => "hpb",
505 page => "pg",
506 order => "o",
507 searchtext => "s",
508 searchtype => "st",
509 snapshot_format => "sf",
510 extra_options => "opt",
511 search_use_regexp => "sr",
513 our %cgi_param_mapping = @cgi_param_mapping;
515 # we will also need to know the possible actions, for validation
516 our %actions = (
517 "blame" => \&git_blame,
518 "blobdiff" => \&git_blobdiff,
519 "blobdiff_plain" => \&git_blobdiff_plain,
520 "blob" => \&git_blob,
521 "blob_plain" => \&git_blob_plain,
522 "commitdiff" => \&git_commitdiff,
523 "commitdiff_plain" => \&git_commitdiff_plain,
524 "commit" => \&git_commit,
525 "forks" => \&git_forks,
526 "heads" => \&git_heads,
527 "history" => \&git_history,
528 "log" => \&git_log,
529 "patch" => \&git_patch,
530 "patches" => \&git_patches,
531 "rss" => \&git_rss,
532 "atom" => \&git_atom,
533 "search" => \&git_search,
534 "search_help" => \&git_search_help,
535 "shortlog" => \&git_shortlog,
536 "summary" => \&git_summary,
537 "tag" => \&git_tag,
538 "tags" => \&git_tags,
539 "tree" => \&git_tree,
540 "snapshot" => \&git_snapshot,
541 "object" => \&git_object,
542 # those below don't need $project
543 "opml" => \&git_opml,
544 "project_list" => \&git_project_list,
545 "project_index" => \&git_project_index,
548 # finally, we have the hash of allowed extra_options for the commands that
549 # allow them
550 our %allowed_options = (
551 "--no-merges" => [ qw(rss atom log shortlog history) ],
554 # fill %input_params with the CGI parameters. All values except for 'opt'
555 # should be single values, but opt can be an array. We should probably
556 # build an array of parameters that can be multi-valued, but since for the time
557 # being it's only this one, we just single it out
558 while (my ($name, $symbol) = each %cgi_param_mapping) {
559 if ($symbol eq 'opt') {
560 $input_params{$name} = [ $cgi->param($symbol) ];
561 } else {
562 $input_params{$name} = $cgi->param($symbol);
566 # now read PATH_INFO and update the parameter list for missing parameters
567 sub evaluate_path_info {
568 return if defined $input_params{'project'};
569 return if !$path_info;
570 $path_info =~ s,^/+,,;
571 return if !$path_info;
573 # find which part of PATH_INFO is project
574 my $project = $path_info;
575 $project =~ s,/+$,,;
576 while ($project && !check_head_link("$projectroot/$project")) {
577 $project =~ s,/*[^/]*$,,;
579 return unless $project;
580 $input_params{'project'} = $project;
582 # do not change any parameters if an action is given using the query string
583 return if $input_params{'action'};
584 $path_info =~ s,^\Q$project\E/*,,;
586 # next, check if we have an action
587 my $action = $path_info;
588 $action =~ s,/.*$,,;
589 if (exists $actions{$action}) {
590 $path_info =~ s,^$action/*,,;
591 $input_params{'action'} = $action;
594 # list of actions that want hash_base instead of hash, but can have no
595 # pathname (f) parameter
596 my @wants_base = (
597 'tree',
598 'history',
601 # we want to catch
602 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
603 my ($parentrefname, $parentpathname, $refname, $pathname) =
604 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
606 # first, analyze the 'current' part
607 if (defined $pathname) {
608 # we got "branch:filename" or "branch:dir/"
609 # we could use git_get_type(branch:pathname), but:
610 # - it needs $git_dir
611 # - it does a git() call
612 # - the convention of terminating directories with a slash
613 # makes it superfluous
614 # - embedding the action in the PATH_INFO would make it even
615 # more superfluous
616 $pathname =~ s,^/+,,;
617 if (!$pathname || substr($pathname, -1) eq "/") {
618 $input_params{'action'} ||= "tree";
619 $pathname =~ s,/$,,;
620 } else {
621 # the default action depends on whether we had parent info
622 # or not
623 if ($parentrefname) {
624 $input_params{'action'} ||= "blobdiff_plain";
625 } else {
626 $input_params{'action'} ||= "blob_plain";
629 $input_params{'hash_base'} ||= $refname;
630 $input_params{'file_name'} ||= $pathname;
631 } elsif (defined $refname) {
632 # we got "branch". In this case we have to choose if we have to
633 # set hash or hash_base.
635 # Most of the actions without a pathname only want hash to be
636 # set, except for the ones specified in @wants_base that want
637 # hash_base instead. It should also be noted that hand-crafted
638 # links having 'history' as an action and no pathname or hash
639 # set will fail, but that happens regardless of PATH_INFO.
640 $input_params{'action'} ||= "shortlog";
641 if (grep { $_ eq $input_params{'action'} } @wants_base) {
642 $input_params{'hash_base'} ||= $refname;
643 } else {
644 $input_params{'hash'} ||= $refname;
648 # next, handle the 'parent' part, if present
649 if (defined $parentrefname) {
650 # a missing pathspec defaults to the 'current' filename, allowing e.g.
651 # someproject/blobdiff/oldrev..newrev:/filename
652 if ($parentpathname) {
653 $parentpathname =~ s,^/+,,;
654 $parentpathname =~ s,/$,,;
655 $input_params{'file_parent'} ||= $parentpathname;
656 } else {
657 $input_params{'file_parent'} ||= $input_params{'file_name'};
659 # we assume that hash_parent_base is wanted if a path was specified,
660 # or if the action wants hash_base instead of hash
661 if (defined $input_params{'file_parent'} ||
662 grep { $_ eq $input_params{'action'} } @wants_base) {
663 $input_params{'hash_parent_base'} ||= $parentrefname;
664 } else {
665 $input_params{'hash_parent'} ||= $parentrefname;
669 # for the snapshot action, we allow URLs in the form
670 # $project/snapshot/$hash.ext
671 # where .ext determines the snapshot and gets removed from the
672 # passed $refname to provide the $hash.
674 # To be able to tell that $refname includes the format extension, we
675 # require the following two conditions to be satisfied:
676 # - the hash input parameter MUST have been set from the $refname part
677 # of the URL (i.e. they must be equal)
678 # - the snapshot format MUST NOT have been defined already (e.g. from
679 # CGI parameter sf)
680 # It's also useless to try any matching unless $refname has a dot,
681 # so we check for that too
682 if (defined $input_params{'action'} &&
683 $input_params{'action'} eq 'snapshot' &&
684 defined $refname && index($refname, '.') != -1 &&
685 $refname eq $input_params{'hash'} &&
686 !defined $input_params{'snapshot_format'}) {
687 # We loop over the known snapshot formats, checking for
688 # extensions. Allowed extensions are both the defined suffix
689 # (which includes the initial dot already) and the snapshot
690 # format key itself, with a prepended dot
691 while (my ($fmt, $opt) = each %known_snapshot_formats) {
692 my $hash = $refname;
693 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
694 next;
696 my $sfx = $1;
697 # a valid suffix was found, so set the snapshot format
698 # and reset the hash parameter
699 $input_params{'snapshot_format'} = $fmt;
700 $input_params{'hash'} = $hash;
701 # we also set the format suffix to the one requested
702 # in the URL: this way a request for e.g. .tgz returns
703 # a .tgz instead of a .tar.gz
704 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
705 last;
709 evaluate_path_info();
711 our $action = $input_params{'action'};
712 if (defined $action) {
713 if (!validate_action($action)) {
714 die_error(400, "Invalid action parameter");
718 # parameters which are pathnames
719 our $project = $input_params{'project'};
720 if (defined $project) {
721 if (!validate_project($project)) {
722 undef $project;
723 die_error(404, "No such project");
727 our $file_name = $input_params{'file_name'};
728 if (defined $file_name) {
729 if (!validate_pathname($file_name)) {
730 die_error(400, "Invalid file parameter");
734 our $file_parent = $input_params{'file_parent'};
735 if (defined $file_parent) {
736 if (!validate_pathname($file_parent)) {
737 die_error(400, "Invalid file parent parameter");
741 # parameters which are refnames
742 our $hash = $input_params{'hash'};
743 if (defined $hash) {
744 if (!validate_refname($hash)) {
745 die_error(400, "Invalid hash parameter");
749 our $hash_parent = $input_params{'hash_parent'};
750 if (defined $hash_parent) {
751 if (!validate_refname($hash_parent)) {
752 die_error(400, "Invalid hash parent parameter");
756 our $hash_base = $input_params{'hash_base'};
757 if (defined $hash_base) {
758 if (!validate_refname($hash_base)) {
759 die_error(400, "Invalid hash base parameter");
763 our @extra_options = @{$input_params{'extra_options'}};
764 # @extra_options is always defined, since it can only be (currently) set from
765 # CGI, and $cgi->param() returns the empty array in array context if the param
766 # is not set
767 foreach my $opt (@extra_options) {
768 if (not exists $allowed_options{$opt}) {
769 die_error(400, "Invalid option parameter");
771 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
772 die_error(400, "Invalid option parameter for this action");
776 our $hash_parent_base = $input_params{'hash_parent_base'};
777 if (defined $hash_parent_base) {
778 if (!validate_refname($hash_parent_base)) {
779 die_error(400, "Invalid hash parent base parameter");
783 # other parameters
784 our $page = $input_params{'page'};
785 if (defined $page) {
786 if ($page =~ m/[^0-9]/) {
787 die_error(400, "Invalid page parameter");
791 our $searchtype = $input_params{'searchtype'};
792 if (defined $searchtype) {
793 if ($searchtype =~ m/[^a-z]/) {
794 die_error(400, "Invalid searchtype parameter");
798 our $search_use_regexp = $input_params{'search_use_regexp'};
800 our $searchtext = $input_params{'searchtext'};
801 our $search_regexp;
802 if (defined $searchtext) {
803 if (length($searchtext) < 2) {
804 die_error(403, "At least two characters are required for search parameter");
806 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
809 # path to the current git repository
810 our $git_dir;
811 $git_dir = "$projectroot/$project" if $project;
813 # list of supported snapshot formats
814 our @snapshot_fmts = gitweb_get_feature('snapshot');
815 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
817 # dispatch
818 if (!defined $action) {
819 if (defined $hash) {
820 $action = git_get_type($hash);
821 } elsif (defined $hash_base && defined $file_name) {
822 $action = git_get_type("$hash_base:$file_name");
823 } elsif (defined $project) {
824 $action = 'summary';
825 } else {
826 $action = 'project_list';
829 if (!defined($actions{$action})) {
830 die_error(400, "Unknown action");
832 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
833 !$project) {
834 die_error(400, "Project needed");
836 $actions{$action}->();
837 exit;
839 ## ======================================================================
840 ## action links
842 sub href {
843 my %params = @_;
844 # default is to use -absolute url() i.e. $my_uri
845 my $href = $params{-full} ? $my_url : $my_uri;
847 $params{'project'} = $project unless exists $params{'project'};
849 if ($params{-replay}) {
850 while (my ($name, $symbol) = each %cgi_param_mapping) {
851 if (!exists $params{$name}) {
852 $params{$name} = $input_params{$name};
857 my $use_pathinfo = gitweb_check_feature('pathinfo');
858 if ($use_pathinfo and defined $params{'project'}) {
859 # try to put as many parameters as possible in PATH_INFO:
860 # - project name
861 # - action
862 # - hash_parent or hash_parent_base:/file_parent
863 # - hash or hash_base:/filename
864 # - the snapshot_format as an appropriate suffix
866 # When the script is the root DirectoryIndex for the domain,
867 # $href here would be something like http://gitweb.example.com/
868 # Thus, we strip any trailing / from $href, to spare us double
869 # slashes in the final URL
870 $href =~ s,/$,,;
872 # Then add the project name, if present
873 $href .= "/".esc_url($params{'project'});
874 delete $params{'project'};
876 # since we destructively absorb parameters, we keep this
877 # boolean that remembers if we're handling a snapshot
878 my $is_snapshot = $params{'action'} eq 'snapshot';
880 # Summary just uses the project path URL, any other action is
881 # added to the URL
882 if (defined $params{'action'}) {
883 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
884 delete $params{'action'};
887 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
888 # stripping nonexistent or useless pieces
889 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
890 || $params{'hash_parent'} || $params{'hash'});
891 if (defined $params{'hash_base'}) {
892 if (defined $params{'hash_parent_base'}) {
893 $href .= esc_url($params{'hash_parent_base'});
894 # skip the file_parent if it's the same as the file_name
895 delete $params{'file_parent'} if $params{'file_parent'} eq $params{'file_name'};
896 if (defined $params{'file_parent'} && $params{'file_parent'} !~ /\.\./) {
897 $href .= ":/".esc_url($params{'file_parent'});
898 delete $params{'file_parent'};
900 $href .= "..";
901 delete $params{'hash_parent'};
902 delete $params{'hash_parent_base'};
903 } elsif (defined $params{'hash_parent'}) {
904 $href .= esc_url($params{'hash_parent'}). "..";
905 delete $params{'hash_parent'};
908 $href .= esc_url($params{'hash_base'});
909 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
910 $href .= ":/".esc_url($params{'file_name'});
911 delete $params{'file_name'};
913 delete $params{'hash'};
914 delete $params{'hash_base'};
915 } elsif (defined $params{'hash'}) {
916 $href .= esc_url($params{'hash'});
917 delete $params{'hash'};
920 # If the action was a snapshot, we can absorb the
921 # snapshot_format parameter too
922 if ($is_snapshot) {
923 my $fmt = $params{'snapshot_format'};
924 # snapshot_format should always be defined when href()
925 # is called, but just in case some code forgets, we
926 # fall back to the default
927 $fmt ||= $snapshot_fmts[0];
928 $href .= $known_snapshot_formats{$fmt}{'suffix'};
929 delete $params{'snapshot_format'};
933 # now encode the parameters explicitly
934 my @result = ();
935 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
936 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
937 if (defined $params{$name}) {
938 if (ref($params{$name}) eq "ARRAY") {
939 foreach my $par (@{$params{$name}}) {
940 push @result, $symbol . "=" . esc_param($par);
942 } else {
943 push @result, $symbol . "=" . esc_param($params{$name});
947 $href .= "?" . join(';', @result) if scalar @result;
949 return $href;
953 ## ======================================================================
954 ## validation, quoting/unquoting and escaping
956 sub validate_action {
957 my $input = shift || return undef;
958 return undef unless exists $actions{$input};
959 return $input;
962 sub validate_project {
963 my $input = shift || return undef;
964 if (!validate_pathname($input) ||
965 !(-d "$projectroot/$input") ||
966 !check_export_ok("$projectroot/$input") ||
967 ($strict_export && !project_in_list($input))) {
968 return undef;
969 } else {
970 return $input;
974 sub validate_pathname {
975 my $input = shift || return undef;
977 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
978 # at the beginning, at the end, and between slashes.
979 # also this catches doubled slashes
980 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
981 return undef;
983 # no null characters
984 if ($input =~ m!\0!) {
985 return undef;
987 return $input;
990 sub validate_refname {
991 my $input = shift || return undef;
993 # textual hashes are O.K.
994 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
995 return $input;
997 # it must be correct pathname
998 $input = validate_pathname($input)
999 or return undef;
1000 # restrictions on ref name according to git-check-ref-format
1001 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1002 return undef;
1004 return $input;
1007 # decode sequences of octets in utf8 into Perl's internal form,
1008 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1009 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1010 sub to_utf8 {
1011 my $str = shift;
1012 if (utf8::valid($str)) {
1013 utf8::decode($str);
1014 return $str;
1015 } else {
1016 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1020 # quote unsafe chars, but keep the slash, even when it's not
1021 # correct, but quoted slashes look too horrible in bookmarks
1022 sub esc_param {
1023 my $str = shift;
1024 $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
1025 $str =~ s/\+/%2B/g;
1026 $str =~ s/ /\+/g;
1027 return $str;
1030 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1031 sub esc_url {
1032 my $str = shift;
1033 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1034 $str =~ s/\+/%2B/g;
1035 $str =~ s/ /\+/g;
1036 return $str;
1039 # replace invalid utf8 character with SUBSTITUTION sequence
1040 sub esc_html {
1041 my $str = shift;
1042 my %opts = @_;
1044 $str = to_utf8($str);
1045 $str = $cgi->escapeHTML($str);
1046 if ($opts{'-nbsp'}) {
1047 $str =~ s/ /&nbsp;/g;
1049 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1050 return $str;
1053 # quote control characters and escape filename to HTML
1054 sub esc_path {
1055 my $str = shift;
1056 my %opts = @_;
1058 $str = to_utf8($str);
1059 $str = $cgi->escapeHTML($str);
1060 if ($opts{'-nbsp'}) {
1061 $str =~ s/ /&nbsp;/g;
1063 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1064 return $str;
1067 # Make control characters "printable", using character escape codes (CEC)
1068 sub quot_cec {
1069 my $cntrl = shift;
1070 my %opts = @_;
1071 my %es = ( # character escape codes, aka escape sequences
1072 "\t" => '\t', # tab (HT)
1073 "\n" => '\n', # line feed (LF)
1074 "\r" => '\r', # carrige return (CR)
1075 "\f" => '\f', # form feed (FF)
1076 "\b" => '\b', # backspace (BS)
1077 "\a" => '\a', # alarm (bell) (BEL)
1078 "\e" => '\e', # escape (ESC)
1079 "\013" => '\v', # vertical tab (VT)
1080 "\000" => '\0', # nul character (NUL)
1082 my $chr = ( (exists $es{$cntrl})
1083 ? $es{$cntrl}
1084 : sprintf('\%2x', ord($cntrl)) );
1085 if ($opts{-nohtml}) {
1086 return $chr;
1087 } else {
1088 return "<span class=\"cntrl\">$chr</span>";
1092 # Alternatively use unicode control pictures codepoints,
1093 # Unicode "printable representation" (PR)
1094 sub quot_upr {
1095 my $cntrl = shift;
1096 my %opts = @_;
1098 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1099 if ($opts{-nohtml}) {
1100 return $chr;
1101 } else {
1102 return "<span class=\"cntrl\">$chr</span>";
1106 # git may return quoted and escaped filenames
1107 sub unquote {
1108 my $str = shift;
1110 sub unq {
1111 my $seq = shift;
1112 my %es = ( # character escape codes, aka escape sequences
1113 't' => "\t", # tab (HT, TAB)
1114 'n' => "\n", # newline (NL)
1115 'r' => "\r", # return (CR)
1116 'f' => "\f", # form feed (FF)
1117 'b' => "\b", # backspace (BS)
1118 'a' => "\a", # alarm (bell) (BEL)
1119 'e' => "\e", # escape (ESC)
1120 'v' => "\013", # vertical tab (VT)
1123 if ($seq =~ m/^[0-7]{1,3}$/) {
1124 # octal char sequence
1125 return chr(oct($seq));
1126 } elsif (exists $es{$seq}) {
1127 # C escape sequence, aka character escape code
1128 return $es{$seq};
1130 # quoted ordinary character
1131 return $seq;
1134 if ($str =~ m/^"(.*)"$/) {
1135 # needs unquoting
1136 $str = $1;
1137 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1139 return $str;
1142 # escape tabs (convert tabs to spaces)
1143 sub untabify {
1144 my $line = shift;
1146 while ((my $pos = index($line, "\t")) != -1) {
1147 if (my $count = (8 - ($pos % 8))) {
1148 my $spaces = ' ' x $count;
1149 $line =~ s/\t/$spaces/;
1153 return $line;
1156 sub project_in_list {
1157 my $project = shift;
1158 my @list = git_get_projects_list();
1159 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1162 ## ----------------------------------------------------------------------
1163 ## HTML aware string manipulation
1165 # Try to chop given string on a word boundary between position
1166 # $len and $len+$add_len. If there is no word boundary there,
1167 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1168 # (marking chopped part) would be longer than given string.
1169 sub chop_str {
1170 my $str = shift;
1171 my $len = shift;
1172 my $add_len = shift || 10;
1173 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1175 # Make sure perl knows it is utf8 encoded so we don't
1176 # cut in the middle of a utf8 multibyte char.
1177 $str = to_utf8($str);
1179 # allow only $len chars, but don't cut a word if it would fit in $add_len
1180 # if it doesn't fit, cut it if it's still longer than the dots we would add
1181 # remove chopped character entities entirely
1183 # when chopping in the middle, distribute $len into left and right part
1184 # return early if chopping wouldn't make string shorter
1185 if ($where eq 'center') {
1186 return $str if ($len + 5 >= length($str)); # filler is length 5
1187 $len = int($len/2);
1188 } else {
1189 return $str if ($len + 4 >= length($str)); # filler is length 4
1192 # regexps: ending and beginning with word part up to $add_len
1193 my $endre = qr/.{$len}\w{0,$add_len}/;
1194 my $begre = qr/\w{0,$add_len}.{$len}/;
1196 if ($where eq 'left') {
1197 $str =~ m/^(.*?)($begre)$/;
1198 my ($lead, $body) = ($1, $2);
1199 if (length($lead) > 4) {
1200 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1201 $lead = " ...";
1203 return "$lead$body";
1205 } elsif ($where eq 'center') {
1206 $str =~ m/^($endre)(.*)$/;
1207 my ($left, $str) = ($1, $2);
1208 $str =~ m/^(.*?)($begre)$/;
1209 my ($mid, $right) = ($1, $2);
1210 if (length($mid) > 5) {
1211 $left =~ s/&[^;]*$//;
1212 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1213 $mid = " ... ";
1215 return "$left$mid$right";
1217 } else {
1218 $str =~ m/^($endre)(.*)$/;
1219 my $body = $1;
1220 my $tail = $2;
1221 if (length($tail) > 4) {
1222 $body =~ s/&[^;]*$//;
1223 $tail = "... ";
1225 return "$body$tail";
1229 # takes the same arguments as chop_str, but also wraps a <span> around the
1230 # result with a title attribute if it does get chopped. Additionally, the
1231 # string is HTML-escaped.
1232 sub chop_and_escape_str {
1233 my ($str) = @_;
1235 my $chopped = chop_str(@_);
1236 if ($chopped eq $str) {
1237 return esc_html($chopped);
1238 } else {
1239 $str =~ s/[[:cntrl:]]/?/g;
1240 return $cgi->span({-title=>$str}, esc_html($chopped));
1244 ## ----------------------------------------------------------------------
1245 ## functions returning short strings
1247 # CSS class for given age value (in seconds)
1248 sub age_class {
1249 my $age = shift;
1251 if (!defined $age) {
1252 return "noage";
1253 } elsif ($age < 60*60*2) {
1254 return "age0";
1255 } elsif ($age < 60*60*24*2) {
1256 return "age1";
1257 } else {
1258 return "age2";
1262 # convert age in seconds to "nn units ago" string
1263 sub age_string {
1264 my $age = shift;
1265 my $age_str;
1267 if ($age > 60*60*24*365*2) {
1268 $age_str = (int $age/60/60/24/365);
1269 $age_str .= " years ago";
1270 } elsif ($age > 60*60*24*(365/12)*2) {
1271 $age_str = int $age/60/60/24/(365/12);
1272 $age_str .= " months ago";
1273 } elsif ($age > 60*60*24*7*2) {
1274 $age_str = int $age/60/60/24/7;
1275 $age_str .= " weeks ago";
1276 } elsif ($age > 60*60*24*2) {
1277 $age_str = int $age/60/60/24;
1278 $age_str .= " days ago";
1279 } elsif ($age > 60*60*2) {
1280 $age_str = int $age/60/60;
1281 $age_str .= " hours ago";
1282 } elsif ($age > 60*2) {
1283 $age_str = int $age/60;
1284 $age_str .= " min ago";
1285 } elsif ($age > 2) {
1286 $age_str = int $age;
1287 $age_str .= " sec ago";
1288 } else {
1289 $age_str .= " right now";
1291 return $age_str;
1294 use constant {
1295 S_IFINVALID => 0030000,
1296 S_IFGITLINK => 0160000,
1299 # submodule/subproject, a commit object reference
1300 sub S_ISGITLINK {
1301 my $mode = shift;
1303 return (($mode & S_IFMT) == S_IFGITLINK)
1306 # convert file mode in octal to symbolic file mode string
1307 sub mode_str {
1308 my $mode = oct shift;
1310 if (S_ISGITLINK($mode)) {
1311 return 'm---------';
1312 } elsif (S_ISDIR($mode & S_IFMT)) {
1313 return 'drwxr-xr-x';
1314 } elsif (S_ISLNK($mode)) {
1315 return 'lrwxrwxrwx';
1316 } elsif (S_ISREG($mode)) {
1317 # git cares only about the executable bit
1318 if ($mode & S_IXUSR) {
1319 return '-rwxr-xr-x';
1320 } else {
1321 return '-rw-r--r--';
1323 } else {
1324 return '----------';
1328 # convert file mode in octal to file type string
1329 sub file_type {
1330 my $mode = shift;
1332 if ($mode !~ m/^[0-7]+$/) {
1333 return $mode;
1334 } else {
1335 $mode = oct $mode;
1338 if (S_ISGITLINK($mode)) {
1339 return "submodule";
1340 } elsif (S_ISDIR($mode & S_IFMT)) {
1341 return "directory";
1342 } elsif (S_ISLNK($mode)) {
1343 return "symlink";
1344 } elsif (S_ISREG($mode)) {
1345 return "file";
1346 } else {
1347 return "unknown";
1351 # convert file mode in octal to file type description string
1352 sub file_type_long {
1353 my $mode = shift;
1355 if ($mode !~ m/^[0-7]+$/) {
1356 return $mode;
1357 } else {
1358 $mode = oct $mode;
1361 if (S_ISGITLINK($mode)) {
1362 return "submodule";
1363 } elsif (S_ISDIR($mode & S_IFMT)) {
1364 return "directory";
1365 } elsif (S_ISLNK($mode)) {
1366 return "symlink";
1367 } elsif (S_ISREG($mode)) {
1368 if ($mode & S_IXUSR) {
1369 return "executable";
1370 } else {
1371 return "file";
1373 } else {
1374 return "unknown";
1379 ## ----------------------------------------------------------------------
1380 ## functions returning short HTML fragments, or transforming HTML fragments
1381 ## which don't belong to other sections
1383 # format line of commit message.
1384 sub format_log_line_html {
1385 my $line = shift;
1387 $line = esc_html($line, -nbsp=>1);
1388 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1389 $cgi->a({-href => href(action=>"object", hash=>$1),
1390 -class => "text"}, $1);
1391 }eg;
1393 return $line;
1396 # format marker of refs pointing to given object
1398 # the destination action is chosen based on object type and current context:
1399 # - for annotated tags, we choose the tag view unless it's the current view
1400 # already, in which case we go to shortlog view
1401 # - for other refs, we keep the current view if we're in history, shortlog or
1402 # log view, and select shortlog otherwise
1403 sub format_ref_marker {
1404 my ($refs, $id) = @_;
1405 my $markers = '';
1407 if (defined $refs->{$id}) {
1408 foreach my $ref (@{$refs->{$id}}) {
1409 # this code exploits the fact that non-lightweight tags are the
1410 # only indirect objects, and that they are the only objects for which
1411 # we want to use tag instead of shortlog as action
1412 my ($type, $name) = qw();
1413 my $indirect = ($ref =~ s/\^\{\}$//);
1414 # e.g. tags/v2.6.11 or heads/next
1415 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1416 $type = $1;
1417 $name = $2;
1418 } else {
1419 $type = "ref";
1420 $name = $ref;
1423 my $class = $type;
1424 $class .= " indirect" if $indirect;
1426 my $dest_action = "shortlog";
1428 if ($indirect) {
1429 $dest_action = "tag" unless $action eq "tag";
1430 } elsif ($action =~ /^(history|(short)?log)$/) {
1431 $dest_action = $action;
1434 my $dest = "";
1435 $dest .= "refs/" unless $ref =~ m!^refs/!;
1436 $dest .= $ref;
1438 my $link = $cgi->a({
1439 -href => href(
1440 action=>$dest_action,
1441 hash=>$dest
1442 )}, $name);
1444 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1445 $link . "</span>";
1449 if ($markers) {
1450 return ' <span class="refs">'. $markers . '</span>';
1451 } else {
1452 return "";
1456 # format, perhaps shortened and with markers, title line
1457 sub format_subject_html {
1458 my ($long, $short, $href, $extra) = @_;
1459 $extra = '' unless defined($extra);
1461 if (length($short) < length($long)) {
1462 $long =~ s/[[:cntrl:]]/?/g;
1463 return $cgi->a({-href => $href, -class => "list subject",
1464 -title => to_utf8($long)},
1465 esc_html($short) . $extra);
1466 } else {
1467 return $cgi->a({-href => $href, -class => "list subject"},
1468 esc_html($long) . $extra);
1472 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1473 sub format_git_diff_header_line {
1474 my $line = shift;
1475 my $diffinfo = shift;
1476 my ($from, $to) = @_;
1478 if ($diffinfo->{'nparents'}) {
1479 # combined diff
1480 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1481 if ($to->{'href'}) {
1482 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1483 esc_path($to->{'file'}));
1484 } else { # file was deleted (no href)
1485 $line .= esc_path($to->{'file'});
1487 } else {
1488 # "ordinary" diff
1489 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1490 if ($from->{'href'}) {
1491 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1492 'a/' . esc_path($from->{'file'}));
1493 } else { # file was added (no href)
1494 $line .= 'a/' . esc_path($from->{'file'});
1496 $line .= ' ';
1497 if ($to->{'href'}) {
1498 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1499 'b/' . esc_path($to->{'file'}));
1500 } else { # file was deleted
1501 $line .= 'b/' . esc_path($to->{'file'});
1505 return "<div class=\"diff header\">$line</div>\n";
1508 # format extended diff header line, before patch itself
1509 sub format_extended_diff_header_line {
1510 my $line = shift;
1511 my $diffinfo = shift;
1512 my ($from, $to) = @_;
1514 # match <path>
1515 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1516 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1517 esc_path($from->{'file'}));
1519 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1520 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1521 esc_path($to->{'file'}));
1523 # match single <mode>
1524 if ($line =~ m/\s(\d{6})$/) {
1525 $line .= '<span class="info"> (' .
1526 file_type_long($1) .
1527 ')</span>';
1529 # match <hash>
1530 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1531 # can match only for combined diff
1532 $line = 'index ';
1533 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1534 if ($from->{'href'}[$i]) {
1535 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1536 -class=>"hash"},
1537 substr($diffinfo->{'from_id'}[$i],0,7));
1538 } else {
1539 $line .= '0' x 7;
1541 # separator
1542 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1544 $line .= '..';
1545 if ($to->{'href'}) {
1546 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1547 substr($diffinfo->{'to_id'},0,7));
1548 } else {
1549 $line .= '0' x 7;
1552 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1553 # can match only for ordinary diff
1554 my ($from_link, $to_link);
1555 if ($from->{'href'}) {
1556 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1557 substr($diffinfo->{'from_id'},0,7));
1558 } else {
1559 $from_link = '0' x 7;
1561 if ($to->{'href'}) {
1562 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1563 substr($diffinfo->{'to_id'},0,7));
1564 } else {
1565 $to_link = '0' x 7;
1567 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1568 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1571 return $line . "<br/>\n";
1574 # format from-file/to-file diff header
1575 sub format_diff_from_to_header {
1576 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1577 my $line;
1578 my $result = '';
1580 $line = $from_line;
1581 #assert($line =~ m/^---/) if DEBUG;
1582 # no extra formatting for "^--- /dev/null"
1583 if (! $diffinfo->{'nparents'}) {
1584 # ordinary (single parent) diff
1585 if ($line =~ m!^--- "?a/!) {
1586 if ($from->{'href'}) {
1587 $line = '--- a/' .
1588 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1589 esc_path($from->{'file'}));
1590 } else {
1591 $line = '--- a/' .
1592 esc_path($from->{'file'});
1595 $result .= qq!<div class="diff from_file">$line</div>\n!;
1597 } else {
1598 # combined diff (merge commit)
1599 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1600 if ($from->{'href'}[$i]) {
1601 $line = '--- ' .
1602 $cgi->a({-href=>href(action=>"blobdiff",
1603 hash_parent=>$diffinfo->{'from_id'}[$i],
1604 hash_parent_base=>$parents[$i],
1605 file_parent=>$from->{'file'}[$i],
1606 hash=>$diffinfo->{'to_id'},
1607 hash_base=>$hash,
1608 file_name=>$to->{'file'}),
1609 -class=>"path",
1610 -title=>"diff" . ($i+1)},
1611 $i+1) .
1612 '/' .
1613 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1614 esc_path($from->{'file'}[$i]));
1615 } else {
1616 $line = '--- /dev/null';
1618 $result .= qq!<div class="diff from_file">$line</div>\n!;
1622 $line = $to_line;
1623 #assert($line =~ m/^\+\+\+/) if DEBUG;
1624 # no extra formatting for "^+++ /dev/null"
1625 if ($line =~ m!^\+\+\+ "?b/!) {
1626 if ($to->{'href'}) {
1627 $line = '+++ b/' .
1628 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1629 esc_path($to->{'file'}));
1630 } else {
1631 $line = '+++ b/' .
1632 esc_path($to->{'file'});
1635 $result .= qq!<div class="diff to_file">$line</div>\n!;
1637 return $result;
1640 # create note for patch simplified by combined diff
1641 sub format_diff_cc_simplified {
1642 my ($diffinfo, @parents) = @_;
1643 my $result = '';
1645 $result .= "<div class=\"diff header\">" .
1646 "diff --cc ";
1647 if (!is_deleted($diffinfo)) {
1648 $result .= $cgi->a({-href => href(action=>"blob",
1649 hash_base=>$hash,
1650 hash=>$diffinfo->{'to_id'},
1651 file_name=>$diffinfo->{'to_file'}),
1652 -class => "path"},
1653 esc_path($diffinfo->{'to_file'}));
1654 } else {
1655 $result .= esc_path($diffinfo->{'to_file'});
1657 $result .= "</div>\n" . # class="diff header"
1658 "<div class=\"diff nodifferences\">" .
1659 "Simple merge" .
1660 "</div>\n"; # class="diff nodifferences"
1662 return $result;
1665 # format patch (diff) line (not to be used for diff headers)
1666 sub format_diff_line {
1667 my $line = shift;
1668 my ($from, $to) = @_;
1669 my $diff_class = "";
1671 chomp $line;
1673 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1674 # combined diff
1675 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1676 if ($line =~ m/^\@{3}/) {
1677 $diff_class = " chunk_header";
1678 } elsif ($line =~ m/^\\/) {
1679 $diff_class = " incomplete";
1680 } elsif ($prefix =~ tr/+/+/) {
1681 $diff_class = " add";
1682 } elsif ($prefix =~ tr/-/-/) {
1683 $diff_class = " rem";
1685 } else {
1686 # assume ordinary diff
1687 my $char = substr($line, 0, 1);
1688 if ($char eq '+') {
1689 $diff_class = " add";
1690 } elsif ($char eq '-') {
1691 $diff_class = " rem";
1692 } elsif ($char eq '@') {
1693 $diff_class = " chunk_header";
1694 } elsif ($char eq "\\") {
1695 $diff_class = " incomplete";
1698 $line = untabify($line);
1699 if ($from && $to && $line =~ m/^\@{2} /) {
1700 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1701 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1703 $from_lines = 0 unless defined $from_lines;
1704 $to_lines = 0 unless defined $to_lines;
1706 if ($from->{'href'}) {
1707 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1708 -class=>"list"}, $from_text);
1710 if ($to->{'href'}) {
1711 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1712 -class=>"list"}, $to_text);
1714 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1715 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1716 return "<div class=\"diff$diff_class\">$line</div>\n";
1717 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1718 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1719 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1721 @from_text = split(' ', $ranges);
1722 for (my $i = 0; $i < @from_text; ++$i) {
1723 ($from_start[$i], $from_nlines[$i]) =
1724 (split(',', substr($from_text[$i], 1)), 0);
1727 $to_text = pop @from_text;
1728 $to_start = pop @from_start;
1729 $to_nlines = pop @from_nlines;
1731 $line = "<span class=\"chunk_info\">$prefix ";
1732 for (my $i = 0; $i < @from_text; ++$i) {
1733 if ($from->{'href'}[$i]) {
1734 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1735 -class=>"list"}, $from_text[$i]);
1736 } else {
1737 $line .= $from_text[$i];
1739 $line .= " ";
1741 if ($to->{'href'}) {
1742 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1743 -class=>"list"}, $to_text);
1744 } else {
1745 $line .= $to_text;
1747 $line .= " $prefix</span>" .
1748 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1749 return "<div class=\"diff$diff_class\">$line</div>\n";
1751 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1754 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1755 # linked. Pass the hash of the tree/commit to snapshot.
1756 sub format_snapshot_links {
1757 my ($hash) = @_;
1758 my $num_fmts = @snapshot_fmts;
1759 if ($num_fmts > 1) {
1760 # A parenthesized list of links bearing format names.
1761 # e.g. "snapshot (_tar.gz_ _zip_)"
1762 return "snapshot (" . join(' ', map
1763 $cgi->a({
1764 -href => href(
1765 action=>"snapshot",
1766 hash=>$hash,
1767 snapshot_format=>$_
1769 }, $known_snapshot_formats{$_}{'display'})
1770 , @snapshot_fmts) . ")";
1771 } elsif ($num_fmts == 1) {
1772 # A single "snapshot" link whose tooltip bears the format name.
1773 # i.e. "_snapshot_"
1774 my ($fmt) = @snapshot_fmts;
1775 return
1776 $cgi->a({
1777 -href => href(
1778 action=>"snapshot",
1779 hash=>$hash,
1780 snapshot_format=>$fmt
1782 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1783 }, "snapshot");
1784 } else { # $num_fmts == 0
1785 return undef;
1789 ## ......................................................................
1790 ## functions returning values to be passed, perhaps after some
1791 ## transformation, to other functions; e.g. returning arguments to href()
1793 # returns hash to be passed to href to generate gitweb URL
1794 # in -title key it returns description of link
1795 sub get_feed_info {
1796 my $format = shift || 'Atom';
1797 my %res = (action => lc($format));
1799 # feed links are possible only for project views
1800 return unless (defined $project);
1801 # some views should link to OPML, or to generic project feed,
1802 # or don't have specific feed yet (so they should use generic)
1803 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1805 my $branch;
1806 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1807 # from tag links; this also makes possible to detect branch links
1808 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1809 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1810 $branch = $1;
1812 # find log type for feed description (title)
1813 my $type = 'log';
1814 if (defined $file_name) {
1815 $type = "history of $file_name";
1816 $type .= "/" if ($action eq 'tree');
1817 $type .= " on '$branch'" if (defined $branch);
1818 } else {
1819 $type = "log of $branch" if (defined $branch);
1822 $res{-title} = $type;
1823 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
1824 $res{'file_name'} = $file_name;
1826 return %res;
1829 ## ----------------------------------------------------------------------
1830 ## git utility subroutines, invoking git commands
1832 # returns path to the core git executable and the --git-dir parameter as list
1833 sub git_cmd {
1834 return $GIT, '--git-dir='.$git_dir;
1837 # quote the given arguments for passing them to the shell
1838 # quote_command("command", "arg 1", "arg with ' and ! characters")
1839 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
1840 # Try to avoid using this function wherever possible.
1841 sub quote_command {
1842 return join(' ',
1843 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
1846 # get HEAD ref of given project as hash
1847 sub git_get_head_hash {
1848 my $project = shift;
1849 my $o_git_dir = $git_dir;
1850 my $retval = undef;
1851 $git_dir = "$projectroot/$project";
1852 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1853 my $head = <$fd>;
1854 close $fd;
1855 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1856 $retval = $1;
1859 if (defined $o_git_dir) {
1860 $git_dir = $o_git_dir;
1862 return $retval;
1865 # get type of given object
1866 sub git_get_type {
1867 my $hash = shift;
1869 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1870 my $type = <$fd>;
1871 close $fd or return;
1872 chomp $type;
1873 return $type;
1876 # repository configuration
1877 our $config_file = '';
1878 our %config;
1880 # store multiple values for single key as anonymous array reference
1881 # single values stored directly in the hash, not as [ <value> ]
1882 sub hash_set_multi {
1883 my ($hash, $key, $value) = @_;
1885 if (!exists $hash->{$key}) {
1886 $hash->{$key} = $value;
1887 } elsif (!ref $hash->{$key}) {
1888 $hash->{$key} = [ $hash->{$key}, $value ];
1889 } else {
1890 push @{$hash->{$key}}, $value;
1894 # return hash of git project configuration
1895 # optionally limited to some section, e.g. 'gitweb'
1896 sub git_parse_project_config {
1897 my $section_regexp = shift;
1898 my %config;
1900 local $/ = "\0";
1902 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
1903 or return;
1905 while (my $keyval = <$fh>) {
1906 chomp $keyval;
1907 my ($key, $value) = split(/\n/, $keyval, 2);
1909 hash_set_multi(\%config, $key, $value)
1910 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
1912 close $fh;
1914 return %config;
1917 # convert config value to boolean: 'true' or 'false'
1918 # no value, number > 0, 'true' and 'yes' values are true
1919 # rest of values are treated as false (never as error)
1920 sub config_to_bool {
1921 my $val = shift;
1923 return 1 if !defined $val; # section.key
1925 # strip leading and trailing whitespace
1926 $val =~ s/^\s+//;
1927 $val =~ s/\s+$//;
1929 return (($val =~ /^\d+$/ && $val) || # section.key = 1
1930 ($val =~ /^(?:true|yes)$/i)); # section.key = true
1933 # convert config value to simple decimal number
1934 # an optional value suffix of 'k', 'm', or 'g' will cause the value
1935 # to be multiplied by 1024, 1048576, or 1073741824
1936 sub config_to_int {
1937 my $val = shift;
1939 # strip leading and trailing whitespace
1940 $val =~ s/^\s+//;
1941 $val =~ s/\s+$//;
1943 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
1944 $unit = lc($unit);
1945 # unknown unit is treated as 1
1946 return $num * ($unit eq 'g' ? 1073741824 :
1947 $unit eq 'm' ? 1048576 :
1948 $unit eq 'k' ? 1024 : 1);
1950 return $val;
1953 # convert config value to array reference, if needed
1954 sub config_to_multi {
1955 my $val = shift;
1957 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
1960 sub git_get_project_config {
1961 my ($key, $type) = @_;
1963 # key sanity check
1964 return unless ($key);
1965 $key =~ s/^gitweb\.//;
1966 return if ($key =~ m/\W/);
1968 # type sanity check
1969 if (defined $type) {
1970 $type =~ s/^--//;
1971 $type = undef
1972 unless ($type eq 'bool' || $type eq 'int');
1975 # get config
1976 if (!defined $config_file ||
1977 $config_file ne "$git_dir/config") {
1978 %config = git_parse_project_config('gitweb');
1979 $config_file = "$git_dir/config";
1982 # check if config variable (key) exists
1983 return unless exists $config{"gitweb.$key"};
1985 # ensure given type
1986 if (!defined $type) {
1987 return $config{"gitweb.$key"};
1988 } elsif ($type eq 'bool') {
1989 # backward compatibility: 'git config --bool' returns true/false
1990 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
1991 } elsif ($type eq 'int') {
1992 return config_to_int($config{"gitweb.$key"});
1994 return $config{"gitweb.$key"};
1997 # get hash of given path at given ref
1998 sub git_get_hash_by_path {
1999 my $base = shift;
2000 my $path = shift || return undef;
2001 my $type = shift;
2003 $path =~ s,/+$,,;
2005 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2006 or die_error(500, "Open git-ls-tree failed");
2007 my $line = <$fd>;
2008 close $fd or return undef;
2010 if (!defined $line) {
2011 # there is no tree or hash given by $path at $base
2012 return undef;
2015 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2016 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2017 if (defined $type && $type ne $2) {
2018 # type doesn't match
2019 return undef;
2021 return $3;
2024 # get path of entry with given hash at given tree-ish (ref)
2025 # used to get 'from' filename for combined diff (merge commit) for renames
2026 sub git_get_path_by_hash {
2027 my $base = shift || return;
2028 my $hash = shift || return;
2030 local $/ = "\0";
2032 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2033 or return undef;
2034 while (my $line = <$fd>) {
2035 chomp $line;
2037 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2038 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2039 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2040 close $fd;
2041 return $1;
2044 close $fd;
2045 return undef;
2048 ## ......................................................................
2049 ## git utility functions, directly accessing git repository
2051 sub git_get_project_description {
2052 my $path = shift;
2054 $git_dir = "$projectroot/$path";
2055 open my $fd, '<', "$git_dir/description"
2056 or return git_get_project_config('description');
2057 my $descr = <$fd>;
2058 close $fd;
2059 if (defined $descr) {
2060 chomp $descr;
2062 return $descr;
2065 sub git_get_project_ctags {
2066 my $path = shift;
2067 my $ctags = {};
2069 $git_dir = "$projectroot/$path";
2070 opendir my $dh, "$git_dir/ctags"
2071 or return $ctags;
2072 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2073 open my $ct, '<', $_ or next;
2074 my $val = <$ct>;
2075 chomp $val;
2076 close $ct;
2077 my $ctag = $_; $ctag =~ s#.*/##;
2078 $ctags->{$ctag} = $val;
2080 closedir $dh;
2081 $ctags;
2084 sub git_populate_project_tagcloud {
2085 my $ctags = shift;
2087 # First, merge different-cased tags; tags vote on casing
2088 my %ctags_lc;
2089 foreach (keys %$ctags) {
2090 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2091 if (not $ctags_lc{lc $_}->{topcount}
2092 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2093 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2094 $ctags_lc{lc $_}->{topname} = $_;
2098 my $cloud;
2099 if (eval { require HTML::TagCloud; 1; }) {
2100 $cloud = HTML::TagCloud->new;
2101 foreach (sort keys %ctags_lc) {
2102 # Pad the title with spaces so that the cloud looks
2103 # less crammed.
2104 my $title = $ctags_lc{$_}->{topname};
2105 $title =~ s/ /&nbsp;/g;
2106 $title =~ s/^/&nbsp;/g;
2107 $title =~ s/$/&nbsp;/g;
2108 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2110 } else {
2111 $cloud = \%ctags_lc;
2113 $cloud;
2116 sub git_show_project_tagcloud {
2117 my ($cloud, $count) = @_;
2118 print STDERR ref($cloud)."..\n";
2119 if (ref $cloud eq 'HTML::TagCloud') {
2120 return $cloud->html_and_css($count);
2121 } else {
2122 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2123 return '<p align="center">' . join (', ', map {
2124 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2125 } splice(@tags, 0, $count)) . '</p>';
2129 sub git_get_project_url_list {
2130 my $path = shift;
2132 $git_dir = "$projectroot/$path";
2133 open my $fd, '<', "$git_dir/cloneurl"
2134 or return wantarray ?
2135 @{ config_to_multi(git_get_project_config('url')) } :
2136 config_to_multi(git_get_project_config('url'));
2137 my @git_project_url_list = map { chomp; $_ } <$fd>;
2138 close $fd;
2140 return wantarray ? @git_project_url_list : \@git_project_url_list;
2143 sub git_get_projects_list {
2144 my ($filter) = @_;
2145 my @list;
2147 $filter ||= '';
2148 $filter =~ s/\.git$//;
2150 my $check_forks = gitweb_check_feature('forks');
2152 if (-d $projects_list) {
2153 # search in directory
2154 my $dir = $projects_list . ($filter ? "/$filter" : '');
2155 # remove the trailing "/"
2156 $dir =~ s!/+$!!;
2157 my $pfxlen = length("$dir");
2158 my $pfxdepth = ($dir =~ tr!/!!);
2160 File::Find::find({
2161 follow_fast => 1, # follow symbolic links
2162 follow_skip => 2, # ignore duplicates
2163 dangling_symlinks => 0, # ignore dangling symlinks, silently
2164 wanted => sub {
2165 # skip project-list toplevel, if we get it.
2166 return if (m!^[/.]$!);
2167 # only directories can be git repositories
2168 return unless (-d $_);
2169 # don't traverse too deep (Find is super slow on os x)
2170 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2171 $File::Find::prune = 1;
2172 return;
2175 my $subdir = substr($File::Find::name, $pfxlen + 1);
2176 # we check related file in $projectroot
2177 my $path = ($filter ? "$filter/" : '') . $subdir;
2178 if (check_export_ok("$projectroot/$path")) {
2179 push @list, { path => $path };
2180 $File::Find::prune = 1;
2183 }, "$dir");
2185 } elsif (-f $projects_list) {
2186 # read from file(url-encoded):
2187 # 'git%2Fgit.git Linus+Torvalds'
2188 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2189 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2190 my %paths;
2191 open my $fd, '<', $projects_list or return;
2192 PROJECT:
2193 while (my $line = <$fd>) {
2194 chomp $line;
2195 my ($path, $owner) = split ' ', $line;
2196 $path = unescape($path);
2197 $owner = unescape($owner);
2198 if (!defined $path) {
2199 next;
2201 if ($filter ne '') {
2202 # looking for forks;
2203 my $pfx = substr($path, 0, length($filter));
2204 if ($pfx ne $filter) {
2205 next PROJECT;
2207 my $sfx = substr($path, length($filter));
2208 if ($sfx !~ /^\/.*\.git$/) {
2209 next PROJECT;
2211 } elsif ($check_forks) {
2212 PATH:
2213 foreach my $filter (keys %paths) {
2214 # looking for forks;
2215 my $pfx = substr($path, 0, length($filter));
2216 if ($pfx ne $filter) {
2217 next PATH;
2219 my $sfx = substr($path, length($filter));
2220 if ($sfx !~ /^\/.*\.git$/) {
2221 next PATH;
2223 # is a fork, don't include it in
2224 # the list
2225 next PROJECT;
2228 if (check_export_ok("$projectroot/$path")) {
2229 my $pr = {
2230 path => $path,
2231 owner => to_utf8($owner),
2233 push @list, $pr;
2234 (my $forks_path = $path) =~ s/\.git$//;
2235 $paths{$forks_path}++;
2238 close $fd;
2240 return @list;
2243 our $gitweb_project_owner = undef;
2244 sub git_get_project_list_from_file {
2246 return if (defined $gitweb_project_owner);
2248 $gitweb_project_owner = {};
2249 # read from file (url-encoded):
2250 # 'git%2Fgit.git Linus+Torvalds'
2251 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2252 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2253 if (-f $projects_list) {
2254 open(my $fd, '<', $projects_list);
2255 while (my $line = <$fd>) {
2256 chomp $line;
2257 my ($pr, $ow) = split ' ', $line;
2258 $pr = unescape($pr);
2259 $ow = unescape($ow);
2260 $gitweb_project_owner->{$pr} = to_utf8($ow);
2262 close $fd;
2266 sub git_get_project_owner {
2267 my $project = shift;
2268 my $owner;
2270 return undef unless $project;
2271 $git_dir = "$projectroot/$project";
2273 if (!defined $gitweb_project_owner) {
2274 git_get_project_list_from_file();
2277 if (exists $gitweb_project_owner->{$project}) {
2278 $owner = $gitweb_project_owner->{$project};
2280 if (!defined $owner){
2281 $owner = git_get_project_config('owner');
2283 if (!defined $owner) {
2284 $owner = get_file_owner("$git_dir");
2287 return $owner;
2290 sub git_get_last_activity {
2291 my ($path) = @_;
2292 my $fd;
2294 $git_dir = "$projectroot/$path";
2295 open($fd, "-|", git_cmd(), 'for-each-ref',
2296 '--format=%(committer)',
2297 '--sort=-committerdate',
2298 '--count=1',
2299 'refs/heads') or return;
2300 my $most_recent = <$fd>;
2301 close $fd or return;
2302 if (defined $most_recent &&
2303 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2304 my $timestamp = $1;
2305 my $age = time - $timestamp;
2306 return ($age, age_string($age));
2308 return (undef, undef);
2311 sub git_get_references {
2312 my $type = shift || "";
2313 my %refs;
2314 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2315 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2316 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2317 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2318 or return;
2320 while (my $line = <$fd>) {
2321 chomp $line;
2322 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2323 if (defined $refs{$1}) {
2324 push @{$refs{$1}}, $2;
2325 } else {
2326 $refs{$1} = [ $2 ];
2330 close $fd or return;
2331 return \%refs;
2334 sub git_get_rev_name_tags {
2335 my $hash = shift || return undef;
2337 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2338 or return;
2339 my $name_rev = <$fd>;
2340 close $fd;
2342 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2343 return $1;
2344 } else {
2345 # catches also '$hash undefined' output
2346 return undef;
2350 ## ----------------------------------------------------------------------
2351 ## parse to hash functions
2353 sub parse_date {
2354 my $epoch = shift;
2355 my $tz = shift || "-0000";
2357 my %date;
2358 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2359 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2360 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2361 $date{'hour'} = $hour;
2362 $date{'minute'} = $min;
2363 $date{'mday'} = $mday;
2364 $date{'day'} = $days[$wday];
2365 $date{'month'} = $months[$mon];
2366 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2367 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2368 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2369 $mday, $months[$mon], $hour ,$min;
2370 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2371 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2373 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2374 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2375 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2376 $date{'hour_local'} = $hour;
2377 $date{'minute_local'} = $min;
2378 $date{'tz_local'} = $tz;
2379 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2380 1900+$year, $mon+1, $mday,
2381 $hour, $min, $sec, $tz);
2382 return %date;
2385 sub parse_tag {
2386 my $tag_id = shift;
2387 my %tag;
2388 my @comment;
2390 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2391 $tag{'id'} = $tag_id;
2392 while (my $line = <$fd>) {
2393 chomp $line;
2394 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2395 $tag{'object'} = $1;
2396 } elsif ($line =~ m/^type (.+)$/) {
2397 $tag{'type'} = $1;
2398 } elsif ($line =~ m/^tag (.+)$/) {
2399 $tag{'name'} = $1;
2400 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2401 $tag{'author'} = $1;
2402 $tag{'epoch'} = $2;
2403 $tag{'tz'} = $3;
2404 } elsif ($line =~ m/--BEGIN/) {
2405 push @comment, $line;
2406 last;
2407 } elsif ($line eq "") {
2408 last;
2411 push @comment, <$fd>;
2412 $tag{'comment'} = \@comment;
2413 close $fd or return;
2414 if (!defined $tag{'name'}) {
2415 return
2417 return %tag
2420 sub parse_commit_text {
2421 my ($commit_text, $withparents) = @_;
2422 my @commit_lines = split '\n', $commit_text;
2423 my %co;
2425 pop @commit_lines; # Remove '\0'
2427 if (! @commit_lines) {
2428 return;
2431 my $header = shift @commit_lines;
2432 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2433 return;
2435 ($co{'id'}, my @parents) = split ' ', $header;
2436 while (my $line = shift @commit_lines) {
2437 last if $line eq "\n";
2438 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2439 $co{'tree'} = $1;
2440 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2441 push @parents, $1;
2442 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2443 $co{'author'} = $1;
2444 $co{'author_epoch'} = $2;
2445 $co{'author_tz'} = $3;
2446 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2447 $co{'author_name'} = $1;
2448 $co{'author_email'} = $2;
2449 } else {
2450 $co{'author_name'} = $co{'author'};
2452 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2453 $co{'committer'} = $1;
2454 $co{'committer_epoch'} = $2;
2455 $co{'committer_tz'} = $3;
2456 $co{'committer_name'} = $co{'committer'};
2457 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2458 $co{'committer_name'} = $1;
2459 $co{'committer_email'} = $2;
2460 } else {
2461 $co{'committer_name'} = $co{'committer'};
2465 if (!defined $co{'tree'}) {
2466 return;
2468 $co{'parents'} = \@parents;
2469 $co{'parent'} = $parents[0];
2471 foreach my $title (@commit_lines) {
2472 $title =~ s/^ //;
2473 if ($title ne "") {
2474 $co{'title'} = chop_str($title, 80, 5);
2475 # remove leading stuff of merges to make the interesting part visible
2476 if (length($title) > 50) {
2477 $title =~ s/^Automatic //;
2478 $title =~ s/^merge (of|with) /Merge ... /i;
2479 if (length($title) > 50) {
2480 $title =~ s/(http|rsync):\/\///;
2482 if (length($title) > 50) {
2483 $title =~ s/(master|www|rsync)\.//;
2485 if (length($title) > 50) {
2486 $title =~ s/kernel.org:?//;
2488 if (length($title) > 50) {
2489 $title =~ s/\/pub\/scm//;
2492 $co{'title_short'} = chop_str($title, 50, 5);
2493 last;
2496 if (! defined $co{'title'} || $co{'title'} eq "") {
2497 $co{'title'} = $co{'title_short'} = '(no commit message)';
2499 # remove added spaces
2500 foreach my $line (@commit_lines) {
2501 $line =~ s/^ //;
2503 $co{'comment'} = \@commit_lines;
2505 my $age = time - $co{'committer_epoch'};
2506 $co{'age'} = $age;
2507 $co{'age_string'} = age_string($age);
2508 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2509 if ($age > 60*60*24*7*2) {
2510 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2511 $co{'age_string_age'} = $co{'age_string'};
2512 } else {
2513 $co{'age_string_date'} = $co{'age_string'};
2514 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2516 return %co;
2519 sub parse_commit {
2520 my ($commit_id) = @_;
2521 my %co;
2523 local $/ = "\0";
2525 open my $fd, "-|", git_cmd(), "rev-list",
2526 "--parents",
2527 "--header",
2528 "--max-count=1",
2529 $commit_id,
2530 "--",
2531 or die_error(500, "Open git-rev-list failed");
2532 %co = parse_commit_text(<$fd>, 1);
2533 close $fd;
2535 return %co;
2538 sub parse_commits {
2539 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2540 my @cos;
2542 $maxcount ||= 1;
2543 $skip ||= 0;
2545 local $/ = "\0";
2547 open my $fd, "-|", git_cmd(), "rev-list",
2548 "--header",
2549 @args,
2550 ("--max-count=" . $maxcount),
2551 ("--skip=" . $skip),
2552 @extra_options,
2553 $commit_id,
2554 "--",
2555 ($filename ? ($filename) : ())
2556 or die_error(500, "Open git-rev-list failed");
2557 while (my $line = <$fd>) {
2558 my %co = parse_commit_text($line);
2559 push @cos, \%co;
2561 close $fd;
2563 return wantarray ? @cos : \@cos;
2566 # parse line of git-diff-tree "raw" output
2567 sub parse_difftree_raw_line {
2568 my $line = shift;
2569 my %res;
2571 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2572 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2573 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2574 $res{'from_mode'} = $1;
2575 $res{'to_mode'} = $2;
2576 $res{'from_id'} = $3;
2577 $res{'to_id'} = $4;
2578 $res{'status'} = $5;
2579 $res{'similarity'} = $6;
2580 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2581 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2582 } else {
2583 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2586 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2587 # combined diff (for merge commit)
2588 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2589 $res{'nparents'} = length($1);
2590 $res{'from_mode'} = [ split(' ', $2) ];
2591 $res{'to_mode'} = pop @{$res{'from_mode'}};
2592 $res{'from_id'} = [ split(' ', $3) ];
2593 $res{'to_id'} = pop @{$res{'from_id'}};
2594 $res{'status'} = [ split('', $4) ];
2595 $res{'to_file'} = unquote($5);
2597 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2598 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2599 $res{'commit'} = $1;
2602 return wantarray ? %res : \%res;
2605 # wrapper: return parsed line of git-diff-tree "raw" output
2606 # (the argument might be raw line, or parsed info)
2607 sub parsed_difftree_line {
2608 my $line_or_ref = shift;
2610 if (ref($line_or_ref) eq "HASH") {
2611 # pre-parsed (or generated by hand)
2612 return $line_or_ref;
2613 } else {
2614 return parse_difftree_raw_line($line_or_ref);
2618 # parse line of git-ls-tree output
2619 sub parse_ls_tree_line {
2620 my $line = shift;
2621 my %opts = @_;
2622 my %res;
2624 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2625 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2627 $res{'mode'} = $1;
2628 $res{'type'} = $2;
2629 $res{'hash'} = $3;
2630 if ($opts{'-z'}) {
2631 $res{'name'} = $4;
2632 } else {
2633 $res{'name'} = unquote($4);
2636 return wantarray ? %res : \%res;
2639 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2640 sub parse_from_to_diffinfo {
2641 my ($diffinfo, $from, $to, @parents) = @_;
2643 if ($diffinfo->{'nparents'}) {
2644 # combined diff
2645 $from->{'file'} = [];
2646 $from->{'href'} = [];
2647 fill_from_file_info($diffinfo, @parents)
2648 unless exists $diffinfo->{'from_file'};
2649 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2650 $from->{'file'}[$i] =
2651 defined $diffinfo->{'from_file'}[$i] ?
2652 $diffinfo->{'from_file'}[$i] :
2653 $diffinfo->{'to_file'};
2654 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2655 $from->{'href'}[$i] = href(action=>"blob",
2656 hash_base=>$parents[$i],
2657 hash=>$diffinfo->{'from_id'}[$i],
2658 file_name=>$from->{'file'}[$i]);
2659 } else {
2660 $from->{'href'}[$i] = undef;
2663 } else {
2664 # ordinary (not combined) diff
2665 $from->{'file'} = $diffinfo->{'from_file'};
2666 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2667 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2668 hash=>$diffinfo->{'from_id'},
2669 file_name=>$from->{'file'});
2670 } else {
2671 delete $from->{'href'};
2675 $to->{'file'} = $diffinfo->{'to_file'};
2676 if (!is_deleted($diffinfo)) { # file exists in result
2677 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2678 hash=>$diffinfo->{'to_id'},
2679 file_name=>$to->{'file'});
2680 } else {
2681 delete $to->{'href'};
2685 ## ......................................................................
2686 ## parse to array of hashes functions
2688 sub git_get_heads_list {
2689 my $limit = shift;
2690 my @headslist;
2692 open my $fd, '-|', git_cmd(), 'for-each-ref',
2693 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2694 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2695 'refs/heads'
2696 or return;
2697 while (my $line = <$fd>) {
2698 my %ref_item;
2700 chomp $line;
2701 my ($refinfo, $committerinfo) = split(/\0/, $line);
2702 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2703 my ($committer, $epoch, $tz) =
2704 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2705 $ref_item{'fullname'} = $name;
2706 $name =~ s!^refs/heads/!!;
2708 $ref_item{'name'} = $name;
2709 $ref_item{'id'} = $hash;
2710 $ref_item{'title'} = $title || '(no commit message)';
2711 $ref_item{'epoch'} = $epoch;
2712 if ($epoch) {
2713 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2714 } else {
2715 $ref_item{'age'} = "unknown";
2718 push @headslist, \%ref_item;
2720 close $fd;
2722 return wantarray ? @headslist : \@headslist;
2725 sub git_get_tags_list {
2726 my $limit = shift;
2727 my @tagslist;
2729 open my $fd, '-|', git_cmd(), 'for-each-ref',
2730 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2731 '--format=%(objectname) %(objecttype) %(refname) '.
2732 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2733 'refs/tags'
2734 or return;
2735 while (my $line = <$fd>) {
2736 my %ref_item;
2738 chomp $line;
2739 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2740 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2741 my ($creator, $epoch, $tz) =
2742 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2743 $ref_item{'fullname'} = $name;
2744 $name =~ s!^refs/tags/!!;
2746 $ref_item{'type'} = $type;
2747 $ref_item{'id'} = $id;
2748 $ref_item{'name'} = $name;
2749 if ($type eq "tag") {
2750 $ref_item{'subject'} = $title;
2751 $ref_item{'reftype'} = $reftype;
2752 $ref_item{'refid'} = $refid;
2753 } else {
2754 $ref_item{'reftype'} = $type;
2755 $ref_item{'refid'} = $id;
2758 if ($type eq "tag" || $type eq "commit") {
2759 $ref_item{'epoch'} = $epoch;
2760 if ($epoch) {
2761 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2762 } else {
2763 $ref_item{'age'} = "unknown";
2767 push @tagslist, \%ref_item;
2769 close $fd;
2771 return wantarray ? @tagslist : \@tagslist;
2774 ## ----------------------------------------------------------------------
2775 ## filesystem-related functions
2777 sub get_file_owner {
2778 my $path = shift;
2780 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2781 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2782 if (!defined $gcos) {
2783 return undef;
2785 my $owner = $gcos;
2786 $owner =~ s/[,;].*$//;
2787 return to_utf8($owner);
2790 # assume that file exists
2791 sub insert_file {
2792 my $filename = shift;
2794 open my $fd, '<', $filename;
2795 print map { to_utf8($_) } <$fd>;
2796 close $fd;
2799 ## ......................................................................
2800 ## mimetype related functions
2802 sub mimetype_guess_file {
2803 my $filename = shift;
2804 my $mimemap = shift;
2805 -r $mimemap or return undef;
2807 my %mimemap;
2808 open(my $mh, '<', $mimemap) or return undef;
2809 while (<$mh>) {
2810 next if m/^#/; # skip comments
2811 my ($mimetype, $exts) = split(/\t+/);
2812 if (defined $exts) {
2813 my @exts = split(/\s+/, $exts);
2814 foreach my $ext (@exts) {
2815 $mimemap{$ext} = $mimetype;
2819 close($mh);
2821 $filename =~ /\.([^.]*)$/;
2822 return $mimemap{$1};
2825 sub mimetype_guess {
2826 my $filename = shift;
2827 my $mime;
2828 $filename =~ /\./ or return undef;
2830 if ($mimetypes_file) {
2831 my $file = $mimetypes_file;
2832 if ($file !~ m!^/!) { # if it is relative path
2833 # it is relative to project
2834 $file = "$projectroot/$project/$file";
2836 $mime = mimetype_guess_file($filename, $file);
2838 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2839 return $mime;
2842 sub blob_mimetype {
2843 my $fd = shift;
2844 my $filename = shift;
2846 if ($filename) {
2847 my $mime = mimetype_guess($filename);
2848 $mime and return $mime;
2851 # just in case
2852 return $default_blob_plain_mimetype unless $fd;
2854 if (-T $fd) {
2855 return 'text/plain';
2856 } elsif (! $filename) {
2857 return 'application/octet-stream';
2858 } elsif ($filename =~ m/\.png$/i) {
2859 return 'image/png';
2860 } elsif ($filename =~ m/\.gif$/i) {
2861 return 'image/gif';
2862 } elsif ($filename =~ m/\.jpe?g$/i) {
2863 return 'image/jpeg';
2864 } else {
2865 return 'application/octet-stream';
2869 sub blob_contenttype {
2870 my ($fd, $file_name, $type) = @_;
2872 $type ||= blob_mimetype($fd, $file_name);
2873 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
2874 $type .= "; charset=$default_text_plain_charset";
2877 return $type;
2880 ## ======================================================================
2881 ## functions printing HTML: header, footer, error page
2883 sub git_header_html {
2884 my $status = shift || "200 OK";
2885 my $expires = shift;
2887 my $title = "$site_name";
2888 if (defined $project) {
2889 $title .= " - " . to_utf8($project);
2890 if (defined $action) {
2891 $title .= "/$action";
2892 if (defined $file_name) {
2893 $title .= " - " . esc_path($file_name);
2894 if ($action eq "tree" && $file_name !~ m|/$|) {
2895 $title .= "/";
2900 my $content_type;
2901 # require explicit support from the UA if we are to send the page as
2902 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2903 # we have to do this because MSIE sometimes globs '*/*', pretending to
2904 # support xhtml+xml but choking when it gets what it asked for.
2905 if (defined $cgi->http('HTTP_ACCEPT') &&
2906 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2907 $cgi->Accept('application/xhtml+xml') != 0) {
2908 $content_type = 'application/xhtml+xml';
2909 } else {
2910 $content_type = 'text/html';
2912 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2913 -status=> $status, -expires => $expires);
2914 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2915 print <<EOF;
2916 <?xml version="1.0" encoding="utf-8"?>
2917 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2918 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2919 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2920 <!-- git core binaries version $git_version -->
2921 <head>
2922 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2923 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2924 <meta name="robots" content="index, nofollow"/>
2925 <title>$title</title>
2927 # the stylesheet, favicon etc urls won't work correctly with path_info
2928 # unless we set the appropriate base URL
2929 if ($ENV{'PATH_INFO'}) {
2930 print "<base href=\"".esc_url($base_url)."\" />\n";
2932 # print out each stylesheet that exist, providing backwards capability
2933 # for those people who defined $stylesheet in a config file
2934 if (defined $stylesheet) {
2935 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2936 } else {
2937 foreach my $stylesheet (@stylesheets) {
2938 next unless $stylesheet;
2939 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2942 if (defined $project) {
2943 my %href_params = get_feed_info();
2944 if (!exists $href_params{'-title'}) {
2945 $href_params{'-title'} = 'log';
2948 foreach my $format qw(RSS Atom) {
2949 my $type = lc($format);
2950 my %link_attr = (
2951 '-rel' => 'alternate',
2952 '-title' => "$project - $href_params{'-title'} - $format feed",
2953 '-type' => "application/$type+xml"
2956 $href_params{'action'} = $type;
2957 $link_attr{'-href'} = href(%href_params);
2958 print "<link ".
2959 "rel=\"$link_attr{'-rel'}\" ".
2960 "title=\"$link_attr{'-title'}\" ".
2961 "href=\"$link_attr{'-href'}\" ".
2962 "type=\"$link_attr{'-type'}\" ".
2963 "/>\n";
2965 $href_params{'extra_options'} = '--no-merges';
2966 $link_attr{'-href'} = href(%href_params);
2967 $link_attr{'-title'} .= ' (no merges)';
2968 print "<link ".
2969 "rel=\"$link_attr{'-rel'}\" ".
2970 "title=\"$link_attr{'-title'}\" ".
2971 "href=\"$link_attr{'-href'}\" ".
2972 "type=\"$link_attr{'-type'}\" ".
2973 "/>\n";
2976 } else {
2977 printf('<link rel="alternate" title="%s projects list" '.
2978 'href="%s" type="text/plain; charset=utf-8" />'."\n",
2979 $site_name, href(project=>undef, action=>"project_index"));
2980 printf('<link rel="alternate" title="%s projects feeds" '.
2981 'href="%s" type="text/x-opml" />'."\n",
2982 $site_name, href(project=>undef, action=>"opml"));
2984 if (defined $favicon) {
2985 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
2988 print "</head>\n" .
2989 "<body>\n";
2991 if (-f $site_header) {
2992 insert_file($site_header);
2995 print "<div class=\"page_header\">\n" .
2996 $cgi->a({-href => esc_url($logo_url),
2997 -title => $logo_label},
2998 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2999 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3000 if (defined $project) {
3001 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3002 if (defined $action) {
3003 print " / $action";
3005 print "\n";
3007 print "</div>\n";
3009 my $have_search = gitweb_check_feature('search');
3010 if (defined $project && $have_search) {
3011 if (!defined $searchtext) {
3012 $searchtext = "";
3014 my $search_hash;
3015 if (defined $hash_base) {
3016 $search_hash = $hash_base;
3017 } elsif (defined $hash) {
3018 $search_hash = $hash;
3019 } else {
3020 $search_hash = "HEAD";
3022 my $action = $my_uri;
3023 my $use_pathinfo = gitweb_check_feature('pathinfo');
3024 if ($use_pathinfo) {
3025 $action .= "/".esc_url($project);
3027 print $cgi->startform(-method => "get", -action => $action) .
3028 "<div class=\"search\">\n" .
3029 (!$use_pathinfo &&
3030 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3031 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3032 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3033 $cgi->popup_menu(-name => 'st', -default => 'commit',
3034 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3035 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3036 " search:\n",
3037 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3038 "<span title=\"Extended regular expression\">" .
3039 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3040 -checked => $search_use_regexp) .
3041 "</span>" .
3042 "</div>" .
3043 $cgi->end_form() . "\n";
3047 sub git_footer_html {
3048 my $feed_class = 'rss_logo';
3050 print "<div class=\"page_footer\">\n";
3051 if (defined $project) {
3052 my $descr = git_get_project_description($project);
3053 if (defined $descr) {
3054 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3057 my %href_params = get_feed_info();
3058 if (!%href_params) {
3059 $feed_class .= ' generic';
3061 $href_params{'-title'} ||= 'log';
3063 foreach my $format qw(RSS Atom) {
3064 $href_params{'action'} = lc($format);
3065 print $cgi->a({-href => href(%href_params),
3066 -title => "$href_params{'-title'} $format feed",
3067 -class => $feed_class}, $format)."\n";
3070 } else {
3071 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3072 -class => $feed_class}, "OPML") . " ";
3073 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3074 -class => $feed_class}, "TXT") . "\n";
3076 print "</div>\n"; # class="page_footer"
3078 if (-f $site_footer) {
3079 insert_file($site_footer);
3082 print "</body>\n" .
3083 "</html>";
3086 # die_error(<http_status_code>, <error_message>)
3087 # Example: die_error(404, 'Hash not found')
3088 # By convention, use the following status codes (as defined in RFC 2616):
3089 # 400: Invalid or missing CGI parameters, or
3090 # requested object exists but has wrong type.
3091 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3092 # this server or project.
3093 # 404: Requested object/revision/project doesn't exist.
3094 # 500: The server isn't configured properly, or
3095 # an internal error occurred (e.g. failed assertions caused by bugs), or
3096 # an unknown error occurred (e.g. the git binary died unexpectedly).
3097 sub die_error {
3098 my $status = shift || 500;
3099 my $error = shift || "Internal server error";
3101 my %http_responses = (400 => '400 Bad Request',
3102 403 => '403 Forbidden',
3103 404 => '404 Not Found',
3104 500 => '500 Internal Server Error');
3105 git_header_html($http_responses{$status});
3106 print <<EOF;
3107 <div class="page_body">
3108 <br /><br />
3109 $status - $error
3110 <br />
3111 </div>
3113 git_footer_html();
3114 exit;
3117 ## ----------------------------------------------------------------------
3118 ## functions printing or outputting HTML: navigation
3120 sub git_print_page_nav {
3121 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3122 $extra = '' if !defined $extra; # pager or formats
3124 my @navs = qw(summary log commit commitdiff tree);
3125 if ($suppress) {
3126 @navs = grep { $_ ne $suppress } @navs;
3129 my %arg = map { $_ => {action=>$_} } @navs;
3130 if (defined $head) {
3131 for (qw(commit commitdiff)) {
3132 $arg{$_}{'hash'} = $head;
3134 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3135 $arg{'log'}{'hash'} = $head;
3139 $arg{'log'}{'action'} = 'shortlog';
3140 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3141 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3143 my @actions = gitweb_get_feature('actions');
3144 my %repl = (
3145 '%' => '%',
3146 'n' => $project, # project name
3147 'f' => $git_dir, # project path within filesystem
3148 'h' => $treehead || '', # current hash ('h' parameter)
3149 'b' => $treebase || '', # hash base ('hb' parameter)
3151 while (@actions) {
3152 my ($label, $link, $pos) = splice(@actions,0,3);
3153 # insert
3154 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3155 # munch munch
3156 $link =~ s/%([%nfhb])/$repl{$1}/g;
3157 $arg{$label}{'_href'} = $link;
3160 print "<div class=\"page_nav\">\n" .
3161 (join " | ",
3162 map { $_ eq $current ?
3163 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3164 } @navs);
3165 print "<br/>\n$extra<br/>\n" .
3166 "</div>\n";
3169 sub format_paging_nav {
3170 my ($action, $hash, $head, $page, $has_next_link) = @_;
3171 my $paging_nav;
3174 if ($hash ne $head || $page) {
3175 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3176 } else {
3177 $paging_nav .= "HEAD";
3180 if ($page > 0) {
3181 $paging_nav .= " &sdot; " .
3182 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3183 -accesskey => "p", -title => "Alt-p"}, "prev");
3184 } else {
3185 $paging_nav .= " &sdot; prev";
3188 if ($has_next_link) {
3189 $paging_nav .= " &sdot; " .
3190 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3191 -accesskey => "n", -title => "Alt-n"}, "next");
3192 } else {
3193 $paging_nav .= " &sdot; next";
3196 return $paging_nav;
3199 sub format_log_nav {
3200 my ($action, $hash, $head, $page, $has_next_link) = @_;
3201 my $paging_nav;
3203 if ($action eq 'shortlog') {
3204 $paging_nav .= 'shortlog';
3205 } else {
3206 $paging_nav .= $cgi->a({-href => href(action=>'shortlog', -replay=>1)}, 'shortlog');
3208 $paging_nav .= ' | ';
3209 if ($action eq 'log') {
3210 $paging_nav .= 'fulllog';
3211 } else {
3212 $paging_nav .= $cgi->a({-href => href(action=>'log', -replay=>1)}, 'fulllog');
3215 $paging_nav .= " | " . format_paging_nav($action, $hash, $head, $page, $has_next_link);
3216 return $paging_nav;
3219 ## ......................................................................
3220 ## functions printing or outputting HTML: div
3222 sub git_print_header_div {
3223 my ($action, $title, $hash, $hash_base) = @_;
3224 my %args = ();
3226 $args{'action'} = $action;
3227 $args{'hash'} = $hash if $hash;
3228 $args{'hash_base'} = $hash_base if $hash_base;
3230 print "<div class=\"header\">\n" .
3231 $cgi->a({-href => href(%args), -class => "title"},
3232 $title ? $title : $action) .
3233 "\n</div>\n";
3236 sub git_print_authorship {
3237 my $co = shift;
3239 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3240 print "<div class=\"author_date\">" .
3241 esc_html($co->{'author_name'}) .
3242 " [$ad{'rfc2822'}";
3243 if ($ad{'hour_local'} < 6) {
3244 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3245 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3246 } else {
3247 printf(" (%02d:%02d %s)",
3248 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3250 print "]</div>\n";
3253 sub git_print_page_path {
3254 my $name = shift;
3255 my $type = shift;
3256 my $hb = shift;
3259 print "<div class=\"page_path\">";
3260 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3261 -title => 'tree root'}, to_utf8("[$project]"));
3262 print " / ";
3263 if (defined $name) {
3264 my @dirname = split '/', $name;
3265 my $basename = pop @dirname;
3266 my $fullname = '';
3268 foreach my $dir (@dirname) {
3269 $fullname .= ($fullname ? '/' : '') . $dir;
3270 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3271 hash_base=>$hb),
3272 -title => $fullname}, esc_path($dir));
3273 print " / ";
3275 if (defined $type && $type eq 'blob') {
3276 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3277 hash_base=>$hb),
3278 -title => $name}, esc_path($basename));
3279 } elsif (defined $type && $type eq 'tree') {
3280 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3281 hash_base=>$hb),
3282 -title => $name}, esc_path($basename));
3283 print " / ";
3284 } else {
3285 print esc_path($basename);
3288 print "<br/></div>\n";
3291 sub git_print_log {
3292 my $log = shift;
3293 my %opts = @_;
3295 if ($opts{'-remove_title'}) {
3296 # remove title, i.e. first line of log
3297 shift @$log;
3299 # remove leading empty lines
3300 while (defined $log->[0] && $log->[0] eq "") {
3301 shift @$log;
3304 # print log
3305 my $signoff = 0;
3306 my $empty = 0;
3307 foreach my $line (@$log) {
3308 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3309 $signoff = 1;
3310 $empty = 0;
3311 if (! $opts{'-remove_signoff'}) {
3312 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3313 next;
3314 } else {
3315 # remove signoff lines
3316 next;
3318 } else {
3319 $signoff = 0;
3322 # print only one empty line
3323 # do not print empty line after signoff
3324 if ($line eq "") {
3325 next if ($empty || $signoff);
3326 $empty = 1;
3327 } else {
3328 $empty = 0;
3331 print format_log_line_html($line) . "<br/>\n";
3334 if ($opts{'-final_empty_line'}) {
3335 # end with single empty line
3336 print "<br/>\n" unless $empty;
3340 # return link target (what link points to)
3341 sub git_get_link_target {
3342 my $hash = shift;
3343 my $link_target;
3345 # read link
3346 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3347 or return;
3349 local $/ = undef;
3350 $link_target = <$fd>;
3352 close $fd
3353 or return;
3355 return $link_target;
3358 # given link target, and the directory (basedir) the link is in,
3359 # return target of link relative to top directory (top tree);
3360 # return undef if it is not possible (including absolute links).
3361 sub normalize_link_target {
3362 my ($link_target, $basedir) = @_;
3364 # absolute symlinks (beginning with '/') cannot be normalized
3365 return if (substr($link_target, 0, 1) eq '/');
3367 # normalize link target to path from top (root) tree (dir)
3368 my $path;
3369 if ($basedir) {
3370 $path = $basedir . '/' . $link_target;
3371 } else {
3372 # we are in top (root) tree (dir)
3373 $path = $link_target;
3376 # remove //, /./, and /../
3377 my @path_parts;
3378 foreach my $part (split('/', $path)) {
3379 # discard '.' and ''
3380 next if (!$part || $part eq '.');
3381 # handle '..'
3382 if ($part eq '..') {
3383 if (@path_parts) {
3384 pop @path_parts;
3385 } else {
3386 # link leads outside repository (outside top dir)
3387 return;
3389 } else {
3390 push @path_parts, $part;
3393 $path = join('/', @path_parts);
3395 return $path;
3398 # print tree entry (row of git_tree), but without encompassing <tr> element
3399 sub git_print_tree_entry {
3400 my ($t, $basedir, $hash_base, $have_blame) = @_;
3402 my %base_key = ();
3403 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3405 # The format of a table row is: mode list link. Where mode is
3406 # the mode of the entry, list is the name of the entry, an href,
3407 # and link is the action links of the entry.
3409 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3410 if ($t->{'type'} eq "blob") {
3411 print "<td class=\"list\">" .
3412 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3413 file_name=>"$basedir$t->{'name'}", %base_key),
3414 -class => "list"}, esc_path($t->{'name'}));
3415 if (S_ISLNK(oct $t->{'mode'})) {
3416 my $link_target = git_get_link_target($t->{'hash'});
3417 if ($link_target) {
3418 my $norm_target = normalize_link_target($link_target, $basedir);
3419 if (defined $norm_target) {
3420 print " -> " .
3421 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3422 file_name=>$norm_target),
3423 -title => $norm_target}, esc_path($link_target));
3424 } else {
3425 print " -> " . esc_path($link_target);
3429 print "</td>\n";
3430 print "<td class=\"link\">";
3431 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3432 file_name=>"$basedir$t->{'name'}", %base_key)},
3433 "blob");
3434 if ($have_blame) {
3435 print " | " .
3436 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3437 file_name=>"$basedir$t->{'name'}", %base_key)},
3438 "blame");
3440 if (defined $hash_base) {
3441 print " | " .
3442 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3443 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3444 "history");
3446 print " | " .
3447 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3448 file_name=>"$basedir$t->{'name'}")},
3449 "raw");
3450 print "</td>\n";
3452 } elsif ($t->{'type'} eq "tree") {
3453 print "<td class=\"list\">";
3454 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3455 file_name=>"$basedir$t->{'name'}", %base_key)},
3456 esc_path($t->{'name'}));
3457 print "</td>\n";
3458 print "<td class=\"link\">";
3459 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3460 file_name=>"$basedir$t->{'name'}", %base_key)},
3461 "tree");
3462 if (defined $hash_base) {
3463 print " | " .
3464 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3465 file_name=>"$basedir$t->{'name'}")},
3466 "history");
3468 print "</td>\n";
3469 } else {
3470 # unknown object: we can only present history for it
3471 # (this includes 'commit' object, i.e. submodule support)
3472 print "<td class=\"list\">" .
3473 esc_path($t->{'name'}) .
3474 "</td>\n";
3475 print "<td class=\"link\">";
3476 if (defined $hash_base) {
3477 print $cgi->a({-href => href(action=>"history",
3478 hash_base=>$hash_base,
3479 file_name=>"$basedir$t->{'name'}")},
3480 "history");
3482 print "</td>\n";
3486 ## ......................................................................
3487 ## functions printing large fragments of HTML
3489 # get pre-image filenames for merge (combined) diff
3490 sub fill_from_file_info {
3491 my ($diff, @parents) = @_;
3493 $diff->{'from_file'} = [ ];
3494 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3495 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3496 if ($diff->{'status'}[$i] eq 'R' ||
3497 $diff->{'status'}[$i] eq 'C') {
3498 $diff->{'from_file'}[$i] =
3499 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3503 return $diff;
3506 # is current raw difftree line of file deletion
3507 sub is_deleted {
3508 my $diffinfo = shift;
3510 return $diffinfo->{'to_id'} eq ('0' x 40);
3513 # does patch correspond to [previous] difftree raw line
3514 # $diffinfo - hashref of parsed raw diff format
3515 # $patchinfo - hashref of parsed patch diff format
3516 # (the same keys as in $diffinfo)
3517 sub is_patch_split {
3518 my ($diffinfo, $patchinfo) = @_;
3520 return defined $diffinfo && defined $patchinfo
3521 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3525 sub git_difftree_body {
3526 my ($difftree, $hash, @parents) = @_;
3527 my ($parent) = $parents[0];
3528 my $have_blame = gitweb_check_feature('blame');
3529 print "<div class=\"list_head\">\n";
3530 if ($#{$difftree} > 10) {
3531 print(($#{$difftree} + 1) . " files changed:\n");
3533 print "</div>\n";
3535 print "<table class=\"" .
3536 (@parents > 1 ? "combined " : "") .
3537 "diff_tree\">\n";
3539 # header only for combined diff in 'commitdiff' view
3540 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3541 if ($has_header) {
3542 # table header
3543 print "<thead><tr>\n" .
3544 "<th></th><th></th>\n"; # filename, patchN link
3545 for (my $i = 0; $i < @parents; $i++) {
3546 my $par = $parents[$i];
3547 print "<th>" .
3548 $cgi->a({-href => href(action=>"commitdiff",
3549 hash=>$hash, hash_parent=>$par),
3550 -title => 'commitdiff to parent number ' .
3551 ($i+1) . ': ' . substr($par,0,7)},
3552 $i+1) .
3553 "&nbsp;</th>\n";
3555 print "</tr></thead>\n<tbody>\n";
3558 my $alternate = 1;
3559 my $patchno = 0;
3560 foreach my $line (@{$difftree}) {
3561 my $diff = parsed_difftree_line($line);
3563 if ($alternate) {
3564 print "<tr class=\"dark\">\n";
3565 } else {
3566 print "<tr class=\"light\">\n";
3568 $alternate ^= 1;
3570 if (exists $diff->{'nparents'}) { # combined diff
3572 fill_from_file_info($diff, @parents)
3573 unless exists $diff->{'from_file'};
3575 if (!is_deleted($diff)) {
3576 # file exists in the result (child) commit
3577 print "<td>" .
3578 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3579 file_name=>$diff->{'to_file'},
3580 hash_base=>$hash),
3581 -class => "list"}, esc_path($diff->{'to_file'})) .
3582 "</td>\n";
3583 } else {
3584 print "<td>" .
3585 esc_path($diff->{'to_file'}) .
3586 "</td>\n";
3589 if ($action eq 'commitdiff') {
3590 # link to patch
3591 $patchno++;
3592 print "<td class=\"link\">" .
3593 $cgi->a({-href => "#patch$patchno"}, "patch") .
3594 " | " .
3595 "</td>\n";
3598 my $has_history = 0;
3599 my $not_deleted = 0;
3600 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3601 my $hash_parent = $parents[$i];
3602 my $from_hash = $diff->{'from_id'}[$i];
3603 my $from_path = $diff->{'from_file'}[$i];
3604 my $status = $diff->{'status'}[$i];
3606 $has_history ||= ($status ne 'A');
3607 $not_deleted ||= ($status ne 'D');
3609 if ($status eq 'A') {
3610 print "<td class=\"link\" align=\"right\"> | </td>\n";
3611 } elsif ($status eq 'D') {
3612 print "<td class=\"link\">" .
3613 $cgi->a({-href => href(action=>"blob",
3614 hash_base=>$hash,
3615 hash=>$from_hash,
3616 file_name=>$from_path)},
3617 "blob" . ($i+1)) .
3618 " | </td>\n";
3619 } else {
3620 if ($diff->{'to_id'} eq $from_hash) {
3621 print "<td class=\"link nochange\">";
3622 } else {
3623 print "<td class=\"link\">";
3625 print $cgi->a({-href => href(action=>"blobdiff",
3626 hash=>$diff->{'to_id'},
3627 hash_parent=>$from_hash,
3628 hash_base=>$hash,
3629 hash_parent_base=>$hash_parent,
3630 file_name=>$diff->{'to_file'},
3631 file_parent=>$from_path)},
3632 "diff" . ($i+1)) .
3633 " | </td>\n";
3637 print "<td class=\"link\">";
3638 if ($not_deleted) {
3639 print $cgi->a({-href => href(action=>"blob",
3640 hash=>$diff->{'to_id'},
3641 file_name=>$diff->{'to_file'},
3642 hash_base=>$hash)},
3643 "blob");
3644 print " | " if ($has_history);
3646 if ($has_history) {
3647 print $cgi->a({-href => href(action=>"history",
3648 file_name=>$diff->{'to_file'},
3649 hash_base=>$hash)},
3650 "history");
3652 print "</td>\n";
3654 print "</tr>\n";
3655 next; # instead of 'else' clause, to avoid extra indent
3657 # else ordinary diff
3659 my ($to_mode_oct, $to_mode_str, $to_file_type);
3660 my ($from_mode_oct, $from_mode_str, $from_file_type);
3661 if ($diff->{'to_mode'} ne ('0' x 6)) {
3662 $to_mode_oct = oct $diff->{'to_mode'};
3663 if (S_ISREG($to_mode_oct)) { # only for regular file
3664 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3666 $to_file_type = file_type($diff->{'to_mode'});
3668 if ($diff->{'from_mode'} ne ('0' x 6)) {
3669 $from_mode_oct = oct $diff->{'from_mode'};
3670 if (S_ISREG($to_mode_oct)) { # only for regular file
3671 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3673 $from_file_type = file_type($diff->{'from_mode'});
3676 if ($diff->{'status'} eq "A") { # created
3677 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3678 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3679 $mode_chng .= "]</span>";
3680 print "<td>";
3681 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3682 hash_base=>$hash, file_name=>$diff->{'file'}),
3683 -class => "list"}, esc_path($diff->{'file'}));
3684 print "</td>\n";
3685 print "<td>$mode_chng</td>\n";
3686 print "<td class=\"link\">";
3687 if ($action eq 'commitdiff') {
3688 # link to patch
3689 $patchno++;
3690 print $cgi->a({-href => "#patch$patchno"}, "patch");
3691 print " | ";
3693 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3694 hash_base=>$hash, file_name=>$diff->{'file'})},
3695 "blob");
3696 print "</td>\n";
3698 } elsif ($diff->{'status'} eq "D") { # deleted
3699 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3700 print "<td>";
3701 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3702 hash_base=>$parent, file_name=>$diff->{'file'}),
3703 -class => "list"}, esc_path($diff->{'file'}));
3704 print "</td>\n";
3705 print "<td>$mode_chng</td>\n";
3706 print "<td class=\"link\">";
3707 if ($action eq 'commitdiff') {
3708 # link to patch
3709 $patchno++;
3710 print $cgi->a({-href => "#patch$patchno"}, "patch");
3711 print " | ";
3713 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3714 hash_base=>$parent, file_name=>$diff->{'file'})},
3715 "blob") . " | ";
3716 if ($have_blame) {
3717 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3718 file_name=>$diff->{'file'})},
3719 "blame") . " | ";
3721 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3722 file_name=>$diff->{'file'})},
3723 "history");
3724 print "</td>\n";
3726 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3727 my $mode_chnge = "";
3728 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3729 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3730 if ($from_file_type ne $to_file_type) {
3731 $mode_chnge .= " from $from_file_type to $to_file_type";
3733 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3734 if ($from_mode_str && $to_mode_str) {
3735 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3736 } elsif ($to_mode_str) {
3737 $mode_chnge .= " mode: $to_mode_str";
3740 $mode_chnge .= "]</span>\n";
3742 print "<td>";
3743 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3744 hash_base=>$hash, file_name=>$diff->{'file'}),
3745 -class => "list"}, esc_path($diff->{'file'}));
3746 print "</td>\n";
3747 print "<td>$mode_chnge</td>\n";
3748 print "<td class=\"link\">";
3749 if ($action eq 'commitdiff') {
3750 # link to patch
3751 $patchno++;
3752 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3753 " | ";
3754 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3755 # "commit" view and modified file (not onlu mode changed)
3756 print $cgi->a({-href => href(action=>"blobdiff",
3757 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3758 hash_base=>$hash, hash_parent_base=>$parent,
3759 file_name=>$diff->{'file'})},
3760 "diff") .
3761 " | ";
3763 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3764 hash_base=>$hash, file_name=>$diff->{'file'})},
3765 "blob") . " | ";
3766 if ($have_blame) {
3767 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3768 file_name=>$diff->{'file'})},
3769 "blame") . " | ";
3771 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3772 file_name=>$diff->{'file'})},
3773 "history");
3774 print "</td>\n";
3776 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3777 my %status_name = ('R' => 'moved', 'C' => 'copied');
3778 my $nstatus = $status_name{$diff->{'status'}};
3779 my $mode_chng = "";
3780 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3781 # mode also for directories, so we cannot use $to_mode_str
3782 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3784 print "<td>" .
3785 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3786 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3787 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3788 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3789 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3790 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3791 -class => "list"}, esc_path($diff->{'from_file'})) .
3792 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3793 "<td class=\"link\">";
3794 if ($action eq 'commitdiff') {
3795 # link to patch
3796 $patchno++;
3797 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3798 " | ";
3799 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3800 # "commit" view and modified file (not only pure rename or copy)
3801 print $cgi->a({-href => href(action=>"blobdiff",
3802 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3803 hash_base=>$hash, hash_parent_base=>$parent,
3804 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3805 "diff") .
3806 " | ";
3808 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3809 hash_base=>$parent, file_name=>$diff->{'to_file'})},
3810 "blob") . " | ";
3811 if ($have_blame) {
3812 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3813 file_name=>$diff->{'to_file'})},
3814 "blame") . " | ";
3816 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3817 file_name=>$diff->{'to_file'})},
3818 "history");
3819 print "</td>\n";
3821 } # we should not encounter Unmerged (U) or Unknown (X) status
3822 print "</tr>\n";
3824 print "</tbody>" if $has_header;
3825 print "</table>\n";
3828 sub git_patchset_body {
3829 my ($fd, $difftree, $hash, @hash_parents) = @_;
3830 my ($hash_parent) = $hash_parents[0];
3832 my $is_combined = (@hash_parents > 1);
3833 my $patch_idx = 0;
3834 my $patch_number = 0;
3835 my $patch_line;
3836 my $diffinfo;
3837 my $to_name;
3838 my (%from, %to);
3840 print "<div class=\"patchset\">\n";
3842 # skip to first patch
3843 while ($patch_line = <$fd>) {
3844 chomp $patch_line;
3846 last if ($patch_line =~ m/^diff /);
3849 PATCH:
3850 while ($patch_line) {
3852 # parse "git diff" header line
3853 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
3854 # $1 is from_name, which we do not use
3855 $to_name = unquote($2);
3856 $to_name =~ s!^b/!!;
3857 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
3858 # $1 is 'cc' or 'combined', which we do not use
3859 $to_name = unquote($2);
3860 } else {
3861 $to_name = undef;
3864 # check if current patch belong to current raw line
3865 # and parse raw git-diff line if needed
3866 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
3867 # this is continuation of a split patch
3868 print "<div class=\"patch cont\">\n";
3869 } else {
3870 # advance raw git-diff output if needed
3871 $patch_idx++ if defined $diffinfo;
3873 # read and prepare patch information
3874 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3876 # compact combined diff output can have some patches skipped
3877 # find which patch (using pathname of result) we are at now;
3878 if ($is_combined) {
3879 while ($to_name ne $diffinfo->{'to_file'}) {
3880 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3881 format_diff_cc_simplified($diffinfo, @hash_parents) .
3882 "</div>\n"; # class="patch"
3884 $patch_idx++;
3885 $patch_number++;
3887 last if $patch_idx > $#$difftree;
3888 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3892 # modifies %from, %to hashes
3893 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3895 # this is first patch for raw difftree line with $patch_idx index
3896 # we index @$difftree array from 0, but number patches from 1
3897 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3900 # git diff header
3901 #assert($patch_line =~ m/^diff /) if DEBUG;
3902 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3903 $patch_number++;
3904 # print "git diff" header
3905 print format_git_diff_header_line($patch_line, $diffinfo,
3906 \%from, \%to);
3908 # print extended diff header
3909 print "<div class=\"diff extended_header\">\n";
3910 EXTENDED_HEADER:
3911 while ($patch_line = <$fd>) {
3912 chomp $patch_line;
3914 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3916 print format_extended_diff_header_line($patch_line, $diffinfo,
3917 \%from, \%to);
3919 print "</div>\n"; # class="diff extended_header"
3921 # from-file/to-file diff header
3922 if (! $patch_line) {
3923 print "</div>\n"; # class="patch"
3924 last PATCH;
3926 next PATCH if ($patch_line =~ m/^diff /);
3927 #assert($patch_line =~ m/^---/) if DEBUG;
3929 my $last_patch_line = $patch_line;
3930 $patch_line = <$fd>;
3931 chomp $patch_line;
3932 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3934 print format_diff_from_to_header($last_patch_line, $patch_line,
3935 $diffinfo, \%from, \%to,
3936 @hash_parents);
3938 # the patch itself
3939 LINE:
3940 while ($patch_line = <$fd>) {
3941 chomp $patch_line;
3943 next PATCH if ($patch_line =~ m/^diff /);
3945 print format_diff_line($patch_line, \%from, \%to);
3948 } continue {
3949 print "</div>\n"; # class="patch"
3952 # for compact combined (--cc) format, with chunk and patch simpliciaction
3953 # patchset might be empty, but there might be unprocessed raw lines
3954 for (++$patch_idx if $patch_number > 0;
3955 $patch_idx < @$difftree;
3956 ++$patch_idx) {
3957 # read and prepare patch information
3958 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3960 # generate anchor for "patch" links in difftree / whatchanged part
3961 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3962 format_diff_cc_simplified($diffinfo, @hash_parents) .
3963 "</div>\n"; # class="patch"
3965 $patch_number++;
3968 if ($patch_number == 0) {
3969 if (@hash_parents > 1) {
3970 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3971 } else {
3972 print "<div class=\"diff nodifferences\">No differences found</div>\n";
3976 print "</div>\n"; # class="patchset"
3979 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3981 # fills project list info (age, description, owner, forks) for each
3982 # project in the list, removing invalid projects from returned list
3983 # NOTE: modifies $projlist, but does not remove entries from it
3984 sub fill_project_list_info {
3985 my ($projlist, $check_forks) = @_;
3986 my @projects;
3988 my $show_ctags = gitweb_check_feature('ctags');
3989 PROJECT:
3990 foreach my $pr (@$projlist) {
3991 my (@activity) = git_get_last_activity($pr->{'path'});
3992 unless (@activity) {
3993 next PROJECT;
3995 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
3996 if (!defined $pr->{'descr'}) {
3997 my $descr = git_get_project_description($pr->{'path'}) || "";
3998 $descr = to_utf8($descr);
3999 $pr->{'descr_long'} = $descr;
4000 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4002 if (!defined $pr->{'owner'}) {
4003 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4005 if ($check_forks) {
4006 my $pname = $pr->{'path'};
4007 if (($pname =~ s/\.git$//) &&
4008 ($pname !~ /\/$/) &&
4009 (-d "$projectroot/$pname")) {
4010 $pr->{'forks'} = "-d $projectroot/$pname";
4011 } else {
4012 $pr->{'forks'} = 0;
4015 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4016 push @projects, $pr;
4019 return @projects;
4022 # print 'sort by' <th> element, generating 'sort by $name' replay link
4023 # if that order is not selected
4024 sub print_sort_th {
4025 my ($name, $order, $header) = @_;
4026 $header ||= ucfirst($name);
4028 if ($order eq $name) {
4029 print "<th>$header</th>\n";
4030 } else {
4031 print "<th>" .
4032 $cgi->a({-href => href(-replay=>1, order=>$name),
4033 -class => "header"}, $header) .
4034 "</th>\n";
4038 sub git_project_list_body {
4039 # actually uses global variable $project
4040 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4042 my $check_forks = gitweb_check_feature('forks');
4043 my @projects = fill_project_list_info($projlist, $check_forks);
4045 $order ||= $default_projects_order;
4046 $from = 0 unless defined $from;
4047 $to = $#projects if (!defined $to || $#projects < $to);
4049 my %order_info = (
4050 project => { key => 'path', type => 'str' },
4051 descr => { key => 'descr_long', type => 'str' },
4052 owner => { key => 'owner', type => 'str' },
4053 age => { key => 'age', type => 'num' }
4055 my $oi = $order_info{$order};
4056 if ($oi->{'type'} eq 'str') {
4057 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4058 } else {
4059 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4062 my $show_ctags = gitweb_check_feature('ctags');
4063 if ($show_ctags) {
4064 my %ctags;
4065 foreach my $p (@projects) {
4066 foreach my $ct (keys %{$p->{'ctags'}}) {
4067 $ctags{$ct} += $p->{'ctags'}->{$ct};
4070 my $cloud = git_populate_project_tagcloud(\%ctags);
4071 print git_show_project_tagcloud($cloud, 64);
4074 print "<table class=\"project_list\">\n";
4075 unless ($no_header) {
4076 print "<tr>\n";
4077 if ($check_forks) {
4078 print "<th></th>\n";
4080 print_sort_th('project', $order, 'Project');
4081 print_sort_th('descr', $order, 'Description');
4082 print_sort_th('owner', $order, 'Owner');
4083 print_sort_th('age', $order, 'Last Change');
4084 print "<th></th>\n" . # for links
4085 "</tr>\n";
4087 my $alternate = 1;
4088 my $tagfilter = $cgi->param('by_tag');
4089 for (my $i = $from; $i <= $to; $i++) {
4090 my $pr = $projects[$i];
4092 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4093 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4094 and not $pr->{'descr_long'} =~ /$searchtext/;
4095 # Weed out forks or non-matching entries of search
4096 if ($check_forks) {
4097 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4098 $forkbase="^$forkbase" if $forkbase;
4099 next if not $searchtext and not $tagfilter and $show_ctags
4100 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4103 if ($alternate) {
4104 print "<tr class=\"dark\">\n";
4105 } else {
4106 print "<tr class=\"light\">\n";
4108 $alternate ^= 1;
4109 if ($check_forks) {
4110 print "<td>";
4111 if ($pr->{'forks'}) {
4112 print "<!-- $pr->{'forks'} -->\n";
4113 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4115 print "</td>\n";
4117 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4118 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4119 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4120 -class => "list", -title => $pr->{'descr_long'}},
4121 esc_html($pr->{'descr'})) . "</td>\n" .
4122 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4123 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4124 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4125 "<td class=\"link\">" .
4126 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4127 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "log") . " | " .
4128 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4129 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4130 "</td>\n" .
4131 "</tr>\n";
4133 if (defined $extra) {
4134 print "<tr>\n";
4135 if ($check_forks) {
4136 print "<td></td>\n";
4138 print "<td colspan=\"5\">$extra</td>\n" .
4139 "</tr>\n";
4141 print "</table>\n";
4144 sub git_shortlog_body {
4145 # uses global variable $project
4146 my ($commitlist, $from, $to, $refs, $extra) = @_;
4148 $from = 0 unless defined $from;
4149 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4151 print "<table class=\"shortlog\">\n";
4152 my $alternate = 1;
4153 for (my $i = $from; $i <= $to; $i++) {
4154 my %co = %{$commitlist->[$i]};
4155 my $commit = $co{'id'};
4156 my $ref = format_ref_marker($refs, $commit);
4157 if ($alternate) {
4158 print "<tr class=\"dark\">\n";
4159 } else {
4160 print "<tr class=\"light\">\n";
4162 $alternate ^= 1;
4163 my $author = chop_and_escape_str($co{'author_name'}, 10);
4164 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4165 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4166 "<td><i>" . $author . "</i></td>\n" .
4167 "<td>";
4168 print format_subject_html($co{'title'}, $co{'title_short'},
4169 href(action=>"commit", hash=>$commit), $ref);
4170 print "</td>\n" .
4171 "<td class=\"link\">" .
4172 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4173 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4174 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4175 my $snapshot_links = format_snapshot_links($commit);
4176 if (defined $snapshot_links) {
4177 print " | " . $snapshot_links;
4179 print "</td>\n" .
4180 "</tr>\n";
4182 if (defined $extra) {
4183 print "<tr>\n" .
4184 "<td colspan=\"4\">$extra</td>\n" .
4185 "</tr>\n";
4187 print "</table>\n";
4190 sub git_history_body {
4191 # Warning: assumes constant type (blob or tree) during history
4192 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4194 $from = 0 unless defined $from;
4195 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4197 print "<table class=\"history\">\n";
4198 my $alternate = 1;
4199 for (my $i = $from; $i <= $to; $i++) {
4200 my %co = %{$commitlist->[$i]};
4201 if (!%co) {
4202 next;
4204 my $commit = $co{'id'};
4206 my $ref = format_ref_marker($refs, $commit);
4208 if ($alternate) {
4209 print "<tr class=\"dark\">\n";
4210 } else {
4211 print "<tr class=\"light\">\n";
4213 $alternate ^= 1;
4214 # shortlog uses chop_str($co{'author_name'}, 10)
4215 my $author = chop_and_escape_str($co{'author_name'}, 15, 3);
4216 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4217 "<td><i>" . $author . "</i></td>\n" .
4218 "<td>";
4219 # originally git_history used chop_str($co{'title'}, 50)
4220 print format_subject_html($co{'title'}, $co{'title_short'},
4221 href(action=>"commit", hash=>$commit), $ref);
4222 print "</td>\n" .
4223 "<td class=\"link\">" .
4224 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4225 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4227 if ($ftype eq 'blob') {
4228 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4229 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4230 if (defined $blob_current && defined $blob_parent &&
4231 $blob_current ne $blob_parent) {
4232 print " | " .
4233 $cgi->a({-href => href(action=>"blobdiff",
4234 hash=>$blob_current, hash_parent=>$blob_parent,
4235 hash_base=>$hash_base, hash_parent_base=>$commit,
4236 file_name=>$file_name)},
4237 "diff to current");
4240 print "</td>\n" .
4241 "</tr>\n";
4243 if (defined $extra) {
4244 print "<tr>\n" .
4245 "<td colspan=\"4\">$extra</td>\n" .
4246 "</tr>\n";
4248 print "</table>\n";
4251 sub git_tags_body {
4252 # uses global variable $project
4253 my ($taglist, $from, $to, $extra) = @_;
4254 $from = 0 unless defined $from;
4255 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4257 print "<table class=\"tags\">\n";
4258 my $alternate = 1;
4259 for (my $i = $from; $i <= $to; $i++) {
4260 my $entry = $taglist->[$i];
4261 my %tag = %$entry;
4262 my $comment = $tag{'subject'};
4263 my $comment_short;
4264 if (defined $comment) {
4265 $comment_short = chop_str($comment, 30, 5);
4267 if ($alternate) {
4268 print "<tr class=\"dark\">\n";
4269 } else {
4270 print "<tr class=\"light\">\n";
4272 $alternate ^= 1;
4273 if (defined $tag{'age'}) {
4274 print "<td><i>$tag{'age'}</i></td>\n";
4275 } else {
4276 print "<td></td>\n";
4278 print "<td>" .
4279 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4280 -class => "list name"}, esc_html($tag{'name'})) .
4281 "</td>\n" .
4282 "<td>";
4283 if (defined $comment) {
4284 print format_subject_html($comment, $comment_short,
4285 href(action=>"tag", hash=>$tag{'id'}));
4287 print "</td>\n" .
4288 "<td class=\"selflink\">";
4289 if ($tag{'type'} eq "tag") {
4290 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4291 } else {
4292 print "&nbsp;";
4294 print "</td>\n" .
4295 "<td class=\"link\">" . " | " .
4296 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4297 if ($tag{'reftype'} eq "commit") {
4298 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "log");
4299 } elsif ($tag{'reftype'} eq "blob") {
4300 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4302 print "</td>\n" .
4303 "</tr>";
4305 if (defined $extra) {
4306 print "<tr>\n" .
4307 "<td colspan=\"5\">$extra</td>\n" .
4308 "</tr>\n";
4310 print "</table>\n";
4313 sub git_heads_body {
4314 # uses global variable $project
4315 my ($headlist, $head, $from, $to, $extra) = @_;
4316 $from = 0 unless defined $from;
4317 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4319 print "<table class=\"heads\">\n";
4320 my $alternate = 1;
4321 for (my $i = $from; $i <= $to; $i++) {
4322 my $entry = $headlist->[$i];
4323 my %ref = %$entry;
4324 my $curr = $ref{'id'} eq $head;
4325 if ($alternate) {
4326 print "<tr class=\"dark\">\n";
4327 } else {
4328 print "<tr class=\"light\">\n";
4330 $alternate ^= 1;
4331 print "<td><i>$ref{'age'}</i></td>\n" .
4332 ($curr ? "<td class=\"current_head\">" : "<td>") .
4333 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4334 -class => "list name"},esc_html($ref{'name'})) .
4335 "</td>\n" .
4336 "<td class=\"link\">" .
4337 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "log") . " | " .
4338 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4339 "</td>\n" .
4340 "</tr>";
4342 if (defined $extra) {
4343 print "<tr>\n" .
4344 "<td colspan=\"3\">$extra</td>\n" .
4345 "</tr>\n";
4347 print "</table>\n";
4350 sub git_search_grep_body {
4351 my ($commitlist, $from, $to, $extra) = @_;
4352 $from = 0 unless defined $from;
4353 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4355 print "<table class=\"commit_search\">\n";
4356 my $alternate = 1;
4357 for (my $i = $from; $i <= $to; $i++) {
4358 my %co = %{$commitlist->[$i]};
4359 if (!%co) {
4360 next;
4362 my $commit = $co{'id'};
4363 if ($alternate) {
4364 print "<tr class=\"dark\">\n";
4365 } else {
4366 print "<tr class=\"light\">\n";
4368 $alternate ^= 1;
4369 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
4370 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4371 "<td><i>" . $author . "</i></td>\n" .
4372 "<td>" .
4373 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4374 -class => "list subject"},
4375 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4376 my $comment = $co{'comment'};
4377 foreach my $line (@$comment) {
4378 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4379 my ($lead, $match, $trail) = ($1, $2, $3);
4380 $match = chop_str($match, 70, 5, 'center');
4381 my $contextlen = int((80 - length($match))/2);
4382 $contextlen = 30 if ($contextlen > 30);
4383 $lead = chop_str($lead, $contextlen, 10, 'left');
4384 $trail = chop_str($trail, $contextlen, 10, 'right');
4386 $lead = esc_html($lead);
4387 $match = esc_html($match);
4388 $trail = esc_html($trail);
4390 print "$lead<span class=\"match\">$match</span>$trail<br />";
4393 print "</td>\n" .
4394 "<td class=\"link\">" .
4395 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4396 " | " .
4397 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4398 " | " .
4399 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4400 print "</td>\n" .
4401 "</tr>\n";
4403 if (defined $extra) {
4404 print "<tr>\n" .
4405 "<td colspan=\"3\">$extra</td>\n" .
4406 "</tr>\n";
4408 print "</table>\n";
4411 ## ======================================================================
4412 ## ======================================================================
4413 ## actions
4415 sub git_project_list {
4416 my $order = $input_params{'order'};
4417 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4418 die_error(400, "Unknown order parameter");
4421 my @list = git_get_projects_list();
4422 if (!@list) {
4423 die_error(404, "No projects found");
4426 git_header_html();
4427 if (-f $home_text) {
4428 print "<div class=\"index_include\">\n";
4429 insert_file($home_text);
4430 print "</div>\n";
4432 print $cgi->startform(-method => "get") .
4433 "<p class=\"projsearch\">Search:\n" .
4434 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4435 "</p>" .
4436 $cgi->end_form() . "\n";
4437 git_project_list_body(\@list, $order);
4438 git_footer_html();
4441 sub git_forks {
4442 my $order = $input_params{'order'};
4443 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4444 die_error(400, "Unknown order parameter");
4447 my @list = git_get_projects_list($project);
4448 if (!@list) {
4449 die_error(404, "No forks found");
4452 git_header_html();
4453 git_print_page_nav('','');
4454 git_print_header_div('summary', "$project forks");
4455 git_project_list_body(\@list, $order);
4456 git_footer_html();
4459 sub git_project_index {
4460 my @projects = git_get_projects_list($project);
4462 print $cgi->header(
4463 -type => 'text/plain',
4464 -charset => 'utf-8',
4465 -content_disposition => 'inline; filename="index.aux"');
4467 foreach my $pr (@projects) {
4468 if (!exists $pr->{'owner'}) {
4469 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4472 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4473 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4474 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4475 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4476 $path =~ s/ /\+/g;
4477 $owner =~ s/ /\+/g;
4479 print "$path $owner\n";
4483 sub git_summary {
4484 my $descr = git_get_project_description($project) || "none";
4485 my %co = parse_commit("HEAD");
4486 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4487 my $head = $co{'id'};
4489 my $owner = git_get_project_owner($project);
4491 my $refs = git_get_references();
4492 # These get_*_list functions return one more to allow us to see if
4493 # there are more ...
4494 my @taglist = git_get_tags_list(16);
4495 my @headlist = git_get_heads_list(16);
4496 my @forklist;
4497 my $check_forks = gitweb_check_feature('forks');
4499 if ($check_forks) {
4500 @forklist = git_get_projects_list($project);
4503 git_header_html();
4504 git_print_page_nav('summary','', $head);
4506 print "<div class=\"title\">&nbsp;</div>\n";
4507 print "<table class=\"projects_list\">\n" .
4508 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4509 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4510 if (defined $cd{'rfc2822'}) {
4511 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4514 # use per project git URL list in $projectroot/$project/cloneurl
4515 # or make project git URL from git base URL and project name
4516 my $url_tag = "URL";
4517 my @url_list = git_get_project_url_list($project);
4518 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4519 foreach my $git_url (@url_list) {
4520 next unless $git_url;
4521 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4522 $url_tag = "";
4525 # Tag cloud
4526 my $show_ctags = gitweb_check_feature('ctags');
4527 if ($show_ctags) {
4528 my $ctags = git_get_project_ctags($project);
4529 my $cloud = git_populate_project_tagcloud($ctags);
4530 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4531 print "</td>\n<td>" unless %$ctags;
4532 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4533 print "</td>\n<td>" if %$ctags;
4534 print git_show_project_tagcloud($cloud, 48);
4535 print "</td></tr>";
4538 print "</table>\n";
4540 # If XSS prevention is on, we don't include README.html.
4541 # TODO: Allow a readme in some safe format.
4542 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4543 print "<div class=\"title\">readme</div>\n" .
4544 "<div class=\"readme\">\n";
4545 insert_file("$projectroot/$project/README.html");
4546 print "\n</div>\n"; # class="readme"
4549 # we need to request one more than 16 (0..15) to check if
4550 # those 16 are all
4551 my @commitlist = $head ? parse_commits($head, 17) : ();
4552 if (@commitlist) {
4553 git_print_header_div('shortlog');
4554 git_shortlog_body(\@commitlist, 0, 15, $refs,
4555 $#commitlist <= 15 ? undef :
4556 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4559 if (@taglist) {
4560 git_print_header_div('tags');
4561 git_tags_body(\@taglist, 0, 15,
4562 $#taglist <= 15 ? undef :
4563 $cgi->a({-href => href(action=>"tags")}, "..."));
4566 if (@headlist) {
4567 git_print_header_div('heads');
4568 git_heads_body(\@headlist, $head, 0, 15,
4569 $#headlist <= 15 ? undef :
4570 $cgi->a({-href => href(action=>"heads")}, "..."));
4573 if (@forklist) {
4574 git_print_header_div('forks');
4575 git_project_list_body(\@forklist, 'age', 0, 15,
4576 $#forklist <= 15 ? undef :
4577 $cgi->a({-href => href(action=>"forks")}, "..."),
4578 'no_header');
4581 git_footer_html();
4584 sub git_tag {
4585 my $head = git_get_head_hash($project);
4586 git_header_html();
4587 git_print_page_nav('','', $head,undef,$head);
4588 my %tag = parse_tag($hash);
4590 if (! %tag) {
4591 die_error(404, "Unknown tag object");
4594 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4595 print "<div class=\"title_text\">\n" .
4596 "<table class=\"object_header\">\n" .
4597 "<tr>\n" .
4598 "<td>object</td>\n" .
4599 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4600 $tag{'object'}) . "</td>\n" .
4601 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4602 $tag{'type'}) . "</td>\n" .
4603 "</tr>\n";
4604 if (defined($tag{'author'})) {
4605 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
4606 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
4607 print "<tr><td></td><td>" . $ad{'rfc2822'} .
4608 sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
4609 "</td></tr>\n";
4611 print "</table>\n\n" .
4612 "</div>\n";
4613 print "<div class=\"page_body\">";
4614 my $comment = $tag{'comment'};
4615 foreach my $line (@$comment) {
4616 chomp $line;
4617 print esc_html($line, -nbsp=>1) . "<br/>\n";
4619 print "</div>\n";
4620 git_footer_html();
4623 sub git_blame {
4624 # permissions
4625 gitweb_check_feature('blame')
4626 or die_error(403, "Blame view not allowed");
4628 # error checking
4629 die_error(400, "No file name given") unless $file_name;
4630 $hash_base ||= git_get_head_hash($project);
4631 die_error(404, "Couldn't find base commit") unless $hash_base;
4632 my %co = parse_commit($hash_base)
4633 or die_error(404, "Commit not found");
4634 my $ftype = "blob";
4635 if (!defined $hash) {
4636 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4637 or die_error(404, "Error looking up file");
4638 } else {
4639 $ftype = git_get_type($hash);
4640 if ($ftype !~ "blob") {
4641 die_error(400, "Object is not a blob");
4645 # run git-blame --porcelain
4646 open my $fd, "-|", git_cmd(), "blame", '-p',
4647 $hash_base, '--', $file_name
4648 or die_error(500, "Open git-blame failed");
4650 # page header
4651 git_header_html();
4652 my $formats_nav =
4653 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4654 "blob") .
4655 " | " .
4656 $cgi->a({-href => href(action=>"history", -replay=>1)},
4657 "history") .
4658 " | " .
4659 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4660 "HEAD");
4661 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4662 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4663 git_print_page_path($file_name, $ftype, $hash_base);
4665 # page body
4666 my @rev_color = qw(light2 dark2);
4667 my $num_colors = scalar(@rev_color);
4668 my $current_color = 0;
4669 my %metainfo = ();
4671 print <<HTML;
4672 <div class="page_body">
4673 <table class="blame">
4674 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4675 HTML
4676 LINE:
4677 while (my $line = <$fd>) {
4678 chomp $line;
4679 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4680 # no <lines in group> for subsequent lines in group of lines
4681 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4682 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
4683 if (!exists $metainfo{$full_rev}) {
4684 $metainfo{$full_rev} = {};
4686 my $meta = $metainfo{$full_rev};
4687 my $data;
4688 while ($data = <$fd>) {
4689 chomp $data;
4690 last if ($data =~ s/^\t//); # contents of line
4691 if ($data =~ /^(\S+) (.*)$/) {
4692 $meta->{$1} = $2;
4695 my $short_rev = substr($full_rev, 0, 8);
4696 my $author = $meta->{'author'};
4697 my %date =
4698 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
4699 my $date = $date{'iso-tz'};
4700 if ($group_size) {
4701 $current_color = ($current_color + 1) % $num_colors;
4703 print "<tr id=\"l$lineno\" class=\"$rev_color[$current_color]\">\n";
4704 if ($group_size) {
4705 print "<td class=\"sha1\"";
4706 print " title=\"". esc_html($author) . ", $date\"";
4707 print " rowspan=\"$group_size\"" if ($group_size > 1);
4708 print ">";
4709 print $cgi->a({-href => href(action=>"commit",
4710 hash=>$full_rev,
4711 file_name=>$file_name)},
4712 esc_html($short_rev));
4713 print "</td>\n";
4715 my $parent_commit;
4716 if (!exists $meta->{'parent'}) {
4717 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
4718 or die_error(500, "Open git-rev-parse failed");
4719 $parent_commit = <$dd>;
4720 close $dd;
4721 chomp($parent_commit);
4722 $meta->{'parent'} = $parent_commit;
4723 } else {
4724 $parent_commit = $meta->{'parent'};
4726 my $blamed = href(action => 'blame',
4727 file_name => $meta->{'filename'},
4728 hash_base => $parent_commit);
4729 print "<td class=\"linenr\">";
4730 print $cgi->a({ -href => "$blamed#l$orig_lineno",
4731 -class => "linenr" },
4732 esc_html($lineno));
4733 print "</td>";
4734 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4735 print "</tr>\n";
4737 print "</table>\n";
4738 print "</div>";
4739 close $fd
4740 or print "Reading blob failed\n";
4742 # page footer
4743 git_footer_html();
4746 sub git_tags {
4747 my $head = git_get_head_hash($project);
4748 git_header_html();
4749 git_print_page_nav('','', $head,undef,$head);
4750 git_print_header_div('summary', $project);
4752 my @tagslist = git_get_tags_list();
4753 if (@tagslist) {
4754 git_tags_body(\@tagslist);
4756 git_footer_html();
4759 sub git_heads {
4760 my $head = git_get_head_hash($project);
4761 git_header_html();
4762 git_print_page_nav('','', $head,undef,$head);
4763 git_print_header_div('summary', $project);
4765 my @headslist = git_get_heads_list();
4766 if (@headslist) {
4767 git_heads_body(\@headslist, $head);
4769 git_footer_html();
4772 sub git_blob_plain {
4773 my $type = shift;
4774 my $expires;
4776 if (!defined $hash) {
4777 if (defined $file_name) {
4778 my $base = $hash_base || git_get_head_hash($project);
4779 $hash = git_get_hash_by_path($base, $file_name, "blob")
4780 or die_error(404, "Cannot find file");
4781 } else {
4782 die_error(400, "No file name defined");
4784 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4785 # blobs defined by non-textual hash id's can be cached
4786 $expires = "+1d";
4789 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4790 or die_error(500, "Open git-cat-file blob '$hash' failed");
4792 # content-type (can include charset)
4793 $type = blob_contenttype($fd, $file_name, $type);
4795 # "save as" filename, even when no $file_name is given
4796 my $save_as = "$hash";
4797 if (defined $file_name) {
4798 $save_as = $file_name;
4799 } elsif ($type =~ m/^text\//) {
4800 $save_as .= '.txt';
4803 # With XSS prevention on, blobs of all types except a few known safe
4804 # ones are served with "Content-Disposition: attachment" to make sure
4805 # they don't run in our security domain. For certain image types,
4806 # blob view writes an <img> tag referring to blob_plain view, and we
4807 # want to be sure not to break that by serving the image as an
4808 # attachment (though Firefox 3 doesn't seem to care).
4809 my $sandbox = $prevent_xss &&
4810 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
4812 print $cgi->header(
4813 -type => $type,
4814 -expires => $expires,
4815 -content_disposition =>
4816 ($sandbox ? 'attachment' : 'inline')
4817 . '; filename="' . $save_as . '"');
4818 local $/ = undef;
4819 binmode STDOUT, ':raw';
4820 print <$fd>;
4821 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4822 close $fd;
4825 sub git_blob {
4826 my $expires;
4828 if (!defined $hash) {
4829 if (defined $file_name) {
4830 my $base = $hash_base || git_get_head_hash($project);
4831 $hash = git_get_hash_by_path($base, $file_name, "blob")
4832 or die_error(404, "Cannot find file");
4833 } else {
4834 die_error(400, "No file name defined");
4836 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4837 # blobs defined by non-textual hash id's can be cached
4838 $expires = "+1d";
4841 my $have_blame = gitweb_check_feature('blame');
4842 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4843 or die_error(500, "Couldn't cat $file_name, $hash");
4844 my $mimetype = blob_mimetype($fd, $file_name);
4845 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
4846 close $fd;
4847 return git_blob_plain($mimetype);
4849 # we can have blame only for text/* mimetype
4850 $have_blame &&= ($mimetype =~ m!^text/!);
4852 git_header_html(undef, $expires);
4853 my $formats_nav = '';
4854 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4855 if (defined $file_name) {
4856 if ($have_blame) {
4857 $formats_nav .=
4858 $cgi->a({-href => href(action=>"blame", -replay=>1)},
4859 "blame") .
4860 " | ";
4862 $formats_nav .=
4863 $cgi->a({-href => href(action=>"history", -replay=>1)},
4864 "history") .
4865 " | " .
4866 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4867 "raw") .
4868 " | " .
4869 $cgi->a({-href => href(action=>"blob",
4870 hash_base=>"HEAD", file_name=>$file_name)},
4871 "HEAD");
4872 } else {
4873 $formats_nav .=
4874 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4875 "raw");
4877 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4878 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4879 } else {
4880 print "<div class=\"page_nav\">\n" .
4881 "<br/><br/></div>\n" .
4882 "<div class=\"title\">$hash</div>\n";
4884 git_print_page_path($file_name, "blob", $hash_base);
4885 print "<div class=\"page_body\">\n";
4886 if ($mimetype =~ m!^image/!) {
4887 print qq!<img type="$mimetype"!;
4888 if ($file_name) {
4889 print qq! alt="$file_name" title="$file_name"!;
4891 print qq! src="! .
4892 href(action=>"blob_plain", hash=>$hash,
4893 hash_base=>$hash_base, file_name=>$file_name) .
4894 qq!" />\n!;
4895 } else {
4896 my $nr;
4897 while (my $line = <$fd>) {
4898 chomp $line;
4899 $nr++;
4900 $line = untabify($line);
4901 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4902 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4905 close $fd
4906 or print "Reading blob failed.\n";
4907 print "</div>";
4908 git_footer_html();
4911 sub git_tree {
4912 if (!defined $hash_base) {
4913 $hash_base = "HEAD";
4915 if (!defined $hash) {
4916 if (defined $file_name) {
4917 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4918 } else {
4919 $hash = $hash_base;
4922 die_error(404, "No such tree") unless defined($hash);
4924 my @entries = ();
4926 local $/ = "\0";
4927 open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4928 or die_error(500, "Open git-ls-tree failed");
4929 @entries = map { chomp; $_ } <$fd>;
4930 close $fd
4931 or die_error(404, "Reading tree failed");
4934 my $refs = git_get_references();
4935 my $ref = format_ref_marker($refs, $hash_base);
4936 git_header_html();
4937 my $basedir = '';
4938 my $have_blame = gitweb_check_feature('blame');
4939 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4940 my @views_nav = ();
4941 if (defined $file_name) {
4942 push @views_nav,
4943 $cgi->a({-href => href(action=>"history", -replay=>1)},
4944 "history"),
4945 $cgi->a({-href => href(action=>"tree",
4946 hash_base=>"HEAD", file_name=>$file_name)},
4947 "HEAD"),
4949 my $snapshot_links = format_snapshot_links($hash);
4950 if (defined $snapshot_links) {
4951 # FIXME: Should be available when we have no hash base as well.
4952 push @views_nav, $snapshot_links;
4954 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4955 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4956 } else {
4957 undef $hash_base;
4958 print "<div class=\"page_nav\">\n";
4959 print "<br/><br/></div>\n";
4960 print "<div class=\"title\">$hash</div>\n";
4962 if (defined $file_name) {
4963 $basedir = $file_name;
4964 if ($basedir ne '' && substr($basedir, -1) ne '/') {
4965 $basedir .= '/';
4967 git_print_page_path($file_name, 'tree', $hash_base);
4969 print "<div class=\"page_body\">\n";
4970 print "<table class=\"tree\">\n";
4971 my $alternate = 1;
4972 # '..' (top directory) link if possible
4973 if (defined $hash_base &&
4974 defined $file_name && $file_name =~ m![^/]+$!) {
4975 if ($alternate) {
4976 print "<tr class=\"dark\">\n";
4977 } else {
4978 print "<tr class=\"light\">\n";
4980 $alternate ^= 1;
4982 my $up = $file_name;
4983 $up =~ s!/?[^/]+$!!;
4984 undef $up unless $up;
4985 # based on git_print_tree_entry
4986 print '<td class="mode">' . mode_str('040000') . "</td>\n";
4987 print '<td class="list">';
4988 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4989 file_name=>$up)},
4990 "..");
4991 print "</td>\n";
4992 print "<td class=\"link\"></td>\n";
4994 print "</tr>\n";
4996 foreach my $line (@entries) {
4997 my %t = parse_ls_tree_line($line, -z => 1);
4999 if ($alternate) {
5000 print "<tr class=\"dark\">\n";
5001 } else {
5002 print "<tr class=\"light\">\n";
5004 $alternate ^= 1;
5006 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5008 print "</tr>\n";
5010 print "</table>\n" .
5011 "</div>";
5012 git_footer_html();
5015 sub git_snapshot {
5016 my $format = $input_params{'snapshot_format'};
5017 if (!@snapshot_fmts) {
5018 die_error(403, "Snapshots not allowed");
5020 # default to first supported snapshot format
5021 $format ||= $snapshot_fmts[0];
5022 if ($format !~ m/^[a-z0-9]+$/) {
5023 die_error(400, "Invalid snapshot format parameter");
5024 } elsif (!exists($known_snapshot_formats{$format})) {
5025 die_error(400, "Unknown snapshot format");
5026 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5027 die_error(403, "Unsupported snapshot format");
5030 if (!defined $hash) {
5031 $hash = git_get_head_hash($project);
5034 my $name = $project;
5035 $name =~ s,([^/])/*\.git$,$1,;
5036 $name = basename($name);
5037 my $filename = to_utf8($name);
5038 $name =~ s/\047/\047\\\047\047/g;
5039 my $cmd;
5040 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5041 $cmd = quote_command(
5042 git_cmd(), 'archive',
5043 "--format=$known_snapshot_formats{$format}{'format'}",
5044 "--prefix=$name/", $hash);
5045 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5046 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5049 print $cgi->header(
5050 -type => $known_snapshot_formats{$format}{'type'},
5051 -content_disposition => 'inline; filename="' . "$filename" . '"',
5052 -status => '200 OK');
5054 open my $fd, "-|", $cmd
5055 or die_error(500, "Execute git-archive failed");
5056 binmode STDOUT, ':raw';
5057 print <$fd>;
5058 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5059 close $fd;
5062 sub git_log {
5063 my $head = git_get_head_hash($project);
5064 if (!defined $hash) {
5065 $hash = $head;
5067 if (!defined $page) {
5068 $page = 0;
5070 my $refs = git_get_references();
5072 my @commitlist = parse_commits($hash, 101, (100 * $page));
5074 my $paging_nav = format_log_nav('log', $hash, $head, $page, $#commitlist >= 100);
5077 local $action = 'fulllog';
5078 git_header_html();
5080 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5082 if (!@commitlist) {
5083 my %co = parse_commit($hash);
5085 git_print_header_div('summary', $project);
5086 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5088 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5089 for (my $i = 0; $i <= $to; $i++) {
5090 my %co = %{$commitlist[$i]};
5091 next if !%co;
5092 my $commit = $co{'id'};
5093 my $ref = format_ref_marker($refs, $commit);
5094 my %ad = parse_date($co{'author_epoch'});
5095 git_print_header_div('commit',
5096 "<span class=\"age\">$co{'age_string'}</span>" .
5097 esc_html($co{'title'}) . $ref,
5098 $commit);
5099 print "<div class=\"title_text\">\n" .
5100 "<div class=\"log_link\">\n" .
5101 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5102 " | " .
5103 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5104 " | " .
5105 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5106 "<br/>\n" .
5107 "</div>\n" .
5108 "<i>" . esc_html($co{'author_name'}) . " [$ad{'rfc2822'}]</i><br/>\n" .
5109 "</div>\n";
5111 print "<div class=\"log_body\">\n";
5112 git_print_log($co{'comment'}, -final_empty_line=> 1);
5113 print "</div>\n";
5115 if ($#commitlist >= 100) {
5116 print "<div class=\"page_nav\">\n";
5117 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5118 -accesskey => "n", -title => "Alt-n"}, "next");
5119 print "</div>\n";
5121 git_footer_html();
5124 sub git_commit {
5125 $hash ||= $hash_base || "HEAD";
5126 my %co = parse_commit($hash)
5127 or die_error(404, "Unknown commit object");
5128 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5129 my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
5131 my $parent = $co{'parent'};
5132 my $parents = $co{'parents'}; # listref
5134 # we need to prepare $formats_nav before any parameter munging
5135 my $formats_nav;
5136 if (!defined $parent) {
5137 # --root commitdiff
5138 $formats_nav .= '(initial)';
5139 } elsif (@$parents == 1) {
5140 # single parent commit
5141 $formats_nav .=
5142 '(parent: ' .
5143 $cgi->a({-href => href(action=>"commit",
5144 hash=>$parent)},
5145 esc_html(substr($parent, 0, 7))) .
5146 ')';
5147 } else {
5148 # merge commit
5149 $formats_nav .=
5150 '(merge: ' .
5151 join(' ', map {
5152 $cgi->a({-href => href(action=>"commit",
5153 hash=>$_)},
5154 esc_html(substr($_, 0, 7)));
5155 } @$parents ) .
5156 ')';
5158 if (gitweb_check_feature('patches')) {
5159 $formats_nav .= " | " .
5160 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5161 "patch");
5164 if (!defined $parent) {
5165 $parent = "--root";
5167 my @difftree;
5168 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5169 @diff_opts,
5170 (@$parents <= 1 ? $parent : '-c'),
5171 $hash, "--"
5172 or die_error(500, "Open git-diff-tree failed");
5173 @difftree = map { chomp; $_ } <$fd>;
5174 close $fd or die_error(404, "Reading git-diff-tree failed");
5176 # non-textual hash id's can be cached
5177 my $expires;
5178 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5179 $expires = "+1d";
5181 my $refs = git_get_references();
5182 my $ref = format_ref_marker($refs, $co{'id'});
5184 git_header_html(undef, $expires);
5185 git_print_page_nav('commit', '',
5186 $hash, $co{'tree'}, $hash,
5187 $formats_nav);
5189 if (defined $co{'parent'}) {
5190 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5191 } else {
5192 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5194 print "<div class=\"title_text\">\n" .
5195 "<table class=\"object_header\">\n";
5196 print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
5197 "<tr>" .
5198 "<td></td><td> $ad{'rfc2822'}";
5199 if ($ad{'hour_local'} < 6) {
5200 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
5201 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
5202 } else {
5203 printf(" (%02d:%02d %s)",
5204 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
5206 print "</td>" .
5207 "</tr>\n";
5208 print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
5209 print "<tr><td></td><td> $cd{'rfc2822'}" .
5210 sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
5211 "</td></tr>\n";
5212 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5213 print "<tr>" .
5214 "<td>tree</td>" .
5215 "<td class=\"sha1\">" .
5216 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5217 class => "list"}, $co{'tree'}) .
5218 "</td>" .
5219 "<td class=\"link\">" .
5220 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5221 "tree");
5222 my $snapshot_links = format_snapshot_links($hash);
5223 if (defined $snapshot_links) {
5224 print " | " . $snapshot_links;
5226 print "</td>" .
5227 "</tr>\n";
5229 foreach my $par (@$parents) {
5230 print "<tr>" .
5231 "<td>parent</td>" .
5232 "<td class=\"sha1\">" .
5233 $cgi->a({-href => href(action=>"commit", hash=>$par),
5234 class => "list"}, $par) .
5235 "</td>" .
5236 "<td class=\"link\">" .
5237 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5238 " | " .
5239 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5240 "</td>" .
5241 "</tr>\n";
5243 print "</table>".
5244 "</div>\n";
5246 print "<div class=\"page_body\">\n";
5247 git_print_log($co{'comment'});
5248 print "</div>\n";
5250 git_difftree_body(\@difftree, $hash, @$parents);
5252 git_footer_html();
5255 sub git_object {
5256 # object is defined by:
5257 # - hash or hash_base alone
5258 # - hash_base and file_name
5259 my $type;
5261 # - hash or hash_base alone
5262 if ($hash || ($hash_base && !defined $file_name)) {
5263 my $object_id = $hash || $hash_base;
5265 open my $fd, "-|", quote_command(
5266 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5267 or die_error(404, "Object does not exist");
5268 $type = <$fd>;
5269 chomp $type;
5270 close $fd
5271 or die_error(404, "Object does not exist");
5273 # - hash_base and file_name
5274 } elsif ($hash_base && defined $file_name) {
5275 $file_name =~ s,/+$,,;
5277 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5278 or die_error(404, "Base object does not exist");
5280 # here errors should not hapen
5281 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5282 or die_error(500, "Open git-ls-tree failed");
5283 my $line = <$fd>;
5284 close $fd;
5286 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5287 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5288 die_error(404, "File or directory for given base does not exist");
5290 $type = $2;
5291 $hash = $3;
5292 } else {
5293 die_error(400, "Not enough information to find object");
5296 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5297 hash=>$hash, hash_base=>$hash_base,
5298 file_name=>$file_name),
5299 -status => '302 Found');
5302 sub git_blobdiff {
5303 my $format = shift || 'html';
5305 my $fd;
5306 my @difftree;
5307 my %diffinfo;
5308 my $expires;
5310 # preparing $fd and %diffinfo for git_patchset_body
5311 # new style URI
5312 if (defined $hash_base && defined $hash_parent_base) {
5313 if (defined $file_name) {
5314 # read raw output
5315 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5316 $hash_parent_base, $hash_base,
5317 "--", (defined $file_parent ? $file_parent : ()), $file_name
5318 or die_error(500, "Open git-diff-tree failed");
5319 @difftree = map { chomp; $_ } <$fd>;
5320 close $fd
5321 or die_error(404, "Reading git-diff-tree failed");
5322 @difftree
5323 or die_error(404, "Blob diff not found");
5325 } elsif (defined $hash &&
5326 $hash =~ /[0-9a-fA-F]{40}/) {
5327 # try to find filename from $hash
5329 # read filtered raw output
5330 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5331 $hash_parent_base, $hash_base, "--"
5332 or die_error(500, "Open git-diff-tree failed");
5333 @difftree =
5334 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5335 # $hash == to_id
5336 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5337 map { chomp; $_ } <$fd>;
5338 close $fd
5339 or die_error(404, "Reading git-diff-tree failed");
5340 @difftree
5341 or die_error(404, "Blob diff not found");
5343 } else {
5344 die_error(400, "Missing one of the blob diff parameters");
5347 if (@difftree > 1) {
5348 die_error(400, "Ambiguous blob diff specification");
5351 %diffinfo = parse_difftree_raw_line($difftree[0]);
5352 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5353 $file_name ||= $diffinfo{'to_file'};
5355 $hash_parent ||= $diffinfo{'from_id'};
5356 $hash ||= $diffinfo{'to_id'};
5358 # non-textual hash id's can be cached
5359 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5360 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5361 $expires = '+1d';
5364 # open patch output
5365 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5366 '-p', ($format eq 'html' ? "--full-index" : ()),
5367 $hash_parent_base, $hash_base,
5368 "--", (defined $file_parent ? $file_parent : ()), $file_name
5369 or die_error(500, "Open git-diff-tree failed");
5372 # old/legacy style URI -- not generated anymore since 1.4.3.
5373 if (!%diffinfo) {
5374 die_error('404 Not Found', "Missing one of the blob diff parameters")
5377 # header
5378 if ($format eq 'html') {
5379 my $formats_nav =
5380 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5381 "raw");
5382 git_header_html(undef, $expires);
5383 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5384 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5385 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5386 } else {
5387 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5388 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5390 if (defined $file_name) {
5391 git_print_page_path($file_name, "blob", $hash_base);
5392 } else {
5393 print "<div class=\"page_path\"></div>\n";
5396 } elsif ($format eq 'plain') {
5397 print $cgi->header(
5398 -type => 'text/plain',
5399 -charset => 'utf-8',
5400 -expires => $expires,
5401 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5403 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5405 } else {
5406 die_error(400, "Unknown blobdiff format");
5409 # patch
5410 if ($format eq 'html') {
5411 print "<div class=\"page_body\">\n";
5413 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5414 close $fd;
5416 print "</div>\n"; # class="page_body"
5417 git_footer_html();
5419 } else {
5420 while (my $line = <$fd>) {
5421 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5422 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5424 print $line;
5426 last if $line =~ m!^\+\+\+!;
5428 local $/ = undef;
5429 print <$fd>;
5430 close $fd;
5434 sub git_blobdiff_plain {
5435 git_blobdiff('plain');
5438 sub git_commitdiff {
5439 my %params = @_;
5440 my $format = $params{-format} || 'html';
5442 my ($patch_max) = gitweb_get_feature('patches');
5443 if ($format eq 'patch') {
5444 die_error(403, "Patch view not allowed") unless $patch_max;
5447 $hash ||= $hash_base || "HEAD";
5448 my %co = parse_commit($hash)
5449 or die_error(404, "Unknown commit object");
5451 # choose format for commitdiff for merge
5452 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5453 $hash_parent = '--cc';
5455 # we need to prepare $formats_nav before almost any parameter munging
5456 my $formats_nav;
5457 if ($format eq 'html') {
5458 $formats_nav =
5459 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5460 "raw");
5461 if ($patch_max) {
5462 $formats_nav .= " | " .
5463 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5464 "patch");
5467 if (defined $hash_parent &&
5468 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5469 # commitdiff with two commits given
5470 my $hash_parent_short = $hash_parent;
5471 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5472 $hash_parent_short = substr($hash_parent, 0, 7);
5474 $formats_nav .=
5475 ' (from';
5476 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5477 if ($co{'parents'}[$i] eq $hash_parent) {
5478 $formats_nav .= ' parent ' . ($i+1);
5479 last;
5482 $formats_nav .= ': ' .
5483 $cgi->a({-href => href(action=>"commitdiff",
5484 hash=>$hash_parent)},
5485 esc_html($hash_parent_short)) .
5486 ')';
5487 } elsif (!$co{'parent'}) {
5488 # --root commitdiff
5489 $formats_nav .= ' (initial)';
5490 } elsif (scalar @{$co{'parents'}} == 1) {
5491 # single parent commit
5492 $formats_nav .=
5493 ' (parent: ' .
5494 $cgi->a({-href => href(action=>"commitdiff",
5495 hash=>$co{'parent'})},
5496 esc_html(substr($co{'parent'}, 0, 7))) .
5497 ')';
5498 } else {
5499 # merge commit
5500 if ($hash_parent eq '--cc') {
5501 $formats_nav .= ' | ' .
5502 $cgi->a({-href => href(action=>"commitdiff",
5503 hash=>$hash, hash_parent=>'-c')},
5504 'combined');
5505 } else { # $hash_parent eq '-c'
5506 $formats_nav .= ' | ' .
5507 $cgi->a({-href => href(action=>"commitdiff",
5508 hash=>$hash, hash_parent=>'--cc')},
5509 'compact');
5511 $formats_nav .=
5512 ' (merge: ' .
5513 join(' ', map {
5514 $cgi->a({-href => href(action=>"commitdiff",
5515 hash=>$_)},
5516 esc_html(substr($_, 0, 7)));
5517 } @{$co{'parents'}} ) .
5518 ')';
5522 my $hash_parent_param = $hash_parent;
5523 if (!defined $hash_parent_param) {
5524 # --cc for multiple parents, --root for parentless
5525 $hash_parent_param =
5526 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5529 # read commitdiff
5530 my $fd;
5531 my @difftree;
5532 if ($format eq 'html') {
5533 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5534 "--no-commit-id", "--patch-with-raw", "--full-index",
5535 $hash_parent_param, $hash, "--"
5536 or die_error(500, "Open git-diff-tree failed");
5538 while (my $line = <$fd>) {
5539 chomp $line;
5540 # empty line ends raw part of diff-tree output
5541 last unless $line;
5542 push @difftree, scalar parse_difftree_raw_line($line);
5545 } elsif ($format eq 'plain') {
5546 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5547 '-p', $hash_parent_param, $hash, "--"
5548 or die_error(500, "Open git-diff-tree failed");
5549 } elsif ($format eq 'patch') {
5550 # For commit ranges, we limit the output to the number of
5551 # patches specified in the 'patches' feature.
5552 # For single commits, we limit the output to a single patch,
5553 # diverging from the git-format-patch default.
5554 my @commit_spec = ();
5555 if ($hash_parent) {
5556 if ($patch_max > 0) {
5557 push @commit_spec, "-$patch_max";
5559 push @commit_spec, '-n', "$hash_parent..$hash";
5560 } else {
5561 if ($params{-single}) {
5562 push @commit_spec, '-1';
5563 } else {
5564 if ($patch_max > 0) {
5565 push @commit_spec, "-$patch_max";
5567 push @commit_spec, "-n";
5569 push @commit_spec, '--root', $hash;
5571 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5572 '--stdout', @commit_spec
5573 or die_error(500, "Open git-format-patch failed");
5574 } else {
5575 die_error(400, "Unknown commitdiff format");
5578 # non-textual hash id's can be cached
5579 my $expires;
5580 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5581 $expires = "+1d";
5584 # write commit message
5585 if ($format eq 'html') {
5586 my $refs = git_get_references();
5587 my $ref = format_ref_marker($refs, $co{'id'});
5589 git_header_html(undef, $expires);
5590 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5591 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5592 git_print_authorship(\%co);
5593 print "<div class=\"page_body\">\n";
5594 if (@{$co{'comment'}} > 1) {
5595 print "<div class=\"log\">\n";
5596 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5597 print "</div>\n"; # class="log"
5600 } elsif ($format eq 'plain') {
5601 my $refs = git_get_references("tags");
5602 my $tagname = git_get_rev_name_tags($hash);
5603 my $filename = basename($project) . "-$hash.patch";
5605 print $cgi->header(
5606 -type => 'text/plain',
5607 -charset => 'utf-8',
5608 -expires => $expires,
5609 -content_disposition => 'inline; filename="' . "$filename" . '"');
5610 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5611 print "From: " . to_utf8($co{'author'}) . "\n";
5612 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5613 print "Subject: " . to_utf8($co{'title'}) . "\n";
5615 print "X-Git-Tag: $tagname\n" if $tagname;
5616 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5618 foreach my $line (@{$co{'comment'}}) {
5619 print to_utf8($line) . "\n";
5621 print "---\n\n";
5622 } elsif ($format eq 'patch') {
5623 my $filename = basename($project) . "-$hash.patch";
5625 print $cgi->header(
5626 -type => 'text/plain',
5627 -charset => 'utf-8',
5628 -expires => $expires,
5629 -content_disposition => 'inline; filename="' . "$filename" . '"');
5632 # write patch
5633 if ($format eq 'html') {
5634 my $use_parents = !defined $hash_parent ||
5635 $hash_parent eq '-c' || $hash_parent eq '--cc';
5636 git_difftree_body(\@difftree, $hash,
5637 $use_parents ? @{$co{'parents'}} : $hash_parent);
5638 print "<br/>\n";
5640 git_patchset_body($fd, \@difftree, $hash,
5641 $use_parents ? @{$co{'parents'}} : $hash_parent);
5642 close $fd;
5643 print "</div>\n"; # class="page_body"
5644 git_footer_html();
5646 } elsif ($format eq 'plain') {
5647 local $/ = undef;
5648 print <$fd>;
5649 close $fd
5650 or print "Reading git-diff-tree failed\n";
5651 } elsif ($format eq 'patch') {
5652 local $/ = undef;
5653 print <$fd>;
5654 close $fd
5655 or print "Reading git-format-patch failed\n";
5659 sub git_commitdiff_plain {
5660 git_commitdiff(-format => 'plain');
5663 # format-patch-style patches
5664 sub git_patch {
5665 git_commitdiff(-format => 'patch', -single=> 1);
5668 sub git_patches {
5669 git_commitdiff(-format => 'patch');
5672 sub git_history {
5673 if (!defined $hash_base) {
5674 $hash_base = git_get_head_hash($project);
5676 if (!defined $page) {
5677 $page = 0;
5679 my $ftype;
5680 my %co = parse_commit($hash_base)
5681 or die_error(404, "Unknown commit object");
5683 my $refs = git_get_references();
5684 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5686 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5687 $file_name, "--full-history")
5688 or die_error(404, "No such file or directory on given branch");
5690 if (!defined $hash && defined $file_name) {
5691 # some commits could have deleted file in question,
5692 # and not have it in tree, but one of them has to have it
5693 for (my $i = 0; $i <= @commitlist; $i++) {
5694 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5695 last if defined $hash;
5698 if (defined $hash) {
5699 $ftype = git_get_type($hash);
5701 if (!defined $ftype) {
5702 die_error(500, "Unknown type of object");
5705 my $paging_nav = '';
5706 if ($page > 0) {
5707 $paging_nav .=
5708 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5709 file_name=>$file_name)},
5710 "first");
5711 $paging_nav .= " &sdot; " .
5712 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5713 -accesskey => "p", -title => "Alt-p"}, "prev");
5714 } else {
5715 $paging_nav .= "first";
5716 $paging_nav .= " &sdot; prev";
5718 my $next_link = '';
5719 if ($#commitlist >= 100) {
5720 $next_link =
5721 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5722 -accesskey => "n", -title => "Alt-n"}, "next");
5723 $paging_nav .= " &sdot; $next_link";
5724 } else {
5725 $paging_nav .= " &sdot; next";
5728 git_header_html();
5729 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5730 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5731 git_print_page_path($file_name, $ftype, $hash_base);
5733 git_history_body(\@commitlist, 0, 99,
5734 $refs, $hash_base, $ftype, $next_link);
5736 git_footer_html();
5739 sub git_search {
5740 gitweb_check_feature('search') or die_error(403, "Search is disabled");
5741 if (!defined $searchtext) {
5742 die_error(400, "Text field is empty");
5744 if (!defined $hash) {
5745 $hash = git_get_head_hash($project);
5747 my %co = parse_commit($hash);
5748 if (!%co) {
5749 die_error(404, "Unknown commit object");
5751 if (!defined $page) {
5752 $page = 0;
5755 $searchtype ||= 'commit';
5756 if ($searchtype eq 'pickaxe') {
5757 # pickaxe may take all resources of your box and run for several minutes
5758 # with every query - so decide by yourself how public you make this feature
5759 gitweb_check_feature('pickaxe')
5760 or die_error(403, "Pickaxe is disabled");
5762 if ($searchtype eq 'grep') {
5763 gitweb_check_feature('grep')
5764 or die_error(403, "Grep is disabled");
5767 git_header_html();
5769 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5770 my $greptype;
5771 if ($searchtype eq 'commit') {
5772 $greptype = "--grep=";
5773 } elsif ($searchtype eq 'author') {
5774 $greptype = "--author=";
5775 } elsif ($searchtype eq 'committer') {
5776 $greptype = "--committer=";
5778 $greptype .= $searchtext;
5779 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5780 $greptype, '--regexp-ignore-case',
5781 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5783 my $paging_nav = '';
5784 if ($page > 0) {
5785 $paging_nav .=
5786 $cgi->a({-href => href(action=>"search", hash=>$hash,
5787 searchtext=>$searchtext,
5788 searchtype=>$searchtype)},
5789 "first");
5790 $paging_nav .= " &sdot; " .
5791 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5792 -accesskey => "p", -title => "Alt-p"}, "prev");
5793 } else {
5794 $paging_nav .= "first";
5795 $paging_nav .= " &sdot; prev";
5797 my $next_link = '';
5798 if ($#commitlist >= 100) {
5799 $next_link =
5800 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5801 -accesskey => "n", -title => "Alt-n"}, "next");
5802 $paging_nav .= " &sdot; $next_link";
5803 } else {
5804 $paging_nav .= " &sdot; next";
5807 if ($#commitlist >= 100) {
5810 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5811 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5812 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5815 if ($searchtype eq 'pickaxe') {
5816 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5817 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5819 print "<table class=\"pickaxe search\">\n";
5820 my $alternate = 1;
5821 local $/ = "\n";
5822 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5823 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5824 ($search_use_regexp ? '--pickaxe-regex' : ());
5825 undef %co;
5826 my @files;
5827 while (my $line = <$fd>) {
5828 chomp $line;
5829 next unless $line;
5831 my %set = parse_difftree_raw_line($line);
5832 if (defined $set{'commit'}) {
5833 # finish previous commit
5834 if (%co) {
5835 print "</td>\n" .
5836 "<td class=\"link\">" .
5837 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5838 " | " .
5839 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5840 print "</td>\n" .
5841 "</tr>\n";
5844 if ($alternate) {
5845 print "<tr class=\"dark\">\n";
5846 } else {
5847 print "<tr class=\"light\">\n";
5849 $alternate ^= 1;
5850 %co = parse_commit($set{'commit'});
5851 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5852 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5853 "<td><i>$author</i></td>\n" .
5854 "<td>" .
5855 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5856 -class => "list subject"},
5857 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5858 } elsif (defined $set{'to_id'}) {
5859 next if ($set{'to_id'} =~ m/^0{40}$/);
5861 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5862 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
5863 -class => "list"},
5864 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5865 "<br/>\n";
5868 close $fd;
5870 # finish last commit (warning: repetition!)
5871 if (%co) {
5872 print "</td>\n" .
5873 "<td class=\"link\">" .
5874 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5875 " | " .
5876 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5877 print "</td>\n" .
5878 "</tr>\n";
5881 print "</table>\n";
5884 if ($searchtype eq 'grep') {
5885 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5886 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5888 print "<table class=\"grep_search\">\n";
5889 my $alternate = 1;
5890 my $matches = 0;
5891 local $/ = "\n";
5892 open my $fd, "-|", git_cmd(), 'grep', '-n',
5893 $search_use_regexp ? ('-E', '-i') : '-F',
5894 $searchtext, $co{'tree'};
5895 my $lastfile = '';
5896 while (my $line = <$fd>) {
5897 chomp $line;
5898 my ($file, $lno, $ltext, $binary);
5899 last if ($matches++ > 1000);
5900 if ($line =~ /^Binary file (.+) matches$/) {
5901 $file = $1;
5902 $binary = 1;
5903 } else {
5904 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5906 if ($file ne $lastfile) {
5907 $lastfile and print "</td></tr>\n";
5908 if ($alternate++) {
5909 print "<tr class=\"dark\">\n";
5910 } else {
5911 print "<tr class=\"light\">\n";
5913 print "<td class=\"list\">".
5914 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5915 file_name=>"$file"),
5916 -class => "list"}, esc_path($file));
5917 print "</td><td>\n";
5918 $lastfile = $file;
5920 if ($binary) {
5921 print "<div class=\"binary\">Binary file</div>\n";
5922 } else {
5923 $ltext = untabify($ltext);
5924 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
5925 $ltext = esc_html($1, -nbsp=>1);
5926 $ltext .= '<span class="match">';
5927 $ltext .= esc_html($2, -nbsp=>1);
5928 $ltext .= '</span>';
5929 $ltext .= esc_html($3, -nbsp=>1);
5930 } else {
5931 $ltext = esc_html($ltext, -nbsp=>1);
5933 print "<div class=\"pre\">" .
5934 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5935 file_name=>"$file").'#l'.$lno,
5936 -class => "linenr"}, sprintf('%4i', $lno))
5937 . ' ' . $ltext . "</div>\n";
5940 if ($lastfile) {
5941 print "</td></tr>\n";
5942 if ($matches > 1000) {
5943 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5945 } else {
5946 print "<div class=\"diff nodifferences\">No matches found</div>\n";
5948 close $fd;
5950 print "</table>\n";
5952 git_footer_html();
5955 sub git_search_help {
5956 git_header_html();
5957 git_print_page_nav('','', $hash,$hash,$hash);
5958 print <<EOT;
5959 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
5960 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
5961 the pattern entered is recognized as the POSIX extended
5962 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
5963 insensitive).</p>
5964 <dl>
5965 <dt><b>commit</b></dt>
5966 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
5968 my $have_grep = gitweb_check_feature('grep');
5969 if ($have_grep) {
5970 print <<EOT;
5971 <dt><b>grep</b></dt>
5972 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5973 a different one) are searched for the given pattern. On large trees, this search can take
5974 a while and put some strain on the server, so please use it with some consideration. Note that
5975 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
5976 case-sensitive.</dd>
5979 print <<EOT;
5980 <dt><b>author</b></dt>
5981 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
5982 <dt><b>committer</b></dt>
5983 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
5985 my $have_pickaxe = gitweb_check_feature('pickaxe');
5986 if ($have_pickaxe) {
5987 print <<EOT;
5988 <dt><b>pickaxe</b></dt>
5989 <dd>All commits that caused the string to appear or disappear from any file (changes that
5990 added, removed or "modified" the string) will be listed. This search can take a while and
5991 takes a lot of strain on the server, so please use it wisely. Note that since you may be
5992 interested even in changes just changing the case as well, this search is case sensitive.</dd>
5995 print "</dl>\n";
5996 git_footer_html();
5999 sub git_shortlog {
6000 my $head = git_get_head_hash($project);
6001 if (!defined $hash) {
6002 $hash = $head;
6004 if (!defined $page) {
6005 $page = 0;
6007 my $refs = git_get_references();
6009 my $commit_hash = $hash;
6010 if (defined $hash_parent) {
6011 $commit_hash = "$hash_parent..$hash";
6013 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6015 my $paging_nav = format_log_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6017 my $next_link = '';
6018 if ($#commitlist >= 100) {
6019 $next_link =
6020 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6021 -accesskey => "n", -title => "Alt-n"}, "next");
6023 my $patch_max = gitweb_check_feature('patches');
6024 if ($patch_max) {
6025 if ($patch_max < 0 || @commitlist <= $patch_max) {
6026 $paging_nav .= " &sdot; " .
6027 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6028 "patches");
6032 git_header_html();
6033 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6034 git_print_header_div('summary', $project);
6036 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6038 git_footer_html();
6041 ## ......................................................................
6042 ## feeds (RSS, Atom; OPML)
6044 sub git_feed {
6045 my $format = shift || 'atom';
6046 my $have_blame = gitweb_check_feature('blame');
6048 # Atom: http://www.atomenabled.org/developers/syndication/
6049 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6050 if ($format ne 'rss' && $format ne 'atom') {
6051 die_error(400, "Unknown web feed format");
6054 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6055 my $head = $hash || 'HEAD';
6056 my @commitlist = parse_commits($head, 150, 0, $file_name);
6058 my %latest_commit;
6059 my %latest_date;
6060 my $content_type = "application/$format+xml";
6061 if (defined $cgi->http('HTTP_ACCEPT') &&
6062 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6063 # browser (feed reader) prefers text/xml
6064 $content_type = 'text/xml';
6066 if (defined($commitlist[0])) {
6067 %latest_commit = %{$commitlist[0]};
6068 my $latest_epoch = $latest_commit{'committer_epoch'};
6069 %latest_date = parse_date($latest_epoch);
6070 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6071 if (defined $if_modified) {
6072 my $since;
6073 if (eval { require HTTP::Date; 1; }) {
6074 $since = HTTP::Date::str2time($if_modified);
6075 } elsif (eval { require Time::ParseDate; 1; }) {
6076 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6078 if (defined $since && $latest_epoch <= $since) {
6079 print $cgi->header(
6080 -type => $content_type,
6081 -charset => 'utf-8',
6082 -last_modified => $latest_date{'rfc2822'},
6083 -status => '304 Not Modified');
6084 return;
6087 print $cgi->header(
6088 -type => $content_type,
6089 -charset => 'utf-8',
6090 -last_modified => $latest_date{'rfc2822'});
6091 } else {
6092 print $cgi->header(
6093 -type => $content_type,
6094 -charset => 'utf-8');
6097 # Optimization: skip generating the body if client asks only
6098 # for Last-Modified date.
6099 return if ($cgi->request_method() eq 'HEAD');
6101 # header variables
6102 my $title = "$site_name - $project/$action";
6103 my $feed_type = 'log';
6104 if (defined $hash) {
6105 $title .= " - '$hash'";
6106 $feed_type = 'branch log';
6107 if (defined $file_name) {
6108 $title .= " :: $file_name";
6109 $feed_type = 'history';
6111 } elsif (defined $file_name) {
6112 $title .= " - $file_name";
6113 $feed_type = 'history';
6115 $title .= " $feed_type";
6116 my $descr = git_get_project_description($project);
6117 if (defined $descr) {
6118 $descr = esc_html($descr);
6119 } else {
6120 $descr = "$project " .
6121 ($format eq 'rss' ? 'RSS' : 'Atom') .
6122 " feed";
6124 my $owner = git_get_project_owner($project);
6125 $owner = esc_html($owner);
6127 #header
6128 my $alt_url;
6129 if (defined $file_name) {
6130 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6131 } elsif (defined $hash) {
6132 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6133 } else {
6134 $alt_url = href(-full=>1, action=>"summary");
6136 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6137 if ($format eq 'rss') {
6138 print <<XML;
6139 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6140 <channel>
6142 print "<title>$title</title>\n" .
6143 "<link>$alt_url</link>\n" .
6144 "<description>$descr</description>\n" .
6145 "<language>en</language>\n" .
6146 # project owner is responsible for 'editorial' content
6147 "<managingEditor>$owner</managingEditor>\n";
6148 if (defined $logo || defined $favicon) {
6149 # prefer the logo to the favicon, since RSS
6150 # doesn't allow both
6151 my $img = esc_url($logo || $favicon);
6152 print "<image>\n" .
6153 "<url>$img</url>\n" .
6154 "<title>$title</title>\n" .
6155 "<link>$alt_url</link>\n" .
6156 "</image>\n";
6158 if (%latest_date) {
6159 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6160 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6162 print "<generator>gitweb v.$version/$git_version</generator>\n";
6163 } elsif ($format eq 'atom') {
6164 print <<XML;
6165 <feed xmlns="http://www.w3.org/2005/Atom">
6167 print "<title>$title</title>\n" .
6168 "<subtitle>$descr</subtitle>\n" .
6169 '<link rel="alternate" type="text/html" href="' .
6170 $alt_url . '" />' . "\n" .
6171 '<link rel="self" type="' . $content_type . '" href="' .
6172 $cgi->self_url() . '" />' . "\n" .
6173 "<id>" . href(-full=>1) . "</id>\n" .
6174 # use project owner for feed author
6175 "<author><name>$owner</name></author>\n";
6176 if (defined $favicon) {
6177 print "<icon>" . esc_url($favicon) . "</icon>\n";
6179 if (defined $logo_url) {
6180 # not twice as wide as tall: 72 x 27 pixels
6181 print "<logo>" . esc_url($logo) . "</logo>\n";
6183 if (! %latest_date) {
6184 # dummy date to keep the feed valid until commits trickle in:
6185 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6186 } else {
6187 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6189 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6192 # contents
6193 for (my $i = 0; $i <= $#commitlist; $i++) {
6194 my %co = %{$commitlist[$i]};
6195 my $commit = $co{'id'};
6196 # we read 150, we always show 30 and the ones more recent than 48 hours
6197 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6198 last;
6200 my %cd = parse_date($co{'author_epoch'});
6202 # get list of changed files
6203 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6204 $co{'parent'} || "--root",
6205 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6206 or next;
6207 my @difftree = map { chomp; $_ } <$fd>;
6208 close $fd
6209 or next;
6211 # print element (entry, item)
6212 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6213 if ($format eq 'rss') {
6214 print "<item>\n" .
6215 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6216 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6217 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6218 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6219 "<link>$co_url</link>\n" .
6220 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6221 "<content:encoded>" .
6222 "<![CDATA[\n";
6223 } elsif ($format eq 'atom') {
6224 print "<entry>\n" .
6225 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6226 "<updated>$cd{'iso-8601'}</updated>\n" .
6227 "<author>\n" .
6228 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6229 if ($co{'author_email'}) {
6230 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6232 print "</author>\n" .
6233 # use committer for contributor
6234 "<contributor>\n" .
6235 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6236 if ($co{'committer_email'}) {
6237 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6239 print "</contributor>\n" .
6240 "<published>$cd{'iso-8601'}</published>\n" .
6241 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6242 "<id>$co_url</id>\n" .
6243 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6244 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6246 my $comment = $co{'comment'};
6247 print "<pre>\n";
6248 foreach my $line (@$comment) {
6249 $line = esc_html($line);
6250 print "$line\n";
6252 print "</pre><ul>\n";
6253 foreach my $difftree_line (@difftree) {
6254 my %difftree = parse_difftree_raw_line($difftree_line);
6255 next if !$difftree{'from_id'};
6257 my $file = $difftree{'file'} || $difftree{'to_file'};
6259 print "<li>" .
6260 "[" .
6261 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6262 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6263 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6264 file_name=>$file, file_parent=>$difftree{'from_file'}),
6265 -title => "diff"}, 'D');
6266 if ($have_blame) {
6267 print $cgi->a({-href => href(-full=>1, action=>"blame",
6268 file_name=>$file, hash_base=>$commit),
6269 -title => "blame"}, 'B');
6271 # if this is not a feed of a file history
6272 if (!defined $file_name || $file_name ne $file) {
6273 print $cgi->a({-href => href(-full=>1, action=>"history",
6274 file_name=>$file, hash=>$commit),
6275 -title => "history"}, 'H');
6277 $file = esc_path($file);
6278 print "] ".
6279 "$file</li>\n";
6281 if ($format eq 'rss') {
6282 print "</ul>]]>\n" .
6283 "</content:encoded>\n" .
6284 "</item>\n";
6285 } elsif ($format eq 'atom') {
6286 print "</ul>\n</div>\n" .
6287 "</content>\n" .
6288 "</entry>\n";
6292 # end of feed
6293 if ($format eq 'rss') {
6294 print "</channel>\n</rss>\n";
6295 } elsif ($format eq 'atom') {
6296 print "</feed>\n";
6300 sub git_rss {
6301 git_feed('rss');
6304 sub git_atom {
6305 git_feed('atom');
6308 sub git_opml {
6309 my @list = git_get_projects_list();
6311 print $cgi->header(
6312 -type => 'text/xml',
6313 -charset => 'utf-8',
6314 -content_disposition => 'inline; filename="opml.xml"');
6316 print <<XML;
6317 <?xml version="1.0" encoding="utf-8"?>
6318 <opml version="1.0">
6319 <head>
6320 <title>$site_name OPML Export</title>
6321 </head>
6322 <body>
6323 <outline text="git RSS feeds">
6326 foreach my $pr (@list) {
6327 my %proj = %$pr;
6328 my $head = git_get_head_hash($proj{'path'});
6329 if (!defined $head) {
6330 next;
6332 $git_dir = "$projectroot/$proj{'path'}";
6333 my %co = parse_commit($head);
6334 if (!%co) {
6335 next;
6338 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6339 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6340 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6341 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6343 print <<XML;
6344 </outline>
6345 </body>
6346 </opml>