Merge commit 'refs/top-bases/t/email/obfuscate' into t/email/obfuscate
[git/repo.git] / gitweb / gitweb.perl
blobe69eb54945075121d7e93a03c96e295c4ad99e6b
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 # if we're called with PATH_INFO, we have to strip that
31 # from the URL to find our real URL
32 if (my $path_info = $ENV{"PATH_INFO"}) {
33 $my_url =~ s,\Q$path_info\E$,,;
34 $my_uri =~ s,\Q$path_info\E$,,;
37 # core git executable to use
38 # this can just be "git" if your webserver has a sensible PATH
39 our $GIT = "++GIT_BINDIR++/git";
41 # absolute fs-path which will be prepended to the project path
42 #our $projectroot = "/pub/scm";
43 our $projectroot = "++GITWEB_PROJECTROOT++";
45 # fs traversing limit for getting project list
46 # the number is relative to the projectroot
47 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
49 # target of the home link on top of all pages
50 our $home_link = $my_uri || "/";
52 # string of the home link on top of all pages
53 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
55 # name of your site or organization to appear in page titles
56 # replace this with something more descriptive for clearer bookmarks
57 our $site_name = "++GITWEB_SITENAME++"
58 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
60 # filename of html text to include at top of each page
61 our $site_header = "++GITWEB_SITE_HEADER++";
62 # html text to include at home page
63 our $home_text = "++GITWEB_HOMETEXT++";
64 # filename of html text to include at bottom of each page
65 our $site_footer = "++GITWEB_SITE_FOOTER++";
67 # URI of stylesheets
68 our @stylesheets = ("++GITWEB_CSS++");
69 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
70 our $stylesheet = undef;
71 # URI of GIT logo (72x27 size)
72 our $logo = "++GITWEB_LOGO++";
73 # URI of GIT favicon, assumed to be image/png type
74 our $favicon = "++GITWEB_FAVICON++";
76 # URI and label (title) of GIT logo link
77 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
78 #our $logo_label = "git documentation";
79 our $logo_url = "http://git.or.cz/";
80 our $logo_label = "git homepage";
82 # source of projects list
83 our $projects_list = "++GITWEB_LIST++";
85 # the width (in characters) of the projects list "Description" column
86 our $projects_list_description_width = 25;
88 # default order of projects list
89 # valid values are none, project, descr, owner, and age
90 our $default_projects_order = "project";
92 # show repository only if this file exists
93 # (only effective if this variable evaluates to true)
94 our $export_ok = "++GITWEB_EXPORT_OK++";
96 # only allow viewing of repositories also shown on the overview page
97 our $strict_export = "++GITWEB_STRICT_EXPORT++";
99 # list of git base URLs used for URL to where fetch project from,
100 # i.e. full URL is "$git_base_url/$project"
101 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
103 # default blob_plain mimetype and default charset for text/plain blob
104 our $default_blob_plain_mimetype = 'text/plain';
105 our $default_text_plain_charset = undef;
107 # file to use for guessing MIME types before trying /etc/mime.types
108 # (relative to the current git repository)
109 our $mimetypes_file = undef;
111 # assume this charset if line contains non-UTF-8 characters;
112 # it should be valid encoding (see Encoding::Supported(3pm) for list),
113 # for which encoding all byte sequences are valid, for example
114 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
115 # could be even 'utf-8' for the old behavior)
116 our $fallback_encoding = 'latin1';
118 # rename detection options for git-diff and git-diff-tree
119 # - default is '-M', with the cost proportional to
120 # (number of removed files) * (number of new files).
121 # - more costly is '-C' (which implies '-M'), with the cost proportional to
122 # (number of changed files + number of removed files) * (number of new files)
123 # - even more costly is '-C', '--find-copies-harder' with cost
124 # (number of files in the original tree) * (number of new files)
125 # - one might want to include '-B' option, e.g. '-B', '-M'
126 our @diff_opts = ('-M'); # taken from git_commit
128 # information about snapshot formats that gitweb is capable of serving
129 our %known_snapshot_formats = (
130 # name => {
131 # 'display' => display name,
132 # 'type' => mime type,
133 # 'suffix' => filename suffix,
134 # 'format' => --format for git-archive,
135 # 'compressor' => [compressor command and arguments]
136 # (array reference, optional)}
138 'tgz' => {
139 'display' => 'tar.gz',
140 'type' => 'application/x-gzip',
141 'suffix' => '.tar.gz',
142 'format' => 'tar',
143 'compressor' => ['gzip']},
145 'tbz2' => {
146 'display' => 'tar.bz2',
147 'type' => 'application/x-bzip2',
148 'suffix' => '.tar.bz2',
149 'format' => 'tar',
150 'compressor' => ['bzip2']},
152 'zip' => {
153 'display' => 'zip',
154 'type' => 'application/x-zip',
155 'suffix' => '.zip',
156 'format' => 'zip'},
159 # Aliases so we understand old gitweb.snapshot values in repository
160 # configuration.
161 our %known_snapshot_format_aliases = (
162 'gzip' => 'tgz',
163 'bzip2' => 'tbz2',
165 # backward compatibility: legacy gitweb config support
166 'x-gzip' => undef, 'gz' => undef,
167 'x-bzip2' => undef, 'bz2' => undef,
168 'x-zip' => undef, '' => undef,
171 # You define site-wide feature defaults here; override them with
172 # $GITWEB_CONFIG as necessary.
173 our %feature = (
174 # feature => {
175 # 'sub' => feature-sub (subroutine),
176 # 'override' => allow-override (boolean),
177 # 'default' => [ default options...] (array reference)}
179 # if feature is overridable (it means that allow-override has true value),
180 # then feature-sub will be called with default options as parameters;
181 # return value of feature-sub indicates if to enable specified feature
183 # if there is no 'sub' key (no feature-sub), then feature cannot be
184 # overriden
186 # use gitweb_check_feature(<feature>) to check if <feature> is enabled
188 # Enable the 'blame' blob view, showing the last commit that modified
189 # each line in the file. This can be very CPU-intensive.
191 # To enable system wide have in $GITWEB_CONFIG
192 # $feature{'blame'}{'default'} = [1];
193 # To have project specific config enable override in $GITWEB_CONFIG
194 # $feature{'blame'}{'override'} = 1;
195 # and in project config gitweb.blame = 0|1;
196 'blame' => {
197 'sub' => \&feature_blame,
198 'override' => 0,
199 'default' => [0]},
201 # Enable the 'snapshot' link, providing a compressed archive of any
202 # tree. This can potentially generate high traffic if you have large
203 # project.
205 # Value is a list of formats defined in %known_snapshot_formats that
206 # you wish to offer.
207 # To disable system wide have in $GITWEB_CONFIG
208 # $feature{'snapshot'}{'default'} = [];
209 # To have project specific config enable override in $GITWEB_CONFIG
210 # $feature{'snapshot'}{'override'} = 1;
211 # and in project config, a comma-separated list of formats or "none"
212 # to disable. Example: gitweb.snapshot = tbz2,zip;
213 'snapshot' => {
214 'sub' => \&feature_snapshot,
215 'override' => 0,
216 'default' => ['tgz']},
218 # Enable text search, which will list the commits which match author,
219 # committer or commit text to a given string. Enabled by default.
220 # Project specific override is not supported.
221 'search' => {
222 'override' => 0,
223 'default' => [1]},
225 # Enable grep search, which will list the files in currently selected
226 # tree containing the given string. Enabled by default. This can be
227 # potentially CPU-intensive, of course.
229 # To enable system wide have in $GITWEB_CONFIG
230 # $feature{'grep'}{'default'} = [1];
231 # To have project specific config enable override in $GITWEB_CONFIG
232 # $feature{'grep'}{'override'} = 1;
233 # and in project config gitweb.grep = 0|1;
234 'grep' => {
235 'override' => 0,
236 'default' => [1]},
238 # Enable the pickaxe search, which will list the commits that modified
239 # a given string in a file. This can be practical and quite faster
240 # alternative to 'blame', but still potentially CPU-intensive.
242 # To enable system wide have in $GITWEB_CONFIG
243 # $feature{'pickaxe'}{'default'} = [1];
244 # To have project specific config enable override in $GITWEB_CONFIG
245 # $feature{'pickaxe'}{'override'} = 1;
246 # and in project config gitweb.pickaxe = 0|1;
247 'pickaxe' => {
248 'sub' => \&feature_pickaxe,
249 'override' => 0,
250 'default' => [1]},
252 # Make gitweb use an alternative format of the URLs which can be
253 # more readable and natural-looking: project name is embedded
254 # directly in the path and the query string contains other
255 # auxiliary information. All gitweb installations recognize
256 # URL in either format; this configures in which formats gitweb
257 # generates links.
259 # To enable system wide have in $GITWEB_CONFIG
260 # $feature{'pathinfo'}{'default'} = [1];
261 # Project specific override is not supported.
263 # Note that you will need to change the default location of CSS,
264 # favicon, logo and possibly other files to an absolute URL. Also,
265 # if gitweb.cgi serves as your indexfile, you will need to force
266 # $my_uri to contain the script name in your $GITWEB_CONFIG.
267 'pathinfo' => {
268 'override' => 0,
269 'default' => [0]},
271 # Make gitweb consider projects in project root subdirectories
272 # to be forks of existing projects. Given project $projname.git,
273 # projects matching $projname/*.git will not be shown in the main
274 # projects list, instead a '+' mark will be added to $projname
275 # there and a 'forks' view will be enabled for the project, listing
276 # all the forks. If project list is taken from a file, forks have
277 # to be listed after the main project.
279 # To enable system wide have in $GITWEB_CONFIG
280 # $feature{'forks'}{'default'} = [1];
281 # Project specific override is not supported.
282 'forks' => {
283 'override' => 0,
284 'default' => [0]},
286 # Insert custom links to the action bar of all project pages.
287 # This enables you mainly to link to third-party scripts integrating
288 # into gitweb; e.g. git-browser for graphical history representation
289 # or custom web-based repository administration interface.
291 # The 'default' value consists of a list of triplets in the form
292 # (label, link, position) where position is the label after which
293 # to inster the link and link is a format string where %n expands
294 # to the project name, %f to the project path within the filesystem,
295 # %h to the current hash (h gitweb parameter) and %b to the current
296 # hash base (hb gitweb parameter).
298 # To enable system wide have in $GITWEB_CONFIG e.g.
299 # $feature{'actions'}{'default'} = [('graphiclog',
300 # '/git-browser/by-commit.html?r=%n', 'summary')];
301 # Project specific override is not supported.
302 'actions' => {
303 'override' => 0,
304 'default' => []},
306 # Allow gitweb scan project content tags described in ctags/
307 # of project repository, and display the popular Web 2.0-ish
308 # "tag cloud" near the project list. Note that this is something
309 # COMPLETELY different from the normal Git tags.
311 # gitweb by itself can show existing tags, but it does not handle
312 # tagging itself; you need an external application for that.
313 # For an example script, check Girocco's cgi/tagproj.cgi.
314 # You may want to install the HTML::TagCloud Perl module to get
315 # a pretty tag cloud instead of just a list of tags.
317 # To enable system wide have in $GITWEB_CONFIG
318 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
319 # Project specific override is not supported.
320 'ctags' => {
321 'override' => 0,
322 'default' => [0]},
325 # email obfuscation
326 our $email;
327 if (eval { require HTML::Email::Obfuscate; 1 }) {
328 $email = HTML::Email::Obfuscate->new(lite => 1);
331 sub gitweb_check_feature {
332 my ($name) = @_;
333 return unless exists $feature{$name};
334 my ($sub, $override, @defaults) = (
335 $feature{$name}{'sub'},
336 $feature{$name}{'override'},
337 @{$feature{$name}{'default'}});
338 if (!$override) { return @defaults; }
339 if (!defined $sub) {
340 warn "feature $name is not overrideable";
341 return @defaults;
343 return $sub->(@defaults);
346 sub feature_blame {
347 my ($val) = git_get_project_config('blame', '--bool');
349 if ($val eq 'true') {
350 return 1;
351 } elsif ($val eq 'false') {
352 return 0;
355 return $_[0];
358 sub feature_snapshot {
359 my (@fmts) = @_;
361 my ($val) = git_get_project_config('snapshot');
363 if ($val) {
364 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
367 return @fmts;
370 sub feature_grep {
371 my ($val) = git_get_project_config('grep', '--bool');
373 if ($val eq 'true') {
374 return (1);
375 } elsif ($val eq 'false') {
376 return (0);
379 return ($_[0]);
382 sub feature_pickaxe {
383 my ($val) = git_get_project_config('pickaxe', '--bool');
385 if ($val eq 'true') {
386 return (1);
387 } elsif ($val eq 'false') {
388 return (0);
391 return ($_[0]);
394 # checking HEAD file with -e is fragile if the repository was
395 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
396 # and then pruned.
397 sub check_head_link {
398 my ($dir) = @_;
399 my $headfile = "$dir/HEAD";
400 return ((-e $headfile) ||
401 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
404 sub check_export_ok {
405 my ($dir) = @_;
406 return (check_head_link($dir) &&
407 (!$export_ok || -e "$dir/$export_ok"));
410 # process alternate names for backward compatibility
411 # filter out unsupported (unknown) snapshot formats
412 sub filter_snapshot_fmts {
413 my @fmts = @_;
415 @fmts = map {
416 exists $known_snapshot_format_aliases{$_} ?
417 $known_snapshot_format_aliases{$_} : $_} @fmts;
418 @fmts = grep(exists $known_snapshot_formats{$_}, @fmts);
422 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
423 if (-e $GITWEB_CONFIG) {
424 do $GITWEB_CONFIG;
425 } else {
426 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
427 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
430 # version of the core git binary
431 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
433 $projects_list ||= $projectroot;
435 # ======================================================================
436 # input validation and dispatch
437 our $action = $cgi->param('a');
438 if (defined $action) {
439 if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
440 die_error(400, "Invalid action parameter");
444 # parameters which are pathnames
445 our $project = $cgi->param('p');
446 if (defined $project) {
447 if (!validate_pathname($project) ||
448 !(-d "$projectroot/$project") ||
449 !check_head_link("$projectroot/$project") ||
450 ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
451 ($strict_export && !project_in_list($project))) {
452 undef $project;
453 die_error(404, "No such project");
457 our $file_name = $cgi->param('f');
458 if (defined $file_name) {
459 if (!validate_pathname($file_name)) {
460 die_error(400, "Invalid file parameter");
464 our $file_parent = $cgi->param('fp');
465 if (defined $file_parent) {
466 if (!validate_pathname($file_parent)) {
467 die_error(400, "Invalid file parent parameter");
471 # parameters which are refnames
472 our $hash = $cgi->param('h');
473 if (defined $hash) {
474 if (!validate_refname($hash)) {
475 die_error(400, "Invalid hash parameter");
479 our $hash_parent = $cgi->param('hp');
480 if (defined $hash_parent) {
481 if (!validate_refname($hash_parent)) {
482 die_error(400, "Invalid hash parent parameter");
486 our $hash_base = $cgi->param('hb');
487 if (defined $hash_base) {
488 if (!validate_refname($hash_base)) {
489 die_error(400, "Invalid hash base parameter");
493 my %allowed_options = (
494 "--no-merges" => [ qw(rss atom log shortlog history) ],
497 our @extra_options = $cgi->param('opt');
498 if (defined @extra_options) {
499 foreach my $opt (@extra_options) {
500 if (not exists $allowed_options{$opt}) {
501 die_error(400, "Invalid option parameter");
503 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
504 die_error(400, "Invalid option parameter for this action");
509 our $hash_parent_base = $cgi->param('hpb');
510 if (defined $hash_parent_base) {
511 if (!validate_refname($hash_parent_base)) {
512 die_error(400, "Invalid hash parent base parameter");
516 # other parameters
517 our $page = $cgi->param('pg');
518 if (defined $page) {
519 if ($page =~ m/[^0-9]/) {
520 die_error(400, "Invalid page parameter");
524 our $searchtype = $cgi->param('st');
525 if (defined $searchtype) {
526 if ($searchtype =~ m/[^a-z]/) {
527 die_error(400, "Invalid searchtype parameter");
531 our $search_use_regexp = $cgi->param('sr');
533 our $searchtext = $cgi->param('s');
534 our $search_regexp;
535 if (defined $searchtext) {
536 if (length($searchtext) < 2) {
537 die_error(403, "At least two characters are required for search parameter");
539 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
542 # now read PATH_INFO and use it as alternative to parameters
543 sub evaluate_path_info {
544 return if defined $project;
545 my $path_info = $ENV{"PATH_INFO"};
546 return if !$path_info;
547 $path_info =~ s,^/+,,;
548 return if !$path_info;
549 # find which part of PATH_INFO is project
550 $project = $path_info;
551 $project =~ s,/+$,,;
552 while ($project && !check_head_link("$projectroot/$project")) {
553 $project =~ s,/*[^/]*$,,;
555 # validate project
556 $project = validate_pathname($project);
557 if (!$project ||
558 ($export_ok && !-e "$projectroot/$project/$export_ok") ||
559 ($strict_export && !project_in_list($project))) {
560 undef $project;
561 return;
563 # do not change any parameters if an action is given using the query string
564 return if $action;
565 $path_info =~ s,^\Q$project\E/*,,;
566 my ($refname, $pathname) = split(/:/, $path_info, 2);
567 if (defined $pathname) {
568 # we got "project.git/branch:filename" or "project.git/branch:dir/"
569 # we could use git_get_type(branch:pathname), but it needs $git_dir
570 $pathname =~ s,^/+,,;
571 if (!$pathname || substr($pathname, -1) eq "/") {
572 $action ||= "tree";
573 $pathname =~ s,/$,,;
574 } else {
575 $action ||= "blob_plain";
577 $hash_base ||= validate_refname($refname);
578 $file_name ||= validate_pathname($pathname);
579 } elsif (defined $refname) {
580 # we got "project.git/branch"
581 $action ||= "shortlog";
582 $hash ||= validate_refname($refname);
585 evaluate_path_info();
587 # path to the current git repository
588 our $git_dir;
589 $git_dir = "$projectroot/$project" if $project;
591 # dispatch
592 my %actions = (
593 "blame" => \&git_blame,
594 "blobdiff" => \&git_blobdiff,
595 "blobdiff_plain" => \&git_blobdiff_plain,
596 "blob" => \&git_blob,
597 "blob_plain" => \&git_blob_plain,
598 "commitdiff" => \&git_commitdiff,
599 "commitdiff_plain" => \&git_commitdiff_plain,
600 "commit" => \&git_commit,
601 "forks" => \&git_forks,
602 "heads" => \&git_heads,
603 "history" => \&git_history,
604 "log" => \&git_log,
605 "rss" => \&git_rss,
606 "atom" => \&git_atom,
607 "search" => \&git_search,
608 "search_help" => \&git_search_help,
609 "shortlog" => \&git_shortlog,
610 "summary" => \&git_summary,
611 "tag" => \&git_tag,
612 "tags" => \&git_tags,
613 "tree" => \&git_tree,
614 "snapshot" => \&git_snapshot,
615 "object" => \&git_object,
616 # those below don't need $project
617 "opml" => \&git_opml,
618 "project_list" => \&git_project_list,
619 "project_index" => \&git_project_index,
622 if (!defined $action) {
623 if (defined $hash) {
624 $action = git_get_type($hash);
625 } elsif (defined $hash_base && defined $file_name) {
626 $action = git_get_type("$hash_base:$file_name");
627 } elsif (defined $project) {
628 $action = 'summary';
629 } else {
630 $action = 'project_list';
633 if (!defined($actions{$action})) {
634 die_error(400, "Unknown action");
636 if ($action !~ m/^(opml|project_list|project_index)$/ &&
637 !$project) {
638 die_error(400, "Project needed");
640 $actions{$action}->();
641 exit;
643 ## ======================================================================
644 ## action links
646 sub href (%) {
647 my %params = @_;
648 # default is to use -absolute url() i.e. $my_uri
649 my $href = $params{-full} ? $my_url : $my_uri;
651 # XXX: Warning: If you touch this, check the search form for updating,
652 # too.
654 my @mapping = (
655 project => "p",
656 action => "a",
657 file_name => "f",
658 file_parent => "fp",
659 hash => "h",
660 hash_parent => "hp",
661 hash_base => "hb",
662 hash_parent_base => "hpb",
663 page => "pg",
664 order => "o",
665 searchtext => "s",
666 searchtype => "st",
667 snapshot_format => "sf",
668 extra_options => "opt",
669 search_use_regexp => "sr",
671 my %mapping = @mapping;
673 $params{'project'} = $project unless exists $params{'project'};
675 if ($params{-replay}) {
676 while (my ($name, $symbol) = each %mapping) {
677 if (!exists $params{$name}) {
678 # to allow for multivalued params we use arrayref form
679 $params{$name} = [ $cgi->param($symbol) ];
684 my ($use_pathinfo) = gitweb_check_feature('pathinfo');
685 if ($use_pathinfo) {
686 # use PATH_INFO for project name
687 $href .= "/".esc_url($params{'project'}) if defined $params{'project'};
688 delete $params{'project'};
690 # Summary just uses the project path URL
691 if (defined $params{'action'} && $params{'action'} eq 'summary') {
692 delete $params{'action'};
696 # now encode the parameters explicitly
697 my @result = ();
698 for (my $i = 0; $i < @mapping; $i += 2) {
699 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
700 if (defined $params{$name}) {
701 if (ref($params{$name}) eq "ARRAY") {
702 foreach my $par (@{$params{$name}}) {
703 push @result, $symbol . "=" . esc_param($par);
705 } else {
706 push @result, $symbol . "=" . esc_param($params{$name});
710 $href .= "?" . join(';', @result) if scalar @result;
712 return $href;
716 ## ======================================================================
717 ## validation, quoting/unquoting and escaping
719 sub validate_pathname {
720 my $input = shift || return undef;
722 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
723 # at the beginning, at the end, and between slashes.
724 # also this catches doubled slashes
725 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
726 return undef;
728 # no null characters
729 if ($input =~ m!\0!) {
730 return undef;
732 return $input;
735 sub validate_refname {
736 my $input = shift || return undef;
738 # textual hashes are O.K.
739 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
740 return $input;
742 # it must be correct pathname
743 $input = validate_pathname($input)
744 or return undef;
745 # restrictions on ref name according to git-check-ref-format
746 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
747 return undef;
749 return $input;
752 # decode sequences of octets in utf8 into Perl's internal form,
753 # which is utf-8 with utf8 flag set if needed. gitweb writes out
754 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
755 sub to_utf8 {
756 my $str = shift;
757 if (utf8::valid($str)) {
758 utf8::decode($str);
759 return $str;
760 } else {
761 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
765 # quote unsafe chars, but keep the slash, even when it's not
766 # correct, but quoted slashes look too horrible in bookmarks
767 sub esc_param {
768 my $str = shift;
769 $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
770 $str =~ s/\+/%2B/g;
771 $str =~ s/ /\+/g;
772 return $str;
775 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
776 sub esc_url {
777 my $str = shift;
778 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
779 $str =~ s/\+/%2B/g;
780 $str =~ s/ /\+/g;
781 return $str;
784 # replace invalid utf8 character with SUBSTITUTION sequence
785 sub esc_html ($;%) {
786 my $str = shift;
787 my %opts = @_;
789 $str = to_utf8($str);
790 $str = $cgi->escapeHTML($str);
791 if ($opts{'-nbsp'}) {
792 $str =~ s/ /&nbsp;/g;
794 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
795 return $str;
798 # quote control characters and escape filename to HTML
799 sub esc_path {
800 my $str = shift;
801 my %opts = @_;
803 $str = to_utf8($str);
804 $str = $cgi->escapeHTML($str);
805 if ($opts{'-nbsp'}) {
806 $str =~ s/ /&nbsp;/g;
808 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
809 return $str;
812 # Make control characters "printable", using character escape codes (CEC)
813 sub quot_cec {
814 my $cntrl = shift;
815 my %opts = @_;
816 my %es = ( # character escape codes, aka escape sequences
817 "\t" => '\t', # tab (HT)
818 "\n" => '\n', # line feed (LF)
819 "\r" => '\r', # carrige return (CR)
820 "\f" => '\f', # form feed (FF)
821 "\b" => '\b', # backspace (BS)
822 "\a" => '\a', # alarm (bell) (BEL)
823 "\e" => '\e', # escape (ESC)
824 "\013" => '\v', # vertical tab (VT)
825 "\000" => '\0', # nul character (NUL)
827 my $chr = ( (exists $es{$cntrl})
828 ? $es{$cntrl}
829 : sprintf('\%2x', ord($cntrl)) );
830 if ($opts{-nohtml}) {
831 return $chr;
832 } else {
833 return "<span class=\"cntrl\">$chr</span>";
837 # Alternatively use unicode control pictures codepoints,
838 # Unicode "printable representation" (PR)
839 sub quot_upr {
840 my $cntrl = shift;
841 my %opts = @_;
843 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
844 if ($opts{-nohtml}) {
845 return $chr;
846 } else {
847 return "<span class=\"cntrl\">$chr</span>";
851 # git may return quoted and escaped filenames
852 sub unquote {
853 my $str = shift;
855 sub unq {
856 my $seq = shift;
857 my %es = ( # character escape codes, aka escape sequences
858 't' => "\t", # tab (HT, TAB)
859 'n' => "\n", # newline (NL)
860 'r' => "\r", # return (CR)
861 'f' => "\f", # form feed (FF)
862 'b' => "\b", # backspace (BS)
863 'a' => "\a", # alarm (bell) (BEL)
864 'e' => "\e", # escape (ESC)
865 'v' => "\013", # vertical tab (VT)
868 if ($seq =~ m/^[0-7]{1,3}$/) {
869 # octal char sequence
870 return chr(oct($seq));
871 } elsif (exists $es{$seq}) {
872 # C escape sequence, aka character escape code
873 return $es{$seq};
875 # quoted ordinary character
876 return $seq;
879 if ($str =~ m/^"(.*)"$/) {
880 # needs unquoting
881 $str = $1;
882 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
884 return $str;
887 # escape tabs (convert tabs to spaces)
888 sub untabify {
889 my $line = shift;
891 while ((my $pos = index($line, "\t")) != -1) {
892 if (my $count = (8 - ($pos % 8))) {
893 my $spaces = ' ' x $count;
894 $line =~ s/\t/$spaces/;
898 return $line;
901 sub project_in_list {
902 my $project = shift;
903 my @list = git_get_projects_list();
904 return @list && scalar(grep { $_->{'path'} eq $project } @list);
907 ## ----------------------------------------------------------------------
908 ## HTML aware string manipulation
910 # Try to chop given string on a word boundary between position
911 # $len and $len+$add_len. If there is no word boundary there,
912 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
913 # (marking chopped part) would be longer than given string.
914 sub chop_str {
915 my $str = shift;
916 my $len = shift;
917 my $add_len = shift || 10;
918 my $where = shift || 'right'; # 'left' | 'center' | 'right'
920 # Make sure perl knows it is utf8 encoded so we don't
921 # cut in the middle of a utf8 multibyte char.
922 $str = to_utf8($str);
924 # allow only $len chars, but don't cut a word if it would fit in $add_len
925 # if it doesn't fit, cut it if it's still longer than the dots we would add
926 # remove chopped character entities entirely
928 # when chopping in the middle, distribute $len into left and right part
929 # return early if chopping wouldn't make string shorter
930 if ($where eq 'center') {
931 return $str if ($len + 5 >= length($str)); # filler is length 5
932 $len = int($len/2);
933 } else {
934 return $str if ($len + 4 >= length($str)); # filler is length 4
937 # regexps: ending and beginning with word part up to $add_len
938 my $endre = qr/.{$len}\w{0,$add_len}/;
939 my $begre = qr/\w{0,$add_len}.{$len}/;
941 if ($where eq 'left') {
942 $str =~ m/^(.*?)($begre)$/;
943 my ($lead, $body) = ($1, $2);
944 if (length($lead) > 4) {
945 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
946 $lead = " ...";
948 return "$lead$body";
950 } elsif ($where eq 'center') {
951 $str =~ m/^($endre)(.*)$/;
952 my ($left, $str) = ($1, $2);
953 $str =~ m/^(.*?)($begre)$/;
954 my ($mid, $right) = ($1, $2);
955 if (length($mid) > 5) {
956 $left =~ s/&[^;]*$//;
957 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
958 $mid = " ... ";
960 return "$left$mid$right";
962 } else {
963 $str =~ m/^($endre)(.*)$/;
964 my $body = $1;
965 my $tail = $2;
966 if (length($tail) > 4) {
967 $body =~ s/&[^;]*$//;
968 $tail = "... ";
970 return "$body$tail";
974 # pass-through email filter, obfuscating it when possible
975 sub email_obfuscate {
976 my ($str) = @_;
977 if ($email) {
978 $str = $email->escape_html($str);
979 # Stock HTML::Email::Obfuscate version likes to produce
980 # invalid XHTML...
981 $str =~ s#<(/?)B>#<$1b>#g;
982 return $str;
983 } else {
984 $str = esc_html($str);
985 $str =~ s/@/&#x40;/;
986 return $str;
990 # takes the same arguments as chop_str, but also wraps a <span> around the
991 # result with a title attribute if it does get chopped. Additionally, the
992 # string is HTML-escaped.
993 sub chop_and_escape_str {
994 my ($str) = @_;
996 my $chopped = chop_str(@_);
997 if ($chopped eq $str) {
998 return email_obfuscate($chopped);
999 } else {
1000 $str =~ s/([[:cntrl:]])/?/g;
1001 return $cgi->span({-title=>$str}, email_obfuscate($chopped));
1005 ## ----------------------------------------------------------------------
1006 ## functions returning short strings
1008 # CSS class for given age value (in seconds)
1009 sub age_class {
1010 my $age = shift;
1012 if (!defined $age) {
1013 return "noage";
1014 } elsif ($age < 60*60*2) {
1015 return "age0";
1016 } elsif ($age < 60*60*24*2) {
1017 return "age1";
1018 } else {
1019 return "age2";
1023 # convert age in seconds to "nn units ago" string
1024 sub age_string {
1025 my $age = shift;
1026 my $age_str;
1028 if ($age > 60*60*24*365*2) {
1029 $age_str = (int $age/60/60/24/365);
1030 $age_str .= " years ago";
1031 } elsif ($age > 60*60*24*(365/12)*2) {
1032 $age_str = int $age/60/60/24/(365/12);
1033 $age_str .= " months ago";
1034 } elsif ($age > 60*60*24*7*2) {
1035 $age_str = int $age/60/60/24/7;
1036 $age_str .= " weeks ago";
1037 } elsif ($age > 60*60*24*2) {
1038 $age_str = int $age/60/60/24;
1039 $age_str .= " days ago";
1040 } elsif ($age > 60*60*2) {
1041 $age_str = int $age/60/60;
1042 $age_str .= " hours ago";
1043 } elsif ($age > 60*2) {
1044 $age_str = int $age/60;
1045 $age_str .= " min ago";
1046 } elsif ($age > 2) {
1047 $age_str = int $age;
1048 $age_str .= " sec ago";
1049 } else {
1050 $age_str .= " right now";
1052 return $age_str;
1055 use constant {
1056 S_IFINVALID => 0030000,
1057 S_IFGITLINK => 0160000,
1060 # submodule/subproject, a commit object reference
1061 sub S_ISGITLINK($) {
1062 my $mode = shift;
1064 return (($mode & S_IFMT) == S_IFGITLINK)
1067 # convert file mode in octal to symbolic file mode string
1068 sub mode_str {
1069 my $mode = oct shift;
1071 if (S_ISGITLINK($mode)) {
1072 return 'm---------';
1073 } elsif (S_ISDIR($mode & S_IFMT)) {
1074 return 'drwxr-xr-x';
1075 } elsif (S_ISLNK($mode)) {
1076 return 'lrwxrwxrwx';
1077 } elsif (S_ISREG($mode)) {
1078 # git cares only about the executable bit
1079 if ($mode & S_IXUSR) {
1080 return '-rwxr-xr-x';
1081 } else {
1082 return '-rw-r--r--';
1084 } else {
1085 return '----------';
1089 # convert file mode in octal to file type string
1090 sub file_type {
1091 my $mode = shift;
1093 if ($mode !~ m/^[0-7]+$/) {
1094 return $mode;
1095 } else {
1096 $mode = oct $mode;
1099 if (S_ISGITLINK($mode)) {
1100 return "submodule";
1101 } elsif (S_ISDIR($mode & S_IFMT)) {
1102 return "directory";
1103 } elsif (S_ISLNK($mode)) {
1104 return "symlink";
1105 } elsif (S_ISREG($mode)) {
1106 return "file";
1107 } else {
1108 return "unknown";
1112 # convert file mode in octal to file type description string
1113 sub file_type_long {
1114 my $mode = shift;
1116 if ($mode !~ m/^[0-7]+$/) {
1117 return $mode;
1118 } else {
1119 $mode = oct $mode;
1122 if (S_ISGITLINK($mode)) {
1123 return "submodule";
1124 } elsif (S_ISDIR($mode & S_IFMT)) {
1125 return "directory";
1126 } elsif (S_ISLNK($mode)) {
1127 return "symlink";
1128 } elsif (S_ISREG($mode)) {
1129 if ($mode & S_IXUSR) {
1130 return "executable";
1131 } else {
1132 return "file";
1134 } else {
1135 return "unknown";
1140 ## ----------------------------------------------------------------------
1141 ## functions returning short HTML fragments, or transforming HTML fragments
1142 ## which don't belong to other sections
1144 # format line of commit message.
1145 sub format_log_line_html {
1146 my $line = shift;
1148 $line = esc_html($line, -nbsp=>1);
1149 if ($line =~ m/([0-9a-fA-F]{8,40})/) {
1150 my $hash_text = $1;
1151 my $link =
1152 $cgi->a({-href => href(action=>"object", hash=>$hash_text),
1153 -class => "text"}, $hash_text);
1154 $line =~ s/$hash_text/$link/;
1156 return $line;
1159 # format marker of refs pointing to given object
1161 # the destination action is chosen based on object type and current context:
1162 # - for annotated tags, we choose the tag view unless it's the current view
1163 # already, in which case we go to shortlog view
1164 # - for other refs, we keep the current view if we're in history, shortlog or
1165 # log view, and select shortlog otherwise
1166 sub format_ref_marker {
1167 my ($refs, $id) = @_;
1168 my $markers = '';
1170 if (defined $refs->{$id}) {
1171 foreach my $ref (@{$refs->{$id}}) {
1172 # this code exploits the fact that non-lightweight tags are the
1173 # only indirect objects, and that they are the only objects for which
1174 # we want to use tag instead of shortlog as action
1175 my ($type, $name) = qw();
1176 my $indirect = ($ref =~ s/\^\{\}$//);
1177 # e.g. tags/v2.6.11 or heads/next
1178 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1179 $type = $1;
1180 $name = $2;
1181 } else {
1182 $type = "ref";
1183 $name = $ref;
1186 my $class = $type;
1187 $class .= " indirect" if $indirect;
1189 my $dest_action = "shortlog";
1191 if ($indirect) {
1192 $dest_action = "tag" unless $action eq "tag";
1193 } elsif ($action =~ /^(history|(short)?log)$/) {
1194 $dest_action = $action;
1197 my $dest = "";
1198 $dest .= "refs/" unless $ref =~ m!^refs/!;
1199 $dest .= $ref;
1201 my $link = $cgi->a({
1202 -href => href(
1203 action=>$dest_action,
1204 hash=>$dest
1205 )}, $name);
1207 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1208 $link . "</span>";
1212 if ($markers) {
1213 return ' <span class="refs">'. $markers . '</span>';
1214 } else {
1215 return "";
1219 # format, perhaps shortened and with markers, title line
1220 sub format_subject_html {
1221 my ($long, $short, $href, $extra) = @_;
1222 $extra = '' unless defined($extra);
1224 if (length($short) < length($long)) {
1225 return $cgi->a({-href => $href, -class => "list subject",
1226 -title => to_utf8($long)},
1227 esc_html($short) . $extra);
1228 } else {
1229 return $cgi->a({-href => $href, -class => "list subject"},
1230 esc_html($long) . $extra);
1234 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1235 sub format_git_diff_header_line {
1236 my $line = shift;
1237 my $diffinfo = shift;
1238 my ($from, $to) = @_;
1240 if ($diffinfo->{'nparents'}) {
1241 # combined diff
1242 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1243 if ($to->{'href'}) {
1244 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1245 esc_path($to->{'file'}));
1246 } else { # file was deleted (no href)
1247 $line .= esc_path($to->{'file'});
1249 } else {
1250 # "ordinary" diff
1251 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1252 if ($from->{'href'}) {
1253 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1254 'a/' . esc_path($from->{'file'}));
1255 } else { # file was added (no href)
1256 $line .= 'a/' . esc_path($from->{'file'});
1258 $line .= ' ';
1259 if ($to->{'href'}) {
1260 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1261 'b/' . esc_path($to->{'file'}));
1262 } else { # file was deleted
1263 $line .= 'b/' . esc_path($to->{'file'});
1267 return "<div class=\"diff header\">$line</div>\n";
1270 # format extended diff header line, before patch itself
1271 sub format_extended_diff_header_line {
1272 my $line = shift;
1273 my $diffinfo = shift;
1274 my ($from, $to) = @_;
1276 # match <path>
1277 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1278 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1279 esc_path($from->{'file'}));
1281 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1282 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1283 esc_path($to->{'file'}));
1285 # match single <mode>
1286 if ($line =~ m/\s(\d{6})$/) {
1287 $line .= '<span class="info"> (' .
1288 file_type_long($1) .
1289 ')</span>';
1291 # match <hash>
1292 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1293 # can match only for combined diff
1294 $line = 'index ';
1295 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1296 if ($from->{'href'}[$i]) {
1297 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1298 -class=>"hash"},
1299 substr($diffinfo->{'from_id'}[$i],0,7));
1300 } else {
1301 $line .= '0' x 7;
1303 # separator
1304 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1306 $line .= '..';
1307 if ($to->{'href'}) {
1308 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1309 substr($diffinfo->{'to_id'},0,7));
1310 } else {
1311 $line .= '0' x 7;
1314 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1315 # can match only for ordinary diff
1316 my ($from_link, $to_link);
1317 if ($from->{'href'}) {
1318 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1319 substr($diffinfo->{'from_id'},0,7));
1320 } else {
1321 $from_link = '0' x 7;
1323 if ($to->{'href'}) {
1324 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1325 substr($diffinfo->{'to_id'},0,7));
1326 } else {
1327 $to_link = '0' x 7;
1329 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1330 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1333 return $line . "<br/>\n";
1336 # format from-file/to-file diff header
1337 sub format_diff_from_to_header {
1338 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1339 my $line;
1340 my $result = '';
1342 $line = $from_line;
1343 #assert($line =~ m/^---/) if DEBUG;
1344 # no extra formatting for "^--- /dev/null"
1345 if (! $diffinfo->{'nparents'}) {
1346 # ordinary (single parent) diff
1347 if ($line =~ m!^--- "?a/!) {
1348 if ($from->{'href'}) {
1349 $line = '--- a/' .
1350 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1351 esc_path($from->{'file'}));
1352 } else {
1353 $line = '--- a/' .
1354 esc_path($from->{'file'});
1357 $result .= qq!<div class="diff from_file">$line</div>\n!;
1359 } else {
1360 # combined diff (merge commit)
1361 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1362 if ($from->{'href'}[$i]) {
1363 $line = '--- ' .
1364 $cgi->a({-href=>href(action=>"blobdiff",
1365 hash_parent=>$diffinfo->{'from_id'}[$i],
1366 hash_parent_base=>$parents[$i],
1367 file_parent=>$from->{'file'}[$i],
1368 hash=>$diffinfo->{'to_id'},
1369 hash_base=>$hash,
1370 file_name=>$to->{'file'}),
1371 -class=>"path",
1372 -title=>"diff" . ($i+1)},
1373 $i+1) .
1374 '/' .
1375 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1376 esc_path($from->{'file'}[$i]));
1377 } else {
1378 $line = '--- /dev/null';
1380 $result .= qq!<div class="diff from_file">$line</div>\n!;
1384 $line = $to_line;
1385 #assert($line =~ m/^\+\+\+/) if DEBUG;
1386 # no extra formatting for "^+++ /dev/null"
1387 if ($line =~ m!^\+\+\+ "?b/!) {
1388 if ($to->{'href'}) {
1389 $line = '+++ b/' .
1390 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1391 esc_path($to->{'file'}));
1392 } else {
1393 $line = '+++ b/' .
1394 esc_path($to->{'file'});
1397 $result .= qq!<div class="diff to_file">$line</div>\n!;
1399 return $result;
1402 # create note for patch simplified by combined diff
1403 sub format_diff_cc_simplified {
1404 my ($diffinfo, @parents) = @_;
1405 my $result = '';
1407 $result .= "<div class=\"diff header\">" .
1408 "diff --cc ";
1409 if (!is_deleted($diffinfo)) {
1410 $result .= $cgi->a({-href => href(action=>"blob",
1411 hash_base=>$hash,
1412 hash=>$diffinfo->{'to_id'},
1413 file_name=>$diffinfo->{'to_file'}),
1414 -class => "path"},
1415 esc_path($diffinfo->{'to_file'}));
1416 } else {
1417 $result .= esc_path($diffinfo->{'to_file'});
1419 $result .= "</div>\n" . # class="diff header"
1420 "<div class=\"diff nodifferences\">" .
1421 "Simple merge" .
1422 "</div>\n"; # class="diff nodifferences"
1424 return $result;
1427 # format patch (diff) line (not to be used for diff headers)
1428 sub format_diff_line {
1429 my $line = shift;
1430 my ($from, $to) = @_;
1431 my $diff_class = "";
1433 chomp $line;
1435 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1436 # combined diff
1437 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1438 if ($line =~ m/^\@{3}/) {
1439 $diff_class = " chunk_header";
1440 } elsif ($line =~ m/^\\/) {
1441 $diff_class = " incomplete";
1442 } elsif ($prefix =~ tr/+/+/) {
1443 $diff_class = " add";
1444 } elsif ($prefix =~ tr/-/-/) {
1445 $diff_class = " rem";
1447 } else {
1448 # assume ordinary diff
1449 my $char = substr($line, 0, 1);
1450 if ($char eq '+') {
1451 $diff_class = " add";
1452 } elsif ($char eq '-') {
1453 $diff_class = " rem";
1454 } elsif ($char eq '@') {
1455 $diff_class = " chunk_header";
1456 } elsif ($char eq "\\") {
1457 $diff_class = " incomplete";
1460 $line = untabify($line);
1461 if ($from && $to && $line =~ m/^\@{2} /) {
1462 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1463 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1465 $from_lines = 0 unless defined $from_lines;
1466 $to_lines = 0 unless defined $to_lines;
1468 if ($from->{'href'}) {
1469 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1470 -class=>"list"}, $from_text);
1472 if ($to->{'href'}) {
1473 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1474 -class=>"list"}, $to_text);
1476 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1477 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1478 return "<div class=\"diff$diff_class\">$line</div>\n";
1479 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1480 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1481 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1483 @from_text = split(' ', $ranges);
1484 for (my $i = 0; $i < @from_text; ++$i) {
1485 ($from_start[$i], $from_nlines[$i]) =
1486 (split(',', substr($from_text[$i], 1)), 0);
1489 $to_text = pop @from_text;
1490 $to_start = pop @from_start;
1491 $to_nlines = pop @from_nlines;
1493 $line = "<span class=\"chunk_info\">$prefix ";
1494 for (my $i = 0; $i < @from_text; ++$i) {
1495 if ($from->{'href'}[$i]) {
1496 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1497 -class=>"list"}, $from_text[$i]);
1498 } else {
1499 $line .= $from_text[$i];
1501 $line .= " ";
1503 if ($to->{'href'}) {
1504 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1505 -class=>"list"}, $to_text);
1506 } else {
1507 $line .= $to_text;
1509 $line .= " $prefix</span>" .
1510 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1511 return "<div class=\"diff$diff_class\">$line</div>\n";
1513 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1516 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1517 # linked. Pass the hash of the tree/commit to snapshot.
1518 sub format_snapshot_links {
1519 my ($hash) = @_;
1520 my @snapshot_fmts = gitweb_check_feature('snapshot');
1521 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1522 my $num_fmts = @snapshot_fmts;
1523 if ($num_fmts > 1) {
1524 # A parenthesized list of links bearing format names.
1525 # e.g. "snapshot (_tar.gz_ _zip_)"
1526 return "snapshot (" . join(' ', map
1527 $cgi->a({
1528 -href => href(
1529 action=>"snapshot",
1530 hash=>$hash,
1531 snapshot_format=>$_
1533 }, $known_snapshot_formats{$_}{'display'})
1534 , @snapshot_fmts) . ")";
1535 } elsif ($num_fmts == 1) {
1536 # A single "snapshot" link whose tooltip bears the format name.
1537 # i.e. "_snapshot_"
1538 my ($fmt) = @snapshot_fmts;
1539 return
1540 $cgi->a({
1541 -href => href(
1542 action=>"snapshot",
1543 hash=>$hash,
1544 snapshot_format=>$fmt
1546 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1547 }, "snapshot");
1548 } else { # $num_fmts == 0
1549 return undef;
1553 ## ......................................................................
1554 ## functions returning values to be passed, perhaps after some
1555 ## transformation, to other functions; e.g. returning arguments to href()
1557 # returns hash to be passed to href to generate gitweb URL
1558 # in -title key it returns description of link
1559 sub get_feed_info {
1560 my $format = shift || 'Atom';
1561 my %res = (action => lc($format));
1563 # feed links are possible only for project views
1564 return unless (defined $project);
1565 # some views should link to OPML, or to generic project feed,
1566 # or don't have specific feed yet (so they should use generic)
1567 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1569 my $branch;
1570 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1571 # from tag links; this also makes possible to detect branch links
1572 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1573 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1574 $branch = $1;
1576 # find log type for feed description (title)
1577 my $type = 'log';
1578 if (defined $file_name) {
1579 $type = "history of $file_name";
1580 $type .= "/" if ($action eq 'tree');
1581 $type .= " on '$branch'" if (defined $branch);
1582 } else {
1583 $type = "log of $branch" if (defined $branch);
1586 $res{-title} = $type;
1587 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
1588 $res{'file_name'} = $file_name;
1590 return %res;
1593 ## ----------------------------------------------------------------------
1594 ## git utility subroutines, invoking git commands
1596 # returns path to the core git executable and the --git-dir parameter as list
1597 sub git_cmd {
1598 return $GIT, '--git-dir='.$git_dir;
1601 # quote the given arguments for passing them to the shell
1602 # quote_command("command", "arg 1", "arg with ' and ! characters")
1603 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
1604 # Try to avoid using this function wherever possible.
1605 sub quote_command {
1606 return join(' ',
1607 map( { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ ));
1610 # get HEAD ref of given project as hash
1611 sub git_get_head_hash {
1612 my $project = shift;
1613 my $o_git_dir = $git_dir;
1614 my $retval = undef;
1615 $git_dir = "$projectroot/$project";
1616 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1617 my $head = <$fd>;
1618 close $fd;
1619 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1620 $retval = $1;
1623 if (defined $o_git_dir) {
1624 $git_dir = $o_git_dir;
1626 return $retval;
1629 # get type of given object
1630 sub git_get_type {
1631 my $hash = shift;
1633 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1634 my $type = <$fd>;
1635 close $fd or return;
1636 chomp $type;
1637 return $type;
1640 # repository configuration
1641 our $config_file = '';
1642 our %config;
1644 # store multiple values for single key as anonymous array reference
1645 # single values stored directly in the hash, not as [ <value> ]
1646 sub hash_set_multi {
1647 my ($hash, $key, $value) = @_;
1649 if (!exists $hash->{$key}) {
1650 $hash->{$key} = $value;
1651 } elsif (!ref $hash->{$key}) {
1652 $hash->{$key} = [ $hash->{$key}, $value ];
1653 } else {
1654 push @{$hash->{$key}}, $value;
1658 # return hash of git project configuration
1659 # optionally limited to some section, e.g. 'gitweb'
1660 sub git_parse_project_config {
1661 my $section_regexp = shift;
1662 my %config;
1664 local $/ = "\0";
1666 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
1667 or return;
1669 while (my $keyval = <$fh>) {
1670 chomp $keyval;
1671 my ($key, $value) = split(/\n/, $keyval, 2);
1673 hash_set_multi(\%config, $key, $value)
1674 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
1676 close $fh;
1678 return %config;
1681 # convert config value to boolean, 'true' or 'false'
1682 # no value, number > 0, 'true' and 'yes' values are true
1683 # rest of values are treated as false (never as error)
1684 sub config_to_bool {
1685 my $val = shift;
1687 # strip leading and trailing whitespace
1688 $val =~ s/^\s+//;
1689 $val =~ s/\s+$//;
1691 return (!defined $val || # section.key
1692 ($val =~ /^\d+$/ && $val) || # section.key = 1
1693 ($val =~ /^(?:true|yes)$/i)); # section.key = true
1696 # convert config value to simple decimal number
1697 # an optional value suffix of 'k', 'm', or 'g' will cause the value
1698 # to be multiplied by 1024, 1048576, or 1073741824
1699 sub config_to_int {
1700 my $val = shift;
1702 # strip leading and trailing whitespace
1703 $val =~ s/^\s+//;
1704 $val =~ s/\s+$//;
1706 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
1707 $unit = lc($unit);
1708 # unknown unit is treated as 1
1709 return $num * ($unit eq 'g' ? 1073741824 :
1710 $unit eq 'm' ? 1048576 :
1711 $unit eq 'k' ? 1024 : 1);
1713 return $val;
1716 # convert config value to array reference, if needed
1717 sub config_to_multi {
1718 my $val = shift;
1720 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
1723 sub git_get_project_config {
1724 my ($key, $type) = @_;
1726 # key sanity check
1727 return unless ($key);
1728 $key =~ s/^gitweb\.//;
1729 return if ($key =~ m/\W/);
1731 # type sanity check
1732 if (defined $type) {
1733 $type =~ s/^--//;
1734 $type = undef
1735 unless ($type eq 'bool' || $type eq 'int');
1738 # get config
1739 if (!defined $config_file ||
1740 $config_file ne "$git_dir/config") {
1741 %config = git_parse_project_config('gitweb');
1742 $config_file = "$git_dir/config";
1745 # ensure given type
1746 if (!defined $type) {
1747 return $config{"gitweb.$key"};
1748 } elsif ($type eq 'bool') {
1749 # backward compatibility: 'git config --bool' returns true/false
1750 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
1751 } elsif ($type eq 'int') {
1752 return config_to_int($config{"gitweb.$key"});
1754 return $config{"gitweb.$key"};
1757 # get hash of given path at given ref
1758 sub git_get_hash_by_path {
1759 my $base = shift;
1760 my $path = shift || return undef;
1761 my $type = shift;
1763 $path =~ s,/+$,,;
1765 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1766 or die_error(500, "Open git-ls-tree failed");
1767 my $line = <$fd>;
1768 close $fd or return undef;
1770 if (!defined $line) {
1771 # there is no tree or hash given by $path at $base
1772 return undef;
1775 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
1776 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1777 if (defined $type && $type ne $2) {
1778 # type doesn't match
1779 return undef;
1781 return $3;
1784 # get path of entry with given hash at given tree-ish (ref)
1785 # used to get 'from' filename for combined diff (merge commit) for renames
1786 sub git_get_path_by_hash {
1787 my $base = shift || return;
1788 my $hash = shift || return;
1790 local $/ = "\0";
1792 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1793 or return undef;
1794 while (my $line = <$fd>) {
1795 chomp $line;
1797 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
1798 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
1799 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1800 close $fd;
1801 return $1;
1804 close $fd;
1805 return undef;
1808 ## ......................................................................
1809 ## git utility functions, directly accessing git repository
1811 sub git_get_project_description {
1812 my $path = shift;
1814 $git_dir = "$projectroot/$path";
1815 open my $fd, "$git_dir/description"
1816 or return git_get_project_config('description');
1817 my $descr = <$fd>;
1818 close $fd;
1819 if (defined $descr) {
1820 chomp $descr;
1822 return $descr;
1825 sub git_get_project_ctags {
1826 my $path = shift;
1827 my $ctags = {};
1829 $git_dir = "$projectroot/$path";
1830 foreach (<$git_dir/ctags/*>) {
1831 open CT, $_ or next;
1832 my $val = <CT>;
1833 chomp $val;
1834 close CT;
1835 my $ctag = $_; $ctag =~ s#.*/##;
1836 $ctags->{$ctag} = $val;
1838 $ctags;
1841 sub git_populate_project_tagcloud {
1842 my $ctags = shift;
1844 # First, merge different-cased tags; tags vote on casing
1845 my %ctags_lc;
1846 foreach (keys %$ctags) {
1847 $ctags_lc{lc $_}->{count} += $ctags->{$_};
1848 if (not $ctags_lc{lc $_}->{topcount}
1849 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
1850 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
1851 $ctags_lc{lc $_}->{topname} = $_;
1855 my $cloud;
1856 if (eval { require HTML::TagCloud; 1; }) {
1857 $cloud = HTML::TagCloud->new;
1858 foreach (sort keys %ctags_lc) {
1859 # Pad the title with spaces so that the cloud looks
1860 # less crammed.
1861 my $title = $ctags_lc{$_}->{topname};
1862 $title =~ s/ /&nbsp;/g;
1863 $title =~ s/^/&nbsp;/g;
1864 $title =~ s/$/&nbsp;/g;
1865 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
1867 } else {
1868 $cloud = \%ctags_lc;
1870 $cloud;
1873 sub git_show_project_tagcloud {
1874 my ($cloud, $count) = @_;
1875 print STDERR ref($cloud)."..\n";
1876 if (ref $cloud eq 'HTML::TagCloud') {
1877 return $cloud->html_and_css($count);
1878 } else {
1879 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
1880 return '<p align="center">' . join (', ', map {
1881 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
1882 } splice(@tags, 0, $count)) . '</p>';
1886 sub git_get_project_url_list {
1887 my $path = shift;
1889 $git_dir = "$projectroot/$path";
1890 open my $fd, "$git_dir/cloneurl"
1891 or return wantarray ?
1892 @{ config_to_multi(git_get_project_config('url')) } :
1893 config_to_multi(git_get_project_config('url'));
1894 my @git_project_url_list = map { chomp; $_ } <$fd>;
1895 close $fd;
1897 return wantarray ? @git_project_url_list : \@git_project_url_list;
1900 sub git_get_projects_list {
1901 my ($filter) = @_;
1902 my @list;
1904 $filter ||= '';
1905 $filter =~ s/\.git$//;
1907 my ($check_forks) = gitweb_check_feature('forks');
1909 if (-d $projects_list) {
1910 # search in directory
1911 my $dir = $projects_list . ($filter ? "/$filter" : '');
1912 # remove the trailing "/"
1913 $dir =~ s!/+$!!;
1914 my $pfxlen = length("$dir");
1915 my $pfxdepth = ($dir =~ tr!/!!);
1917 File::Find::find({
1918 follow_fast => 1, # follow symbolic links
1919 follow_skip => 2, # ignore duplicates
1920 dangling_symlinks => 0, # ignore dangling symlinks, silently
1921 wanted => sub {
1922 # skip project-list toplevel, if we get it.
1923 return if (m!^[/.]$!);
1924 # only directories can be git repositories
1925 return unless (-d $_);
1926 # don't traverse too deep (Find is super slow on os x)
1927 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
1928 $File::Find::prune = 1;
1929 return;
1932 my $subdir = substr($File::Find::name, $pfxlen + 1);
1933 # we check related file in $projectroot
1934 if (check_export_ok("$projectroot/$filter/$subdir")) {
1935 push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1936 $File::Find::prune = 1;
1939 }, "$dir");
1941 } elsif (-f $projects_list) {
1942 # read from file(url-encoded):
1943 # 'git%2Fgit.git Linus+Torvalds'
1944 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1945 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1946 my %paths;
1947 open my ($fd), $projects_list or return;
1948 PROJECT:
1949 while (my $line = <$fd>) {
1950 chomp $line;
1951 my ($path, $owner) = split ' ', $line;
1952 $path = unescape($path);
1953 $owner = unescape($owner);
1954 if (!defined $path) {
1955 next;
1957 if ($filter ne '') {
1958 # looking for forks;
1959 my $pfx = substr($path, 0, length($filter));
1960 if ($pfx ne $filter) {
1961 next PROJECT;
1963 my $sfx = substr($path, length($filter));
1964 if ($sfx !~ /^\/.*\.git$/) {
1965 next PROJECT;
1967 } elsif ($check_forks) {
1968 PATH:
1969 foreach my $filter (keys %paths) {
1970 # looking for forks;
1971 my $pfx = substr($path, 0, length($filter));
1972 if ($pfx ne $filter) {
1973 next PATH;
1975 my $sfx = substr($path, length($filter));
1976 if ($sfx !~ /^\/.*\.git$/) {
1977 next PATH;
1979 # is a fork, don't include it in
1980 # the list
1981 next PROJECT;
1984 if (check_export_ok("$projectroot/$path")) {
1985 my $pr = {
1986 path => $path,
1987 owner => to_utf8($owner),
1989 push @list, $pr;
1990 (my $forks_path = $path) =~ s/\.git$//;
1991 $paths{$forks_path}++;
1994 close $fd;
1996 return @list;
1999 our $gitweb_project_owner = undef;
2000 sub git_get_project_list_from_file {
2002 return if (defined $gitweb_project_owner);
2004 $gitweb_project_owner = {};
2005 # read from file (url-encoded):
2006 # 'git%2Fgit.git Linus+Torvalds'
2007 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2008 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2009 if (-f $projects_list) {
2010 open (my $fd , $projects_list);
2011 while (my $line = <$fd>) {
2012 chomp $line;
2013 my ($pr, $ow) = split ' ', $line;
2014 $pr = unescape($pr);
2015 $ow = unescape($ow);
2016 $gitweb_project_owner->{$pr} = to_utf8($ow);
2018 close $fd;
2022 sub git_get_project_owner {
2023 my $project = shift;
2024 my $owner;
2026 return undef unless $project;
2027 $git_dir = "$projectroot/$project";
2029 if (!defined $gitweb_project_owner) {
2030 git_get_project_list_from_file();
2033 if (exists $gitweb_project_owner->{$project}) {
2034 $owner = $gitweb_project_owner->{$project};
2036 if (!defined $owner){
2037 $owner = git_get_project_config('owner');
2039 if (!defined $owner) {
2040 $owner = get_file_owner("$git_dir");
2043 return $owner;
2046 sub git_get_last_activity {
2047 my ($path) = @_;
2048 my $fd;
2050 $git_dir = "$projectroot/$path";
2051 open($fd, "-|", git_cmd(), 'for-each-ref',
2052 '--format=%(committer)',
2053 '--sort=-committerdate',
2054 '--count=1',
2055 'refs/heads') or return;
2056 my $most_recent = <$fd>;
2057 close $fd or return;
2058 if (defined $most_recent &&
2059 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2060 my $timestamp = $1;
2061 my $age = time - $timestamp;
2062 return ($age, age_string($age));
2064 return (undef, undef);
2067 sub git_get_references {
2068 my $type = shift || "";
2069 my %refs;
2070 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2071 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2072 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2073 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2074 or return;
2076 while (my $line = <$fd>) {
2077 chomp $line;
2078 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2079 if (defined $refs{$1}) {
2080 push @{$refs{$1}}, $2;
2081 } else {
2082 $refs{$1} = [ $2 ];
2086 close $fd or return;
2087 return \%refs;
2090 sub git_get_rev_name_tags {
2091 my $hash = shift || return undef;
2093 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2094 or return;
2095 my $name_rev = <$fd>;
2096 close $fd;
2098 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2099 return $1;
2100 } else {
2101 # catches also '$hash undefined' output
2102 return undef;
2106 ## ----------------------------------------------------------------------
2107 ## parse to hash functions
2109 sub parse_date {
2110 my $epoch = shift;
2111 my $tz = shift || "-0000";
2113 my %date;
2114 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2115 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2116 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2117 $date{'hour'} = $hour;
2118 $date{'minute'} = $min;
2119 $date{'mday'} = $mday;
2120 $date{'day'} = $days[$wday];
2121 $date{'month'} = $months[$mon];
2122 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2123 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2124 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2125 $mday, $months[$mon], $hour ,$min;
2126 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2127 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2129 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2130 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2131 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2132 $date{'hour_local'} = $hour;
2133 $date{'minute_local'} = $min;
2134 $date{'tz_local'} = $tz;
2135 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2136 1900+$year, $mon+1, $mday,
2137 $hour, $min, $sec, $tz);
2138 return %date;
2141 sub parse_tag {
2142 my $tag_id = shift;
2143 my %tag;
2144 my @comment;
2146 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2147 $tag{'id'} = $tag_id;
2148 while (my $line = <$fd>) {
2149 chomp $line;
2150 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2151 $tag{'object'} = $1;
2152 } elsif ($line =~ m/^type (.+)$/) {
2153 $tag{'type'} = $1;
2154 } elsif ($line =~ m/^tag (.+)$/) {
2155 $tag{'name'} = $1;
2156 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2157 $tag{'author'} = $1;
2158 $tag{'epoch'} = $2;
2159 $tag{'tz'} = $3;
2160 } elsif ($line =~ m/--BEGIN/) {
2161 push @comment, $line;
2162 last;
2163 } elsif ($line eq "") {
2164 last;
2167 push @comment, <$fd>;
2168 $tag{'comment'} = \@comment;
2169 close $fd or return;
2170 if (!defined $tag{'name'}) {
2171 return
2173 return %tag
2176 sub parse_commit_text {
2177 my ($commit_text, $withparents) = @_;
2178 my @commit_lines = split '\n', $commit_text;
2179 my %co;
2181 pop @commit_lines; # Remove '\0'
2183 if (! @commit_lines) {
2184 return;
2187 my $header = shift @commit_lines;
2188 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2189 return;
2191 ($co{'id'}, my @parents) = split ' ', $header;
2192 while (my $line = shift @commit_lines) {
2193 last if $line eq "\n";
2194 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2195 $co{'tree'} = $1;
2196 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2197 push @parents, $1;
2198 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2199 $co{'author'} = $1;
2200 $co{'author_epoch'} = $2;
2201 $co{'author_tz'} = $3;
2202 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2203 $co{'author_name'} = $1;
2204 $co{'author_email'} = $2;
2205 } else {
2206 $co{'author_name'} = $co{'author'};
2208 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2209 $co{'committer'} = $1;
2210 $co{'committer_epoch'} = $2;
2211 $co{'committer_tz'} = $3;
2212 $co{'committer_name'} = $co{'committer'};
2213 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2214 $co{'committer_name'} = $1;
2215 $co{'committer_email'} = $2;
2216 } else {
2217 $co{'committer_name'} = $co{'committer'};
2221 if (!defined $co{'tree'}) {
2222 return;
2224 $co{'parents'} = \@parents;
2225 $co{'parent'} = $parents[0];
2227 foreach my $title (@commit_lines) {
2228 $title =~ s/^ //;
2229 if ($title ne "") {
2230 $co{'title'} = chop_str($title, 80, 5);
2231 # remove leading stuff of merges to make the interesting part visible
2232 if (length($title) > 50) {
2233 $title =~ s/^Automatic //;
2234 $title =~ s/^merge (of|with) /Merge ... /i;
2235 if (length($title) > 50) {
2236 $title =~ s/(http|rsync):\/\///;
2238 if (length($title) > 50) {
2239 $title =~ s/(master|www|rsync)\.//;
2241 if (length($title) > 50) {
2242 $title =~ s/kernel.org:?//;
2244 if (length($title) > 50) {
2245 $title =~ s/\/pub\/scm//;
2248 $co{'title_short'} = chop_str($title, 50, 5);
2249 last;
2252 if (! defined $co{'title'} || $co{'title'} eq "") {
2253 $co{'title'} = $co{'title_short'} = '(no commit message)';
2255 # remove added spaces
2256 foreach my $line (@commit_lines) {
2257 $line =~ s/^ //;
2259 $co{'comment'} = \@commit_lines;
2261 my $age = time - $co{'committer_epoch'};
2262 $co{'age'} = $age;
2263 $co{'age_string'} = age_string($age);
2264 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2265 if ($age > 60*60*24*7*2) {
2266 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2267 $co{'age_string_age'} = $co{'age_string'};
2268 } else {
2269 $co{'age_string_date'} = $co{'age_string'};
2270 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2272 return %co;
2275 sub parse_commit {
2276 my ($commit_id) = @_;
2277 my %co;
2279 local $/ = "\0";
2281 open my $fd, "-|", git_cmd(), "rev-list",
2282 "--parents",
2283 "--header",
2284 "--max-count=1",
2285 $commit_id,
2286 "--",
2287 or die_error(500, "Open git-rev-list failed");
2288 %co = parse_commit_text(<$fd>, 1);
2289 close $fd;
2291 return %co;
2294 sub parse_commits {
2295 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2296 my @cos;
2298 $maxcount ||= 1;
2299 $skip ||= 0;
2301 local $/ = "\0";
2303 open my $fd, "-|", git_cmd(), "rev-list",
2304 "--header",
2305 @args,
2306 ("--max-count=" . $maxcount),
2307 ("--skip=" . $skip),
2308 @extra_options,
2309 $commit_id,
2310 "--",
2311 ($filename ? ($filename) : ())
2312 or die_error(500, "Open git-rev-list failed");
2313 while (my $line = <$fd>) {
2314 my %co = parse_commit_text($line);
2315 push @cos, \%co;
2317 close $fd;
2319 return wantarray ? @cos : \@cos;
2322 # parse line of git-diff-tree "raw" output
2323 sub parse_difftree_raw_line {
2324 my $line = shift;
2325 my %res;
2327 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2328 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2329 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2330 $res{'from_mode'} = $1;
2331 $res{'to_mode'} = $2;
2332 $res{'from_id'} = $3;
2333 $res{'to_id'} = $4;
2334 $res{'status'} = $5;
2335 $res{'similarity'} = $6;
2336 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2337 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2338 } else {
2339 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2342 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2343 # combined diff (for merge commit)
2344 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2345 $res{'nparents'} = length($1);
2346 $res{'from_mode'} = [ split(' ', $2) ];
2347 $res{'to_mode'} = pop @{$res{'from_mode'}};
2348 $res{'from_id'} = [ split(' ', $3) ];
2349 $res{'to_id'} = pop @{$res{'from_id'}};
2350 $res{'status'} = [ split('', $4) ];
2351 $res{'to_file'} = unquote($5);
2353 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2354 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2355 $res{'commit'} = $1;
2358 return wantarray ? %res : \%res;
2361 # wrapper: return parsed line of git-diff-tree "raw" output
2362 # (the argument might be raw line, or parsed info)
2363 sub parsed_difftree_line {
2364 my $line_or_ref = shift;
2366 if (ref($line_or_ref) eq "HASH") {
2367 # pre-parsed (or generated by hand)
2368 return $line_or_ref;
2369 } else {
2370 return parse_difftree_raw_line($line_or_ref);
2374 # parse line of git-ls-tree output
2375 sub parse_ls_tree_line ($;%) {
2376 my $line = shift;
2377 my %opts = @_;
2378 my %res;
2380 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2381 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2383 $res{'mode'} = $1;
2384 $res{'type'} = $2;
2385 $res{'hash'} = $3;
2386 if ($opts{'-z'}) {
2387 $res{'name'} = $4;
2388 } else {
2389 $res{'name'} = unquote($4);
2392 return wantarray ? %res : \%res;
2395 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2396 sub parse_from_to_diffinfo {
2397 my ($diffinfo, $from, $to, @parents) = @_;
2399 if ($diffinfo->{'nparents'}) {
2400 # combined diff
2401 $from->{'file'} = [];
2402 $from->{'href'} = [];
2403 fill_from_file_info($diffinfo, @parents)
2404 unless exists $diffinfo->{'from_file'};
2405 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2406 $from->{'file'}[$i] =
2407 defined $diffinfo->{'from_file'}[$i] ?
2408 $diffinfo->{'from_file'}[$i] :
2409 $diffinfo->{'to_file'};
2410 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2411 $from->{'href'}[$i] = href(action=>"blob",
2412 hash_base=>$parents[$i],
2413 hash=>$diffinfo->{'from_id'}[$i],
2414 file_name=>$from->{'file'}[$i]);
2415 } else {
2416 $from->{'href'}[$i] = undef;
2419 } else {
2420 # ordinary (not combined) diff
2421 $from->{'file'} = $diffinfo->{'from_file'};
2422 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2423 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2424 hash=>$diffinfo->{'from_id'},
2425 file_name=>$from->{'file'});
2426 } else {
2427 delete $from->{'href'};
2431 $to->{'file'} = $diffinfo->{'to_file'};
2432 if (!is_deleted($diffinfo)) { # file exists in result
2433 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2434 hash=>$diffinfo->{'to_id'},
2435 file_name=>$to->{'file'});
2436 } else {
2437 delete $to->{'href'};
2441 ## ......................................................................
2442 ## parse to array of hashes functions
2444 sub git_get_heads_list {
2445 my $limit = shift;
2446 my @headslist;
2448 open my $fd, '-|', git_cmd(), 'for-each-ref',
2449 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2450 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2451 'refs/heads'
2452 or return;
2453 while (my $line = <$fd>) {
2454 my %ref_item;
2456 chomp $line;
2457 my ($refinfo, $committerinfo) = split(/\0/, $line);
2458 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2459 my ($committer, $epoch, $tz) =
2460 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2461 $ref_item{'fullname'} = $name;
2462 $name =~ s!^refs/heads/!!;
2464 $ref_item{'name'} = $name;
2465 $ref_item{'id'} = $hash;
2466 $ref_item{'title'} = $title || '(no commit message)';
2467 $ref_item{'epoch'} = $epoch;
2468 if ($epoch) {
2469 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2470 } else {
2471 $ref_item{'age'} = "unknown";
2474 push @headslist, \%ref_item;
2476 close $fd;
2478 return wantarray ? @headslist : \@headslist;
2481 sub git_get_tags_list {
2482 my $limit = shift;
2483 my @tagslist;
2485 open my $fd, '-|', git_cmd(), 'for-each-ref',
2486 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2487 '--format=%(objectname) %(objecttype) %(refname) '.
2488 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2489 'refs/tags'
2490 or return;
2491 while (my $line = <$fd>) {
2492 my %ref_item;
2494 chomp $line;
2495 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2496 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2497 my ($creator, $epoch, $tz) =
2498 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2499 $ref_item{'fullname'} = $name;
2500 $name =~ s!^refs/tags/!!;
2502 $ref_item{'type'} = $type;
2503 $ref_item{'id'} = $id;
2504 $ref_item{'name'} = $name;
2505 if ($type eq "tag") {
2506 $ref_item{'subject'} = $title;
2507 $ref_item{'reftype'} = $reftype;
2508 $ref_item{'refid'} = $refid;
2509 } else {
2510 $ref_item{'reftype'} = $type;
2511 $ref_item{'refid'} = $id;
2514 if ($type eq "tag" || $type eq "commit") {
2515 $ref_item{'epoch'} = $epoch;
2516 if ($epoch) {
2517 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2518 } else {
2519 $ref_item{'age'} = "unknown";
2523 push @tagslist, \%ref_item;
2525 close $fd;
2527 return wantarray ? @tagslist : \@tagslist;
2530 ## ----------------------------------------------------------------------
2531 ## filesystem-related functions
2533 sub get_file_owner {
2534 my $path = shift;
2536 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2537 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2538 if (!defined $gcos) {
2539 return undef;
2541 my $owner = $gcos;
2542 $owner =~ s/[,;].*$//;
2543 return to_utf8($owner);
2546 ## ......................................................................
2547 ## mimetype related functions
2549 sub mimetype_guess_file {
2550 my $filename = shift;
2551 my $mimemap = shift;
2552 -r $mimemap or return undef;
2554 my %mimemap;
2555 open(MIME, $mimemap) or return undef;
2556 while (<MIME>) {
2557 next if m/^#/; # skip comments
2558 my ($mime, $exts) = split(/\t+/);
2559 if (defined $exts) {
2560 my @exts = split(/\s+/, $exts);
2561 foreach my $ext (@exts) {
2562 $mimemap{$ext} = $mime;
2566 close(MIME);
2568 $filename =~ /\.([^.]*)$/;
2569 return $mimemap{$1};
2572 sub mimetype_guess {
2573 my $filename = shift;
2574 my $mime;
2575 $filename =~ /\./ or return undef;
2577 if ($mimetypes_file) {
2578 my $file = $mimetypes_file;
2579 if ($file !~ m!^/!) { # if it is relative path
2580 # it is relative to project
2581 $file = "$projectroot/$project/$file";
2583 $mime = mimetype_guess_file($filename, $file);
2585 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2586 return $mime;
2589 sub blob_mimetype {
2590 my $fd = shift;
2591 my $filename = shift;
2593 if ($filename) {
2594 my $mime = mimetype_guess($filename);
2595 $mime and return $mime;
2598 # just in case
2599 return $default_blob_plain_mimetype unless $fd;
2601 if (-T $fd) {
2602 return 'text/plain';
2603 } elsif (! $filename) {
2604 return 'application/octet-stream';
2605 } elsif ($filename =~ m/\.png$/i) {
2606 return 'image/png';
2607 } elsif ($filename =~ m/\.gif$/i) {
2608 return 'image/gif';
2609 } elsif ($filename =~ m/\.jpe?g$/i) {
2610 return 'image/jpeg';
2611 } else {
2612 return 'application/octet-stream';
2616 sub blob_contenttype {
2617 my ($fd, $file_name, $type) = @_;
2619 $type ||= blob_mimetype($fd, $file_name);
2620 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
2621 $type .= "; charset=$default_text_plain_charset";
2624 return $type;
2627 ## ======================================================================
2628 ## functions printing HTML: header, footer, error page
2630 sub git_header_html {
2631 my $status = shift || "200 OK";
2632 my $expires = shift;
2634 my $title = "$site_name";
2635 if (defined $project) {
2636 $title .= " - " . to_utf8($project);
2637 if (defined $action) {
2638 $title .= "/$action";
2639 if (defined $file_name) {
2640 $title .= " - " . esc_path($file_name);
2641 if ($action eq "tree" && $file_name !~ m|/$|) {
2642 $title .= "/";
2647 my $content_type;
2648 # require explicit support from the UA if we are to send the page as
2649 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2650 # we have to do this because MSIE sometimes globs '*/*', pretending to
2651 # support xhtml+xml but choking when it gets what it asked for.
2652 if (defined $cgi->http('HTTP_ACCEPT') &&
2653 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2654 $cgi->Accept('application/xhtml+xml') != 0) {
2655 $content_type = 'application/xhtml+xml';
2656 } else {
2657 $content_type = 'text/html';
2659 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2660 -status=> $status, -expires => $expires);
2661 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2662 print <<EOF;
2663 <?xml version="1.0" encoding="utf-8"?>
2664 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2665 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2666 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2667 <!-- git core binaries version $git_version -->
2668 <head>
2669 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2670 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2671 <meta name="robots" content="index, nofollow"/>
2672 <title>$title</title>
2674 # print out each stylesheet that exist
2675 if (defined $stylesheet) {
2676 #provides backwards capability for those people who define style sheet in a config file
2677 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2678 } else {
2679 foreach my $stylesheet (@stylesheets) {
2680 next unless $stylesheet;
2681 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2684 if (defined $project) {
2685 my %href_params = get_feed_info();
2686 if (!exists $href_params{'-title'}) {
2687 $href_params{'-title'} = 'log';
2690 foreach my $format qw(RSS Atom) {
2691 my $type = lc($format);
2692 my %link_attr = (
2693 '-rel' => 'alternate',
2694 '-title' => "$project - $href_params{'-title'} - $format feed",
2695 '-type' => "application/$type+xml"
2698 $href_params{'action'} = $type;
2699 $link_attr{'-href'} = href(%href_params);
2700 print "<link ".
2701 "rel=\"$link_attr{'-rel'}\" ".
2702 "title=\"$link_attr{'-title'}\" ".
2703 "href=\"$link_attr{'-href'}\" ".
2704 "type=\"$link_attr{'-type'}\" ".
2705 "/>\n";
2707 $href_params{'extra_options'} = '--no-merges';
2708 $link_attr{'-href'} = href(%href_params);
2709 $link_attr{'-title'} .= ' (no merges)';
2710 print "<link ".
2711 "rel=\"$link_attr{'-rel'}\" ".
2712 "title=\"$link_attr{'-title'}\" ".
2713 "href=\"$link_attr{'-href'}\" ".
2714 "type=\"$link_attr{'-type'}\" ".
2715 "/>\n";
2718 } else {
2719 printf('<link rel="alternate" title="%s projects list" '.
2720 'href="%s" type="text/plain; charset=utf-8" />'."\n",
2721 $site_name, href(project=>undef, action=>"project_index"));
2722 printf('<link rel="alternate" title="%s projects feeds" '.
2723 'href="%s" type="text/x-opml" />'."\n",
2724 $site_name, href(project=>undef, action=>"opml"));
2726 if (defined $favicon) {
2727 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
2730 print "</head>\n" .
2731 "<body>\n";
2733 if (-f $site_header) {
2734 open (my $fd, $site_header);
2735 print <$fd>;
2736 close $fd;
2739 print "<div class=\"page_header\">\n" .
2740 $cgi->a({-href => esc_url($logo_url),
2741 -title => $logo_label},
2742 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2743 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2744 if (defined $project) {
2745 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2746 if (defined $action) {
2747 print " / $action";
2749 print "\n";
2751 print "</div>\n";
2753 my ($have_search) = gitweb_check_feature('search');
2754 if (defined $project && $have_search) {
2755 if (!defined $searchtext) {
2756 $searchtext = "";
2758 my $search_hash;
2759 if (defined $hash_base) {
2760 $search_hash = $hash_base;
2761 } elsif (defined $hash) {
2762 $search_hash = $hash;
2763 } else {
2764 $search_hash = "HEAD";
2766 my $action = $my_uri;
2767 my ($use_pathinfo) = gitweb_check_feature('pathinfo');
2768 if ($use_pathinfo) {
2769 $action .= "/".esc_url($project);
2771 print $cgi->startform(-method => "get", -action => $action) .
2772 "<div class=\"search\">\n" .
2773 (!$use_pathinfo &&
2774 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
2775 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
2776 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
2777 $cgi->popup_menu(-name => 'st', -default => 'commit',
2778 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2779 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2780 " search:\n",
2781 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2782 "<span title=\"Extended regular expression\">" .
2783 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
2784 -checked => $search_use_regexp) .
2785 "</span>" .
2786 "</div>" .
2787 $cgi->end_form() . "\n";
2791 sub git_footer_html {
2792 my $feed_class = 'rss_logo';
2794 print "<div class=\"page_footer\">\n";
2795 if (defined $project) {
2796 my $descr = git_get_project_description($project);
2797 if (defined $descr) {
2798 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2801 my %href_params = get_feed_info();
2802 if (!%href_params) {
2803 $feed_class .= ' generic';
2805 $href_params{'-title'} ||= 'log';
2807 foreach my $format qw(RSS Atom) {
2808 $href_params{'action'} = lc($format);
2809 print $cgi->a({-href => href(%href_params),
2810 -title => "$href_params{'-title'} $format feed",
2811 -class => $feed_class}, $format)."\n";
2814 } else {
2815 print $cgi->a({-href => href(project=>undef, action=>"opml"),
2816 -class => $feed_class}, "OPML") . " ";
2817 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
2818 -class => $feed_class}, "TXT") . "\n";
2820 print "</div>\n"; # class="page_footer"
2822 if (-f $site_footer) {
2823 open (my $fd, $site_footer);
2824 print <$fd>;
2825 close $fd;
2828 print "</body>\n" .
2829 "</html>";
2832 # die_error(<http_status_code>, <error_message>)
2833 # Example: die_error(404, 'Hash not found')
2834 # By convention, use the following status codes (as defined in RFC 2616):
2835 # 400: Invalid or missing CGI parameters, or
2836 # requested object exists but has wrong type.
2837 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
2838 # this server or project.
2839 # 404: Requested object/revision/project doesn't exist.
2840 # 500: The server isn't configured properly, or
2841 # an internal error occurred (e.g. failed assertions caused by bugs), or
2842 # an unknown error occurred (e.g. the git binary died unexpectedly).
2843 sub die_error {
2844 my $status = shift || 500;
2845 my $error = shift || "Internal server error";
2847 my %http_responses = (400 => '400 Bad Request',
2848 403 => '403 Forbidden',
2849 404 => '404 Not Found',
2850 500 => '500 Internal Server Error');
2851 git_header_html($http_responses{$status});
2852 print <<EOF;
2853 <div class="page_body">
2854 <br /><br />
2855 $status - $error
2856 <br />
2857 </div>
2859 git_footer_html();
2860 exit;
2863 ## ----------------------------------------------------------------------
2864 ## functions printing or outputting HTML: navigation
2866 sub git_print_page_nav {
2867 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
2868 $extra = '' if !defined $extra; # pager or formats
2870 my @navs = qw(summary shortlog log commit commitdiff tree);
2871 if ($suppress) {
2872 @navs = grep { $_ ne $suppress } @navs;
2875 my %arg = map { $_ => {action=>$_} } @navs;
2876 if (defined $head) {
2877 for (qw(commit commitdiff)) {
2878 $arg{$_}{'hash'} = $head;
2880 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
2881 for (qw(shortlog log)) {
2882 $arg{$_}{'hash'} = $head;
2887 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2888 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2890 my @actions = gitweb_check_feature('actions');
2891 while (@actions) {
2892 my ($label, $link, $pos) = (shift(@actions), shift(@actions), shift(@actions));
2893 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
2894 # munch munch
2895 $link =~ s#%n#$project#g;
2896 $link =~ s#%f#$git_dir#g;
2897 $treehead ? $link =~ s#%h#$treehead#g : $link =~ s#%h##g;
2898 $treebase ? $link =~ s#%b#$treebase#g : $link =~ s#%b##g;
2899 $arg{$label}{'_href'} = $link;
2902 print "<div class=\"page_nav\">\n" .
2903 (join " | ",
2904 map { $_ eq $current ?
2905 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
2906 } @navs);
2907 print "<br/>\n$extra<br/>\n" .
2908 "</div>\n";
2911 sub format_paging_nav {
2912 my ($action, $hash, $head, $page, $has_next_link) = @_;
2913 my $paging_nav;
2916 if ($hash ne $head || $page) {
2917 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2918 } else {
2919 $paging_nav .= "HEAD";
2922 if ($page > 0) {
2923 $paging_nav .= " &sdot; " .
2924 $cgi->a({-href => href(-replay=>1, page=>$page-1),
2925 -accesskey => "p", -title => "Alt-p"}, "prev");
2926 } else {
2927 $paging_nav .= " &sdot; prev";
2930 if ($has_next_link) {
2931 $paging_nav .= " &sdot; " .
2932 $cgi->a({-href => href(-replay=>1, page=>$page+1),
2933 -accesskey => "n", -title => "Alt-n"}, "next");
2934 } else {
2935 $paging_nav .= " &sdot; next";
2938 return $paging_nav;
2941 ## ......................................................................
2942 ## functions printing or outputting HTML: div
2944 sub git_print_header_div {
2945 my ($action, $title, $hash, $hash_base) = @_;
2946 my %args = ();
2948 $args{'action'} = $action;
2949 $args{'hash'} = $hash if $hash;
2950 $args{'hash_base'} = $hash_base if $hash_base;
2952 print "<div class=\"header\">\n" .
2953 $cgi->a({-href => href(%args), -class => "title"},
2954 $title ? $title : $action) .
2955 "\n</div>\n";
2958 #sub git_print_authorship (\%) {
2959 sub git_print_authorship {
2960 my $co = shift;
2962 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2963 print "<div class=\"author_date\">" .
2964 esc_html($co->{'author_name'}) .
2965 " [$ad{'rfc2822'}";
2966 if ($ad{'hour_local'} < 6) {
2967 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2968 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2969 } else {
2970 printf(" (%02d:%02d %s)",
2971 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2973 print "]</div>\n";
2976 sub git_print_page_path {
2977 my $name = shift;
2978 my $type = shift;
2979 my $hb = shift;
2982 print "<div class=\"page_path\">";
2983 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2984 -title => 'tree root'}, to_utf8("[$project]"));
2985 print " / ";
2986 if (defined $name) {
2987 my @dirname = split '/', $name;
2988 my $basename = pop @dirname;
2989 my $fullname = '';
2991 foreach my $dir (@dirname) {
2992 $fullname .= ($fullname ? '/' : '') . $dir;
2993 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2994 hash_base=>$hb),
2995 -title => $fullname}, esc_path($dir));
2996 print " / ";
2998 if (defined $type && $type eq 'blob') {
2999 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3000 hash_base=>$hb),
3001 -title => $name}, esc_path($basename));
3002 } elsif (defined $type && $type eq 'tree') {
3003 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3004 hash_base=>$hb),
3005 -title => $name}, esc_path($basename));
3006 print " / ";
3007 } else {
3008 print esc_path($basename);
3011 print "<br/></div>\n";
3014 # sub git_print_log (\@;%) {
3015 sub git_print_log ($;%) {
3016 my $log = shift;
3017 my %opts = @_;
3019 if ($opts{'-remove_title'}) {
3020 # remove title, i.e. first line of log
3021 shift @$log;
3023 # remove leading empty lines
3024 while (defined $log->[0] && $log->[0] eq "") {
3025 shift @$log;
3028 # print log
3029 my $signoff = 0;
3030 my $empty = 0;
3031 foreach my $line (@$log) {
3032 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3033 $signoff = 1;
3034 $empty = 0;
3035 if (! $opts{'-remove_signoff'}) {
3036 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3037 next;
3038 } else {
3039 # remove signoff lines
3040 next;
3042 } else {
3043 $signoff = 0;
3046 # print only one empty line
3047 # do not print empty line after signoff
3048 if ($line eq "") {
3049 next if ($empty || $signoff);
3050 $empty = 1;
3051 } else {
3052 $empty = 0;
3055 print format_log_line_html($line) . "<br/>\n";
3058 if ($opts{'-final_empty_line'}) {
3059 # end with single empty line
3060 print "<br/>\n" unless $empty;
3064 # return link target (what link points to)
3065 sub git_get_link_target {
3066 my $hash = shift;
3067 my $link_target;
3069 # read link
3070 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3071 or return;
3073 local $/;
3074 $link_target = <$fd>;
3076 close $fd
3077 or return;
3079 return $link_target;
3082 # given link target, and the directory (basedir) the link is in,
3083 # return target of link relative to top directory (top tree);
3084 # return undef if it is not possible (including absolute links).
3085 sub normalize_link_target {
3086 my ($link_target, $basedir, $hash_base) = @_;
3088 # we can normalize symlink target only if $hash_base is provided
3089 return unless $hash_base;
3091 # absolute symlinks (beginning with '/') cannot be normalized
3092 return if (substr($link_target, 0, 1) eq '/');
3094 # normalize link target to path from top (root) tree (dir)
3095 my $path;
3096 if ($basedir) {
3097 $path = $basedir . '/' . $link_target;
3098 } else {
3099 # we are in top (root) tree (dir)
3100 $path = $link_target;
3103 # remove //, /./, and /../
3104 my @path_parts;
3105 foreach my $part (split('/', $path)) {
3106 # discard '.' and ''
3107 next if (!$part || $part eq '.');
3108 # handle '..'
3109 if ($part eq '..') {
3110 if (@path_parts) {
3111 pop @path_parts;
3112 } else {
3113 # link leads outside repository (outside top dir)
3114 return;
3116 } else {
3117 push @path_parts, $part;
3120 $path = join('/', @path_parts);
3122 return $path;
3125 # print tree entry (row of git_tree), but without encompassing <tr> element
3126 sub git_print_tree_entry {
3127 my ($t, $basedir, $hash_base, $have_blame) = @_;
3129 my %base_key = ();
3130 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3132 # The format of a table row is: mode list link. Where mode is
3133 # the mode of the entry, list is the name of the entry, an href,
3134 # and link is the action links of the entry.
3136 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3137 if ($t->{'type'} eq "blob") {
3138 print "<td class=\"list\">" .
3139 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3140 file_name=>"$basedir$t->{'name'}", %base_key),
3141 -class => "list"}, esc_path($t->{'name'}));
3142 if (S_ISLNK(oct $t->{'mode'})) {
3143 my $link_target = git_get_link_target($t->{'hash'});
3144 if ($link_target) {
3145 my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
3146 if (defined $norm_target) {
3147 print " -> " .
3148 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3149 file_name=>$norm_target),
3150 -title => $norm_target}, esc_path($link_target));
3151 } else {
3152 print " -> " . esc_path($link_target);
3156 print "</td>\n";
3157 print "<td class=\"link\">";
3158 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3159 file_name=>"$basedir$t->{'name'}", %base_key)},
3160 "blob");
3161 if ($have_blame) {
3162 print " | " .
3163 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3164 file_name=>"$basedir$t->{'name'}", %base_key)},
3165 "blame");
3167 if (defined $hash_base) {
3168 print " | " .
3169 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3170 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3171 "history");
3173 print " | " .
3174 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3175 file_name=>"$basedir$t->{'name'}")},
3176 "raw");
3177 print "</td>\n";
3179 } elsif ($t->{'type'} eq "tree") {
3180 print "<td class=\"list\">";
3181 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3182 file_name=>"$basedir$t->{'name'}", %base_key)},
3183 esc_path($t->{'name'}));
3184 print "</td>\n";
3185 print "<td class=\"link\">";
3186 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3187 file_name=>"$basedir$t->{'name'}", %base_key)},
3188 "tree");
3189 if (defined $hash_base) {
3190 print " | " .
3191 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3192 file_name=>"$basedir$t->{'name'}")},
3193 "history");
3195 print "</td>\n";
3196 } else {
3197 # unknown object: we can only present history for it
3198 # (this includes 'commit' object, i.e. submodule support)
3199 print "<td class=\"list\">" .
3200 esc_path($t->{'name'}) .
3201 "</td>\n";
3202 print "<td class=\"link\">";
3203 if (defined $hash_base) {
3204 print $cgi->a({-href => href(action=>"history",
3205 hash_base=>$hash_base,
3206 file_name=>"$basedir$t->{'name'}")},
3207 "history");
3209 print "</td>\n";
3213 ## ......................................................................
3214 ## functions printing large fragments of HTML
3216 # get pre-image filenames for merge (combined) diff
3217 sub fill_from_file_info {
3218 my ($diff, @parents) = @_;
3220 $diff->{'from_file'} = [ ];
3221 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3222 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3223 if ($diff->{'status'}[$i] eq 'R' ||
3224 $diff->{'status'}[$i] eq 'C') {
3225 $diff->{'from_file'}[$i] =
3226 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3230 return $diff;
3233 # is current raw difftree line of file deletion
3234 sub is_deleted {
3235 my $diffinfo = shift;
3237 return $diffinfo->{'to_id'} eq ('0' x 40);
3240 # does patch correspond to [previous] difftree raw line
3241 # $diffinfo - hashref of parsed raw diff format
3242 # $patchinfo - hashref of parsed patch diff format
3243 # (the same keys as in $diffinfo)
3244 sub is_patch_split {
3245 my ($diffinfo, $patchinfo) = @_;
3247 return defined $diffinfo && defined $patchinfo
3248 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3252 sub git_difftree_body {
3253 my ($difftree, $hash, @parents) = @_;
3254 my ($parent) = $parents[0];
3255 my ($have_blame) = gitweb_check_feature('blame');
3256 print "<div class=\"list_head\">\n";
3257 if ($#{$difftree} > 10) {
3258 print(($#{$difftree} + 1) . " files changed:\n");
3260 print "</div>\n";
3262 print "<table class=\"" .
3263 (@parents > 1 ? "combined " : "") .
3264 "diff_tree\">\n";
3266 # header only for combined diff in 'commitdiff' view
3267 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3268 if ($has_header) {
3269 # table header
3270 print "<thead><tr>\n" .
3271 "<th></th><th></th>\n"; # filename, patchN link
3272 for (my $i = 0; $i < @parents; $i++) {
3273 my $par = $parents[$i];
3274 print "<th>" .
3275 $cgi->a({-href => href(action=>"commitdiff",
3276 hash=>$hash, hash_parent=>$par),
3277 -title => 'commitdiff to parent number ' .
3278 ($i+1) . ': ' . substr($par,0,7)},
3279 $i+1) .
3280 "&nbsp;</th>\n";
3282 print "</tr></thead>\n<tbody>\n";
3285 my $alternate = 1;
3286 my $patchno = 0;
3287 foreach my $line (@{$difftree}) {
3288 my $diff = parsed_difftree_line($line);
3290 if ($alternate) {
3291 print "<tr class=\"dark\">\n";
3292 } else {
3293 print "<tr class=\"light\">\n";
3295 $alternate ^= 1;
3297 if (exists $diff->{'nparents'}) { # combined diff
3299 fill_from_file_info($diff, @parents)
3300 unless exists $diff->{'from_file'};
3302 if (!is_deleted($diff)) {
3303 # file exists in the result (child) commit
3304 print "<td>" .
3305 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3306 file_name=>$diff->{'to_file'},
3307 hash_base=>$hash),
3308 -class => "list"}, esc_path($diff->{'to_file'})) .
3309 "</td>\n";
3310 } else {
3311 print "<td>" .
3312 esc_path($diff->{'to_file'}) .
3313 "</td>\n";
3316 if ($action eq 'commitdiff') {
3317 # link to patch
3318 $patchno++;
3319 print "<td class=\"link\">" .
3320 $cgi->a({-href => "#patch$patchno"}, "patch") .
3321 " | " .
3322 "</td>\n";
3325 my $has_history = 0;
3326 my $not_deleted = 0;
3327 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3328 my $hash_parent = $parents[$i];
3329 my $from_hash = $diff->{'from_id'}[$i];
3330 my $from_path = $diff->{'from_file'}[$i];
3331 my $status = $diff->{'status'}[$i];
3333 $has_history ||= ($status ne 'A');
3334 $not_deleted ||= ($status ne 'D');
3336 if ($status eq 'A') {
3337 print "<td class=\"link\" align=\"right\"> | </td>\n";
3338 } elsif ($status eq 'D') {
3339 print "<td class=\"link\">" .
3340 $cgi->a({-href => href(action=>"blob",
3341 hash_base=>$hash,
3342 hash=>$from_hash,
3343 file_name=>$from_path)},
3344 "blob" . ($i+1)) .
3345 " | </td>\n";
3346 } else {
3347 if ($diff->{'to_id'} eq $from_hash) {
3348 print "<td class=\"link nochange\">";
3349 } else {
3350 print "<td class=\"link\">";
3352 print $cgi->a({-href => href(action=>"blobdiff",
3353 hash=>$diff->{'to_id'},
3354 hash_parent=>$from_hash,
3355 hash_base=>$hash,
3356 hash_parent_base=>$hash_parent,
3357 file_name=>$diff->{'to_file'},
3358 file_parent=>$from_path)},
3359 "diff" . ($i+1)) .
3360 " | </td>\n";
3364 print "<td class=\"link\">";
3365 if ($not_deleted) {
3366 print $cgi->a({-href => href(action=>"blob",
3367 hash=>$diff->{'to_id'},
3368 file_name=>$diff->{'to_file'},
3369 hash_base=>$hash)},
3370 "blob");
3371 print " | " if ($has_history);
3373 if ($has_history) {
3374 print $cgi->a({-href => href(action=>"history",
3375 file_name=>$diff->{'to_file'},
3376 hash_base=>$hash)},
3377 "history");
3379 print "</td>\n";
3381 print "</tr>\n";
3382 next; # instead of 'else' clause, to avoid extra indent
3384 # else ordinary diff
3386 my ($to_mode_oct, $to_mode_str, $to_file_type);
3387 my ($from_mode_oct, $from_mode_str, $from_file_type);
3388 if ($diff->{'to_mode'} ne ('0' x 6)) {
3389 $to_mode_oct = oct $diff->{'to_mode'};
3390 if (S_ISREG($to_mode_oct)) { # only for regular file
3391 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3393 $to_file_type = file_type($diff->{'to_mode'});
3395 if ($diff->{'from_mode'} ne ('0' x 6)) {
3396 $from_mode_oct = oct $diff->{'from_mode'};
3397 if (S_ISREG($to_mode_oct)) { # only for regular file
3398 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3400 $from_file_type = file_type($diff->{'from_mode'});
3403 if ($diff->{'status'} eq "A") { # created
3404 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3405 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3406 $mode_chng .= "]</span>";
3407 print "<td>";
3408 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3409 hash_base=>$hash, file_name=>$diff->{'file'}),
3410 -class => "list"}, esc_path($diff->{'file'}));
3411 print "</td>\n";
3412 print "<td>$mode_chng</td>\n";
3413 print "<td class=\"link\">";
3414 if ($action eq 'commitdiff') {
3415 # link to patch
3416 $patchno++;
3417 print $cgi->a({-href => "#patch$patchno"}, "patch");
3418 print " | ";
3420 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3421 hash_base=>$hash, file_name=>$diff->{'file'})},
3422 "blob");
3423 print "</td>\n";
3425 } elsif ($diff->{'status'} eq "D") { # deleted
3426 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3427 print "<td>";
3428 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3429 hash_base=>$parent, file_name=>$diff->{'file'}),
3430 -class => "list"}, esc_path($diff->{'file'}));
3431 print "</td>\n";
3432 print "<td>$mode_chng</td>\n";
3433 print "<td class=\"link\">";
3434 if ($action eq 'commitdiff') {
3435 # link to patch
3436 $patchno++;
3437 print $cgi->a({-href => "#patch$patchno"}, "patch");
3438 print " | ";
3440 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3441 hash_base=>$parent, file_name=>$diff->{'file'})},
3442 "blob") . " | ";
3443 if ($have_blame) {
3444 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3445 file_name=>$diff->{'file'})},
3446 "blame") . " | ";
3448 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3449 file_name=>$diff->{'file'})},
3450 "history");
3451 print "</td>\n";
3453 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3454 my $mode_chnge = "";
3455 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3456 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3457 if ($from_file_type ne $to_file_type) {
3458 $mode_chnge .= " from $from_file_type to $to_file_type";
3460 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3461 if ($from_mode_str && $to_mode_str) {
3462 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3463 } elsif ($to_mode_str) {
3464 $mode_chnge .= " mode: $to_mode_str";
3467 $mode_chnge .= "]</span>\n";
3469 print "<td>";
3470 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3471 hash_base=>$hash, file_name=>$diff->{'file'}),
3472 -class => "list"}, esc_path($diff->{'file'}));
3473 print "</td>\n";
3474 print "<td>$mode_chnge</td>\n";
3475 print "<td class=\"link\">";
3476 if ($action eq 'commitdiff') {
3477 # link to patch
3478 $patchno++;
3479 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3480 " | ";
3481 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3482 # "commit" view and modified file (not onlu mode changed)
3483 print $cgi->a({-href => href(action=>"blobdiff",
3484 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3485 hash_base=>$hash, hash_parent_base=>$parent,
3486 file_name=>$diff->{'file'})},
3487 "diff") .
3488 " | ";
3490 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3491 hash_base=>$hash, file_name=>$diff->{'file'})},
3492 "blob") . " | ";
3493 if ($have_blame) {
3494 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3495 file_name=>$diff->{'file'})},
3496 "blame") . " | ";
3498 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3499 file_name=>$diff->{'file'})},
3500 "history");
3501 print "</td>\n";
3503 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3504 my %status_name = ('R' => 'moved', 'C' => 'copied');
3505 my $nstatus = $status_name{$diff->{'status'}};
3506 my $mode_chng = "";
3507 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3508 # mode also for directories, so we cannot use $to_mode_str
3509 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3511 print "<td>" .
3512 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3513 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3514 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3515 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3516 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3517 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3518 -class => "list"}, esc_path($diff->{'from_file'})) .
3519 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3520 "<td class=\"link\">";
3521 if ($action eq 'commitdiff') {
3522 # link to patch
3523 $patchno++;
3524 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3525 " | ";
3526 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3527 # "commit" view and modified file (not only pure rename or copy)
3528 print $cgi->a({-href => href(action=>"blobdiff",
3529 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3530 hash_base=>$hash, hash_parent_base=>$parent,
3531 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3532 "diff") .
3533 " | ";
3535 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3536 hash_base=>$parent, file_name=>$diff->{'to_file'})},
3537 "blob") . " | ";
3538 if ($have_blame) {
3539 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3540 file_name=>$diff->{'to_file'})},
3541 "blame") . " | ";
3543 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3544 file_name=>$diff->{'to_file'})},
3545 "history");
3546 print "</td>\n";
3548 } # we should not encounter Unmerged (U) or Unknown (X) status
3549 print "</tr>\n";
3551 print "</tbody>" if $has_header;
3552 print "</table>\n";
3555 sub git_patchset_body {
3556 my ($fd, $difftree, $hash, @hash_parents) = @_;
3557 my ($hash_parent) = $hash_parents[0];
3559 my $is_combined = (@hash_parents > 1);
3560 my $patch_idx = 0;
3561 my $patch_number = 0;
3562 my $patch_line;
3563 my $diffinfo;
3564 my $to_name;
3565 my (%from, %to);
3567 print "<div class=\"patchset\">\n";
3569 # skip to first patch
3570 while ($patch_line = <$fd>) {
3571 chomp $patch_line;
3573 last if ($patch_line =~ m/^diff /);
3576 PATCH:
3577 while ($patch_line) {
3579 # parse "git diff" header line
3580 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
3581 # $1 is from_name, which we do not use
3582 $to_name = unquote($2);
3583 $to_name =~ s!^b/!!;
3584 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
3585 # $1 is 'cc' or 'combined', which we do not use
3586 $to_name = unquote($2);
3587 } else {
3588 $to_name = undef;
3591 # check if current patch belong to current raw line
3592 # and parse raw git-diff line if needed
3593 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
3594 # this is continuation of a split patch
3595 print "<div class=\"patch cont\">\n";
3596 } else {
3597 # advance raw git-diff output if needed
3598 $patch_idx++ if defined $diffinfo;
3600 # read and prepare patch information
3601 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3603 # compact combined diff output can have some patches skipped
3604 # find which patch (using pathname of result) we are at now;
3605 if ($is_combined) {
3606 while ($to_name ne $diffinfo->{'to_file'}) {
3607 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3608 format_diff_cc_simplified($diffinfo, @hash_parents) .
3609 "</div>\n"; # class="patch"
3611 $patch_idx++;
3612 $patch_number++;
3614 last if $patch_idx > $#$difftree;
3615 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3619 # modifies %from, %to hashes
3620 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3622 # this is first patch for raw difftree line with $patch_idx index
3623 # we index @$difftree array from 0, but number patches from 1
3624 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3627 # git diff header
3628 #assert($patch_line =~ m/^diff /) if DEBUG;
3629 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3630 $patch_number++;
3631 # print "git diff" header
3632 print format_git_diff_header_line($patch_line, $diffinfo,
3633 \%from, \%to);
3635 # print extended diff header
3636 print "<div class=\"diff extended_header\">\n";
3637 EXTENDED_HEADER:
3638 while ($patch_line = <$fd>) {
3639 chomp $patch_line;
3641 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3643 print format_extended_diff_header_line($patch_line, $diffinfo,
3644 \%from, \%to);
3646 print "</div>\n"; # class="diff extended_header"
3648 # from-file/to-file diff header
3649 if (! $patch_line) {
3650 print "</div>\n"; # class="patch"
3651 last PATCH;
3653 next PATCH if ($patch_line =~ m/^diff /);
3654 #assert($patch_line =~ m/^---/) if DEBUG;
3656 my $last_patch_line = $patch_line;
3657 $patch_line = <$fd>;
3658 chomp $patch_line;
3659 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3661 print format_diff_from_to_header($last_patch_line, $patch_line,
3662 $diffinfo, \%from, \%to,
3663 @hash_parents);
3665 # the patch itself
3666 LINE:
3667 while ($patch_line = <$fd>) {
3668 chomp $patch_line;
3670 next PATCH if ($patch_line =~ m/^diff /);
3672 print format_diff_line($patch_line, \%from, \%to);
3675 } continue {
3676 print "</div>\n"; # class="patch"
3679 # for compact combined (--cc) format, with chunk and patch simpliciaction
3680 # patchset might be empty, but there might be unprocessed raw lines
3681 for (++$patch_idx if $patch_number > 0;
3682 $patch_idx < @$difftree;
3683 ++$patch_idx) {
3684 # read and prepare patch information
3685 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3687 # generate anchor for "patch" links in difftree / whatchanged part
3688 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3689 format_diff_cc_simplified($diffinfo, @hash_parents) .
3690 "</div>\n"; # class="patch"
3692 $patch_number++;
3695 if ($patch_number == 0) {
3696 if (@hash_parents > 1) {
3697 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3698 } else {
3699 print "<div class=\"diff nodifferences\">No differences found</div>\n";
3703 print "</div>\n"; # class="patchset"
3706 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3708 # fills project list info (age, description, owner, forks) for each
3709 # project in the list, removing invalid projects from returned list
3710 # NOTE: modifies $projlist, but does not remove entries from it
3711 sub fill_project_list_info {
3712 my ($projlist, $check_forks) = @_;
3713 my @projects;
3715 my $show_ctags = gitweb_check_feature('ctags');
3716 PROJECT:
3717 foreach my $pr (@$projlist) {
3718 my (@activity) = git_get_last_activity($pr->{'path'});
3719 unless (@activity) {
3720 next PROJECT;
3722 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
3723 if (!defined $pr->{'descr'}) {
3724 my $descr = git_get_project_description($pr->{'path'}) || "";
3725 $descr = to_utf8($descr);
3726 $pr->{'descr_long'} = $descr;
3727 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
3729 if (!defined $pr->{'owner'}) {
3730 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3732 if ($check_forks) {
3733 my $pname = $pr->{'path'};
3734 if (($pname =~ s/\.git$//) &&
3735 ($pname !~ /\/$/) &&
3736 (-d "$projectroot/$pname")) {
3737 $pr->{'forks'} = "-d $projectroot/$pname";
3738 } else {
3739 $pr->{'forks'} = 0;
3742 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
3743 push @projects, $pr;
3746 return @projects;
3749 # print 'sort by' <th> element, generating 'sort by $name' replay link
3750 # if that order is not selected
3751 sub print_sort_th {
3752 my ($name, $order, $header) = @_;
3753 $header ||= ucfirst($name);
3755 if ($order eq $name) {
3756 print "<th>$header</th>\n";
3757 } else {
3758 print "<th>" .
3759 $cgi->a({-href => href(-replay=>1, order=>$name),
3760 -class => "header"}, $header) .
3761 "</th>\n";
3765 sub git_project_list_body {
3766 # actually uses global variable $project
3767 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3769 my ($check_forks) = gitweb_check_feature('forks');
3770 my @projects = fill_project_list_info($projlist, $check_forks);
3772 $order ||= $default_projects_order;
3773 $from = 0 unless defined $from;
3774 $to = $#projects if (!defined $to || $#projects < $to);
3776 my %order_info = (
3777 project => { key => 'path', type => 'str' },
3778 descr => { key => 'descr_long', type => 'str' },
3779 owner => { key => 'owner', type => 'str' },
3780 age => { key => 'age', type => 'num' }
3782 my $oi = $order_info{$order};
3783 if ($oi->{'type'} eq 'str') {
3784 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
3785 } else {
3786 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
3789 my $show_ctags = gitweb_check_feature('ctags');
3790 if ($show_ctags) {
3791 my %ctags;
3792 foreach my $p (@projects) {
3793 foreach my $ct (keys %{$p->{'ctags'}}) {
3794 $ctags{$ct} += $p->{'ctags'}->{$ct};
3797 my $cloud = git_populate_project_tagcloud(\%ctags);
3798 print git_show_project_tagcloud($cloud, 64);
3801 print "<table class=\"project_list\">\n";
3802 unless ($no_header) {
3803 print "<tr>\n";
3804 if ($check_forks) {
3805 print "<th></th>\n";
3807 print_sort_th('project', $order, 'Project');
3808 print_sort_th('descr', $order, 'Description');
3809 print_sort_th('owner', $order, 'Owner');
3810 print_sort_th('age', $order, 'Last Change');
3811 print "<th></th>\n" . # for links
3812 "</tr>\n";
3814 my $alternate = 1;
3815 my $tagfilter = $cgi->param('by_tag');
3816 for (my $i = $from; $i <= $to; $i++) {
3817 my $pr = $projects[$i];
3819 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
3820 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
3821 and not $pr->{'descr_long'} =~ /$searchtext/;
3822 # Weed out forks or non-matching entries of search
3823 if ($check_forks) {
3824 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
3825 $forkbase="^$forkbase" if $forkbase;
3826 next if not $searchtext and not $tagfilter and $show_ctags
3827 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
3830 if ($alternate) {
3831 print "<tr class=\"dark\">\n";
3832 } else {
3833 print "<tr class=\"light\">\n";
3835 $alternate ^= 1;
3836 if ($check_forks) {
3837 print "<td>";
3838 if ($pr->{'forks'}) {
3839 print "<!-- $pr->{'forks'} -->\n";
3840 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
3842 print "</td>\n";
3844 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3845 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
3846 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3847 -class => "list", -title => $pr->{'descr_long'}},
3848 esc_html($pr->{'descr'})) . "</td>\n" .
3849 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
3850 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3851 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3852 "<td class=\"link\">" .
3853 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
3854 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3855 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3856 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3857 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3858 "</td>\n" .
3859 "</tr>\n";
3861 if (defined $extra) {
3862 print "<tr>\n";
3863 if ($check_forks) {
3864 print "<td></td>\n";
3866 print "<td colspan=\"5\">$extra</td>\n" .
3867 "</tr>\n";
3869 print "</table>\n";
3872 sub git_shortlog_body {
3873 # uses global variable $project
3874 my ($commitlist, $from, $to, $refs, $extra) = @_;
3876 $from = 0 unless defined $from;
3877 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3879 print "<table class=\"shortlog\">\n";
3880 my $alternate = 1;
3881 for (my $i = $from; $i <= $to; $i++) {
3882 my %co = %{$commitlist->[$i]};
3883 my $commit = $co{'id'};
3884 my $ref = format_ref_marker($refs, $commit);
3885 if ($alternate) {
3886 print "<tr class=\"dark\">\n";
3887 } else {
3888 print "<tr class=\"light\">\n";
3890 $alternate ^= 1;
3891 my $author = chop_and_escape_str($co{'author_name'}, 10);
3892 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3893 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3894 "<td><i>" . $author . "</i></td>\n" .
3895 "<td>";
3896 print format_subject_html($co{'title'}, $co{'title_short'},
3897 href(action=>"commit", hash=>$commit), $ref);
3898 print "</td>\n" .
3899 "<td class=\"link\">" .
3900 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3901 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3902 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3903 my $snapshot_links = format_snapshot_links($commit);
3904 if (defined $snapshot_links) {
3905 print " | " . $snapshot_links;
3907 print "</td>\n" .
3908 "</tr>\n";
3910 if (defined $extra) {
3911 print "<tr>\n" .
3912 "<td colspan=\"4\">$extra</td>\n" .
3913 "</tr>\n";
3915 print "</table>\n";
3918 sub git_history_body {
3919 # Warning: assumes constant type (blob or tree) during history
3920 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3922 $from = 0 unless defined $from;
3923 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3925 print "<table class=\"history\">\n";
3926 my $alternate = 1;
3927 for (my $i = $from; $i <= $to; $i++) {
3928 my %co = %{$commitlist->[$i]};
3929 if (!%co) {
3930 next;
3932 my $commit = $co{'id'};
3934 my $ref = format_ref_marker($refs, $commit);
3936 if ($alternate) {
3937 print "<tr class=\"dark\">\n";
3938 } else {
3939 print "<tr class=\"light\">\n";
3941 $alternate ^= 1;
3942 # shortlog uses chop_str($co{'author_name'}, 10)
3943 my $author = chop_and_escape_str($co{'author_name'}, 15, 3);
3944 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3945 "<td><i>" . $author . "</i></td>\n" .
3946 "<td>";
3947 # originally git_history used chop_str($co{'title'}, 50)
3948 print format_subject_html($co{'title'}, $co{'title_short'},
3949 href(action=>"commit", hash=>$commit), $ref);
3950 print "</td>\n" .
3951 "<td class=\"link\">" .
3952 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3953 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3955 if ($ftype eq 'blob') {
3956 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3957 my $blob_parent = git_get_hash_by_path($commit, $file_name);
3958 if (defined $blob_current && defined $blob_parent &&
3959 $blob_current ne $blob_parent) {
3960 print " | " .
3961 $cgi->a({-href => href(action=>"blobdiff",
3962 hash=>$blob_current, hash_parent=>$blob_parent,
3963 hash_base=>$hash_base, hash_parent_base=>$commit,
3964 file_name=>$file_name)},
3965 "diff to current");
3968 print "</td>\n" .
3969 "</tr>\n";
3971 if (defined $extra) {
3972 print "<tr>\n" .
3973 "<td colspan=\"4\">$extra</td>\n" .
3974 "</tr>\n";
3976 print "</table>\n";
3979 sub git_tags_body {
3980 # uses global variable $project
3981 my ($taglist, $from, $to, $extra) = @_;
3982 $from = 0 unless defined $from;
3983 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3985 print "<table class=\"tags\">\n";
3986 my $alternate = 1;
3987 for (my $i = $from; $i <= $to; $i++) {
3988 my $entry = $taglist->[$i];
3989 my %tag = %$entry;
3990 my $comment = $tag{'subject'};
3991 my $comment_short;
3992 if (defined $comment) {
3993 $comment_short = chop_str($comment, 30, 5);
3995 if ($alternate) {
3996 print "<tr class=\"dark\">\n";
3997 } else {
3998 print "<tr class=\"light\">\n";
4000 $alternate ^= 1;
4001 if (defined $tag{'age'}) {
4002 print "<td><i>$tag{'age'}</i></td>\n";
4003 } else {
4004 print "<td></td>\n";
4006 print "<td>" .
4007 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4008 -class => "list name"}, esc_html($tag{'name'})) .
4009 "</td>\n" .
4010 "<td>";
4011 if (defined $comment) {
4012 print format_subject_html($comment, $comment_short,
4013 href(action=>"tag", hash=>$tag{'id'}));
4015 print "</td>\n" .
4016 "<td class=\"selflink\">";
4017 if ($tag{'type'} eq "tag") {
4018 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4019 } else {
4020 print "&nbsp;";
4022 print "</td>\n" .
4023 "<td class=\"link\">" . " | " .
4024 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4025 if ($tag{'reftype'} eq "commit") {
4026 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4027 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4028 } elsif ($tag{'reftype'} eq "blob") {
4029 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4031 print "</td>\n" .
4032 "</tr>";
4034 if (defined $extra) {
4035 print "<tr>\n" .
4036 "<td colspan=\"5\">$extra</td>\n" .
4037 "</tr>\n";
4039 print "</table>\n";
4042 sub git_heads_body {
4043 # uses global variable $project
4044 my ($headlist, $head, $from, $to, $extra) = @_;
4045 $from = 0 unless defined $from;
4046 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4048 print "<table class=\"heads\">\n";
4049 my $alternate = 1;
4050 for (my $i = $from; $i <= $to; $i++) {
4051 my $entry = $headlist->[$i];
4052 my %ref = %$entry;
4053 my $curr = $ref{'id'} eq $head;
4054 if ($alternate) {
4055 print "<tr class=\"dark\">\n";
4056 } else {
4057 print "<tr class=\"light\">\n";
4059 $alternate ^= 1;
4060 print "<td><i>$ref{'age'}</i></td>\n" .
4061 ($curr ? "<td class=\"current_head\">" : "<td>") .
4062 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4063 -class => "list name"},esc_html($ref{'name'})) .
4064 "</td>\n" .
4065 "<td class=\"link\">" .
4066 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4067 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4068 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4069 "</td>\n" .
4070 "</tr>";
4072 if (defined $extra) {
4073 print "<tr>\n" .
4074 "<td colspan=\"3\">$extra</td>\n" .
4075 "</tr>\n";
4077 print "</table>\n";
4080 sub git_search_grep_body {
4081 my ($commitlist, $from, $to, $extra) = @_;
4082 $from = 0 unless defined $from;
4083 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4085 print "<table class=\"commit_search\">\n";
4086 my $alternate = 1;
4087 for (my $i = $from; $i <= $to; $i++) {
4088 my %co = %{$commitlist->[$i]};
4089 if (!%co) {
4090 next;
4092 my $commit = $co{'id'};
4093 if ($alternate) {
4094 print "<tr class=\"dark\">\n";
4095 } else {
4096 print "<tr class=\"light\">\n";
4098 $alternate ^= 1;
4099 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
4100 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4101 "<td><i>" . $author . "</i></td>\n" .
4102 "<td>" .
4103 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4104 -class => "list subject"},
4105 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4106 my $comment = $co{'comment'};
4107 foreach my $line (@$comment) {
4108 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4109 my ($lead, $match, $trail) = ($1, $2, $3);
4110 $match = chop_str($match, 70, 5, 'center');
4111 my $contextlen = int((80 - length($match))/2);
4112 $contextlen = 30 if ($contextlen > 30);
4113 $lead = chop_str($lead, $contextlen, 10, 'left');
4114 $trail = chop_str($trail, $contextlen, 10, 'right');
4116 $lead = esc_html($lead);
4117 $match = esc_html($match);
4118 $trail = esc_html($trail);
4120 print "$lead<span class=\"match\">$match</span>$trail<br />";
4123 print "</td>\n" .
4124 "<td class=\"link\">" .
4125 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4126 " | " .
4127 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4128 " | " .
4129 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4130 print "</td>\n" .
4131 "</tr>\n";
4133 if (defined $extra) {
4134 print "<tr>\n" .
4135 "<td colspan=\"3\">$extra</td>\n" .
4136 "</tr>\n";
4138 print "</table>\n";
4141 ## ======================================================================
4142 ## ======================================================================
4143 ## actions
4145 sub git_project_list {
4146 my $order = $cgi->param('o');
4147 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4148 die_error(400, "Unknown order parameter");
4151 my @list = git_get_projects_list();
4152 if (!@list) {
4153 die_error(404, "No projects found");
4156 git_header_html();
4157 if (-f $home_text) {
4158 print "<div class=\"index_include\">\n";
4159 open (my $fd, $home_text);
4160 print <$fd>;
4161 close $fd;
4162 print "</div>\n";
4164 print $cgi->startform(-method => "get") .
4165 "<p class=\"projsearch\">Search:\n" .
4166 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4167 "</p>" .
4168 $cgi->end_form() . "\n";
4169 git_project_list_body(\@list, $order);
4170 git_footer_html();
4173 sub git_forks {
4174 my $order = $cgi->param('o');
4175 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4176 die_error(400, "Unknown order parameter");
4179 my @list = git_get_projects_list($project);
4180 if (!@list) {
4181 die_error(404, "No forks found");
4184 git_header_html();
4185 git_print_page_nav('','');
4186 git_print_header_div('summary', "$project forks");
4187 git_project_list_body(\@list, $order);
4188 git_footer_html();
4191 sub git_project_index {
4192 my @projects = git_get_projects_list($project);
4194 print $cgi->header(
4195 -type => 'text/plain',
4196 -charset => 'utf-8',
4197 -content_disposition => 'inline; filename="index.aux"');
4199 foreach my $pr (@projects) {
4200 if (!exists $pr->{'owner'}) {
4201 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4204 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4205 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4206 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4207 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4208 $path =~ s/ /\+/g;
4209 $owner =~ s/ /\+/g;
4211 print "$path $owner\n";
4215 sub git_summary {
4216 my $descr = git_get_project_description($project) || "none";
4217 my %co = parse_commit("HEAD");
4218 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4219 my $head = $co{'id'};
4221 my $owner = git_get_project_owner($project);
4223 my $refs = git_get_references();
4224 # These get_*_list functions return one more to allow us to see if
4225 # there are more ...
4226 my @taglist = git_get_tags_list(16);
4227 my @headlist = git_get_heads_list(16);
4228 my @forklist;
4229 my ($check_forks) = gitweb_check_feature('forks');
4231 if ($check_forks) {
4232 @forklist = git_get_projects_list($project);
4235 git_header_html();
4236 git_print_page_nav('summary','', $head);
4238 print "<div class=\"title\">&nbsp;</div>\n";
4239 print "<table class=\"projects_list\">\n" .
4240 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4241 "<tr id=\"metadata_owner\"><td>owner</td><td>" . email_obfuscate($owner) . "</td></tr>\n";
4242 if (defined $cd{'rfc2822'}) {
4243 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4246 # use per project git URL list in $projectroot/$project/cloneurl
4247 # or make project git URL from git base URL and project name
4248 my $url_tag = "URL";
4249 my @url_list = git_get_project_url_list($project);
4250 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4251 foreach my $git_url (@url_list) {
4252 next unless $git_url;
4253 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4254 $url_tag = "";
4257 # Tag cloud
4258 my $show_ctags = (gitweb_check_feature('ctags'))[0];
4259 if ($show_ctags) {
4260 my $ctags = git_get_project_ctags($project);
4261 my $cloud = git_populate_project_tagcloud($ctags);
4262 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4263 print "</td>\n<td>" unless %$ctags;
4264 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4265 print "</td>\n<td>" if %$ctags;
4266 print git_show_project_tagcloud($cloud, 48);
4267 print "</td></tr>";
4270 print "</table>\n";
4272 if (-s "$projectroot/$project/README.html") {
4273 if (open my $fd, "$projectroot/$project/README.html") {
4274 print "<div class=\"title\">readme</div>\n" .
4275 "<div class=\"readme\">\n";
4276 print $_ while (<$fd>);
4277 print "\n</div>\n"; # class="readme"
4278 close $fd;
4282 # we need to request one more than 16 (0..15) to check if
4283 # those 16 are all
4284 my @commitlist = $head ? parse_commits($head, 17) : ();
4285 if (@commitlist) {
4286 git_print_header_div('shortlog');
4287 git_shortlog_body(\@commitlist, 0, 15, $refs,
4288 $#commitlist <= 15 ? undef :
4289 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4292 if (@taglist) {
4293 git_print_header_div('tags');
4294 git_tags_body(\@taglist, 0, 15,
4295 $#taglist <= 15 ? undef :
4296 $cgi->a({-href => href(action=>"tags")}, "..."));
4299 if (@headlist) {
4300 git_print_header_div('heads');
4301 git_heads_body(\@headlist, $head, 0, 15,
4302 $#headlist <= 15 ? undef :
4303 $cgi->a({-href => href(action=>"heads")}, "..."));
4306 if (@forklist) {
4307 git_print_header_div('forks');
4308 git_project_list_body(\@forklist, 'age', 0, 15,
4309 $#forklist <= 15 ? undef :
4310 $cgi->a({-href => href(action=>"forks")}, "..."),
4311 'no_header');
4314 git_footer_html();
4317 sub git_tag {
4318 my $head = git_get_head_hash($project);
4319 git_header_html();
4320 git_print_page_nav('','', $head,undef,$head);
4321 my %tag = parse_tag($hash);
4323 if (! %tag) {
4324 die_error(404, "Unknown tag object");
4327 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4328 print "<div class=\"title_text\">\n" .
4329 "<table class=\"object_header\">\n" .
4330 "<tr>\n" .
4331 "<td>object</td>\n" .
4332 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4333 $tag{'object'}) . "</td>\n" .
4334 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4335 $tag{'type'}) . "</td>\n" .
4336 "</tr>\n";
4337 if (defined($tag{'author'})) {
4338 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
4339 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
4340 print "<tr><td></td><td>" . $ad{'rfc2822'} .
4341 sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
4342 "</td></tr>\n";
4344 print "</table>\n\n" .
4345 "</div>\n";
4346 print "<div class=\"page_body\">";
4347 my $comment = $tag{'comment'};
4348 foreach my $line (@$comment) {
4349 chomp $line;
4350 print esc_html($line, -nbsp=>1) . "<br/>\n";
4352 print "</div>\n";
4353 git_footer_html();
4356 sub git_blame {
4357 my $fd;
4358 my $ftype;
4360 gitweb_check_feature('blame')
4361 or die_error(403, "Blame view not allowed");
4363 die_error(400, "No file name given") unless $file_name;
4364 $hash_base ||= git_get_head_hash($project);
4365 die_error(404, "Couldn't find base commit") unless ($hash_base);
4366 my %co = parse_commit($hash_base)
4367 or die_error(404, "Commit not found");
4368 if (!defined $hash) {
4369 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4370 or die_error(404, "Error looking up file");
4372 $ftype = git_get_type($hash);
4373 if ($ftype !~ "blob") {
4374 die_error(400, "Object is not a blob");
4376 open ($fd, "-|", git_cmd(), "blame", '-p', '--',
4377 $file_name, $hash_base)
4378 or die_error(500, "Open git-blame failed");
4379 git_header_html();
4380 my $formats_nav =
4381 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4382 "blob") .
4383 " | " .
4384 $cgi->a({-href => href(action=>"history", -replay=>1)},
4385 "history") .
4386 " | " .
4387 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4388 "HEAD");
4389 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4390 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4391 git_print_page_path($file_name, $ftype, $hash_base);
4392 my @rev_color = (qw(light2 dark2));
4393 my $num_colors = scalar(@rev_color);
4394 my $current_color = 0;
4395 my $last_rev;
4396 print <<HTML;
4397 <div class="page_body">
4398 <table class="blame">
4399 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4400 HTML
4401 my %metainfo = ();
4402 while (1) {
4403 $_ = <$fd>;
4404 last unless defined $_;
4405 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4406 /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
4407 if (!exists $metainfo{$full_rev}) {
4408 $metainfo{$full_rev} = {};
4410 my $meta = $metainfo{$full_rev};
4411 while (<$fd>) {
4412 last if (s/^\t//);
4413 if (/^(\S+) (.*)$/) {
4414 $meta->{$1} = $2;
4417 my $data = $_;
4418 chomp $data;
4419 my $rev = substr($full_rev, 0, 8);
4420 my $author = $meta->{'author'};
4421 my %date = parse_date($meta->{'author-time'},
4422 $meta->{'author-tz'});
4423 my $date = $date{'iso-tz'};
4424 if ($group_size) {
4425 $current_color = ++$current_color % $num_colors;
4427 print "<tr class=\"$rev_color[$current_color]\">\n";
4428 if ($group_size) {
4429 print "<td class=\"sha1\"";
4430 print " title=\"". esc_html($author) . ", $date\"";
4431 print " rowspan=\"$group_size\"" if ($group_size > 1);
4432 print ">";
4433 print $cgi->a({-href => href(action=>"commit",
4434 hash=>$full_rev,
4435 file_name=>$file_name)},
4436 esc_html($rev));
4437 print "</td>\n";
4439 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
4440 or die_error(500, "Open git-rev-parse failed");
4441 my $parent_commit = <$dd>;
4442 close $dd;
4443 chomp($parent_commit);
4444 my $blamed = href(action => 'blame',
4445 file_name => $meta->{'filename'},
4446 hash_base => $parent_commit);
4447 print "<td class=\"linenr\">";
4448 print $cgi->a({ -href => "$blamed#l$orig_lineno",
4449 -id => "l$lineno",
4450 -class => "linenr" },
4451 esc_html($lineno));
4452 print "</td>";
4453 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4454 print "</tr>\n";
4456 print "</table>\n";
4457 print "</div>";
4458 close $fd
4459 or print "Reading blob failed\n";
4460 git_footer_html();
4463 sub git_tags {
4464 my $head = git_get_head_hash($project);
4465 git_header_html();
4466 git_print_page_nav('','', $head,undef,$head);
4467 git_print_header_div('summary', $project);
4469 my @tagslist = git_get_tags_list();
4470 if (@tagslist) {
4471 git_tags_body(\@tagslist);
4473 git_footer_html();
4476 sub git_heads {
4477 my $head = git_get_head_hash($project);
4478 git_header_html();
4479 git_print_page_nav('','', $head,undef,$head);
4480 git_print_header_div('summary', $project);
4482 my @headslist = git_get_heads_list();
4483 if (@headslist) {
4484 git_heads_body(\@headslist, $head);
4486 git_footer_html();
4489 sub git_blob_plain {
4490 my $type = shift;
4491 my $expires;
4493 if (!defined $hash) {
4494 if (defined $file_name) {
4495 my $base = $hash_base || git_get_head_hash($project);
4496 $hash = git_get_hash_by_path($base, $file_name, "blob")
4497 or die_error(404, "Cannot find file");
4498 } else {
4499 die_error(400, "No file name defined");
4501 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4502 # blobs defined by non-textual hash id's can be cached
4503 $expires = "+1d";
4506 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4507 or die_error(500, "Open git-cat-file blob '$hash' failed");
4509 # content-type (can include charset)
4510 $type = blob_contenttype($fd, $file_name, $type);
4512 # "save as" filename, even when no $file_name is given
4513 my $save_as = "$hash";
4514 if (defined $file_name) {
4515 $save_as = $file_name;
4516 } elsif ($type =~ m/^text\//) {
4517 $save_as .= '.txt';
4520 print $cgi->header(
4521 -type => $type,
4522 -expires => $expires,
4523 -content_disposition => 'inline; filename="' . $save_as . '"');
4524 undef $/;
4525 binmode STDOUT, ':raw';
4526 print <$fd>;
4527 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4528 $/ = "\n";
4529 close $fd;
4532 sub git_blob {
4533 my $expires;
4535 if (!defined $hash) {
4536 if (defined $file_name) {
4537 my $base = $hash_base || git_get_head_hash($project);
4538 $hash = git_get_hash_by_path($base, $file_name, "blob")
4539 or die_error(404, "Cannot find file");
4540 } else {
4541 die_error(400, "No file name defined");
4543 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4544 # blobs defined by non-textual hash id's can be cached
4545 $expires = "+1d";
4548 my ($have_blame) = gitweb_check_feature('blame');
4549 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4550 or die_error(500, "Couldn't cat $file_name, $hash");
4551 my $mimetype = blob_mimetype($fd, $file_name);
4552 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
4553 close $fd;
4554 return git_blob_plain($mimetype);
4556 # we can have blame only for text/* mimetype
4557 $have_blame &&= ($mimetype =~ m!^text/!);
4559 git_header_html(undef, $expires);
4560 my $formats_nav = '';
4561 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4562 if (defined $file_name) {
4563 if ($have_blame) {
4564 $formats_nav .=
4565 $cgi->a({-href => href(action=>"blame", -replay=>1)},
4566 "blame") .
4567 " | ";
4569 $formats_nav .=
4570 $cgi->a({-href => href(action=>"history", -replay=>1)},
4571 "history") .
4572 " | " .
4573 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4574 "raw") .
4575 " | " .
4576 $cgi->a({-href => href(action=>"blob",
4577 hash_base=>"HEAD", file_name=>$file_name)},
4578 "HEAD");
4579 } else {
4580 $formats_nav .=
4581 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4582 "raw");
4584 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4585 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4586 } else {
4587 print "<div class=\"page_nav\">\n" .
4588 "<br/><br/></div>\n" .
4589 "<div class=\"title\">$hash</div>\n";
4591 git_print_page_path($file_name, "blob", $hash_base);
4592 print "<div class=\"page_body\">\n";
4593 if ($mimetype =~ m!^image/!) {
4594 print qq!<img type="$mimetype"!;
4595 if ($file_name) {
4596 print qq! alt="$file_name" title="$file_name"!;
4598 print qq! src="! .
4599 href(action=>"blob_plain", hash=>$hash,
4600 hash_base=>$hash_base, file_name=>$file_name) .
4601 qq!" />\n!;
4602 } else {
4603 my $nr;
4604 while (my $line = <$fd>) {
4605 chomp $line;
4606 $nr++;
4607 $line = untabify($line);
4608 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4609 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4612 close $fd
4613 or print "Reading blob failed.\n";
4614 print "</div>";
4615 git_footer_html();
4618 sub git_tree {
4619 if (!defined $hash_base) {
4620 $hash_base = "HEAD";
4622 if (!defined $hash) {
4623 if (defined $file_name) {
4624 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4625 } else {
4626 $hash = $hash_base;
4629 die_error(404, "No such tree") unless defined($hash);
4630 $/ = "\0";
4631 open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4632 or die_error(500, "Open git-ls-tree failed");
4633 my @entries = map { chomp; $_ } <$fd>;
4634 close $fd or die_error(404, "Reading tree failed");
4635 $/ = "\n";
4637 my $refs = git_get_references();
4638 my $ref = format_ref_marker($refs, $hash_base);
4639 git_header_html();
4640 my $basedir = '';
4641 my ($have_blame) = gitweb_check_feature('blame');
4642 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4643 my @views_nav = ();
4644 if (defined $file_name) {
4645 push @views_nav,
4646 $cgi->a({-href => href(action=>"history", -replay=>1)},
4647 "history"),
4648 $cgi->a({-href => href(action=>"tree",
4649 hash_base=>"HEAD", file_name=>$file_name)},
4650 "HEAD"),
4652 my $snapshot_links = format_snapshot_links($hash);
4653 if (defined $snapshot_links) {
4654 # FIXME: Should be available when we have no hash base as well.
4655 push @views_nav, $snapshot_links;
4657 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4658 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4659 } else {
4660 undef $hash_base;
4661 print "<div class=\"page_nav\">\n";
4662 print "<br/><br/></div>\n";
4663 print "<div class=\"title\">$hash</div>\n";
4665 if (defined $file_name) {
4666 $basedir = $file_name;
4667 if ($basedir ne '' && substr($basedir, -1) ne '/') {
4668 $basedir .= '/';
4670 git_print_page_path($file_name, 'tree', $hash_base);
4672 print "<div class=\"page_body\">\n";
4673 print "<table class=\"tree\">\n";
4674 my $alternate = 1;
4675 # '..' (top directory) link if possible
4676 if (defined $hash_base &&
4677 defined $file_name && $file_name =~ m![^/]+$!) {
4678 if ($alternate) {
4679 print "<tr class=\"dark\">\n";
4680 } else {
4681 print "<tr class=\"light\">\n";
4683 $alternate ^= 1;
4685 my $up = $file_name;
4686 $up =~ s!/?[^/]+$!!;
4687 undef $up unless $up;
4688 # based on git_print_tree_entry
4689 print '<td class="mode">' . mode_str('040000') . "</td>\n";
4690 print '<td class="list">';
4691 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4692 file_name=>$up)},
4693 "..");
4694 print "</td>\n";
4695 print "<td class=\"link\"></td>\n";
4697 print "</tr>\n";
4699 foreach my $line (@entries) {
4700 my %t = parse_ls_tree_line($line, -z => 1);
4702 if ($alternate) {
4703 print "<tr class=\"dark\">\n";
4704 } else {
4705 print "<tr class=\"light\">\n";
4707 $alternate ^= 1;
4709 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4711 print "</tr>\n";
4713 print "</table>\n" .
4714 "</div>";
4715 git_footer_html();
4718 sub git_snapshot {
4719 my @supported_fmts = gitweb_check_feature('snapshot');
4720 @supported_fmts = filter_snapshot_fmts(@supported_fmts);
4722 my $format = $cgi->param('sf');
4723 if (!@supported_fmts) {
4724 die_error(403, "Snapshots not allowed");
4726 # default to first supported snapshot format
4727 $format ||= $supported_fmts[0];
4728 if ($format !~ m/^[a-z0-9]+$/) {
4729 die_error(400, "Invalid snapshot format parameter");
4730 } elsif (!exists($known_snapshot_formats{$format})) {
4731 die_error(400, "Unknown snapshot format");
4732 } elsif (!grep($_ eq $format, @supported_fmts)) {
4733 die_error(403, "Unsupported snapshot format");
4736 if (!defined $hash) {
4737 $hash = git_get_head_hash($project);
4740 my $name = $project;
4741 $name =~ s,([^/])/*\.git$,$1,;
4742 $name = basename($name);
4743 my $filename = to_utf8($name);
4744 $name =~ s/\047/\047\\\047\047/g;
4745 my $cmd;
4746 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
4747 $cmd = quote_command(
4748 git_cmd(), 'archive',
4749 "--format=$known_snapshot_formats{$format}{'format'}",
4750 "--prefix=$name/", $hash);
4751 if (exists $known_snapshot_formats{$format}{'compressor'}) {
4752 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
4755 print $cgi->header(
4756 -type => $known_snapshot_formats{$format}{'type'},
4757 -content_disposition => 'inline; filename="' . "$filename" . '"',
4758 -status => '200 OK');
4760 open my $fd, "-|", $cmd
4761 or die_error(500, "Execute git-archive failed");
4762 binmode STDOUT, ':raw';
4763 print <$fd>;
4764 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4765 close $fd;
4768 sub git_log {
4769 my $head = git_get_head_hash($project);
4770 if (!defined $hash) {
4771 $hash = $head;
4773 if (!defined $page) {
4774 $page = 0;
4776 my $refs = git_get_references();
4778 my @commitlist = parse_commits($hash, 101, (100 * $page));
4780 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
4782 git_header_html();
4783 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4785 if (!@commitlist) {
4786 my %co = parse_commit($hash);
4788 git_print_header_div('summary', $project);
4789 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4791 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4792 for (my $i = 0; $i <= $to; $i++) {
4793 my %co = %{$commitlist[$i]};
4794 next if !%co;
4795 my $commit = $co{'id'};
4796 my $ref = format_ref_marker($refs, $commit);
4797 my %ad = parse_date($co{'author_epoch'});
4798 git_print_header_div('commit',
4799 "<span class=\"age\">$co{'age_string'}</span>" .
4800 esc_html($co{'title'}) . $ref,
4801 $commit);
4802 print "<div class=\"title_text\">\n" .
4803 "<div class=\"log_link\">\n" .
4804 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4805 " | " .
4806 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4807 " | " .
4808 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4809 "<br/>\n" .
4810 "</div>\n" .
4811 "<i>" . esc_html($co{'author_name'}) . " [$ad{'rfc2822'}]</i><br/>\n" .
4812 "</div>\n";
4814 print "<div class=\"log_body\">\n";
4815 git_print_log($co{'comment'}, -final_empty_line=> 1);
4816 print "</div>\n";
4818 if ($#commitlist >= 100) {
4819 print "<div class=\"page_nav\">\n";
4820 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
4821 -accesskey => "n", -title => "Alt-n"}, "next");
4822 print "</div>\n";
4824 git_footer_html();
4827 sub git_commit {
4828 $hash ||= $hash_base || "HEAD";
4829 my %co = parse_commit($hash)
4830 or die_error(404, "Unknown commit object");
4831 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4832 my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4834 my $parent = $co{'parent'};
4835 my $parents = $co{'parents'}; # listref
4837 # we need to prepare $formats_nav before any parameter munging
4838 my $formats_nav;
4839 if (!defined $parent) {
4840 # --root commitdiff
4841 $formats_nav .= '(initial)';
4842 } elsif (@$parents == 1) {
4843 # single parent commit
4844 $formats_nav .=
4845 '(parent: ' .
4846 $cgi->a({-href => href(action=>"commit",
4847 hash=>$parent)},
4848 esc_html(substr($parent, 0, 7))) .
4849 ')';
4850 } else {
4851 # merge commit
4852 $formats_nav .=
4853 '(merge: ' .
4854 join(' ', map {
4855 $cgi->a({-href => href(action=>"commit",
4856 hash=>$_)},
4857 esc_html(substr($_, 0, 7)));
4858 } @$parents ) .
4859 ')';
4862 if (!defined $parent) {
4863 $parent = "--root";
4865 my @difftree;
4866 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4867 @diff_opts,
4868 (@$parents <= 1 ? $parent : '-c'),
4869 $hash, "--"
4870 or die_error(500, "Open git-diff-tree failed");
4871 @difftree = map { chomp; $_ } <$fd>;
4872 close $fd or die_error(404, "Reading git-diff-tree failed");
4874 # non-textual hash id's can be cached
4875 my $expires;
4876 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4877 $expires = "+1d";
4879 my $refs = git_get_references();
4880 my $ref = format_ref_marker($refs, $co{'id'});
4882 git_header_html(undef, $expires);
4883 git_print_page_nav('commit', '',
4884 $hash, $co{'tree'}, $hash,
4885 $formats_nav);
4887 if (defined $co{'parent'}) {
4888 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4889 } else {
4890 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4892 print "<div class=\"title_text\">\n" .
4893 "<table class=\"object_header\">\n";
4894 print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4895 "<tr>" .
4896 "<td></td><td> $ad{'rfc2822'}";
4897 if ($ad{'hour_local'} < 6) {
4898 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4899 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4900 } else {
4901 printf(" (%02d:%02d %s)",
4902 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4904 print "</td>" .
4905 "</tr>\n";
4906 print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4907 print "<tr><td></td><td> $cd{'rfc2822'}" .
4908 sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4909 "</td></tr>\n";
4910 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4911 print "<tr>" .
4912 "<td>tree</td>" .
4913 "<td class=\"sha1\">" .
4914 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4915 class => "list"}, $co{'tree'}) .
4916 "</td>" .
4917 "<td class=\"link\">" .
4918 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4919 "tree");
4920 my $snapshot_links = format_snapshot_links($hash);
4921 if (defined $snapshot_links) {
4922 print " | " . $snapshot_links;
4924 print "</td>" .
4925 "</tr>\n";
4927 foreach my $par (@$parents) {
4928 print "<tr>" .
4929 "<td>parent</td>" .
4930 "<td class=\"sha1\">" .
4931 $cgi->a({-href => href(action=>"commit", hash=>$par),
4932 class => "list"}, $par) .
4933 "</td>" .
4934 "<td class=\"link\">" .
4935 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
4936 " | " .
4937 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
4938 "</td>" .
4939 "</tr>\n";
4941 print "</table>".
4942 "</div>\n";
4944 print "<div class=\"page_body\">\n";
4945 git_print_log($co{'comment'});
4946 print "</div>\n";
4948 git_difftree_body(\@difftree, $hash, @$parents);
4950 git_footer_html();
4953 sub git_object {
4954 # object is defined by:
4955 # - hash or hash_base alone
4956 # - hash_base and file_name
4957 my $type;
4959 # - hash or hash_base alone
4960 if ($hash || ($hash_base && !defined $file_name)) {
4961 my $object_id = $hash || $hash_base;
4963 open my $fd, "-|", quote_command(
4964 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
4965 or die_error(404, "Object does not exist");
4966 $type = <$fd>;
4967 chomp $type;
4968 close $fd
4969 or die_error(404, "Object does not exist");
4971 # - hash_base and file_name
4972 } elsif ($hash_base && defined $file_name) {
4973 $file_name =~ s,/+$,,;
4975 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
4976 or die_error(404, "Base object does not exist");
4978 # here errors should not hapen
4979 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
4980 or die_error(500, "Open git-ls-tree failed");
4981 my $line = <$fd>;
4982 close $fd;
4984 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
4985 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
4986 die_error(404, "File or directory for given base does not exist");
4988 $type = $2;
4989 $hash = $3;
4990 } else {
4991 die_error(400, "Not enough information to find object");
4994 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
4995 hash=>$hash, hash_base=>$hash_base,
4996 file_name=>$file_name),
4997 -status => '302 Found');
5000 sub git_blobdiff {
5001 my $format = shift || 'html';
5003 my $fd;
5004 my @difftree;
5005 my %diffinfo;
5006 my $expires;
5008 # preparing $fd and %diffinfo for git_patchset_body
5009 # new style URI
5010 if (defined $hash_base && defined $hash_parent_base) {
5011 if (defined $file_name) {
5012 # read raw output
5013 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5014 $hash_parent_base, $hash_base,
5015 "--", (defined $file_parent ? $file_parent : ()), $file_name
5016 or die_error(500, "Open git-diff-tree failed");
5017 @difftree = map { chomp; $_ } <$fd>;
5018 close $fd
5019 or die_error(404, "Reading git-diff-tree failed");
5020 @difftree
5021 or die_error(404, "Blob diff not found");
5023 } elsif (defined $hash &&
5024 $hash =~ /[0-9a-fA-F]{40}/) {
5025 # try to find filename from $hash
5027 # read filtered raw output
5028 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5029 $hash_parent_base, $hash_base, "--"
5030 or die_error(500, "Open git-diff-tree failed");
5031 @difftree =
5032 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5033 # $hash == to_id
5034 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5035 map { chomp; $_ } <$fd>;
5036 close $fd
5037 or die_error(404, "Reading git-diff-tree failed");
5038 @difftree
5039 or die_error(404, "Blob diff not found");
5041 } else {
5042 die_error(400, "Missing one of the blob diff parameters");
5045 if (@difftree > 1) {
5046 die_error(400, "Ambiguous blob diff specification");
5049 %diffinfo = parse_difftree_raw_line($difftree[0]);
5050 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5051 $file_name ||= $diffinfo{'to_file'};
5053 $hash_parent ||= $diffinfo{'from_id'};
5054 $hash ||= $diffinfo{'to_id'};
5056 # non-textual hash id's can be cached
5057 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5058 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5059 $expires = '+1d';
5062 # open patch output
5063 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5064 '-p', ($format eq 'html' ? "--full-index" : ()),
5065 $hash_parent_base, $hash_base,
5066 "--", (defined $file_parent ? $file_parent : ()), $file_name
5067 or die_error(500, "Open git-diff-tree failed");
5070 # old/legacy style URI
5071 if (!%diffinfo && # if new style URI failed
5072 defined $hash && defined $hash_parent) {
5073 # fake git-diff-tree raw output
5074 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
5075 $diffinfo{'from_id'} = $hash_parent;
5076 $diffinfo{'to_id'} = $hash;
5077 if (defined $file_name) {
5078 if (defined $file_parent) {
5079 $diffinfo{'status'} = '2';
5080 $diffinfo{'from_file'} = $file_parent;
5081 $diffinfo{'to_file'} = $file_name;
5082 } else { # assume not renamed
5083 $diffinfo{'status'} = '1';
5084 $diffinfo{'from_file'} = $file_name;
5085 $diffinfo{'to_file'} = $file_name;
5087 } else { # no filename given
5088 $diffinfo{'status'} = '2';
5089 $diffinfo{'from_file'} = $hash_parent;
5090 $diffinfo{'to_file'} = $hash;
5093 # non-textual hash id's can be cached
5094 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
5095 $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5096 $expires = '+1d';
5099 # open patch output
5100 open $fd, "-|", git_cmd(), "diff", @diff_opts,
5101 '-p', ($format eq 'html' ? "--full-index" : ()),
5102 $hash_parent, $hash, "--"
5103 or die_error(500, "Open git-diff failed");
5104 } else {
5105 die_error(400, "Missing one of the blob diff parameters")
5106 unless %diffinfo;
5109 # header
5110 if ($format eq 'html') {
5111 my $formats_nav =
5112 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5113 "raw");
5114 git_header_html(undef, $expires);
5115 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5116 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5117 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5118 } else {
5119 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5120 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5122 if (defined $file_name) {
5123 git_print_page_path($file_name, "blob", $hash_base);
5124 } else {
5125 print "<div class=\"page_path\"></div>\n";
5128 } elsif ($format eq 'plain') {
5129 print $cgi->header(
5130 -type => 'text/plain',
5131 -charset => 'utf-8',
5132 -expires => $expires,
5133 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5135 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5137 } else {
5138 die_error(400, "Unknown blobdiff format");
5141 # patch
5142 if ($format eq 'html') {
5143 print "<div class=\"page_body\">\n";
5145 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5146 close $fd;
5148 print "</div>\n"; # class="page_body"
5149 git_footer_html();
5151 } else {
5152 while (my $line = <$fd>) {
5153 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5154 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5156 print $line;
5158 last if $line =~ m!^\+\+\+!;
5160 local $/ = undef;
5161 print <$fd>;
5162 close $fd;
5166 sub git_blobdiff_plain {
5167 git_blobdiff('plain');
5170 sub git_commitdiff {
5171 my $format = shift || 'html';
5172 $hash ||= $hash_base || "HEAD";
5173 my %co = parse_commit($hash)
5174 or die_error(404, "Unknown commit object");
5176 # choose format for commitdiff for merge
5177 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5178 $hash_parent = '--cc';
5180 # we need to prepare $formats_nav before almost any parameter munging
5181 my $formats_nav;
5182 if ($format eq 'html') {
5183 $formats_nav =
5184 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5185 "raw");
5187 if (defined $hash_parent &&
5188 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5189 # commitdiff with two commits given
5190 my $hash_parent_short = $hash_parent;
5191 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5192 $hash_parent_short = substr($hash_parent, 0, 7);
5194 $formats_nav .=
5195 ' (from';
5196 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5197 if ($co{'parents'}[$i] eq $hash_parent) {
5198 $formats_nav .= ' parent ' . ($i+1);
5199 last;
5202 $formats_nav .= ': ' .
5203 $cgi->a({-href => href(action=>"commitdiff",
5204 hash=>$hash_parent)},
5205 esc_html($hash_parent_short)) .
5206 ')';
5207 } elsif (!$co{'parent'}) {
5208 # --root commitdiff
5209 $formats_nav .= ' (initial)';
5210 } elsif (scalar @{$co{'parents'}} == 1) {
5211 # single parent commit
5212 $formats_nav .=
5213 ' (parent: ' .
5214 $cgi->a({-href => href(action=>"commitdiff",
5215 hash=>$co{'parent'})},
5216 esc_html(substr($co{'parent'}, 0, 7))) .
5217 ')';
5218 } else {
5219 # merge commit
5220 if ($hash_parent eq '--cc') {
5221 $formats_nav .= ' | ' .
5222 $cgi->a({-href => href(action=>"commitdiff",
5223 hash=>$hash, hash_parent=>'-c')},
5224 'combined');
5225 } else { # $hash_parent eq '-c'
5226 $formats_nav .= ' | ' .
5227 $cgi->a({-href => href(action=>"commitdiff",
5228 hash=>$hash, hash_parent=>'--cc')},
5229 'compact');
5231 $formats_nav .=
5232 ' (merge: ' .
5233 join(' ', map {
5234 $cgi->a({-href => href(action=>"commitdiff",
5235 hash=>$_)},
5236 esc_html(substr($_, 0, 7)));
5237 } @{$co{'parents'}} ) .
5238 ')';
5242 my $hash_parent_param = $hash_parent;
5243 if (!defined $hash_parent_param) {
5244 # --cc for multiple parents, --root for parentless
5245 $hash_parent_param =
5246 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5249 # read commitdiff
5250 my $fd;
5251 my @difftree;
5252 if ($format eq 'html') {
5253 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5254 "--no-commit-id", "--patch-with-raw", "--full-index",
5255 $hash_parent_param, $hash, "--"
5256 or die_error(500, "Open git-diff-tree failed");
5258 while (my $line = <$fd>) {
5259 chomp $line;
5260 # empty line ends raw part of diff-tree output
5261 last unless $line;
5262 push @difftree, scalar parse_difftree_raw_line($line);
5265 } elsif ($format eq 'plain') {
5266 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5267 '-p', $hash_parent_param, $hash, "--"
5268 or die_error(500, "Open git-diff-tree failed");
5270 } else {
5271 die_error(400, "Unknown commitdiff format");
5274 # non-textual hash id's can be cached
5275 my $expires;
5276 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5277 $expires = "+1d";
5280 # write commit message
5281 if ($format eq 'html') {
5282 my $refs = git_get_references();
5283 my $ref = format_ref_marker($refs, $co{'id'});
5285 git_header_html(undef, $expires);
5286 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5287 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5288 git_print_authorship(\%co);
5289 print "<div class=\"page_body\">\n";
5290 if (@{$co{'comment'}} > 1) {
5291 print "<div class=\"log\">\n";
5292 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5293 print "</div>\n"; # class="log"
5296 } elsif ($format eq 'plain') {
5297 my $refs = git_get_references("tags");
5298 my $tagname = git_get_rev_name_tags($hash);
5299 my $filename = basename($project) . "-$hash.patch";
5301 print $cgi->header(
5302 -type => 'text/plain',
5303 -charset => 'utf-8',
5304 -expires => $expires,
5305 -content_disposition => 'inline; filename="' . "$filename" . '"');
5306 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5307 print "From: " . to_utf8($co{'author'}) . "\n";
5308 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5309 print "Subject: " . to_utf8($co{'title'}) . "\n";
5311 print "X-Git-Tag: $tagname\n" if $tagname;
5312 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5314 foreach my $line (@{$co{'comment'}}) {
5315 print to_utf8($line) . "\n";
5317 print "---\n\n";
5320 # write patch
5321 if ($format eq 'html') {
5322 my $use_parents = !defined $hash_parent ||
5323 $hash_parent eq '-c' || $hash_parent eq '--cc';
5324 git_difftree_body(\@difftree, $hash,
5325 $use_parents ? @{$co{'parents'}} : $hash_parent);
5326 print "<br/>\n";
5328 git_patchset_body($fd, \@difftree, $hash,
5329 $use_parents ? @{$co{'parents'}} : $hash_parent);
5330 close $fd;
5331 print "</div>\n"; # class="page_body"
5332 git_footer_html();
5334 } elsif ($format eq 'plain') {
5335 local $/ = undef;
5336 print <$fd>;
5337 close $fd
5338 or print "Reading git-diff-tree failed\n";
5342 sub git_commitdiff_plain {
5343 git_commitdiff('plain');
5346 sub git_history {
5347 if (!defined $hash_base) {
5348 $hash_base = git_get_head_hash($project);
5350 if (!defined $page) {
5351 $page = 0;
5353 my $ftype;
5354 my %co = parse_commit($hash_base)
5355 or die_error(404, "Unknown commit object");
5357 my $refs = git_get_references();
5358 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5360 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5361 $file_name, "--full-history")
5362 or die_error(404, "No such file or directory on given branch");
5364 if (!defined $hash && defined $file_name) {
5365 # some commits could have deleted file in question,
5366 # and not have it in tree, but one of them has to have it
5367 for (my $i = 0; $i <= @commitlist; $i++) {
5368 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5369 last if defined $hash;
5372 if (defined $hash) {
5373 $ftype = git_get_type($hash);
5375 if (!defined $ftype) {
5376 die_error(500, "Unknown type of object");
5379 my $paging_nav = '';
5380 if ($page > 0) {
5381 $paging_nav .=
5382 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5383 file_name=>$file_name)},
5384 "first");
5385 $paging_nav .= " &sdot; " .
5386 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5387 -accesskey => "p", -title => "Alt-p"}, "prev");
5388 } else {
5389 $paging_nav .= "first";
5390 $paging_nav .= " &sdot; prev";
5392 my $next_link = '';
5393 if ($#commitlist >= 100) {
5394 $next_link =
5395 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5396 -accesskey => "n", -title => "Alt-n"}, "next");
5397 $paging_nav .= " &sdot; $next_link";
5398 } else {
5399 $paging_nav .= " &sdot; next";
5402 git_header_html();
5403 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5404 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5405 git_print_page_path($file_name, $ftype, $hash_base);
5407 git_history_body(\@commitlist, 0, 99,
5408 $refs, $hash_base, $ftype, $next_link);
5410 git_footer_html();
5413 sub git_search {
5414 gitweb_check_feature('search') or die_error(403, "Search is disabled");
5415 if (!defined $searchtext) {
5416 die_error(400, "Text field is empty");
5418 if (!defined $hash) {
5419 $hash = git_get_head_hash($project);
5421 my %co = parse_commit($hash);
5422 if (!%co) {
5423 die_error(404, "Unknown commit object");
5425 if (!defined $page) {
5426 $page = 0;
5429 $searchtype ||= 'commit';
5430 if ($searchtype eq 'pickaxe') {
5431 # pickaxe may take all resources of your box and run for several minutes
5432 # with every query - so decide by yourself how public you make this feature
5433 gitweb_check_feature('pickaxe')
5434 or die_error(403, "Pickaxe is disabled");
5436 if ($searchtype eq 'grep') {
5437 gitweb_check_feature('grep')
5438 or die_error(403, "Grep is disabled");
5441 git_header_html();
5443 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5444 my $greptype;
5445 if ($searchtype eq 'commit') {
5446 $greptype = "--grep=";
5447 } elsif ($searchtype eq 'author') {
5448 $greptype = "--author=";
5449 } elsif ($searchtype eq 'committer') {
5450 $greptype = "--committer=";
5452 $greptype .= $searchtext;
5453 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5454 $greptype, '--regexp-ignore-case',
5455 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5457 my $paging_nav = '';
5458 if ($page > 0) {
5459 $paging_nav .=
5460 $cgi->a({-href => href(action=>"search", hash=>$hash,
5461 searchtext=>$searchtext,
5462 searchtype=>$searchtype)},
5463 "first");
5464 $paging_nav .= " &sdot; " .
5465 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5466 -accesskey => "p", -title => "Alt-p"}, "prev");
5467 } else {
5468 $paging_nav .= "first";
5469 $paging_nav .= " &sdot; prev";
5471 my $next_link = '';
5472 if ($#commitlist >= 100) {
5473 $next_link =
5474 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5475 -accesskey => "n", -title => "Alt-n"}, "next");
5476 $paging_nav .= " &sdot; $next_link";
5477 } else {
5478 $paging_nav .= " &sdot; next";
5481 if ($#commitlist >= 100) {
5484 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5485 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5486 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5489 if ($searchtype eq 'pickaxe') {
5490 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5491 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5493 print "<table class=\"pickaxe search\">\n";
5494 my $alternate = 1;
5495 $/ = "\n";
5496 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5497 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5498 ($search_use_regexp ? '--pickaxe-regex' : ());
5499 undef %co;
5500 my @files;
5501 while (my $line = <$fd>) {
5502 chomp $line;
5503 next unless $line;
5505 my %set = parse_difftree_raw_line($line);
5506 if (defined $set{'commit'}) {
5507 # finish previous commit
5508 if (%co) {
5509 print "</td>\n" .
5510 "<td class=\"link\">" .
5511 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5512 " | " .
5513 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5514 print "</td>\n" .
5515 "</tr>\n";
5518 if ($alternate) {
5519 print "<tr class=\"dark\">\n";
5520 } else {
5521 print "<tr class=\"light\">\n";
5523 $alternate ^= 1;
5524 %co = parse_commit($set{'commit'});
5525 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5526 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5527 "<td><i>$author</i></td>\n" .
5528 "<td>" .
5529 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5530 -class => "list subject"},
5531 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5532 } elsif (defined $set{'to_id'}) {
5533 next if ($set{'to_id'} =~ m/^0{40}$/);
5535 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5536 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
5537 -class => "list"},
5538 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5539 "<br/>\n";
5542 close $fd;
5544 # finish last commit (warning: repetition!)
5545 if (%co) {
5546 print "</td>\n" .
5547 "<td class=\"link\">" .
5548 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5549 " | " .
5550 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5551 print "</td>\n" .
5552 "</tr>\n";
5555 print "</table>\n";
5558 if ($searchtype eq 'grep') {
5559 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5560 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5562 print "<table class=\"grep_search\">\n";
5563 my $alternate = 1;
5564 my $matches = 0;
5565 $/ = "\n";
5566 open my $fd, "-|", git_cmd(), 'grep', '-n',
5567 $search_use_regexp ? ('-E', '-i') : '-F',
5568 $searchtext, $co{'tree'};
5569 my $lastfile = '';
5570 while (my $line = <$fd>) {
5571 chomp $line;
5572 my ($file, $lno, $ltext, $binary);
5573 last if ($matches++ > 1000);
5574 if ($line =~ /^Binary file (.+) matches$/) {
5575 $file = $1;
5576 $binary = 1;
5577 } else {
5578 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5580 if ($file ne $lastfile) {
5581 $lastfile and print "</td></tr>\n";
5582 if ($alternate++) {
5583 print "<tr class=\"dark\">\n";
5584 } else {
5585 print "<tr class=\"light\">\n";
5587 print "<td class=\"list\">".
5588 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5589 file_name=>"$file"),
5590 -class => "list"}, esc_path($file));
5591 print "</td><td>\n";
5592 $lastfile = $file;
5594 if ($binary) {
5595 print "<div class=\"binary\">Binary file</div>\n";
5596 } else {
5597 $ltext = untabify($ltext);
5598 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
5599 $ltext = esc_html($1, -nbsp=>1);
5600 $ltext .= '<span class="match">';
5601 $ltext .= esc_html($2, -nbsp=>1);
5602 $ltext .= '</span>';
5603 $ltext .= esc_html($3, -nbsp=>1);
5604 } else {
5605 $ltext = esc_html($ltext, -nbsp=>1);
5607 print "<div class=\"pre\">" .
5608 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5609 file_name=>"$file").'#l'.$lno,
5610 -class => "linenr"}, sprintf('%4i', $lno))
5611 . ' ' . $ltext . "</div>\n";
5614 if ($lastfile) {
5615 print "</td></tr>\n";
5616 if ($matches > 1000) {
5617 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5619 } else {
5620 print "<div class=\"diff nodifferences\">No matches found</div>\n";
5622 close $fd;
5624 print "</table>\n";
5626 git_footer_html();
5629 sub git_search_help {
5630 git_header_html();
5631 git_print_page_nav('','', $hash,$hash,$hash);
5632 print <<EOT;
5633 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
5634 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
5635 the pattern entered is recognized as the POSIX extended
5636 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
5637 insensitive).</p>
5638 <dl>
5639 <dt><b>commit</b></dt>
5640 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
5642 my ($have_grep) = gitweb_check_feature('grep');
5643 if ($have_grep) {
5644 print <<EOT;
5645 <dt><b>grep</b></dt>
5646 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5647 a different one) are searched for the given pattern. On large trees, this search can take
5648 a while and put some strain on the server, so please use it with some consideration. Note that
5649 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
5650 case-sensitive.</dd>
5653 print <<EOT;
5654 <dt><b>author</b></dt>
5655 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
5656 <dt><b>committer</b></dt>
5657 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
5659 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5660 if ($have_pickaxe) {
5661 print <<EOT;
5662 <dt><b>pickaxe</b></dt>
5663 <dd>All commits that caused the string to appear or disappear from any file (changes that
5664 added, removed or "modified" the string) will be listed. This search can take a while and
5665 takes a lot of strain on the server, so please use it wisely. Note that since you may be
5666 interested even in changes just changing the case as well, this search is case sensitive.</dd>
5669 print "</dl>\n";
5670 git_footer_html();
5673 sub git_shortlog {
5674 my $head = git_get_head_hash($project);
5675 if (!defined $hash) {
5676 $hash = $head;
5678 if (!defined $page) {
5679 $page = 0;
5681 my $refs = git_get_references();
5683 my $commit_hash = $hash;
5684 if (defined $hash_parent) {
5685 $commit_hash = "$hash_parent..$hash";
5687 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
5689 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
5690 my $next_link = '';
5691 if ($#commitlist >= 100) {
5692 $next_link =
5693 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5694 -accesskey => "n", -title => "Alt-n"}, "next");
5697 git_header_html();
5698 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5699 git_print_header_div('summary', $project);
5701 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5703 git_footer_html();
5706 ## ......................................................................
5707 ## feeds (RSS, Atom; OPML)
5709 sub git_feed {
5710 my $format = shift || 'atom';
5711 my ($have_blame) = gitweb_check_feature('blame');
5713 # Atom: http://www.atomenabled.org/developers/syndication/
5714 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5715 if ($format ne 'rss' && $format ne 'atom') {
5716 die_error(400, "Unknown web feed format");
5719 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5720 my $head = $hash || 'HEAD';
5721 my @commitlist = parse_commits($head, 150, 0, $file_name);
5723 my %latest_commit;
5724 my %latest_date;
5725 my $content_type = "application/$format+xml";
5726 if (defined $cgi->http('HTTP_ACCEPT') &&
5727 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5728 # browser (feed reader) prefers text/xml
5729 $content_type = 'text/xml';
5731 if (defined($commitlist[0])) {
5732 %latest_commit = %{$commitlist[0]};
5733 %latest_date = parse_date($latest_commit{'author_epoch'});
5734 print $cgi->header(
5735 -type => $content_type,
5736 -charset => 'utf-8',
5737 -last_modified => $latest_date{'rfc2822'});
5738 } else {
5739 print $cgi->header(
5740 -type => $content_type,
5741 -charset => 'utf-8');
5744 # Optimization: skip generating the body if client asks only
5745 # for Last-Modified date.
5746 return if ($cgi->request_method() eq 'HEAD');
5748 # header variables
5749 my $title = "$site_name - $project/$action";
5750 my $feed_type = 'log';
5751 if (defined $hash) {
5752 $title .= " - '$hash'";
5753 $feed_type = 'branch log';
5754 if (defined $file_name) {
5755 $title .= " :: $file_name";
5756 $feed_type = 'history';
5758 } elsif (defined $file_name) {
5759 $title .= " - $file_name";
5760 $feed_type = 'history';
5762 $title .= " $feed_type";
5763 my $descr = git_get_project_description($project);
5764 if (defined $descr) {
5765 $descr = esc_html($descr);
5766 } else {
5767 $descr = "$project " .
5768 ($format eq 'rss' ? 'RSS' : 'Atom') .
5769 " feed";
5771 my $owner = git_get_project_owner($project);
5772 $owner = esc_html($owner);
5774 #header
5775 my $alt_url;
5776 if (defined $file_name) {
5777 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5778 } elsif (defined $hash) {
5779 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5780 } else {
5781 $alt_url = href(-full=>1, action=>"summary");
5783 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5784 if ($format eq 'rss') {
5785 print <<XML;
5786 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5787 <channel>
5789 print "<title>$title</title>\n" .
5790 "<link>$alt_url</link>\n" .
5791 "<description>$descr</description>\n" .
5792 "<language>en</language>\n";
5793 } elsif ($format eq 'atom') {
5794 print <<XML;
5795 <feed xmlns="http://www.w3.org/2005/Atom">
5797 print "<title>$title</title>\n" .
5798 "<subtitle>$descr</subtitle>\n" .
5799 '<link rel="alternate" type="text/html" href="' .
5800 $alt_url . '" />' . "\n" .
5801 '<link rel="self" type="' . $content_type . '" href="' .
5802 $cgi->self_url() . '" />' . "\n" .
5803 "<id>" . href(-full=>1) . "</id>\n" .
5804 # use project owner for feed author
5805 '<author><name>'. email_obfuscate($owner) . '</name></author>\n';
5806 if (defined $favicon) {
5807 print "<icon>" . esc_url($favicon) . "</icon>\n";
5809 if (defined $logo_url) {
5810 # not twice as wide as tall: 72 x 27 pixels
5811 print "<logo>" . esc_url($logo) . "</logo>\n";
5813 if (! %latest_date) {
5814 # dummy date to keep the feed valid until commits trickle in:
5815 print "<updated>1970-01-01T00:00:00Z</updated>\n";
5816 } else {
5817 print "<updated>$latest_date{'iso-8601'}</updated>\n";
5821 # contents
5822 for (my $i = 0; $i <= $#commitlist; $i++) {
5823 my %co = %{$commitlist[$i]};
5824 my $commit = $co{'id'};
5825 # we read 150, we always show 30 and the ones more recent than 48 hours
5826 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5827 last;
5829 my %cd = parse_date($co{'author_epoch'});
5831 # get list of changed files
5832 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5833 $co{'parent'} || "--root",
5834 $co{'id'}, "--", (defined $file_name ? $file_name : ())
5835 or next;
5836 my @difftree = map { chomp; $_ } <$fd>;
5837 close $fd
5838 or next;
5840 # print element (entry, item)
5841 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
5842 if ($format eq 'rss') {
5843 print "<item>\n" .
5844 "<title>" . esc_html($co{'title'}) . "</title>\n" .
5845 "<author>" . esc_html($co{'author'}) . "</author>\n" .
5846 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5847 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5848 "<link>$co_url</link>\n" .
5849 "<description>" . esc_html($co{'title'}) . "</description>\n" .
5850 "<content:encoded>" .
5851 "<![CDATA[\n";
5852 } elsif ($format eq 'atom') {
5853 print "<entry>\n" .
5854 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5855 "<updated>$cd{'iso-8601'}</updated>\n" .
5856 "<author>\n" .
5857 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
5858 if ($co{'author_email'}) {
5859 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
5861 print "</author>\n" .
5862 # use committer for contributor
5863 "<contributor>\n" .
5864 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5865 if ($co{'committer_email'}) {
5866 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5868 print "</contributor>\n" .
5869 "<published>$cd{'iso-8601'}</published>\n" .
5870 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5871 "<id>$co_url</id>\n" .
5872 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5873 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5875 my $comment = $co{'comment'};
5876 print "<pre>\n";
5877 foreach my $line (@$comment) {
5878 $line = esc_html($line);
5879 print "$line\n";
5881 print "</pre><ul>\n";
5882 foreach my $difftree_line (@difftree) {
5883 my %difftree = parse_difftree_raw_line($difftree_line);
5884 next if !$difftree{'from_id'};
5886 my $file = $difftree{'file'} || $difftree{'to_file'};
5888 print "<li>" .
5889 "[" .
5890 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5891 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5892 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5893 file_name=>$file, file_parent=>$difftree{'from_file'}),
5894 -title => "diff"}, 'D');
5895 if ($have_blame) {
5896 print $cgi->a({-href => href(-full=>1, action=>"blame",
5897 file_name=>$file, hash_base=>$commit),
5898 -title => "blame"}, 'B');
5900 # if this is not a feed of a file history
5901 if (!defined $file_name || $file_name ne $file) {
5902 print $cgi->a({-href => href(-full=>1, action=>"history",
5903 file_name=>$file, hash=>$commit),
5904 -title => "history"}, 'H');
5906 $file = esc_path($file);
5907 print "] ".
5908 "$file</li>\n";
5910 if ($format eq 'rss') {
5911 print "</ul>]]>\n" .
5912 "</content:encoded>\n" .
5913 "</item>\n";
5914 } elsif ($format eq 'atom') {
5915 print "</ul>\n</div>\n" .
5916 "</content>\n" .
5917 "</entry>\n";
5921 # end of feed
5922 if ($format eq 'rss') {
5923 print "</channel>\n</rss>\n";
5924 } elsif ($format eq 'atom') {
5925 print "</feed>\n";
5929 sub git_rss {
5930 git_feed('rss');
5933 sub git_atom {
5934 git_feed('atom');
5937 sub git_opml {
5938 my @list = git_get_projects_list();
5940 print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
5941 print <<XML;
5942 <?xml version="1.0" encoding="utf-8"?>
5943 <opml version="1.0">
5944 <head>
5945 <title>$site_name OPML Export</title>
5946 </head>
5947 <body>
5948 <outline text="git RSS feeds">
5951 foreach my $pr (@list) {
5952 my %proj = %$pr;
5953 my $head = git_get_head_hash($proj{'path'});
5954 if (!defined $head) {
5955 next;
5957 $git_dir = "$projectroot/$proj{'path'}";
5958 my %co = parse_commit($head);
5959 if (!%co) {
5960 next;
5963 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
5964 my $rss = "$my_url?p=$proj{'path'};a=rss";
5965 my $html = "$my_url?p=$proj{'path'};a=summary";
5966 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
5968 print <<XML;
5969 </outline>
5970 </body>
5971 </opml>