Merge commit 'refs/top-bases/t/blame/incremental' into t/blame/incremental
[git/repo.git] / gitweb / gitweb.perl
blobb0fba673515ac9344cc10868f5dac24c218f0096
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++";
75 # URI of gitweb.js
76 our $gitwebjs = "++GITWEB_GITWEBJS++";
78 # URI and label (title) of GIT logo link
79 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
80 #our $logo_label = "git documentation";
81 our $logo_url = "http://git.or.cz/";
82 our $logo_label = "git homepage";
84 # source of projects list
85 our $projects_list = "++GITWEB_LIST++";
87 # the width (in characters) of the projects list "Description" column
88 our $projects_list_description_width = 25;
90 # default order of projects list
91 # valid values are none, project, descr, owner, and age
92 our $default_projects_order = "project";
94 # show repository only if this file exists
95 # (only effective if this variable evaluates to true)
96 our $export_ok = "++GITWEB_EXPORT_OK++";
98 # only allow viewing of repositories also shown on the overview page
99 our $strict_export = "++GITWEB_STRICT_EXPORT++";
101 # list of git base URLs used for URL to where fetch project from,
102 # i.e. full URL is "$git_base_url/$project"
103 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
105 # default blob_plain mimetype and default charset for text/plain blob
106 our $default_blob_plain_mimetype = 'text/plain';
107 our $default_text_plain_charset = undef;
109 # file to use for guessing MIME types before trying /etc/mime.types
110 # (relative to the current git repository)
111 our $mimetypes_file = undef;
113 # assume this charset if line contains non-UTF-8 characters;
114 # it should be valid encoding (see Encoding::Supported(3pm) for list),
115 # for which encoding all byte sequences are valid, for example
116 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
117 # could be even 'utf-8' for the old behavior)
118 our $fallback_encoding = 'latin1';
120 # rename detection options for git-diff and git-diff-tree
121 # - default is '-M', with the cost proportional to
122 # (number of removed files) * (number of new files).
123 # - more costly is '-C' (which implies '-M'), with the cost proportional to
124 # (number of changed files + number of removed files) * (number of new files)
125 # - even more costly is '-C', '--find-copies-harder' with cost
126 # (number of files in the original tree) * (number of new files)
127 # - one might want to include '-B' option, e.g. '-B', '-M'
128 our @diff_opts = ('-M'); # taken from git_commit
130 # information about snapshot formats that gitweb is capable of serving
131 our %known_snapshot_formats = (
132 # name => {
133 # 'display' => display name,
134 # 'type' => mime type,
135 # 'suffix' => filename suffix,
136 # 'format' => --format for git-archive,
137 # 'compressor' => [compressor command and arguments]
138 # (array reference, optional)}
140 'tgz' => {
141 'display' => 'tar.gz',
142 'type' => 'application/x-gzip',
143 'suffix' => '.tar.gz',
144 'format' => 'tar',
145 'compressor' => ['gzip']},
147 'tbz2' => {
148 'display' => 'tar.bz2',
149 'type' => 'application/x-bzip2',
150 'suffix' => '.tar.bz2',
151 'format' => 'tar',
152 'compressor' => ['bzip2']},
154 'zip' => {
155 'display' => 'zip',
156 'type' => 'application/x-zip',
157 'suffix' => '.zip',
158 'format' => 'zip'},
161 # Aliases so we understand old gitweb.snapshot values in repository
162 # configuration.
163 our %known_snapshot_format_aliases = (
164 'gzip' => 'tgz',
165 'bzip2' => 'tbz2',
167 # backward compatibility: legacy gitweb config support
168 'x-gzip' => undef, 'gz' => undef,
169 'x-bzip2' => undef, 'bz2' => undef,
170 'x-zip' => undef, '' => undef,
173 # You define site-wide feature defaults here; override them with
174 # $GITWEB_CONFIG as necessary.
175 our %feature = (
176 # feature => {
177 # 'sub' => feature-sub (subroutine),
178 # 'override' => allow-override (boolean),
179 # 'default' => [ default options...] (array reference)}
181 # if feature is overridable (it means that allow-override has true value),
182 # then feature-sub will be called with default options as parameters;
183 # return value of feature-sub indicates if to enable specified feature
185 # if there is no 'sub' key (no feature-sub), then feature cannot be
186 # overriden
188 # use gitweb_check_feature(<feature>) to check if <feature> is enabled
190 # Enable the 'blame' blob view, showing the last commit that modified
191 # each line in the file. This can be very CPU-intensive.
193 # To enable system wide have in $GITWEB_CONFIG
194 # $feature{'blame'}{'default'} = [1];
195 # To have project specific config enable override in $GITWEB_CONFIG
196 # $feature{'blame'}{'override'} = 1;
197 # and in project config gitweb.blame = 0|1;
198 'blame' => {
199 'sub' => \&feature_blame,
200 'override' => 0,
201 'default' => [0]},
203 # Enable the 'snapshot' link, providing a compressed archive of any
204 # tree. This can potentially generate high traffic if you have large
205 # project.
207 # Value is a list of formats defined in %known_snapshot_formats that
208 # you wish to offer.
209 # To disable system wide have in $GITWEB_CONFIG
210 # $feature{'snapshot'}{'default'} = [];
211 # To have project specific config enable override in $GITWEB_CONFIG
212 # $feature{'snapshot'}{'override'} = 1;
213 # and in project config, a comma-separated list of formats or "none"
214 # to disable. Example: gitweb.snapshot = tbz2,zip;
215 'snapshot' => {
216 'sub' => \&feature_snapshot,
217 'override' => 0,
218 'default' => ['tgz']},
220 # Enable text search, which will list the commits which match author,
221 # committer or commit text to a given string. Enabled by default.
222 # Project specific override is not supported.
223 'search' => {
224 'override' => 0,
225 'default' => [1]},
227 # Enable grep search, which will list the files in currently selected
228 # tree containing the given string. Enabled by default. This can be
229 # potentially CPU-intensive, of course.
231 # To enable system wide have in $GITWEB_CONFIG
232 # $feature{'grep'}{'default'} = [1];
233 # To have project specific config enable override in $GITWEB_CONFIG
234 # $feature{'grep'}{'override'} = 1;
235 # and in project config gitweb.grep = 0|1;
236 'grep' => {
237 'override' => 0,
238 'default' => [1]},
240 # Enable the pickaxe search, which will list the commits that modified
241 # a given string in a file. This can be practical and quite faster
242 # alternative to 'blame', but still potentially CPU-intensive.
244 # To enable system wide have in $GITWEB_CONFIG
245 # $feature{'pickaxe'}{'default'} = [1];
246 # To have project specific config enable override in $GITWEB_CONFIG
247 # $feature{'pickaxe'}{'override'} = 1;
248 # and in project config gitweb.pickaxe = 0|1;
249 'pickaxe' => {
250 'sub' => \&feature_pickaxe,
251 'override' => 0,
252 'default' => [1]},
254 # Make gitweb use an alternative format of the URLs which can be
255 # more readable and natural-looking: project name is embedded
256 # directly in the path and the query string contains other
257 # auxiliary information. All gitweb installations recognize
258 # URL in either format; this configures in which formats gitweb
259 # generates links.
261 # To enable system wide have in $GITWEB_CONFIG
262 # $feature{'pathinfo'}{'default'} = [1];
263 # Project specific override is not supported.
265 # Note that you will need to change the default location of CSS,
266 # favicon, logo and possibly other files to an absolute URL. Also,
267 # if gitweb.cgi serves as your indexfile, you will need to force
268 # $my_uri to contain the script name in your $GITWEB_CONFIG.
269 'pathinfo' => {
270 'override' => 0,
271 'default' => [0]},
273 # Make gitweb consider projects in project root subdirectories
274 # to be forks of existing projects. Given project $projname.git,
275 # projects matching $projname/*.git will not be shown in the main
276 # projects list, instead a '+' mark will be added to $projname
277 # there and a 'forks' view will be enabled for the project, listing
278 # all the forks. If project list is taken from a file, forks have
279 # to be listed after the main project.
281 # To enable system wide have in $GITWEB_CONFIG
282 # $feature{'forks'}{'default'} = [1];
283 # Project specific override is not supported.
284 'forks' => {
285 'override' => 0,
286 'default' => [0]},
288 # Insert custom links to the action bar of all project pages.
289 # This enables you mainly to link to third-party scripts integrating
290 # into gitweb; e.g. git-browser for graphical history representation
291 # or custom web-based repository administration interface.
293 # The 'default' value consists of a list of triplets in the form
294 # (label, link, position) where position is the label after which
295 # to inster the link and link is a format string where %n expands
296 # to the project name, %f to the project path within the filesystem,
297 # %h to the current hash (h gitweb parameter) and %b to the current
298 # hash base (hb gitweb parameter).
300 # To enable system wide have in $GITWEB_CONFIG e.g.
301 # $feature{'actions'}{'default'} = [('graphiclog',
302 # '/git-browser/by-commit.html?r=%n', 'summary')];
303 # Project specific override is not supported.
304 'actions' => {
305 'override' => 0,
306 'default' => []},
308 # Allow gitweb scan project content tags described in ctags/
309 # of project repository, and display the popular Web 2.0-ish
310 # "tag cloud" near the project list. Note that this is something
311 # COMPLETELY different from the normal Git tags.
313 # gitweb by itself can show existing tags, but it does not handle
314 # tagging itself; you need an external application for that.
315 # For an example script, check Girocco's cgi/tagproj.cgi.
316 # You may want to install the HTML::TagCloud Perl module to get
317 # a pretty tag cloud instead of just a list of tags.
319 # To enable system wide have in $GITWEB_CONFIG
320 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
321 # Project specific override is not supported.
322 'ctags' => {
323 'override' => 0,
324 'default' => [0]},
327 sub gitweb_check_feature {
328 my ($name) = @_;
329 return unless exists $feature{$name};
330 my ($sub, $override, @defaults) = (
331 $feature{$name}{'sub'},
332 $feature{$name}{'override'},
333 @{$feature{$name}{'default'}});
334 if (!$override) { return @defaults; }
335 if (!defined $sub) {
336 warn "feature $name is not overrideable";
337 return @defaults;
339 return $sub->(@defaults);
342 sub feature_blame {
343 my ($val) = git_get_project_config('blame', '--bool');
345 if ($val eq 'true') {
346 return 1;
347 } elsif ($val eq 'false') {
348 return 0;
351 return $_[0];
354 sub feature_snapshot {
355 my (@fmts) = @_;
357 my ($val) = git_get_project_config('snapshot');
359 if ($val) {
360 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
363 return @fmts;
366 sub feature_grep {
367 my ($val) = git_get_project_config('grep', '--bool');
369 if ($val eq 'true') {
370 return (1);
371 } elsif ($val eq 'false') {
372 return (0);
375 return ($_[0]);
378 sub feature_pickaxe {
379 my ($val) = git_get_project_config('pickaxe', '--bool');
381 if ($val eq 'true') {
382 return (1);
383 } elsif ($val eq 'false') {
384 return (0);
387 return ($_[0]);
390 # checking HEAD file with -e is fragile if the repository was
391 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
392 # and then pruned.
393 sub check_head_link {
394 my ($dir) = @_;
395 my $headfile = "$dir/HEAD";
396 return ((-e $headfile) ||
397 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
400 sub check_export_ok {
401 my ($dir) = @_;
402 return (check_head_link($dir) &&
403 (!$export_ok || -e "$dir/$export_ok"));
406 # process alternate names for backward compatibility
407 # filter out unsupported (unknown) snapshot formats
408 sub filter_snapshot_fmts {
409 my @fmts = @_;
411 @fmts = map {
412 exists $known_snapshot_format_aliases{$_} ?
413 $known_snapshot_format_aliases{$_} : $_} @fmts;
414 @fmts = grep(exists $known_snapshot_formats{$_}, @fmts);
418 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
419 if (-e $GITWEB_CONFIG) {
420 do $GITWEB_CONFIG;
421 } else {
422 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
423 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
426 # version of the core git binary
427 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
429 $projects_list ||= $projectroot;
431 # ======================================================================
432 # input validation and dispatch
433 our $action = $cgi->param('a');
434 if (defined $action) {
435 if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
436 die_error(400, "Invalid action parameter");
440 # parameters which are pathnames
441 our $project = $cgi->param('p');
442 if (defined $project) {
443 if (!validate_pathname($project) ||
444 !(-d "$projectroot/$project") ||
445 !check_head_link("$projectroot/$project") ||
446 ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
447 ($strict_export && !project_in_list($project))) {
448 undef $project;
449 die_error(404, "No such project");
453 our $file_name = $cgi->param('f');
454 if (defined $file_name) {
455 if (!validate_pathname($file_name)) {
456 die_error(400, "Invalid file parameter");
460 our $file_parent = $cgi->param('fp');
461 if (defined $file_parent) {
462 if (!validate_pathname($file_parent)) {
463 die_error(400, "Invalid file parent parameter");
467 # parameters which are refnames
468 our $hash = $cgi->param('h');
469 if (defined $hash) {
470 if (!validate_refname($hash)) {
471 die_error(400, "Invalid hash parameter");
475 our $hash_parent = $cgi->param('hp');
476 if (defined $hash_parent) {
477 if (!validate_refname($hash_parent)) {
478 die_error(400, "Invalid hash parent parameter");
482 our $hash_base = $cgi->param('hb');
483 if (defined $hash_base) {
484 if (!validate_refname($hash_base)) {
485 die_error(400, "Invalid hash base parameter");
489 my %allowed_options = (
490 "--no-merges" => [ qw(rss atom log shortlog history) ],
493 our @extra_options = $cgi->param('opt');
494 if (defined @extra_options) {
495 foreach my $opt (@extra_options) {
496 if (not exists $allowed_options{$opt}) {
497 die_error(400, "Invalid option parameter");
499 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
500 die_error(400, "Invalid option parameter for this action");
505 our $hash_parent_base = $cgi->param('hpb');
506 if (defined $hash_parent_base) {
507 if (!validate_refname($hash_parent_base)) {
508 die_error(400, "Invalid hash parent base parameter");
512 # other parameters
513 our $page = $cgi->param('pg');
514 if (defined $page) {
515 if ($page =~ m/[^0-9]/) {
516 die_error(400, "Invalid page parameter");
520 our $searchtype = $cgi->param('st');
521 if (defined $searchtype) {
522 if ($searchtype =~ m/[^a-z]/) {
523 die_error(400, "Invalid searchtype parameter");
527 our $search_use_regexp = $cgi->param('sr');
529 our $searchtext = $cgi->param('s');
530 our $search_regexp;
531 if (defined $searchtext) {
532 if (length($searchtext) < 2) {
533 die_error(403, "At least two characters are required for search parameter");
535 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
538 # now read PATH_INFO and use it as alternative to parameters
539 sub evaluate_path_info {
540 return if defined $project;
541 my $path_info = $ENV{"PATH_INFO"};
542 return if !$path_info;
543 $path_info =~ s,^/+,,;
544 return if !$path_info;
545 # find which part of PATH_INFO is project
546 $project = $path_info;
547 $project =~ s,/+$,,;
548 while ($project && !check_head_link("$projectroot/$project")) {
549 $project =~ s,/*[^/]*$,,;
551 # validate project
552 $project = validate_pathname($project);
553 if (!$project ||
554 ($export_ok && !-e "$projectroot/$project/$export_ok") ||
555 ($strict_export && !project_in_list($project))) {
556 undef $project;
557 return;
559 # do not change any parameters if an action is given using the query string
560 return if $action;
561 $path_info =~ s,^\Q$project\E/*,,;
562 my ($refname, $pathname) = split(/:/, $path_info, 2);
563 if (defined $pathname) {
564 # we got "project.git/branch:filename" or "project.git/branch:dir/"
565 # we could use git_get_type(branch:pathname), but it needs $git_dir
566 $pathname =~ s,^/+,,;
567 if (!$pathname || substr($pathname, -1) eq "/") {
568 $action ||= "tree";
569 $pathname =~ s,/$,,;
570 } else {
571 $action ||= "blob_plain";
573 $hash_base ||= validate_refname($refname);
574 $file_name ||= validate_pathname($pathname);
575 } elsif (defined $refname) {
576 # we got "project.git/branch"
577 $action ||= "shortlog";
578 $hash ||= validate_refname($refname);
581 evaluate_path_info();
583 # path to the current git repository
584 our $git_dir;
585 $git_dir = "$projectroot/$project" if $project;
587 # dispatch
588 my %actions = (
589 "blame" => \&git_blame,
590 "blame_incremental" => \&git_blame_incremental,
591 "blame_data" => \&git_blame_data,
592 "blobdiff" => \&git_blobdiff,
593 "blobdiff_plain" => \&git_blobdiff_plain,
594 "blob" => \&git_blob,
595 "blob_plain" => \&git_blob_plain,
596 "commitdiff" => \&git_commitdiff,
597 "commitdiff_plain" => \&git_commitdiff_plain,
598 "commit" => \&git_commit,
599 "forks" => \&git_forks,
600 "heads" => \&git_heads,
601 "history" => \&git_history,
602 "log" => \&git_log,
603 "rss" => \&git_rss,
604 "atom" => \&git_atom,
605 "search" => \&git_search,
606 "search_help" => \&git_search_help,
607 "shortlog" => \&git_shortlog,
608 "summary" => \&git_summary,
609 "tag" => \&git_tag,
610 "tags" => \&git_tags,
611 "tree" => \&git_tree,
612 "snapshot" => \&git_snapshot,
613 "object" => \&git_object,
614 # those below don't need $project
615 "opml" => \&git_opml,
616 "project_list" => \&git_project_list,
617 "project_index" => \&git_project_index,
620 if (!defined $action) {
621 if (defined $hash) {
622 $action = git_get_type($hash);
623 } elsif (defined $hash_base && defined $file_name) {
624 $action = git_get_type("$hash_base:$file_name");
625 } elsif (defined $project) {
626 $action = 'summary';
627 } else {
628 $action = 'project_list';
631 if (!defined($actions{$action})) {
632 die_error(400, "Unknown action");
634 if ($action !~ m/^(opml|project_list|project_index)$/ &&
635 !$project) {
636 die_error(400, "Project needed");
638 $actions{$action}->();
639 exit;
641 ## ======================================================================
642 ## action links
644 sub href (%) {
645 my %params = @_;
646 # default is to use -absolute url() i.e. $my_uri
647 my $href = $params{-full} ? $my_url : $my_uri;
649 # XXX: Warning: If you touch this, check the search form for updating,
650 # too.
652 my @mapping = (
653 project => "p",
654 action => "a",
655 file_name => "f",
656 file_parent => "fp",
657 hash => "h",
658 hash_parent => "hp",
659 hash_base => "hb",
660 hash_parent_base => "hpb",
661 page => "pg",
662 order => "o",
663 searchtext => "s",
664 searchtype => "st",
665 snapshot_format => "sf",
666 extra_options => "opt",
667 search_use_regexp => "sr",
669 my %mapping = @mapping;
671 $params{'project'} = $project unless exists $params{'project'};
673 if ($params{-replay}) {
674 while (my ($name, $symbol) = each %mapping) {
675 if (!exists $params{$name}) {
676 # to allow for multivalued params we use arrayref form
677 $params{$name} = [ $cgi->param($symbol) ];
682 my ($use_pathinfo) = gitweb_check_feature('pathinfo');
683 if ($use_pathinfo) {
684 # use PATH_INFO for project name
685 $href .= "/".esc_url($params{'project'}) if defined $params{'project'};
686 delete $params{'project'};
688 # Summary just uses the project path URL
689 if (defined $params{'action'} && $params{'action'} eq 'summary') {
690 delete $params{'action'};
694 # now encode the parameters explicitly
695 my @result = ();
696 for (my $i = 0; $i < @mapping; $i += 2) {
697 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
698 if (defined $params{$name}) {
699 if (ref($params{$name}) eq "ARRAY") {
700 foreach my $par (@{$params{$name}}) {
701 push @result, $symbol . "=" . esc_param($par);
703 } else {
704 push @result, $symbol . "=" . esc_param($params{$name});
708 $href .= "?" . join(';', @result) if $params{-partial_query} or scalar @result;
710 return $href;
714 ## ======================================================================
715 ## validation, quoting/unquoting and escaping
717 sub validate_pathname {
718 my $input = shift || return undef;
720 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
721 # at the beginning, at the end, and between slashes.
722 # also this catches doubled slashes
723 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
724 return undef;
726 # no null characters
727 if ($input =~ m!\0!) {
728 return undef;
730 return $input;
733 sub validate_refname {
734 my $input = shift || return undef;
736 # textual hashes are O.K.
737 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
738 return $input;
740 # it must be correct pathname
741 $input = validate_pathname($input)
742 or return undef;
743 # restrictions on ref name according to git-check-ref-format
744 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
745 return undef;
747 return $input;
750 # decode sequences of octets in utf8 into Perl's internal form,
751 # which is utf-8 with utf8 flag set if needed. gitweb writes out
752 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
753 sub to_utf8 {
754 my $str = shift;
755 if (utf8::valid($str)) {
756 utf8::decode($str);
757 return $str;
758 } else {
759 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
763 # quote unsafe chars, but keep the slash, even when it's not
764 # correct, but quoted slashes look too horrible in bookmarks
765 sub esc_param {
766 my $str = shift;
767 $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
768 $str =~ s/\+/%2B/g;
769 $str =~ s/ /\+/g;
770 return $str;
773 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
774 sub esc_url {
775 my $str = shift;
776 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
777 $str =~ s/\+/%2B/g;
778 $str =~ s/ /\+/g;
779 return $str;
782 # replace invalid utf8 character with SUBSTITUTION sequence
783 sub esc_html ($;%) {
784 my $str = shift;
785 my %opts = @_;
787 $str = to_utf8($str);
788 $str = $cgi->escapeHTML($str);
789 if ($opts{'-nbsp'}) {
790 $str =~ s/ /&nbsp;/g;
792 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
793 return $str;
796 # quote control characters and escape filename to HTML
797 sub esc_path {
798 my $str = shift;
799 my %opts = @_;
801 $str = to_utf8($str);
802 $str = $cgi->escapeHTML($str);
803 if ($opts{'-nbsp'}) {
804 $str =~ s/ /&nbsp;/g;
806 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
807 return $str;
810 # Make control characters "printable", using character escape codes (CEC)
811 sub quot_cec {
812 my $cntrl = shift;
813 my %opts = @_;
814 my %es = ( # character escape codes, aka escape sequences
815 "\t" => '\t', # tab (HT)
816 "\n" => '\n', # line feed (LF)
817 "\r" => '\r', # carrige return (CR)
818 "\f" => '\f', # form feed (FF)
819 "\b" => '\b', # backspace (BS)
820 "\a" => '\a', # alarm (bell) (BEL)
821 "\e" => '\e', # escape (ESC)
822 "\013" => '\v', # vertical tab (VT)
823 "\000" => '\0', # nul character (NUL)
825 my $chr = ( (exists $es{$cntrl})
826 ? $es{$cntrl}
827 : sprintf('\%2x', ord($cntrl)) );
828 if ($opts{-nohtml}) {
829 return $chr;
830 } else {
831 return "<span class=\"cntrl\">$chr</span>";
835 # Alternatively use unicode control pictures codepoints,
836 # Unicode "printable representation" (PR)
837 sub quot_upr {
838 my $cntrl = shift;
839 my %opts = @_;
841 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
842 if ($opts{-nohtml}) {
843 return $chr;
844 } else {
845 return "<span class=\"cntrl\">$chr</span>";
849 # git may return quoted and escaped filenames
850 sub unquote {
851 my $str = shift;
853 sub unq {
854 my $seq = shift;
855 my %es = ( # character escape codes, aka escape sequences
856 't' => "\t", # tab (HT, TAB)
857 'n' => "\n", # newline (NL)
858 'r' => "\r", # return (CR)
859 'f' => "\f", # form feed (FF)
860 'b' => "\b", # backspace (BS)
861 'a' => "\a", # alarm (bell) (BEL)
862 'e' => "\e", # escape (ESC)
863 'v' => "\013", # vertical tab (VT)
866 if ($seq =~ m/^[0-7]{1,3}$/) {
867 # octal char sequence
868 return chr(oct($seq));
869 } elsif (exists $es{$seq}) {
870 # C escape sequence, aka character escape code
871 return $es{$seq};
873 # quoted ordinary character
874 return $seq;
877 if ($str =~ m/^"(.*)"$/) {
878 # needs unquoting
879 $str = $1;
880 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
882 return $str;
885 # escape tabs (convert tabs to spaces)
886 sub untabify {
887 my $line = shift;
889 while ((my $pos = index($line, "\t")) != -1) {
890 if (my $count = (8 - ($pos % 8))) {
891 my $spaces = ' ' x $count;
892 $line =~ s/\t/$spaces/;
896 return $line;
899 sub project_in_list {
900 my $project = shift;
901 my @list = git_get_projects_list();
902 return @list && scalar(grep { $_->{'path'} eq $project } @list);
905 ## ----------------------------------------------------------------------
906 ## HTML aware string manipulation
908 # Try to chop given string on a word boundary between position
909 # $len and $len+$add_len. If there is no word boundary there,
910 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
911 # (marking chopped part) would be longer than given string.
912 sub chop_str {
913 my $str = shift;
914 my $len = shift;
915 my $add_len = shift || 10;
916 my $where = shift || 'right'; # 'left' | 'center' | 'right'
918 # Make sure perl knows it is utf8 encoded so we don't
919 # cut in the middle of a utf8 multibyte char.
920 $str = to_utf8($str);
922 # allow only $len chars, but don't cut a word if it would fit in $add_len
923 # if it doesn't fit, cut it if it's still longer than the dots we would add
924 # remove chopped character entities entirely
926 # when chopping in the middle, distribute $len into left and right part
927 # return early if chopping wouldn't make string shorter
928 if ($where eq 'center') {
929 return $str if ($len + 5 >= length($str)); # filler is length 5
930 $len = int($len/2);
931 } else {
932 return $str if ($len + 4 >= length($str)); # filler is length 4
935 # regexps: ending and beginning with word part up to $add_len
936 my $endre = qr/.{$len}\w{0,$add_len}/;
937 my $begre = qr/\w{0,$add_len}.{$len}/;
939 if ($where eq 'left') {
940 $str =~ m/^(.*?)($begre)$/;
941 my ($lead, $body) = ($1, $2);
942 if (length($lead) > 4) {
943 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
944 $lead = " ...";
946 return "$lead$body";
948 } elsif ($where eq 'center') {
949 $str =~ m/^($endre)(.*)$/;
950 my ($left, $str) = ($1, $2);
951 $str =~ m/^(.*?)($begre)$/;
952 my ($mid, $right) = ($1, $2);
953 if (length($mid) > 5) {
954 $left =~ s/&[^;]*$//;
955 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
956 $mid = " ... ";
958 return "$left$mid$right";
960 } else {
961 $str =~ m/^($endre)(.*)$/;
962 my $body = $1;
963 my $tail = $2;
964 if (length($tail) > 4) {
965 $body =~ s/&[^;]*$//;
966 $tail = "... ";
968 return "$body$tail";
972 # takes the same arguments as chop_str, but also wraps a <span> around the
973 # result with a title attribute if it does get chopped. Additionally, the
974 # string is HTML-escaped.
975 sub chop_and_escape_str {
976 my ($str) = @_;
978 my $chopped = chop_str(@_);
979 if ($chopped eq $str) {
980 return esc_html($chopped);
981 } else {
982 $str =~ s/([[:cntrl:]])/?/g;
983 return $cgi->span({-title=>$str}, esc_html($chopped));
987 ## ----------------------------------------------------------------------
988 ## functions returning short strings
990 # CSS class for given age value (in seconds)
991 sub age_class {
992 my $age = shift;
994 if (!defined $age) {
995 return "noage";
996 } elsif ($age < 60*60*2) {
997 return "age0";
998 } elsif ($age < 60*60*24*2) {
999 return "age1";
1000 } else {
1001 return "age2";
1005 # convert age in seconds to "nn units ago" string
1006 sub age_string {
1007 my $age = shift;
1008 my $age_str;
1010 if ($age > 60*60*24*365*2) {
1011 $age_str = (int $age/60/60/24/365);
1012 $age_str .= " years ago";
1013 } elsif ($age > 60*60*24*(365/12)*2) {
1014 $age_str = int $age/60/60/24/(365/12);
1015 $age_str .= " months ago";
1016 } elsif ($age > 60*60*24*7*2) {
1017 $age_str = int $age/60/60/24/7;
1018 $age_str .= " weeks ago";
1019 } elsif ($age > 60*60*24*2) {
1020 $age_str = int $age/60/60/24;
1021 $age_str .= " days ago";
1022 } elsif ($age > 60*60*2) {
1023 $age_str = int $age/60/60;
1024 $age_str .= " hours ago";
1025 } elsif ($age > 60*2) {
1026 $age_str = int $age/60;
1027 $age_str .= " min ago";
1028 } elsif ($age > 2) {
1029 $age_str = int $age;
1030 $age_str .= " sec ago";
1031 } else {
1032 $age_str .= " right now";
1034 return $age_str;
1037 use constant {
1038 S_IFINVALID => 0030000,
1039 S_IFGITLINK => 0160000,
1042 # submodule/subproject, a commit object reference
1043 sub S_ISGITLINK($) {
1044 my $mode = shift;
1046 return (($mode & S_IFMT) == S_IFGITLINK)
1049 # convert file mode in octal to symbolic file mode string
1050 sub mode_str {
1051 my $mode = oct shift;
1053 if (S_ISGITLINK($mode)) {
1054 return 'm---------';
1055 } elsif (S_ISDIR($mode & S_IFMT)) {
1056 return 'drwxr-xr-x';
1057 } elsif (S_ISLNK($mode)) {
1058 return 'lrwxrwxrwx';
1059 } elsif (S_ISREG($mode)) {
1060 # git cares only about the executable bit
1061 if ($mode & S_IXUSR) {
1062 return '-rwxr-xr-x';
1063 } else {
1064 return '-rw-r--r--';
1066 } else {
1067 return '----------';
1071 # convert file mode in octal to file type string
1072 sub file_type {
1073 my $mode = shift;
1075 if ($mode !~ m/^[0-7]+$/) {
1076 return $mode;
1077 } else {
1078 $mode = oct $mode;
1081 if (S_ISGITLINK($mode)) {
1082 return "submodule";
1083 } elsif (S_ISDIR($mode & S_IFMT)) {
1084 return "directory";
1085 } elsif (S_ISLNK($mode)) {
1086 return "symlink";
1087 } elsif (S_ISREG($mode)) {
1088 return "file";
1089 } else {
1090 return "unknown";
1094 # convert file mode in octal to file type description string
1095 sub file_type_long {
1096 my $mode = shift;
1098 if ($mode !~ m/^[0-7]+$/) {
1099 return $mode;
1100 } else {
1101 $mode = oct $mode;
1104 if (S_ISGITLINK($mode)) {
1105 return "submodule";
1106 } elsif (S_ISDIR($mode & S_IFMT)) {
1107 return "directory";
1108 } elsif (S_ISLNK($mode)) {
1109 return "symlink";
1110 } elsif (S_ISREG($mode)) {
1111 if ($mode & S_IXUSR) {
1112 return "executable";
1113 } else {
1114 return "file";
1116 } else {
1117 return "unknown";
1122 ## ----------------------------------------------------------------------
1123 ## functions returning short HTML fragments, or transforming HTML fragments
1124 ## which don't belong to other sections
1126 # format line of commit message.
1127 sub format_log_line_html {
1128 my $line = shift;
1130 $line = esc_html($line, -nbsp=>1);
1131 if ($line =~ m/([0-9a-fA-F]{8,40})/) {
1132 my $hash_text = $1;
1133 my $link =
1134 $cgi->a({-href => href(action=>"object", hash=>$hash_text),
1135 -class => "text"}, $hash_text);
1136 $line =~ s/$hash_text/$link/;
1138 return $line;
1141 # format marker of refs pointing to given object
1143 # the destination action is chosen based on object type and current context:
1144 # - for annotated tags, we choose the tag view unless it's the current view
1145 # already, in which case we go to shortlog view
1146 # - for other refs, we keep the current view if we're in history, shortlog or
1147 # log view, and select shortlog otherwise
1148 sub format_ref_marker {
1149 my ($refs, $id) = @_;
1150 my $markers = '';
1152 if (defined $refs->{$id}) {
1153 foreach my $ref (@{$refs->{$id}}) {
1154 # this code exploits the fact that non-lightweight tags are the
1155 # only indirect objects, and that they are the only objects for which
1156 # we want to use tag instead of shortlog as action
1157 my ($type, $name) = qw();
1158 my $indirect = ($ref =~ s/\^\{\}$//);
1159 # e.g. tags/v2.6.11 or heads/next
1160 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1161 $type = $1;
1162 $name = $2;
1163 } else {
1164 $type = "ref";
1165 $name = $ref;
1168 my $class = $type;
1169 $class .= " indirect" if $indirect;
1171 my $dest_action = "shortlog";
1173 if ($indirect) {
1174 $dest_action = "tag" unless $action eq "tag";
1175 } elsif ($action =~ /^(history|(short)?log)$/) {
1176 $dest_action = $action;
1179 my $dest = "";
1180 $dest .= "refs/" unless $ref =~ m!^refs/!;
1181 $dest .= $ref;
1183 my $link = $cgi->a({
1184 -href => href(
1185 action=>$dest_action,
1186 hash=>$dest
1187 )}, $name);
1189 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1190 $link . "</span>";
1194 if ($markers) {
1195 return ' <span class="refs">'. $markers . '</span>';
1196 } else {
1197 return "";
1201 # format, perhaps shortened and with markers, title line
1202 sub format_subject_html {
1203 my ($long, $short, $href, $extra) = @_;
1204 $extra = '' unless defined($extra);
1206 if (length($short) < length($long)) {
1207 return $cgi->a({-href => $href, -class => "list subject",
1208 -title => to_utf8($long)},
1209 esc_html($short) . $extra);
1210 } else {
1211 return $cgi->a({-href => $href, -class => "list subject"},
1212 esc_html($long) . $extra);
1216 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1217 sub format_git_diff_header_line {
1218 my $line = shift;
1219 my $diffinfo = shift;
1220 my ($from, $to) = @_;
1222 if ($diffinfo->{'nparents'}) {
1223 # combined diff
1224 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1225 if ($to->{'href'}) {
1226 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1227 esc_path($to->{'file'}));
1228 } else { # file was deleted (no href)
1229 $line .= esc_path($to->{'file'});
1231 } else {
1232 # "ordinary" diff
1233 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1234 if ($from->{'href'}) {
1235 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1236 'a/' . esc_path($from->{'file'}));
1237 } else { # file was added (no href)
1238 $line .= 'a/' . esc_path($from->{'file'});
1240 $line .= ' ';
1241 if ($to->{'href'}) {
1242 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1243 'b/' . esc_path($to->{'file'}));
1244 } else { # file was deleted
1245 $line .= 'b/' . esc_path($to->{'file'});
1249 return "<div class=\"diff header\">$line</div>\n";
1252 # format extended diff header line, before patch itself
1253 sub format_extended_diff_header_line {
1254 my $line = shift;
1255 my $diffinfo = shift;
1256 my ($from, $to) = @_;
1258 # match <path>
1259 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1260 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1261 esc_path($from->{'file'}));
1263 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1264 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1265 esc_path($to->{'file'}));
1267 # match single <mode>
1268 if ($line =~ m/\s(\d{6})$/) {
1269 $line .= '<span class="info"> (' .
1270 file_type_long($1) .
1271 ')</span>';
1273 # match <hash>
1274 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1275 # can match only for combined diff
1276 $line = 'index ';
1277 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1278 if ($from->{'href'}[$i]) {
1279 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1280 -class=>"hash"},
1281 substr($diffinfo->{'from_id'}[$i],0,7));
1282 } else {
1283 $line .= '0' x 7;
1285 # separator
1286 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1288 $line .= '..';
1289 if ($to->{'href'}) {
1290 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1291 substr($diffinfo->{'to_id'},0,7));
1292 } else {
1293 $line .= '0' x 7;
1296 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1297 # can match only for ordinary diff
1298 my ($from_link, $to_link);
1299 if ($from->{'href'}) {
1300 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1301 substr($diffinfo->{'from_id'},0,7));
1302 } else {
1303 $from_link = '0' x 7;
1305 if ($to->{'href'}) {
1306 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1307 substr($diffinfo->{'to_id'},0,7));
1308 } else {
1309 $to_link = '0' x 7;
1311 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1312 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1315 return $line . "<br/>\n";
1318 # format from-file/to-file diff header
1319 sub format_diff_from_to_header {
1320 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1321 my $line;
1322 my $result = '';
1324 $line = $from_line;
1325 #assert($line =~ m/^---/) if DEBUG;
1326 # no extra formatting for "^--- /dev/null"
1327 if (! $diffinfo->{'nparents'}) {
1328 # ordinary (single parent) diff
1329 if ($line =~ m!^--- "?a/!) {
1330 if ($from->{'href'}) {
1331 $line = '--- a/' .
1332 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1333 esc_path($from->{'file'}));
1334 } else {
1335 $line = '--- a/' .
1336 esc_path($from->{'file'});
1339 $result .= qq!<div class="diff from_file">$line</div>\n!;
1341 } else {
1342 # combined diff (merge commit)
1343 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1344 if ($from->{'href'}[$i]) {
1345 $line = '--- ' .
1346 $cgi->a({-href=>href(action=>"blobdiff",
1347 hash_parent=>$diffinfo->{'from_id'}[$i],
1348 hash_parent_base=>$parents[$i],
1349 file_parent=>$from->{'file'}[$i],
1350 hash=>$diffinfo->{'to_id'},
1351 hash_base=>$hash,
1352 file_name=>$to->{'file'}),
1353 -class=>"path",
1354 -title=>"diff" . ($i+1)},
1355 $i+1) .
1356 '/' .
1357 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1358 esc_path($from->{'file'}[$i]));
1359 } else {
1360 $line = '--- /dev/null';
1362 $result .= qq!<div class="diff from_file">$line</div>\n!;
1366 $line = $to_line;
1367 #assert($line =~ m/^\+\+\+/) if DEBUG;
1368 # no extra formatting for "^+++ /dev/null"
1369 if ($line =~ m!^\+\+\+ "?b/!) {
1370 if ($to->{'href'}) {
1371 $line = '+++ b/' .
1372 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1373 esc_path($to->{'file'}));
1374 } else {
1375 $line = '+++ b/' .
1376 esc_path($to->{'file'});
1379 $result .= qq!<div class="diff to_file">$line</div>\n!;
1381 return $result;
1384 # create note for patch simplified by combined diff
1385 sub format_diff_cc_simplified {
1386 my ($diffinfo, @parents) = @_;
1387 my $result = '';
1389 $result .= "<div class=\"diff header\">" .
1390 "diff --cc ";
1391 if (!is_deleted($diffinfo)) {
1392 $result .= $cgi->a({-href => href(action=>"blob",
1393 hash_base=>$hash,
1394 hash=>$diffinfo->{'to_id'},
1395 file_name=>$diffinfo->{'to_file'}),
1396 -class => "path"},
1397 esc_path($diffinfo->{'to_file'}));
1398 } else {
1399 $result .= esc_path($diffinfo->{'to_file'});
1401 $result .= "</div>\n" . # class="diff header"
1402 "<div class=\"diff nodifferences\">" .
1403 "Simple merge" .
1404 "</div>\n"; # class="diff nodifferences"
1406 return $result;
1409 # format patch (diff) line (not to be used for diff headers)
1410 sub format_diff_line {
1411 my $line = shift;
1412 my ($from, $to) = @_;
1413 my $diff_class = "";
1415 chomp $line;
1417 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1418 # combined diff
1419 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1420 if ($line =~ m/^\@{3}/) {
1421 $diff_class = " chunk_header";
1422 } elsif ($line =~ m/^\\/) {
1423 $diff_class = " incomplete";
1424 } elsif ($prefix =~ tr/+/+/) {
1425 $diff_class = " add";
1426 } elsif ($prefix =~ tr/-/-/) {
1427 $diff_class = " rem";
1429 } else {
1430 # assume ordinary diff
1431 my $char = substr($line, 0, 1);
1432 if ($char eq '+') {
1433 $diff_class = " add";
1434 } elsif ($char eq '-') {
1435 $diff_class = " rem";
1436 } elsif ($char eq '@') {
1437 $diff_class = " chunk_header";
1438 } elsif ($char eq "\\") {
1439 $diff_class = " incomplete";
1442 $line = untabify($line);
1443 if ($from && $to && $line =~ m/^\@{2} /) {
1444 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1445 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1447 $from_lines = 0 unless defined $from_lines;
1448 $to_lines = 0 unless defined $to_lines;
1450 if ($from->{'href'}) {
1451 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1452 -class=>"list"}, $from_text);
1454 if ($to->{'href'}) {
1455 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1456 -class=>"list"}, $to_text);
1458 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1459 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1460 return "<div class=\"diff$diff_class\">$line</div>\n";
1461 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1462 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1463 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1465 @from_text = split(' ', $ranges);
1466 for (my $i = 0; $i < @from_text; ++$i) {
1467 ($from_start[$i], $from_nlines[$i]) =
1468 (split(',', substr($from_text[$i], 1)), 0);
1471 $to_text = pop @from_text;
1472 $to_start = pop @from_start;
1473 $to_nlines = pop @from_nlines;
1475 $line = "<span class=\"chunk_info\">$prefix ";
1476 for (my $i = 0; $i < @from_text; ++$i) {
1477 if ($from->{'href'}[$i]) {
1478 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1479 -class=>"list"}, $from_text[$i]);
1480 } else {
1481 $line .= $from_text[$i];
1483 $line .= " ";
1485 if ($to->{'href'}) {
1486 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1487 -class=>"list"}, $to_text);
1488 } else {
1489 $line .= $to_text;
1491 $line .= " $prefix</span>" .
1492 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1493 return "<div class=\"diff$diff_class\">$line</div>\n";
1495 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1498 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1499 # linked. Pass the hash of the tree/commit to snapshot.
1500 sub format_snapshot_links {
1501 my ($hash) = @_;
1502 my @snapshot_fmts = gitweb_check_feature('snapshot');
1503 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1504 my $num_fmts = @snapshot_fmts;
1505 if ($num_fmts > 1) {
1506 # A parenthesized list of links bearing format names.
1507 # e.g. "snapshot (_tar.gz_ _zip_)"
1508 return "snapshot (" . join(' ', map
1509 $cgi->a({
1510 -href => href(
1511 action=>"snapshot",
1512 hash=>$hash,
1513 snapshot_format=>$_
1515 }, $known_snapshot_formats{$_}{'display'})
1516 , @snapshot_fmts) . ")";
1517 } elsif ($num_fmts == 1) {
1518 # A single "snapshot" link whose tooltip bears the format name.
1519 # i.e. "_snapshot_"
1520 my ($fmt) = @snapshot_fmts;
1521 return
1522 $cgi->a({
1523 -href => href(
1524 action=>"snapshot",
1525 hash=>$hash,
1526 snapshot_format=>$fmt
1528 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1529 }, "snapshot");
1530 } else { # $num_fmts == 0
1531 return undef;
1535 ## ......................................................................
1536 ## functions returning values to be passed, perhaps after some
1537 ## transformation, to other functions; e.g. returning arguments to href()
1539 # returns hash to be passed to href to generate gitweb URL
1540 # in -title key it returns description of link
1541 sub get_feed_info {
1542 my $format = shift || 'Atom';
1543 my %res = (action => lc($format));
1545 # feed links are possible only for project views
1546 return unless (defined $project);
1547 # some views should link to OPML, or to generic project feed,
1548 # or don't have specific feed yet (so they should use generic)
1549 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1551 my $branch;
1552 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1553 # from tag links; this also makes possible to detect branch links
1554 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1555 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1556 $branch = $1;
1558 # find log type for feed description (title)
1559 my $type = 'log';
1560 if (defined $file_name) {
1561 $type = "history of $file_name";
1562 $type .= "/" if ($action eq 'tree');
1563 $type .= " on '$branch'" if (defined $branch);
1564 } else {
1565 $type = "log of $branch" if (defined $branch);
1568 $res{-title} = $type;
1569 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
1570 $res{'file_name'} = $file_name;
1572 return %res;
1575 ## ----------------------------------------------------------------------
1576 ## git utility subroutines, invoking git commands
1578 # returns path to the core git executable and the --git-dir parameter as list
1579 sub git_cmd {
1580 return $GIT, '--git-dir='.$git_dir;
1583 # quote the given arguments for passing them to the shell
1584 # quote_command("command", "arg 1", "arg with ' and ! characters")
1585 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
1586 # Try to avoid using this function wherever possible.
1587 sub quote_command {
1588 return join(' ',
1589 map( { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ ));
1592 # get HEAD ref of given project as hash
1593 sub git_get_head_hash {
1594 my $project = shift;
1595 my $o_git_dir = $git_dir;
1596 my $retval = undef;
1597 $git_dir = "$projectroot/$project";
1598 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1599 my $head = <$fd>;
1600 close $fd;
1601 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1602 $retval = $1;
1605 if (defined $o_git_dir) {
1606 $git_dir = $o_git_dir;
1608 return $retval;
1611 # get type of given object
1612 sub git_get_type {
1613 my $hash = shift;
1615 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1616 my $type = <$fd>;
1617 close $fd or return;
1618 chomp $type;
1619 return $type;
1622 # repository configuration
1623 our $config_file = '';
1624 our %config;
1626 # store multiple values for single key as anonymous array reference
1627 # single values stored directly in the hash, not as [ <value> ]
1628 sub hash_set_multi {
1629 my ($hash, $key, $value) = @_;
1631 if (!exists $hash->{$key}) {
1632 $hash->{$key} = $value;
1633 } elsif (!ref $hash->{$key}) {
1634 $hash->{$key} = [ $hash->{$key}, $value ];
1635 } else {
1636 push @{$hash->{$key}}, $value;
1640 # return hash of git project configuration
1641 # optionally limited to some section, e.g. 'gitweb'
1642 sub git_parse_project_config {
1643 my $section_regexp = shift;
1644 my %config;
1646 local $/ = "\0";
1648 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
1649 or return;
1651 while (my $keyval = <$fh>) {
1652 chomp $keyval;
1653 my ($key, $value) = split(/\n/, $keyval, 2);
1655 hash_set_multi(\%config, $key, $value)
1656 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
1658 close $fh;
1660 return %config;
1663 # convert config value to boolean, 'true' or 'false'
1664 # no value, number > 0, 'true' and 'yes' values are true
1665 # rest of values are treated as false (never as error)
1666 sub config_to_bool {
1667 my $val = shift;
1669 # strip leading and trailing whitespace
1670 $val =~ s/^\s+//;
1671 $val =~ s/\s+$//;
1673 return (!defined $val || # section.key
1674 ($val =~ /^\d+$/ && $val) || # section.key = 1
1675 ($val =~ /^(?:true|yes)$/i)); # section.key = true
1678 # convert config value to simple decimal number
1679 # an optional value suffix of 'k', 'm', or 'g' will cause the value
1680 # to be multiplied by 1024, 1048576, or 1073741824
1681 sub config_to_int {
1682 my $val = shift;
1684 # strip leading and trailing whitespace
1685 $val =~ s/^\s+//;
1686 $val =~ s/\s+$//;
1688 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
1689 $unit = lc($unit);
1690 # unknown unit is treated as 1
1691 return $num * ($unit eq 'g' ? 1073741824 :
1692 $unit eq 'm' ? 1048576 :
1693 $unit eq 'k' ? 1024 : 1);
1695 return $val;
1698 # convert config value to array reference, if needed
1699 sub config_to_multi {
1700 my $val = shift;
1702 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
1705 sub git_get_project_config {
1706 my ($key, $type) = @_;
1708 # key sanity check
1709 return unless ($key);
1710 $key =~ s/^gitweb\.//;
1711 return if ($key =~ m/\W/);
1713 # type sanity check
1714 if (defined $type) {
1715 $type =~ s/^--//;
1716 $type = undef
1717 unless ($type eq 'bool' || $type eq 'int');
1720 # get config
1721 if (!defined $config_file ||
1722 $config_file ne "$git_dir/config") {
1723 %config = git_parse_project_config('gitweb');
1724 $config_file = "$git_dir/config";
1727 # ensure given type
1728 if (!defined $type) {
1729 return $config{"gitweb.$key"};
1730 } elsif ($type eq 'bool') {
1731 # backward compatibility: 'git config --bool' returns true/false
1732 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
1733 } elsif ($type eq 'int') {
1734 return config_to_int($config{"gitweb.$key"});
1736 return $config{"gitweb.$key"};
1739 # get hash of given path at given ref
1740 sub git_get_hash_by_path {
1741 my $base = shift;
1742 my $path = shift || return undef;
1743 my $type = shift;
1745 $path =~ s,/+$,,;
1747 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1748 or die_error(500, "Open git-ls-tree failed");
1749 my $line = <$fd>;
1750 close $fd or return undef;
1752 if (!defined $line) {
1753 # there is no tree or hash given by $path at $base
1754 return undef;
1757 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
1758 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1759 if (defined $type && $type ne $2) {
1760 # type doesn't match
1761 return undef;
1763 return $3;
1766 # get path of entry with given hash at given tree-ish (ref)
1767 # used to get 'from' filename for combined diff (merge commit) for renames
1768 sub git_get_path_by_hash {
1769 my $base = shift || return;
1770 my $hash = shift || return;
1772 local $/ = "\0";
1774 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1775 or return undef;
1776 while (my $line = <$fd>) {
1777 chomp $line;
1779 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
1780 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
1781 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1782 close $fd;
1783 return $1;
1786 close $fd;
1787 return undef;
1790 ## ......................................................................
1791 ## git utility functions, directly accessing git repository
1793 sub git_get_project_description {
1794 my $path = shift;
1796 $git_dir = "$projectroot/$path";
1797 open my $fd, "$git_dir/description"
1798 or return git_get_project_config('description');
1799 my $descr = <$fd>;
1800 close $fd;
1801 if (defined $descr) {
1802 chomp $descr;
1804 return $descr;
1807 sub git_get_project_ctags {
1808 my $path = shift;
1809 my $ctags = {};
1811 $git_dir = "$projectroot/$path";
1812 foreach (<$git_dir/ctags/*>) {
1813 open CT, $_ or next;
1814 my $val = <CT>;
1815 chomp $val;
1816 close CT;
1817 my $ctag = $_; $ctag =~ s#.*/##;
1818 $ctags->{$ctag} = $val;
1820 $ctags;
1823 sub git_populate_project_tagcloud {
1824 my $ctags = shift;
1826 # First, merge different-cased tags; tags vote on casing
1827 my %ctags_lc;
1828 foreach (keys %$ctags) {
1829 $ctags_lc{lc $_}->{count} += $ctags->{$_};
1830 if (not $ctags_lc{lc $_}->{topcount}
1831 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
1832 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
1833 $ctags_lc{lc $_}->{topname} = $_;
1837 my $cloud;
1838 if (eval { require HTML::TagCloud; 1; }) {
1839 $cloud = HTML::TagCloud->new;
1840 foreach (sort keys %ctags_lc) {
1841 # Pad the title with spaces so that the cloud looks
1842 # less crammed.
1843 my $title = $ctags_lc{$_}->{topname};
1844 $title =~ s/ /&nbsp;/g;
1845 $title =~ s/^/&nbsp;/g;
1846 $title =~ s/$/&nbsp;/g;
1847 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
1849 } else {
1850 $cloud = \%ctags_lc;
1852 $cloud;
1855 sub git_show_project_tagcloud {
1856 my ($cloud, $count) = @_;
1857 print STDERR ref($cloud)."..\n";
1858 if (ref $cloud eq 'HTML::TagCloud') {
1859 return $cloud->html_and_css($count);
1860 } else {
1861 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
1862 return '<p align="center">' . join (', ', map {
1863 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
1864 } splice(@tags, 0, $count)) . '</p>';
1868 sub git_get_project_url_list {
1869 my $path = shift;
1871 $git_dir = "$projectroot/$path";
1872 open my $fd, "$git_dir/cloneurl"
1873 or return wantarray ?
1874 @{ config_to_multi(git_get_project_config('url')) } :
1875 config_to_multi(git_get_project_config('url'));
1876 my @git_project_url_list = map { chomp; $_ } <$fd>;
1877 close $fd;
1879 return wantarray ? @git_project_url_list : \@git_project_url_list;
1882 sub git_get_projects_list {
1883 my ($filter) = @_;
1884 my @list;
1886 $filter ||= '';
1887 $filter =~ s/\.git$//;
1889 my ($check_forks) = gitweb_check_feature('forks');
1891 if (-d $projects_list) {
1892 # search in directory
1893 my $dir = $projects_list . ($filter ? "/$filter" : '');
1894 # remove the trailing "/"
1895 $dir =~ s!/+$!!;
1896 my $pfxlen = length("$dir");
1897 my $pfxdepth = ($dir =~ tr!/!!);
1899 File::Find::find({
1900 follow_fast => 1, # follow symbolic links
1901 follow_skip => 2, # ignore duplicates
1902 dangling_symlinks => 0, # ignore dangling symlinks, silently
1903 wanted => sub {
1904 # skip project-list toplevel, if we get it.
1905 return if (m!^[/.]$!);
1906 # only directories can be git repositories
1907 return unless (-d $_);
1908 # don't traverse too deep (Find is super slow on os x)
1909 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
1910 $File::Find::prune = 1;
1911 return;
1914 my $subdir = substr($File::Find::name, $pfxlen + 1);
1915 # we check related file in $projectroot
1916 if (check_export_ok("$projectroot/$filter/$subdir")) {
1917 push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1918 $File::Find::prune = 1;
1921 }, "$dir");
1923 } elsif (-f $projects_list) {
1924 # read from file(url-encoded):
1925 # 'git%2Fgit.git Linus+Torvalds'
1926 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1927 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1928 my %paths;
1929 open my ($fd), $projects_list or return;
1930 PROJECT:
1931 while (my $line = <$fd>) {
1932 chomp $line;
1933 my ($path, $owner) = split ' ', $line;
1934 $path = unescape($path);
1935 $owner = unescape($owner);
1936 if (!defined $path) {
1937 next;
1939 if ($filter ne '') {
1940 # looking for forks;
1941 my $pfx = substr($path, 0, length($filter));
1942 if ($pfx ne $filter) {
1943 next PROJECT;
1945 my $sfx = substr($path, length($filter));
1946 if ($sfx !~ /^\/.*\.git$/) {
1947 next PROJECT;
1949 } elsif ($check_forks) {
1950 PATH:
1951 foreach my $filter (keys %paths) {
1952 # looking for forks;
1953 my $pfx = substr($path, 0, length($filter));
1954 if ($pfx ne $filter) {
1955 next PATH;
1957 my $sfx = substr($path, length($filter));
1958 if ($sfx !~ /^\/.*\.git$/) {
1959 next PATH;
1961 # is a fork, don't include it in
1962 # the list
1963 next PROJECT;
1966 if (check_export_ok("$projectroot/$path")) {
1967 my $pr = {
1968 path => $path,
1969 owner => to_utf8($owner),
1971 push @list, $pr;
1972 (my $forks_path = $path) =~ s/\.git$//;
1973 $paths{$forks_path}++;
1976 close $fd;
1978 return @list;
1981 our $gitweb_project_owner = undef;
1982 sub git_get_project_list_from_file {
1984 return if (defined $gitweb_project_owner);
1986 $gitweb_project_owner = {};
1987 # read from file (url-encoded):
1988 # 'git%2Fgit.git Linus+Torvalds'
1989 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1990 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1991 if (-f $projects_list) {
1992 open (my $fd , $projects_list);
1993 while (my $line = <$fd>) {
1994 chomp $line;
1995 my ($pr, $ow) = split ' ', $line;
1996 $pr = unescape($pr);
1997 $ow = unescape($ow);
1998 $gitweb_project_owner->{$pr} = to_utf8($ow);
2000 close $fd;
2004 sub git_get_project_owner {
2005 my $project = shift;
2006 my $owner;
2008 return undef unless $project;
2009 $git_dir = "$projectroot/$project";
2011 if (!defined $gitweb_project_owner) {
2012 git_get_project_list_from_file();
2015 if (exists $gitweb_project_owner->{$project}) {
2016 $owner = $gitweb_project_owner->{$project};
2018 if (!defined $owner){
2019 $owner = git_get_project_config('owner');
2021 if (!defined $owner) {
2022 $owner = get_file_owner("$git_dir");
2025 return $owner;
2028 sub git_get_last_activity {
2029 my ($path) = @_;
2030 my $fd;
2032 $git_dir = "$projectroot/$path";
2033 open($fd, "-|", git_cmd(), 'for-each-ref',
2034 '--format=%(committer)',
2035 '--sort=-committerdate',
2036 '--count=1',
2037 'refs/heads') or return;
2038 my $most_recent = <$fd>;
2039 close $fd or return;
2040 if (defined $most_recent &&
2041 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2042 my $timestamp = $1;
2043 my $age = time - $timestamp;
2044 return ($age, age_string($age));
2046 return (undef, undef);
2049 sub git_get_references {
2050 my $type = shift || "";
2051 my %refs;
2052 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2053 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2054 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2055 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2056 or return;
2058 while (my $line = <$fd>) {
2059 chomp $line;
2060 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2061 if (defined $refs{$1}) {
2062 push @{$refs{$1}}, $2;
2063 } else {
2064 $refs{$1} = [ $2 ];
2068 close $fd or return;
2069 return \%refs;
2072 sub git_get_rev_name_tags {
2073 my $hash = shift || return undef;
2075 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2076 or return;
2077 my $name_rev = <$fd>;
2078 close $fd;
2080 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2081 return $1;
2082 } else {
2083 # catches also '$hash undefined' output
2084 return undef;
2088 ## ----------------------------------------------------------------------
2089 ## parse to hash functions
2091 sub parse_date {
2092 my $epoch = shift;
2093 my $tz = shift || "-0000";
2095 my %date;
2096 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2097 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2098 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2099 $date{'hour'} = $hour;
2100 $date{'minute'} = $min;
2101 $date{'mday'} = $mday;
2102 $date{'day'} = $days[$wday];
2103 $date{'month'} = $months[$mon];
2104 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2105 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2106 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2107 $mday, $months[$mon], $hour ,$min;
2108 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2109 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2111 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2112 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2113 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2114 $date{'hour_local'} = $hour;
2115 $date{'minute_local'} = $min;
2116 $date{'tz_local'} = $tz;
2117 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2118 1900+$year, $mon+1, $mday,
2119 $hour, $min, $sec, $tz);
2120 return %date;
2123 sub parse_tag {
2124 my $tag_id = shift;
2125 my %tag;
2126 my @comment;
2128 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2129 $tag{'id'} = $tag_id;
2130 while (my $line = <$fd>) {
2131 chomp $line;
2132 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2133 $tag{'object'} = $1;
2134 } elsif ($line =~ m/^type (.+)$/) {
2135 $tag{'type'} = $1;
2136 } elsif ($line =~ m/^tag (.+)$/) {
2137 $tag{'name'} = $1;
2138 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2139 $tag{'author'} = $1;
2140 $tag{'epoch'} = $2;
2141 $tag{'tz'} = $3;
2142 } elsif ($line =~ m/--BEGIN/) {
2143 push @comment, $line;
2144 last;
2145 } elsif ($line eq "") {
2146 last;
2149 push @comment, <$fd>;
2150 $tag{'comment'} = \@comment;
2151 close $fd or return;
2152 if (!defined $tag{'name'}) {
2153 return
2155 return %tag
2158 sub parse_commit_text {
2159 my ($commit_text, $withparents) = @_;
2160 my @commit_lines = split '\n', $commit_text;
2161 my %co;
2163 pop @commit_lines; # Remove '\0'
2165 if (! @commit_lines) {
2166 return;
2169 my $header = shift @commit_lines;
2170 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2171 return;
2173 ($co{'id'}, my @parents) = split ' ', $header;
2174 while (my $line = shift @commit_lines) {
2175 last if $line eq "\n";
2176 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2177 $co{'tree'} = $1;
2178 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2179 push @parents, $1;
2180 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2181 $co{'author'} = $1;
2182 $co{'author_epoch'} = $2;
2183 $co{'author_tz'} = $3;
2184 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2185 $co{'author_name'} = $1;
2186 $co{'author_email'} = $2;
2187 } else {
2188 $co{'author_name'} = $co{'author'};
2190 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2191 $co{'committer'} = $1;
2192 $co{'committer_epoch'} = $2;
2193 $co{'committer_tz'} = $3;
2194 $co{'committer_name'} = $co{'committer'};
2195 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2196 $co{'committer_name'} = $1;
2197 $co{'committer_email'} = $2;
2198 } else {
2199 $co{'committer_name'} = $co{'committer'};
2203 if (!defined $co{'tree'}) {
2204 return;
2206 $co{'parents'} = \@parents;
2207 $co{'parent'} = $parents[0];
2209 foreach my $title (@commit_lines) {
2210 $title =~ s/^ //;
2211 if ($title ne "") {
2212 $co{'title'} = chop_str($title, 80, 5);
2213 # remove leading stuff of merges to make the interesting part visible
2214 if (length($title) > 50) {
2215 $title =~ s/^Automatic //;
2216 $title =~ s/^merge (of|with) /Merge ... /i;
2217 if (length($title) > 50) {
2218 $title =~ s/(http|rsync):\/\///;
2220 if (length($title) > 50) {
2221 $title =~ s/(master|www|rsync)\.//;
2223 if (length($title) > 50) {
2224 $title =~ s/kernel.org:?//;
2226 if (length($title) > 50) {
2227 $title =~ s/\/pub\/scm//;
2230 $co{'title_short'} = chop_str($title, 50, 5);
2231 last;
2234 if (! defined $co{'title'} || $co{'title'} eq "") {
2235 $co{'title'} = $co{'title_short'} = '(no commit message)';
2237 # remove added spaces
2238 foreach my $line (@commit_lines) {
2239 $line =~ s/^ //;
2241 $co{'comment'} = \@commit_lines;
2243 my $age = time - $co{'committer_epoch'};
2244 $co{'age'} = $age;
2245 $co{'age_string'} = age_string($age);
2246 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2247 if ($age > 60*60*24*7*2) {
2248 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2249 $co{'age_string_age'} = $co{'age_string'};
2250 } else {
2251 $co{'age_string_date'} = $co{'age_string'};
2252 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2254 return %co;
2257 sub parse_commit {
2258 my ($commit_id) = @_;
2259 my %co;
2261 local $/ = "\0";
2263 open my $fd, "-|", git_cmd(), "rev-list",
2264 "--parents",
2265 "--header",
2266 "--max-count=1",
2267 $commit_id,
2268 "--",
2269 or die_error(500, "Open git-rev-list failed");
2270 %co = parse_commit_text(<$fd>, 1);
2271 close $fd;
2273 return %co;
2276 sub parse_commits {
2277 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2278 my @cos;
2280 $maxcount ||= 1;
2281 $skip ||= 0;
2283 local $/ = "\0";
2285 open my $fd, "-|", git_cmd(), "rev-list",
2286 "--header",
2287 @args,
2288 ("--max-count=" . $maxcount),
2289 ("--skip=" . $skip),
2290 @extra_options,
2291 $commit_id,
2292 "--",
2293 ($filename ? ($filename) : ())
2294 or die_error(500, "Open git-rev-list failed");
2295 while (my $line = <$fd>) {
2296 my %co = parse_commit_text($line);
2297 push @cos, \%co;
2299 close $fd;
2301 return wantarray ? @cos : \@cos;
2304 # parse line of git-diff-tree "raw" output
2305 sub parse_difftree_raw_line {
2306 my $line = shift;
2307 my %res;
2309 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2310 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2311 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2312 $res{'from_mode'} = $1;
2313 $res{'to_mode'} = $2;
2314 $res{'from_id'} = $3;
2315 $res{'to_id'} = $4;
2316 $res{'status'} = $5;
2317 $res{'similarity'} = $6;
2318 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2319 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2320 } else {
2321 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2324 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2325 # combined diff (for merge commit)
2326 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2327 $res{'nparents'} = length($1);
2328 $res{'from_mode'} = [ split(' ', $2) ];
2329 $res{'to_mode'} = pop @{$res{'from_mode'}};
2330 $res{'from_id'} = [ split(' ', $3) ];
2331 $res{'to_id'} = pop @{$res{'from_id'}};
2332 $res{'status'} = [ split('', $4) ];
2333 $res{'to_file'} = unquote($5);
2335 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2336 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2337 $res{'commit'} = $1;
2340 return wantarray ? %res : \%res;
2343 # wrapper: return parsed line of git-diff-tree "raw" output
2344 # (the argument might be raw line, or parsed info)
2345 sub parsed_difftree_line {
2346 my $line_or_ref = shift;
2348 if (ref($line_or_ref) eq "HASH") {
2349 # pre-parsed (or generated by hand)
2350 return $line_or_ref;
2351 } else {
2352 return parse_difftree_raw_line($line_or_ref);
2356 # parse line of git-ls-tree output
2357 sub parse_ls_tree_line ($;%) {
2358 my $line = shift;
2359 my %opts = @_;
2360 my %res;
2362 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2363 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2365 $res{'mode'} = $1;
2366 $res{'type'} = $2;
2367 $res{'hash'} = $3;
2368 if ($opts{'-z'}) {
2369 $res{'name'} = $4;
2370 } else {
2371 $res{'name'} = unquote($4);
2374 return wantarray ? %res : \%res;
2377 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2378 sub parse_from_to_diffinfo {
2379 my ($diffinfo, $from, $to, @parents) = @_;
2381 if ($diffinfo->{'nparents'}) {
2382 # combined diff
2383 $from->{'file'} = [];
2384 $from->{'href'} = [];
2385 fill_from_file_info($diffinfo, @parents)
2386 unless exists $diffinfo->{'from_file'};
2387 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2388 $from->{'file'}[$i] =
2389 defined $diffinfo->{'from_file'}[$i] ?
2390 $diffinfo->{'from_file'}[$i] :
2391 $diffinfo->{'to_file'};
2392 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2393 $from->{'href'}[$i] = href(action=>"blob",
2394 hash_base=>$parents[$i],
2395 hash=>$diffinfo->{'from_id'}[$i],
2396 file_name=>$from->{'file'}[$i]);
2397 } else {
2398 $from->{'href'}[$i] = undef;
2401 } else {
2402 # ordinary (not combined) diff
2403 $from->{'file'} = $diffinfo->{'from_file'};
2404 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2405 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2406 hash=>$diffinfo->{'from_id'},
2407 file_name=>$from->{'file'});
2408 } else {
2409 delete $from->{'href'};
2413 $to->{'file'} = $diffinfo->{'to_file'};
2414 if (!is_deleted($diffinfo)) { # file exists in result
2415 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2416 hash=>$diffinfo->{'to_id'},
2417 file_name=>$to->{'file'});
2418 } else {
2419 delete $to->{'href'};
2423 ## ......................................................................
2424 ## parse to array of hashes functions
2426 sub git_get_heads_list {
2427 my $limit = shift;
2428 my @headslist;
2430 open my $fd, '-|', git_cmd(), 'for-each-ref',
2431 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2432 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2433 'refs/heads'
2434 or return;
2435 while (my $line = <$fd>) {
2436 my %ref_item;
2438 chomp $line;
2439 my ($refinfo, $committerinfo) = split(/\0/, $line);
2440 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2441 my ($committer, $epoch, $tz) =
2442 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2443 $ref_item{'fullname'} = $name;
2444 $name =~ s!^refs/heads/!!;
2446 $ref_item{'name'} = $name;
2447 $ref_item{'id'} = $hash;
2448 $ref_item{'title'} = $title || '(no commit message)';
2449 $ref_item{'epoch'} = $epoch;
2450 if ($epoch) {
2451 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2452 } else {
2453 $ref_item{'age'} = "unknown";
2456 push @headslist, \%ref_item;
2458 close $fd;
2460 return wantarray ? @headslist : \@headslist;
2463 sub git_get_tags_list {
2464 my $limit = shift;
2465 my @tagslist;
2467 open my $fd, '-|', git_cmd(), 'for-each-ref',
2468 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2469 '--format=%(objectname) %(objecttype) %(refname) '.
2470 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2471 'refs/tags'
2472 or return;
2473 while (my $line = <$fd>) {
2474 my %ref_item;
2476 chomp $line;
2477 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2478 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2479 my ($creator, $epoch, $tz) =
2480 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2481 $ref_item{'fullname'} = $name;
2482 $name =~ s!^refs/tags/!!;
2484 $ref_item{'type'} = $type;
2485 $ref_item{'id'} = $id;
2486 $ref_item{'name'} = $name;
2487 if ($type eq "tag") {
2488 $ref_item{'subject'} = $title;
2489 $ref_item{'reftype'} = $reftype;
2490 $ref_item{'refid'} = $refid;
2491 } else {
2492 $ref_item{'reftype'} = $type;
2493 $ref_item{'refid'} = $id;
2496 if ($type eq "tag" || $type eq "commit") {
2497 $ref_item{'epoch'} = $epoch;
2498 if ($epoch) {
2499 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2500 } else {
2501 $ref_item{'age'} = "unknown";
2505 push @tagslist, \%ref_item;
2507 close $fd;
2509 return wantarray ? @tagslist : \@tagslist;
2512 ## ----------------------------------------------------------------------
2513 ## filesystem-related functions
2515 sub get_file_owner {
2516 my $path = shift;
2518 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2519 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2520 if (!defined $gcos) {
2521 return undef;
2523 my $owner = $gcos;
2524 $owner =~ s/[,;].*$//;
2525 return to_utf8($owner);
2528 ## ......................................................................
2529 ## mimetype related functions
2531 sub mimetype_guess_file {
2532 my $filename = shift;
2533 my $mimemap = shift;
2534 -r $mimemap or return undef;
2536 my %mimemap;
2537 open(MIME, $mimemap) or return undef;
2538 while (<MIME>) {
2539 next if m/^#/; # skip comments
2540 my ($mime, $exts) = split(/\t+/);
2541 if (defined $exts) {
2542 my @exts = split(/\s+/, $exts);
2543 foreach my $ext (@exts) {
2544 $mimemap{$ext} = $mime;
2548 close(MIME);
2550 $filename =~ /\.([^.]*)$/;
2551 return $mimemap{$1};
2554 sub mimetype_guess {
2555 my $filename = shift;
2556 my $mime;
2557 $filename =~ /\./ or return undef;
2559 if ($mimetypes_file) {
2560 my $file = $mimetypes_file;
2561 if ($file !~ m!^/!) { # if it is relative path
2562 # it is relative to project
2563 $file = "$projectroot/$project/$file";
2565 $mime = mimetype_guess_file($filename, $file);
2567 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2568 return $mime;
2571 sub blob_mimetype {
2572 my $fd = shift;
2573 my $filename = shift;
2575 if ($filename) {
2576 my $mime = mimetype_guess($filename);
2577 $mime and return $mime;
2580 # just in case
2581 return $default_blob_plain_mimetype unless $fd;
2583 if (-T $fd) {
2584 return 'text/plain';
2585 } elsif (! $filename) {
2586 return 'application/octet-stream';
2587 } elsif ($filename =~ m/\.png$/i) {
2588 return 'image/png';
2589 } elsif ($filename =~ m/\.gif$/i) {
2590 return 'image/gif';
2591 } elsif ($filename =~ m/\.jpe?g$/i) {
2592 return 'image/jpeg';
2593 } else {
2594 return 'application/octet-stream';
2598 sub blob_contenttype {
2599 my ($fd, $file_name, $type) = @_;
2601 $type ||= blob_mimetype($fd, $file_name);
2602 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
2603 $type .= "; charset=$default_text_plain_charset";
2606 return $type;
2609 ## ======================================================================
2610 ## functions printing HTML: header, footer, error page
2612 sub git_header_html {
2613 my $status = shift || "200 OK";
2614 my $expires = shift;
2616 my $title = "$site_name";
2617 if (defined $project) {
2618 $title .= " - " . to_utf8($project);
2619 if (defined $action) {
2620 $title .= "/$action";
2621 if (defined $file_name) {
2622 $title .= " - " . esc_path($file_name);
2623 if ($action eq "tree" && $file_name !~ m|/$|) {
2624 $title .= "/";
2629 my $content_type;
2630 # require explicit support from the UA if we are to send the page as
2631 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2632 # we have to do this because MSIE sometimes globs '*/*', pretending to
2633 # support xhtml+xml but choking when it gets what it asked for.
2634 if (defined $cgi->http('HTTP_ACCEPT') &&
2635 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2636 $cgi->Accept('application/xhtml+xml') != 0) {
2637 $content_type = 'application/xhtml+xml';
2638 } else {
2639 $content_type = 'text/html';
2641 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2642 -status=> $status, -expires => $expires);
2643 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2644 print <<EOF;
2645 <?xml version="1.0" encoding="utf-8"?>
2646 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2647 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2648 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2649 <!-- git core binaries version $git_version -->
2650 <head>
2651 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2652 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2653 <meta name="robots" content="index, nofollow"/>
2654 <title>$title</title>
2655 <script type="text/javascript">/* <![CDATA[ */
2656 function fixBlameLinks() {
2657 var allLinks = document.getElementsByTagName("a");
2658 for (var i = 0; i < allLinks.length; i++) {
2659 var link = allLinks.item(i);
2660 if (link.className == 'blamelink')
2661 link.href = link.href.replace("a=blame", "a=blame_incremental");
2664 /* ]]> */</script>
2666 # print out each stylesheet that exist
2667 if (defined $stylesheet) {
2668 #provides backwards capability for those people who define style sheet in a config file
2669 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2670 } else {
2671 foreach my $stylesheet (@stylesheets) {
2672 next unless $stylesheet;
2673 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2676 if (defined $project) {
2677 my %href_params = get_feed_info();
2678 if (!exists $href_params{'-title'}) {
2679 $href_params{'-title'} = 'log';
2682 foreach my $format qw(RSS Atom) {
2683 my $type = lc($format);
2684 my %link_attr = (
2685 '-rel' => 'alternate',
2686 '-title' => "$project - $href_params{'-title'} - $format feed",
2687 '-type' => "application/$type+xml"
2690 $href_params{'action'} = $type;
2691 $link_attr{'-href'} = href(%href_params);
2692 print "<link ".
2693 "rel=\"$link_attr{'-rel'}\" ".
2694 "title=\"$link_attr{'-title'}\" ".
2695 "href=\"$link_attr{'-href'}\" ".
2696 "type=\"$link_attr{'-type'}\" ".
2697 "/>\n";
2699 $href_params{'extra_options'} = '--no-merges';
2700 $link_attr{'-href'} = href(%href_params);
2701 $link_attr{'-title'} .= ' (no merges)';
2702 print "<link ".
2703 "rel=\"$link_attr{'-rel'}\" ".
2704 "title=\"$link_attr{'-title'}\" ".
2705 "href=\"$link_attr{'-href'}\" ".
2706 "type=\"$link_attr{'-type'}\" ".
2707 "/>\n";
2710 } else {
2711 printf('<link rel="alternate" title="%s projects list" '.
2712 'href="%s" type="text/plain; charset=utf-8" />'."\n",
2713 $site_name, href(project=>undef, action=>"project_index"));
2714 printf('<link rel="alternate" title="%s projects feeds" '.
2715 'href="%s" type="text/x-opml" />'."\n",
2716 $site_name, href(project=>undef, action=>"opml"));
2718 if (defined $favicon) {
2719 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
2722 if (defined $gitwebjs) {
2723 print qq(<script src="$gitwebjs" type="text/javascript"></script>\n);
2726 print "</head>\n" .
2727 "<body onload=\"fixBlameLinks();\">\n";
2729 if (-f $site_header) {
2730 open (my $fd, $site_header);
2731 print <$fd>;
2732 close $fd;
2735 print "<div class=\"page_header\">\n" .
2736 $cgi->a({-href => esc_url($logo_url),
2737 -title => $logo_label},
2738 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2739 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2740 if (defined $project) {
2741 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2742 if (defined $action) {
2743 print " / $action";
2745 print "\n";
2747 print "</div>\n";
2749 my ($have_search) = gitweb_check_feature('search');
2750 if (defined $project && $have_search) {
2751 if (!defined $searchtext) {
2752 $searchtext = "";
2754 my $search_hash;
2755 if (defined $hash_base) {
2756 $search_hash = $hash_base;
2757 } elsif (defined $hash) {
2758 $search_hash = $hash;
2759 } else {
2760 $search_hash = "HEAD";
2762 my $action = $my_uri;
2763 my ($use_pathinfo) = gitweb_check_feature('pathinfo');
2764 if ($use_pathinfo) {
2765 $action .= "/".esc_url($project);
2767 print $cgi->startform(-method => "get", -action => $action) .
2768 "<div class=\"search\">\n" .
2769 (!$use_pathinfo &&
2770 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
2771 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
2772 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
2773 $cgi->popup_menu(-name => 'st', -default => 'commit',
2774 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2775 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2776 " search:\n",
2777 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2778 "<span title=\"Extended regular expression\">" .
2779 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
2780 -checked => $search_use_regexp) .
2781 "</span>" .
2782 "</div>" .
2783 $cgi->end_form() . "\n";
2787 sub git_footer_html {
2788 my $feed_class = 'rss_logo';
2790 print "<div class=\"page_footer\">\n";
2791 if (defined $project) {
2792 my $descr = git_get_project_description($project);
2793 if (defined $descr) {
2794 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2797 my %href_params = get_feed_info();
2798 if (!%href_params) {
2799 $feed_class .= ' generic';
2801 $href_params{'-title'} ||= 'log';
2803 foreach my $format qw(RSS Atom) {
2804 $href_params{'action'} = lc($format);
2805 print $cgi->a({-href => href(%href_params),
2806 -title => "$href_params{'-title'} $format feed",
2807 -class => $feed_class}, $format)."\n";
2810 } else {
2811 print $cgi->a({-href => href(project=>undef, action=>"opml"),
2812 -class => $feed_class}, "OPML") . " ";
2813 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
2814 -class => $feed_class}, "TXT") . "\n";
2816 print "</div>\n"; # class="page_footer"
2818 if (-f $site_footer) {
2819 open (my $fd, $site_footer);
2820 print <$fd>;
2821 close $fd;
2824 print "</body>\n" .
2825 "</html>";
2828 # die_error(<http_status_code>, <error_message>)
2829 # Example: die_error(404, 'Hash not found')
2830 # By convention, use the following status codes (as defined in RFC 2616):
2831 # 400: Invalid or missing CGI parameters, or
2832 # requested object exists but has wrong type.
2833 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
2834 # this server or project.
2835 # 404: Requested object/revision/project doesn't exist.
2836 # 500: The server isn't configured properly, or
2837 # an internal error occurred (e.g. failed assertions caused by bugs), or
2838 # an unknown error occurred (e.g. the git binary died unexpectedly).
2839 sub die_error {
2840 my $status = shift || 500;
2841 my $error = shift || "Internal server error";
2843 my %http_responses = (400 => '400 Bad Request',
2844 403 => '403 Forbidden',
2845 404 => '404 Not Found',
2846 500 => '500 Internal Server Error');
2847 git_header_html($http_responses{$status});
2848 print <<EOF;
2849 <div class="page_body">
2850 <br /><br />
2851 $status - $error
2852 <br />
2853 </div>
2855 git_footer_html();
2856 exit;
2859 ## ----------------------------------------------------------------------
2860 ## functions printing or outputting HTML: navigation
2862 sub git_print_page_nav {
2863 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
2864 $extra = '' if !defined $extra; # pager or formats
2866 my @navs = qw(summary shortlog log commit commitdiff tree);
2867 if ($suppress) {
2868 @navs = grep { $_ ne $suppress } @navs;
2871 my %arg = map { $_ => {action=>$_} } @navs;
2872 if (defined $head) {
2873 for (qw(commit commitdiff)) {
2874 $arg{$_}{'hash'} = $head;
2876 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
2877 for (qw(shortlog log)) {
2878 $arg{$_}{'hash'} = $head;
2883 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2884 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2886 my @actions = gitweb_check_feature('actions');
2887 while (@actions) {
2888 my ($label, $link, $pos) = (shift(@actions), shift(@actions), shift(@actions));
2889 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
2890 # munch munch
2891 $link =~ s#%n#$project#g;
2892 $link =~ s#%f#$git_dir#g;
2893 $treehead ? $link =~ s#%h#$treehead#g : $link =~ s#%h##g;
2894 $treebase ? $link =~ s#%b#$treebase#g : $link =~ s#%b##g;
2895 $arg{$label}{'_href'} = $link;
2898 print "<div class=\"page_nav\">\n" .
2899 (join " | ",
2900 map { $_ eq $current ?
2901 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
2902 } @navs);
2903 print "<br/>\n$extra<br/>\n" .
2904 "</div>\n";
2907 sub format_paging_nav {
2908 my ($action, $hash, $head, $page, $has_next_link) = @_;
2909 my $paging_nav;
2912 if ($hash ne $head || $page) {
2913 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2914 } else {
2915 $paging_nav .= "HEAD";
2918 if ($page > 0) {
2919 $paging_nav .= " &sdot; " .
2920 $cgi->a({-href => href(-replay=>1, page=>$page-1),
2921 -accesskey => "p", -title => "Alt-p"}, "prev");
2922 } else {
2923 $paging_nav .= " &sdot; prev";
2926 if ($has_next_link) {
2927 $paging_nav .= " &sdot; " .
2928 $cgi->a({-href => href(-replay=>1, page=>$page+1),
2929 -accesskey => "n", -title => "Alt-n"}, "next");
2930 } else {
2931 $paging_nav .= " &sdot; next";
2934 return $paging_nav;
2937 ## ......................................................................
2938 ## functions printing or outputting HTML: div
2940 sub git_print_header_div {
2941 my ($action, $title, $hash, $hash_base) = @_;
2942 my %args = ();
2944 $args{'action'} = $action;
2945 $args{'hash'} = $hash if $hash;
2946 $args{'hash_base'} = $hash_base if $hash_base;
2948 print "<div class=\"header\">\n" .
2949 $cgi->a({-href => href(%args), -class => "title"},
2950 $title ? $title : $action) .
2951 "\n</div>\n";
2954 #sub git_print_authorship (\%) {
2955 sub git_print_authorship {
2956 my $co = shift;
2958 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2959 print "<div class=\"author_date\">" .
2960 esc_html($co->{'author_name'}) .
2961 " [$ad{'rfc2822'}";
2962 if ($ad{'hour_local'} < 6) {
2963 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2964 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2965 } else {
2966 printf(" (%02d:%02d %s)",
2967 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2969 print "]</div>\n";
2972 sub git_print_page_path {
2973 my $name = shift;
2974 my $type = shift;
2975 my $hb = shift;
2978 print "<div class=\"page_path\">";
2979 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2980 -title => 'tree root'}, to_utf8("[$project]"));
2981 print " / ";
2982 if (defined $name) {
2983 my @dirname = split '/', $name;
2984 my $basename = pop @dirname;
2985 my $fullname = '';
2987 foreach my $dir (@dirname) {
2988 $fullname .= ($fullname ? '/' : '') . $dir;
2989 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2990 hash_base=>$hb),
2991 -title => $fullname}, esc_path($dir));
2992 print " / ";
2994 if (defined $type && $type eq 'blob') {
2995 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
2996 hash_base=>$hb),
2997 -title => $name}, esc_path($basename));
2998 } elsif (defined $type && $type eq 'tree') {
2999 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3000 hash_base=>$hb),
3001 -title => $name}, esc_path($basename));
3002 print " / ";
3003 } else {
3004 print esc_path($basename);
3007 print "<br/></div>\n";
3010 # sub git_print_log (\@;%) {
3011 sub git_print_log ($;%) {
3012 my $log = shift;
3013 my %opts = @_;
3015 if ($opts{'-remove_title'}) {
3016 # remove title, i.e. first line of log
3017 shift @$log;
3019 # remove leading empty lines
3020 while (defined $log->[0] && $log->[0] eq "") {
3021 shift @$log;
3024 # print log
3025 my $signoff = 0;
3026 my $empty = 0;
3027 foreach my $line (@$log) {
3028 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3029 $signoff = 1;
3030 $empty = 0;
3031 if (! $opts{'-remove_signoff'}) {
3032 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3033 next;
3034 } else {
3035 # remove signoff lines
3036 next;
3038 } else {
3039 $signoff = 0;
3042 # print only one empty line
3043 # do not print empty line after signoff
3044 if ($line eq "") {
3045 next if ($empty || $signoff);
3046 $empty = 1;
3047 } else {
3048 $empty = 0;
3051 print format_log_line_html($line) . "<br/>\n";
3054 if ($opts{'-final_empty_line'}) {
3055 # end with single empty line
3056 print "<br/>\n" unless $empty;
3060 # return link target (what link points to)
3061 sub git_get_link_target {
3062 my $hash = shift;
3063 my $link_target;
3065 # read link
3066 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3067 or return;
3069 local $/;
3070 $link_target = <$fd>;
3072 close $fd
3073 or return;
3075 return $link_target;
3078 # given link target, and the directory (basedir) the link is in,
3079 # return target of link relative to top directory (top tree);
3080 # return undef if it is not possible (including absolute links).
3081 sub normalize_link_target {
3082 my ($link_target, $basedir, $hash_base) = @_;
3084 # we can normalize symlink target only if $hash_base is provided
3085 return unless $hash_base;
3087 # absolute symlinks (beginning with '/') cannot be normalized
3088 return if (substr($link_target, 0, 1) eq '/');
3090 # normalize link target to path from top (root) tree (dir)
3091 my $path;
3092 if ($basedir) {
3093 $path = $basedir . '/' . $link_target;
3094 } else {
3095 # we are in top (root) tree (dir)
3096 $path = $link_target;
3099 # remove //, /./, and /../
3100 my @path_parts;
3101 foreach my $part (split('/', $path)) {
3102 # discard '.' and ''
3103 next if (!$part || $part eq '.');
3104 # handle '..'
3105 if ($part eq '..') {
3106 if (@path_parts) {
3107 pop @path_parts;
3108 } else {
3109 # link leads outside repository (outside top dir)
3110 return;
3112 } else {
3113 push @path_parts, $part;
3116 $path = join('/', @path_parts);
3118 return $path;
3121 # print tree entry (row of git_tree), but without encompassing <tr> element
3122 sub git_print_tree_entry {
3123 my ($t, $basedir, $hash_base, $have_blame) = @_;
3125 my %base_key = ();
3126 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3128 # The format of a table row is: mode list link. Where mode is
3129 # the mode of the entry, list is the name of the entry, an href,
3130 # and link is the action links of the entry.
3132 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3133 if ($t->{'type'} eq "blob") {
3134 print "<td class=\"list\">" .
3135 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3136 file_name=>"$basedir$t->{'name'}", %base_key),
3137 -class => "list"}, esc_path($t->{'name'}));
3138 if (S_ISLNK(oct $t->{'mode'})) {
3139 my $link_target = git_get_link_target($t->{'hash'});
3140 if ($link_target) {
3141 my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
3142 if (defined $norm_target) {
3143 print " -> " .
3144 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3145 file_name=>$norm_target),
3146 -title => $norm_target}, esc_path($link_target));
3147 } else {
3148 print " -> " . esc_path($link_target);
3152 print "</td>\n";
3153 print "<td class=\"link\">";
3154 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3155 file_name=>"$basedir$t->{'name'}", %base_key)},
3156 "blob");
3157 if ($have_blame) {
3158 print " | " .
3159 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3160 file_name=>"$basedir$t->{'name'}", %base_key), -class => "blamelink"},
3161 "blame");
3163 if (defined $hash_base) {
3164 print " | " .
3165 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3166 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3167 "history");
3169 print " | " .
3170 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3171 file_name=>"$basedir$t->{'name'}")},
3172 "raw");
3173 print "</td>\n";
3175 } elsif ($t->{'type'} eq "tree") {
3176 print "<td class=\"list\">";
3177 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3178 file_name=>"$basedir$t->{'name'}", %base_key)},
3179 esc_path($t->{'name'}));
3180 print "</td>\n";
3181 print "<td class=\"link\">";
3182 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3183 file_name=>"$basedir$t->{'name'}", %base_key)},
3184 "tree");
3185 if (defined $hash_base) {
3186 print " | " .
3187 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3188 file_name=>"$basedir$t->{'name'}")},
3189 "history");
3191 print "</td>\n";
3192 } else {
3193 # unknown object: we can only present history for it
3194 # (this includes 'commit' object, i.e. submodule support)
3195 print "<td class=\"list\">" .
3196 esc_path($t->{'name'}) .
3197 "</td>\n";
3198 print "<td class=\"link\">";
3199 if (defined $hash_base) {
3200 print $cgi->a({-href => href(action=>"history",
3201 hash_base=>$hash_base,
3202 file_name=>"$basedir$t->{'name'}")},
3203 "history");
3205 print "</td>\n";
3209 ## ......................................................................
3210 ## functions printing large fragments of HTML
3212 # get pre-image filenames for merge (combined) diff
3213 sub fill_from_file_info {
3214 my ($diff, @parents) = @_;
3216 $diff->{'from_file'} = [ ];
3217 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3218 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3219 if ($diff->{'status'}[$i] eq 'R' ||
3220 $diff->{'status'}[$i] eq 'C') {
3221 $diff->{'from_file'}[$i] =
3222 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3226 return $diff;
3229 # is current raw difftree line of file deletion
3230 sub is_deleted {
3231 my $diffinfo = shift;
3233 return $diffinfo->{'to_id'} eq ('0' x 40);
3236 # does patch correspond to [previous] difftree raw line
3237 # $diffinfo - hashref of parsed raw diff format
3238 # $patchinfo - hashref of parsed patch diff format
3239 # (the same keys as in $diffinfo)
3240 sub is_patch_split {
3241 my ($diffinfo, $patchinfo) = @_;
3243 return defined $diffinfo && defined $patchinfo
3244 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3248 sub git_difftree_body {
3249 my ($difftree, $hash, @parents) = @_;
3250 my ($parent) = $parents[0];
3251 my ($have_blame) = gitweb_check_feature('blame');
3252 print "<div class=\"list_head\">\n";
3253 if ($#{$difftree} > 10) {
3254 print(($#{$difftree} + 1) . " files changed:\n");
3256 print "</div>\n";
3258 print "<table class=\"" .
3259 (@parents > 1 ? "combined " : "") .
3260 "diff_tree\">\n";
3262 # header only for combined diff in 'commitdiff' view
3263 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3264 if ($has_header) {
3265 # table header
3266 print "<thead><tr>\n" .
3267 "<th></th><th></th>\n"; # filename, patchN link
3268 for (my $i = 0; $i < @parents; $i++) {
3269 my $par = $parents[$i];
3270 print "<th>" .
3271 $cgi->a({-href => href(action=>"commitdiff",
3272 hash=>$hash, hash_parent=>$par),
3273 -title => 'commitdiff to parent number ' .
3274 ($i+1) . ': ' . substr($par,0,7)},
3275 $i+1) .
3276 "&nbsp;</th>\n";
3278 print "</tr></thead>\n<tbody>\n";
3281 my $alternate = 1;
3282 my $patchno = 0;
3283 foreach my $line (@{$difftree}) {
3284 my $diff = parsed_difftree_line($line);
3286 if ($alternate) {
3287 print "<tr class=\"dark\">\n";
3288 } else {
3289 print "<tr class=\"light\">\n";
3291 $alternate ^= 1;
3293 if (exists $diff->{'nparents'}) { # combined diff
3295 fill_from_file_info($diff, @parents)
3296 unless exists $diff->{'from_file'};
3298 if (!is_deleted($diff)) {
3299 # file exists in the result (child) commit
3300 print "<td>" .
3301 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3302 file_name=>$diff->{'to_file'},
3303 hash_base=>$hash),
3304 -class => "list"}, esc_path($diff->{'to_file'})) .
3305 "</td>\n";
3306 } else {
3307 print "<td>" .
3308 esc_path($diff->{'to_file'}) .
3309 "</td>\n";
3312 if ($action eq 'commitdiff') {
3313 # link to patch
3314 $patchno++;
3315 print "<td class=\"link\">" .
3316 $cgi->a({-href => "#patch$patchno"}, "patch") .
3317 " | " .
3318 "</td>\n";
3321 my $has_history = 0;
3322 my $not_deleted = 0;
3323 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3324 my $hash_parent = $parents[$i];
3325 my $from_hash = $diff->{'from_id'}[$i];
3326 my $from_path = $diff->{'from_file'}[$i];
3327 my $status = $diff->{'status'}[$i];
3329 $has_history ||= ($status ne 'A');
3330 $not_deleted ||= ($status ne 'D');
3332 if ($status eq 'A') {
3333 print "<td class=\"link\" align=\"right\"> | </td>\n";
3334 } elsif ($status eq 'D') {
3335 print "<td class=\"link\">" .
3336 $cgi->a({-href => href(action=>"blob",
3337 hash_base=>$hash,
3338 hash=>$from_hash,
3339 file_name=>$from_path)},
3340 "blob" . ($i+1)) .
3341 " | </td>\n";
3342 } else {
3343 if ($diff->{'to_id'} eq $from_hash) {
3344 print "<td class=\"link nochange\">";
3345 } else {
3346 print "<td class=\"link\">";
3348 print $cgi->a({-href => href(action=>"blobdiff",
3349 hash=>$diff->{'to_id'},
3350 hash_parent=>$from_hash,
3351 hash_base=>$hash,
3352 hash_parent_base=>$hash_parent,
3353 file_name=>$diff->{'to_file'},
3354 file_parent=>$from_path)},
3355 "diff" . ($i+1)) .
3356 " | </td>\n";
3360 print "<td class=\"link\">";
3361 if ($not_deleted) {
3362 print $cgi->a({-href => href(action=>"blob",
3363 hash=>$diff->{'to_id'},
3364 file_name=>$diff->{'to_file'},
3365 hash_base=>$hash)},
3366 "blob");
3367 print " | " if ($has_history);
3369 if ($has_history) {
3370 print $cgi->a({-href => href(action=>"history",
3371 file_name=>$diff->{'to_file'},
3372 hash_base=>$hash)},
3373 "history");
3375 print "</td>\n";
3377 print "</tr>\n";
3378 next; # instead of 'else' clause, to avoid extra indent
3380 # else ordinary diff
3382 my ($to_mode_oct, $to_mode_str, $to_file_type);
3383 my ($from_mode_oct, $from_mode_str, $from_file_type);
3384 if ($diff->{'to_mode'} ne ('0' x 6)) {
3385 $to_mode_oct = oct $diff->{'to_mode'};
3386 if (S_ISREG($to_mode_oct)) { # only for regular file
3387 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3389 $to_file_type = file_type($diff->{'to_mode'});
3391 if ($diff->{'from_mode'} ne ('0' x 6)) {
3392 $from_mode_oct = oct $diff->{'from_mode'};
3393 if (S_ISREG($to_mode_oct)) { # only for regular file
3394 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3396 $from_file_type = file_type($diff->{'from_mode'});
3399 if ($diff->{'status'} eq "A") { # created
3400 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3401 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3402 $mode_chng .= "]</span>";
3403 print "<td>";
3404 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3405 hash_base=>$hash, file_name=>$diff->{'file'}),
3406 -class => "list"}, esc_path($diff->{'file'}));
3407 print "</td>\n";
3408 print "<td>$mode_chng</td>\n";
3409 print "<td class=\"link\">";
3410 if ($action eq 'commitdiff') {
3411 # link to patch
3412 $patchno++;
3413 print $cgi->a({-href => "#patch$patchno"}, "patch");
3414 print " | ";
3416 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3417 hash_base=>$hash, file_name=>$diff->{'file'})},
3418 "blob");
3419 print "</td>\n";
3421 } elsif ($diff->{'status'} eq "D") { # deleted
3422 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3423 print "<td>";
3424 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3425 hash_base=>$parent, file_name=>$diff->{'file'}),
3426 -class => "list"}, esc_path($diff->{'file'}));
3427 print "</td>\n";
3428 print "<td>$mode_chng</td>\n";
3429 print "<td class=\"link\">";
3430 if ($action eq 'commitdiff') {
3431 # link to patch
3432 $patchno++;
3433 print $cgi->a({-href => "#patch$patchno"}, "patch");
3434 print " | ";
3436 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3437 hash_base=>$parent, file_name=>$diff->{'file'})},
3438 "blob") . " | ";
3439 if ($have_blame) {
3440 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3441 file_name=>$diff->{'file'}), -class => "blamelink"},
3442 "blame") . " | ";
3444 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3445 file_name=>$diff->{'file'})},
3446 "history");
3447 print "</td>\n";
3449 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3450 my $mode_chnge = "";
3451 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3452 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3453 if ($from_file_type ne $to_file_type) {
3454 $mode_chnge .= " from $from_file_type to $to_file_type";
3456 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3457 if ($from_mode_str && $to_mode_str) {
3458 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3459 } elsif ($to_mode_str) {
3460 $mode_chnge .= " mode: $to_mode_str";
3463 $mode_chnge .= "]</span>\n";
3465 print "<td>";
3466 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3467 hash_base=>$hash, file_name=>$diff->{'file'}),
3468 -class => "list"}, esc_path($diff->{'file'}));
3469 print "</td>\n";
3470 print "<td>$mode_chnge</td>\n";
3471 print "<td class=\"link\">";
3472 if ($action eq 'commitdiff') {
3473 # link to patch
3474 $patchno++;
3475 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3476 " | ";
3477 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3478 # "commit" view and modified file (not onlu mode changed)
3479 print $cgi->a({-href => href(action=>"blobdiff",
3480 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3481 hash_base=>$hash, hash_parent_base=>$parent,
3482 file_name=>$diff->{'file'})},
3483 "diff") .
3484 " | ";
3486 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3487 hash_base=>$hash, file_name=>$diff->{'file'})},
3488 "blob") . " | ";
3489 if ($have_blame) {
3490 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3491 file_name=>$diff->{'file'}), -class => "blamelink"},
3492 "blame") . " | ";
3494 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3495 file_name=>$diff->{'file'})},
3496 "history");
3497 print "</td>\n";
3499 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3500 my %status_name = ('R' => 'moved', 'C' => 'copied');
3501 my $nstatus = $status_name{$diff->{'status'}};
3502 my $mode_chng = "";
3503 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3504 # mode also for directories, so we cannot use $to_mode_str
3505 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3507 print "<td>" .
3508 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3509 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3510 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3511 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3512 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3513 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3514 -class => "list"}, esc_path($diff->{'from_file'})) .
3515 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3516 "<td class=\"link\">";
3517 if ($action eq 'commitdiff') {
3518 # link to patch
3519 $patchno++;
3520 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3521 " | ";
3522 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3523 # "commit" view and modified file (not only pure rename or copy)
3524 print $cgi->a({-href => href(action=>"blobdiff",
3525 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3526 hash_base=>$hash, hash_parent_base=>$parent,
3527 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3528 "diff") .
3529 " | ";
3531 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3532 hash_base=>$parent, file_name=>$diff->{'to_file'})},
3533 "blob") . " | ";
3534 if ($have_blame) {
3535 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3536 file_name=>$diff->{'to_file'}), -class => "blamelink"},
3537 "blame") . " | ";
3539 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3540 file_name=>$diff->{'to_file'})},
3541 "history");
3542 print "</td>\n";
3544 } # we should not encounter Unmerged (U) or Unknown (X) status
3545 print "</tr>\n";
3547 print "</tbody>" if $has_header;
3548 print "</table>\n";
3551 sub git_patchset_body {
3552 my ($fd, $difftree, $hash, @hash_parents) = @_;
3553 my ($hash_parent) = $hash_parents[0];
3555 my $is_combined = (@hash_parents > 1);
3556 my $patch_idx = 0;
3557 my $patch_number = 0;
3558 my $patch_line;
3559 my $diffinfo;
3560 my $to_name;
3561 my (%from, %to);
3563 print "<div class=\"patchset\">\n";
3565 # skip to first patch
3566 while ($patch_line = <$fd>) {
3567 chomp $patch_line;
3569 last if ($patch_line =~ m/^diff /);
3572 PATCH:
3573 while ($patch_line) {
3575 # parse "git diff" header line
3576 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
3577 # $1 is from_name, which we do not use
3578 $to_name = unquote($2);
3579 $to_name =~ s!^b/!!;
3580 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
3581 # $1 is 'cc' or 'combined', which we do not use
3582 $to_name = unquote($2);
3583 } else {
3584 $to_name = undef;
3587 # check if current patch belong to current raw line
3588 # and parse raw git-diff line if needed
3589 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
3590 # this is continuation of a split patch
3591 print "<div class=\"patch cont\">\n";
3592 } else {
3593 # advance raw git-diff output if needed
3594 $patch_idx++ if defined $diffinfo;
3596 # read and prepare patch information
3597 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3599 # compact combined diff output can have some patches skipped
3600 # find which patch (using pathname of result) we are at now;
3601 if ($is_combined) {
3602 while ($to_name ne $diffinfo->{'to_file'}) {
3603 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3604 format_diff_cc_simplified($diffinfo, @hash_parents) .
3605 "</div>\n"; # class="patch"
3607 $patch_idx++;
3608 $patch_number++;
3610 last if $patch_idx > $#$difftree;
3611 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3615 # modifies %from, %to hashes
3616 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3618 # this is first patch for raw difftree line with $patch_idx index
3619 # we index @$difftree array from 0, but number patches from 1
3620 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3623 # git diff header
3624 #assert($patch_line =~ m/^diff /) if DEBUG;
3625 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3626 $patch_number++;
3627 # print "git diff" header
3628 print format_git_diff_header_line($patch_line, $diffinfo,
3629 \%from, \%to);
3631 # print extended diff header
3632 print "<div class=\"diff extended_header\">\n";
3633 EXTENDED_HEADER:
3634 while ($patch_line = <$fd>) {
3635 chomp $patch_line;
3637 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3639 print format_extended_diff_header_line($patch_line, $diffinfo,
3640 \%from, \%to);
3642 print "</div>\n"; # class="diff extended_header"
3644 # from-file/to-file diff header
3645 if (! $patch_line) {
3646 print "</div>\n"; # class="patch"
3647 last PATCH;
3649 next PATCH if ($patch_line =~ m/^diff /);
3650 #assert($patch_line =~ m/^---/) if DEBUG;
3652 my $last_patch_line = $patch_line;
3653 $patch_line = <$fd>;
3654 chomp $patch_line;
3655 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3657 print format_diff_from_to_header($last_patch_line, $patch_line,
3658 $diffinfo, \%from, \%to,
3659 @hash_parents);
3661 # the patch itself
3662 LINE:
3663 while ($patch_line = <$fd>) {
3664 chomp $patch_line;
3666 next PATCH if ($patch_line =~ m/^diff /);
3668 print format_diff_line($patch_line, \%from, \%to);
3671 } continue {
3672 print "</div>\n"; # class="patch"
3675 # for compact combined (--cc) format, with chunk and patch simpliciaction
3676 # patchset might be empty, but there might be unprocessed raw lines
3677 for (++$patch_idx if $patch_number > 0;
3678 $patch_idx < @$difftree;
3679 ++$patch_idx) {
3680 # read and prepare patch information
3681 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3683 # generate anchor for "patch" links in difftree / whatchanged part
3684 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3685 format_diff_cc_simplified($diffinfo, @hash_parents) .
3686 "</div>\n"; # class="patch"
3688 $patch_number++;
3691 if ($patch_number == 0) {
3692 if (@hash_parents > 1) {
3693 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3694 } else {
3695 print "<div class=\"diff nodifferences\">No differences found</div>\n";
3699 print "</div>\n"; # class="patchset"
3702 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3704 # fills project list info (age, description, owner, forks) for each
3705 # project in the list, removing invalid projects from returned list
3706 # NOTE: modifies $projlist, but does not remove entries from it
3707 sub fill_project_list_info {
3708 my ($projlist, $check_forks) = @_;
3709 my @projects;
3711 my $show_ctags = gitweb_check_feature('ctags');
3712 PROJECT:
3713 foreach my $pr (@$projlist) {
3714 my (@activity) = git_get_last_activity($pr->{'path'});
3715 unless (@activity) {
3716 next PROJECT;
3718 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
3719 if (!defined $pr->{'descr'}) {
3720 my $descr = git_get_project_description($pr->{'path'}) || "";
3721 $descr = to_utf8($descr);
3722 $pr->{'descr_long'} = $descr;
3723 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
3725 if (!defined $pr->{'owner'}) {
3726 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3728 if ($check_forks) {
3729 my $pname = $pr->{'path'};
3730 if (($pname =~ s/\.git$//) &&
3731 ($pname !~ /\/$/) &&
3732 (-d "$projectroot/$pname")) {
3733 $pr->{'forks'} = "-d $projectroot/$pname";
3734 } else {
3735 $pr->{'forks'} = 0;
3738 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
3739 push @projects, $pr;
3742 return @projects;
3745 # print 'sort by' <th> element, generating 'sort by $name' replay link
3746 # if that order is not selected
3747 sub print_sort_th {
3748 my ($name, $order, $header) = @_;
3749 $header ||= ucfirst($name);
3751 if ($order eq $name) {
3752 print "<th>$header</th>\n";
3753 } else {
3754 print "<th>" .
3755 $cgi->a({-href => href(-replay=>1, order=>$name),
3756 -class => "header"}, $header) .
3757 "</th>\n";
3761 sub git_project_list_body {
3762 # actually uses global variable $project
3763 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3765 my ($check_forks) = gitweb_check_feature('forks');
3766 my @projects = fill_project_list_info($projlist, $check_forks);
3768 $order ||= $default_projects_order;
3769 $from = 0 unless defined $from;
3770 $to = $#projects if (!defined $to || $#projects < $to);
3772 my %order_info = (
3773 project => { key => 'path', type => 'str' },
3774 descr => { key => 'descr_long', type => 'str' },
3775 owner => { key => 'owner', type => 'str' },
3776 age => { key => 'age', type => 'num' }
3778 my $oi = $order_info{$order};
3779 if ($oi->{'type'} eq 'str') {
3780 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
3781 } else {
3782 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
3785 my $show_ctags = gitweb_check_feature('ctags');
3786 if ($show_ctags) {
3787 my %ctags;
3788 foreach my $p (@projects) {
3789 foreach my $ct (keys %{$p->{'ctags'}}) {
3790 $ctags{$ct} += $p->{'ctags'}->{$ct};
3793 my $cloud = git_populate_project_tagcloud(\%ctags);
3794 print git_show_project_tagcloud($cloud, 64);
3797 print "<table class=\"project_list\">\n";
3798 unless ($no_header) {
3799 print "<tr>\n";
3800 if ($check_forks) {
3801 print "<th></th>\n";
3803 print_sort_th('project', $order, 'Project');
3804 print_sort_th('descr', $order, 'Description');
3805 print_sort_th('owner', $order, 'Owner');
3806 print_sort_th('age', $order, 'Last Change');
3807 print "<th></th>\n" . # for links
3808 "</tr>\n";
3810 my $alternate = 1;
3811 my $tagfilter = $cgi->param('by_tag');
3812 for (my $i = $from; $i <= $to; $i++) {
3813 my $pr = $projects[$i];
3815 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
3816 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
3817 and not $pr->{'descr_long'} =~ /$searchtext/;
3818 # Weed out forks or non-matching entries of search
3819 if ($check_forks) {
3820 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
3821 $forkbase="^$forkbase" if $forkbase;
3822 next if not $searchtext and not $tagfilter and $show_ctags
3823 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
3826 if ($alternate) {
3827 print "<tr class=\"dark\">\n";
3828 } else {
3829 print "<tr class=\"light\">\n";
3831 $alternate ^= 1;
3832 if ($check_forks) {
3833 print "<td>";
3834 if ($pr->{'forks'}) {
3835 print "<!-- $pr->{'forks'} -->\n";
3836 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
3838 print "</td>\n";
3840 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3841 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
3842 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3843 -class => "list", -title => $pr->{'descr_long'}},
3844 esc_html($pr->{'descr'})) . "</td>\n" .
3845 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
3846 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3847 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3848 "<td class=\"link\">" .
3849 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
3850 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3851 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3852 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3853 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3854 "</td>\n" .
3855 "</tr>\n";
3857 if (defined $extra) {
3858 print "<tr>\n";
3859 if ($check_forks) {
3860 print "<td></td>\n";
3862 print "<td colspan=\"5\">$extra</td>\n" .
3863 "</tr>\n";
3865 print "</table>\n";
3868 sub git_shortlog_body {
3869 # uses global variable $project
3870 my ($commitlist, $from, $to, $refs, $extra) = @_;
3872 $from = 0 unless defined $from;
3873 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3875 print "<table class=\"shortlog\">\n";
3876 my $alternate = 1;
3877 for (my $i = $from; $i <= $to; $i++) {
3878 my %co = %{$commitlist->[$i]};
3879 my $commit = $co{'id'};
3880 my $ref = format_ref_marker($refs, $commit);
3881 if ($alternate) {
3882 print "<tr class=\"dark\">\n";
3883 } else {
3884 print "<tr class=\"light\">\n";
3886 $alternate ^= 1;
3887 my $author = chop_and_escape_str($co{'author_name'}, 10);
3888 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3889 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3890 "<td><i>" . $author . "</i></td>\n" .
3891 "<td>";
3892 print format_subject_html($co{'title'}, $co{'title_short'},
3893 href(action=>"commit", hash=>$commit), $ref);
3894 print "</td>\n" .
3895 "<td class=\"link\">" .
3896 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3897 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3898 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3899 my $snapshot_links = format_snapshot_links($commit);
3900 if (defined $snapshot_links) {
3901 print " | " . $snapshot_links;
3903 print "</td>\n" .
3904 "</tr>\n";
3906 if (defined $extra) {
3907 print "<tr>\n" .
3908 "<td colspan=\"4\">$extra</td>\n" .
3909 "</tr>\n";
3911 print "</table>\n";
3914 sub git_history_body {
3915 # Warning: assumes constant type (blob or tree) during history
3916 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3918 $from = 0 unless defined $from;
3919 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3921 print "<table class=\"history\">\n";
3922 my $alternate = 1;
3923 for (my $i = $from; $i <= $to; $i++) {
3924 my %co = %{$commitlist->[$i]};
3925 if (!%co) {
3926 next;
3928 my $commit = $co{'id'};
3930 my $ref = format_ref_marker($refs, $commit);
3932 if ($alternate) {
3933 print "<tr class=\"dark\">\n";
3934 } else {
3935 print "<tr class=\"light\">\n";
3937 $alternate ^= 1;
3938 # shortlog uses chop_str($co{'author_name'}, 10)
3939 my $author = chop_and_escape_str($co{'author_name'}, 15, 3);
3940 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3941 "<td><i>" . $author . "</i></td>\n" .
3942 "<td>";
3943 # originally git_history used chop_str($co{'title'}, 50)
3944 print format_subject_html($co{'title'}, $co{'title_short'},
3945 href(action=>"commit", hash=>$commit), $ref);
3946 print "</td>\n" .
3947 "<td class=\"link\">" .
3948 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3949 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3951 if ($ftype eq 'blob') {
3952 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3953 my $blob_parent = git_get_hash_by_path($commit, $file_name);
3954 if (defined $blob_current && defined $blob_parent &&
3955 $blob_current ne $blob_parent) {
3956 print " | " .
3957 $cgi->a({-href => href(action=>"blobdiff",
3958 hash=>$blob_current, hash_parent=>$blob_parent,
3959 hash_base=>$hash_base, hash_parent_base=>$commit,
3960 file_name=>$file_name)},
3961 "diff to current");
3964 print "</td>\n" .
3965 "</tr>\n";
3967 if (defined $extra) {
3968 print "<tr>\n" .
3969 "<td colspan=\"4\">$extra</td>\n" .
3970 "</tr>\n";
3972 print "</table>\n";
3975 sub git_tags_body {
3976 # uses global variable $project
3977 my ($taglist, $from, $to, $extra) = @_;
3978 $from = 0 unless defined $from;
3979 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3981 print "<table class=\"tags\">\n";
3982 my $alternate = 1;
3983 for (my $i = $from; $i <= $to; $i++) {
3984 my $entry = $taglist->[$i];
3985 my %tag = %$entry;
3986 my $comment = $tag{'subject'};
3987 my $comment_short;
3988 if (defined $comment) {
3989 $comment_short = chop_str($comment, 30, 5);
3991 if ($alternate) {
3992 print "<tr class=\"dark\">\n";
3993 } else {
3994 print "<tr class=\"light\">\n";
3996 $alternate ^= 1;
3997 if (defined $tag{'age'}) {
3998 print "<td><i>$tag{'age'}</i></td>\n";
3999 } else {
4000 print "<td></td>\n";
4002 print "<td>" .
4003 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4004 -class => "list name"}, esc_html($tag{'name'})) .
4005 "</td>\n" .
4006 "<td>";
4007 if (defined $comment) {
4008 print format_subject_html($comment, $comment_short,
4009 href(action=>"tag", hash=>$tag{'id'}));
4011 print "</td>\n" .
4012 "<td class=\"selflink\">";
4013 if ($tag{'type'} eq "tag") {
4014 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4015 } else {
4016 print "&nbsp;";
4018 print "</td>\n" .
4019 "<td class=\"link\">" . " | " .
4020 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4021 if ($tag{'reftype'} eq "commit") {
4022 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4023 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4024 } elsif ($tag{'reftype'} eq "blob") {
4025 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4027 print "</td>\n" .
4028 "</tr>";
4030 if (defined $extra) {
4031 print "<tr>\n" .
4032 "<td colspan=\"5\">$extra</td>\n" .
4033 "</tr>\n";
4035 print "</table>\n";
4038 sub git_heads_body {
4039 # uses global variable $project
4040 my ($headlist, $head, $from, $to, $extra) = @_;
4041 $from = 0 unless defined $from;
4042 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4044 print "<table class=\"heads\">\n";
4045 my $alternate = 1;
4046 for (my $i = $from; $i <= $to; $i++) {
4047 my $entry = $headlist->[$i];
4048 my %ref = %$entry;
4049 my $curr = $ref{'id'} eq $head;
4050 if ($alternate) {
4051 print "<tr class=\"dark\">\n";
4052 } else {
4053 print "<tr class=\"light\">\n";
4055 $alternate ^= 1;
4056 print "<td><i>$ref{'age'}</i></td>\n" .
4057 ($curr ? "<td class=\"current_head\">" : "<td>") .
4058 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4059 -class => "list name"},esc_html($ref{'name'})) .
4060 "</td>\n" .
4061 "<td class=\"link\">" .
4062 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4063 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4064 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4065 "</td>\n" .
4066 "</tr>";
4068 if (defined $extra) {
4069 print "<tr>\n" .
4070 "<td colspan=\"3\">$extra</td>\n" .
4071 "</tr>\n";
4073 print "</table>\n";
4076 sub git_search_grep_body {
4077 my ($commitlist, $from, $to, $extra) = @_;
4078 $from = 0 unless defined $from;
4079 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4081 print "<table class=\"commit_search\">\n";
4082 my $alternate = 1;
4083 for (my $i = $from; $i <= $to; $i++) {
4084 my %co = %{$commitlist->[$i]};
4085 if (!%co) {
4086 next;
4088 my $commit = $co{'id'};
4089 if ($alternate) {
4090 print "<tr class=\"dark\">\n";
4091 } else {
4092 print "<tr class=\"light\">\n";
4094 $alternate ^= 1;
4095 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
4096 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4097 "<td><i>" . $author . "</i></td>\n" .
4098 "<td>" .
4099 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4100 -class => "list subject"},
4101 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4102 my $comment = $co{'comment'};
4103 foreach my $line (@$comment) {
4104 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4105 my ($lead, $match, $trail) = ($1, $2, $3);
4106 $match = chop_str($match, 70, 5, 'center');
4107 my $contextlen = int((80 - length($match))/2);
4108 $contextlen = 30 if ($contextlen > 30);
4109 $lead = chop_str($lead, $contextlen, 10, 'left');
4110 $trail = chop_str($trail, $contextlen, 10, 'right');
4112 $lead = esc_html($lead);
4113 $match = esc_html($match);
4114 $trail = esc_html($trail);
4116 print "$lead<span class=\"match\">$match</span>$trail<br />";
4119 print "</td>\n" .
4120 "<td class=\"link\">" .
4121 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4122 " | " .
4123 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4124 " | " .
4125 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4126 print "</td>\n" .
4127 "</tr>\n";
4129 if (defined $extra) {
4130 print "<tr>\n" .
4131 "<td colspan=\"3\">$extra</td>\n" .
4132 "</tr>\n";
4134 print "</table>\n";
4137 ## ======================================================================
4138 ## ======================================================================
4139 ## actions
4141 sub git_project_list {
4142 my $order = $cgi->param('o');
4143 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4144 die_error(400, "Unknown order parameter");
4147 my @list = git_get_projects_list();
4148 if (!@list) {
4149 die_error(404, "No projects found");
4152 git_header_html();
4153 if (-f $home_text) {
4154 print "<div class=\"index_include\">\n";
4155 open (my $fd, $home_text);
4156 print <$fd>;
4157 close $fd;
4158 print "</div>\n";
4160 print $cgi->startform(-method => "get") .
4161 "<p class=\"projsearch\">Search:\n" .
4162 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4163 "</p>" .
4164 $cgi->end_form() . "\n";
4165 git_project_list_body(\@list, $order);
4166 git_footer_html();
4169 sub git_forks {
4170 my $order = $cgi->param('o');
4171 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4172 die_error(400, "Unknown order parameter");
4175 my @list = git_get_projects_list($project);
4176 if (!@list) {
4177 die_error(404, "No forks found");
4180 git_header_html();
4181 git_print_page_nav('','');
4182 git_print_header_div('summary', "$project forks");
4183 git_project_list_body(\@list, $order);
4184 git_footer_html();
4187 sub git_project_index {
4188 my @projects = git_get_projects_list($project);
4190 print $cgi->header(
4191 -type => 'text/plain',
4192 -charset => 'utf-8',
4193 -content_disposition => 'inline; filename="index.aux"');
4195 foreach my $pr (@projects) {
4196 if (!exists $pr->{'owner'}) {
4197 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4200 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4201 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4202 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4203 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4204 $path =~ s/ /\+/g;
4205 $owner =~ s/ /\+/g;
4207 print "$path $owner\n";
4211 sub git_summary {
4212 my $descr = git_get_project_description($project) || "none";
4213 my %co = parse_commit("HEAD");
4214 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4215 my $head = $co{'id'};
4217 my $owner = git_get_project_owner($project);
4219 my $refs = git_get_references();
4220 # These get_*_list functions return one more to allow us to see if
4221 # there are more ...
4222 my @taglist = git_get_tags_list(16);
4223 my @headlist = git_get_heads_list(16);
4224 my @forklist;
4225 my ($check_forks) = gitweb_check_feature('forks');
4227 if ($check_forks) {
4228 @forklist = git_get_projects_list($project);
4231 git_header_html();
4232 git_print_page_nav('summary','', $head);
4234 print "<div class=\"title\">&nbsp;</div>\n";
4235 print "<table class=\"projects_list\">\n" .
4236 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4237 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4238 if (defined $cd{'rfc2822'}) {
4239 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4242 # use per project git URL list in $projectroot/$project/cloneurl
4243 # or make project git URL from git base URL and project name
4244 my $url_tag = "URL";
4245 my @url_list = git_get_project_url_list($project);
4246 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4247 foreach my $git_url (@url_list) {
4248 next unless $git_url;
4249 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4250 $url_tag = "";
4253 # Tag cloud
4254 my $show_ctags = (gitweb_check_feature('ctags'))[0];
4255 if ($show_ctags) {
4256 my $ctags = git_get_project_ctags($project);
4257 my $cloud = git_populate_project_tagcloud($ctags);
4258 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4259 print "</td>\n<td>" unless %$ctags;
4260 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4261 print "</td>\n<td>" if %$ctags;
4262 print git_show_project_tagcloud($cloud, 48);
4263 print "</td></tr>";
4266 print "</table>\n";
4268 if (-s "$projectroot/$project/README.html") {
4269 if (open my $fd, "$projectroot/$project/README.html") {
4270 print "<div class=\"title\">readme</div>\n" .
4271 "<div class=\"readme\">\n";
4272 print $_ while (<$fd>);
4273 print "\n</div>\n"; # class="readme"
4274 close $fd;
4278 # we need to request one more than 16 (0..15) to check if
4279 # those 16 are all
4280 my @commitlist = $head ? parse_commits($head, 17) : ();
4281 if (@commitlist) {
4282 git_print_header_div('shortlog');
4283 git_shortlog_body(\@commitlist, 0, 15, $refs,
4284 $#commitlist <= 15 ? undef :
4285 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4288 if (@taglist) {
4289 git_print_header_div('tags');
4290 git_tags_body(\@taglist, 0, 15,
4291 $#taglist <= 15 ? undef :
4292 $cgi->a({-href => href(action=>"tags")}, "..."));
4295 if (@headlist) {
4296 git_print_header_div('heads');
4297 git_heads_body(\@headlist, $head, 0, 15,
4298 $#headlist <= 15 ? undef :
4299 $cgi->a({-href => href(action=>"heads")}, "..."));
4302 if (@forklist) {
4303 git_print_header_div('forks');
4304 git_project_list_body(\@forklist, 'age', 0, 15,
4305 $#forklist <= 15 ? undef :
4306 $cgi->a({-href => href(action=>"forks")}, "..."),
4307 'no_header');
4310 git_footer_html();
4313 sub git_tag {
4314 my $head = git_get_head_hash($project);
4315 git_header_html();
4316 git_print_page_nav('','', $head,undef,$head);
4317 my %tag = parse_tag($hash);
4319 if (! %tag) {
4320 die_error(404, "Unknown tag object");
4323 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4324 print "<div class=\"title_text\">\n" .
4325 "<table class=\"object_header\">\n" .
4326 "<tr>\n" .
4327 "<td>object</td>\n" .
4328 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4329 $tag{'object'}) . "</td>\n" .
4330 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4331 $tag{'type'}) . "</td>\n" .
4332 "</tr>\n";
4333 if (defined($tag{'author'})) {
4334 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
4335 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
4336 print "<tr><td></td><td>" . $ad{'rfc2822'} .
4337 sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
4338 "</td></tr>\n";
4340 print "</table>\n\n" .
4341 "</div>\n";
4342 print "<div class=\"page_body\">";
4343 my $comment = $tag{'comment'};
4344 foreach my $line (@$comment) {
4345 chomp $line;
4346 print esc_html($line, -nbsp=>1) . "<br/>\n";
4348 print "</div>\n";
4349 git_footer_html();
4352 sub git_blame_data {
4353 my $fd;
4354 my $ftype;
4356 my ($have_blame) = gitweb_check_feature('blame');
4357 if (!$have_blame) {
4358 die_error('403 Permission denied', "Permission denied");
4360 die_error('404 Not Found', "File name not defined") if (!$file_name);
4361 $hash_base ||= git_get_head_hash($project);
4362 die_error(undef, "Couldn't find base commit") unless ($hash_base);
4363 my %co = parse_commit($hash_base)
4364 or die_error(undef, "Reading commit failed");
4365 if (!defined $hash) {
4366 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4367 or die_error(undef, "Error looking up file");
4369 $ftype = git_get_type($hash);
4370 if ($ftype !~ "blob") {
4371 die_error("400 Bad Request", "Object is not a blob");
4373 open ($fd, "-|", git_cmd(), "blame", '--incremental', $hash_base, '--',
4374 $file_name)
4375 or die_error(undef, "Open git-blame --incremental failed");
4377 print $cgi->header(-type=>"text/plain", -charset => 'utf-8',
4378 -status=> "200 OK");
4380 while(<$fd>) {
4381 if (/^([0-9a-f]{40}) ([0-9]+) ([0-9]+) ([0-9]+)/ or
4382 /^author-time |^author |^filename /) {
4383 print;
4387 close $fd or print "Reading blame data failed\n";
4390 sub git_blame_common {
4391 my ($type) = @_;
4393 my $fd;
4394 my $ftype;
4396 gitweb_check_feature('blame')
4397 or die_error(403, "Blame view not allowed");
4399 die_error(400, "No file name given") unless $file_name;
4400 $hash_base ||= git_get_head_hash($project);
4401 die_error(404, "Couldn't find base commit") unless ($hash_base);
4402 my %co = parse_commit($hash_base)
4403 or die_error(404, "Commit not found");
4404 if (!defined $hash) {
4405 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4406 or die_error(404, "Error looking up file");
4408 $ftype = git_get_type($hash);
4409 if ($ftype !~ "blob") {
4410 die_error(400, "Object is not a blob");
4412 if ($type eq 'incremental') {
4413 open ($fd, "-|", git_cmd(), 'cat-file', 'blob', $hash)
4414 or die_error(undef, "Open git-cat-file failed");
4415 } else {
4416 open ($fd, "-|", git_cmd(), "blame", '-p', '--',
4417 $file_name, $hash_base)
4418 or die_error(500, "Open git-blame failed");
4420 git_header_html();
4421 my $formats_nav =
4422 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4423 "blob") .
4424 " | " .
4425 $cgi->a({-href => href(action=>"history", -replay=>1)},
4426 "history") .
4427 " | " .
4428 $cgi->a({-href => href(action=>"blame", file_name=>$file_name), -class => "blamelink"},
4429 "HEAD");
4430 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4431 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4432 git_print_page_path($file_name, $ftype, $hash_base);
4433 my @rev_color = (qw(light2 dark2));
4434 my $num_colors = scalar(@rev_color);
4435 my $current_color = 0;
4436 my $last_rev;
4437 print <<HTML;
4438 <div class="page_body">
4439 <table class="blame">
4440 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4441 HTML
4442 my %metainfo = ();
4443 my $linenr = 0;
4444 while (<$fd>) {
4445 chomp;
4446 if ($type eq 'incremental') {
4447 # Empty stage with just the file contents
4448 $linenr += 1;
4449 print "<tr id=\"l$linenr\" class=\"light2\">";
4450 print '<td class="sha1"><a href=""></a></td>';
4451 print "<td class=\"linenr\"><a class=\"linenr\" href=\"\">$linenr</a></td><td class=\"pre\">" . esc_html($_) . "</td>\n";
4452 print "</tr>\n";
4453 next;
4456 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4457 /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
4458 if (!exists $metainfo{$full_rev}) {
4459 $metainfo{$full_rev} = {};
4461 my $meta = $metainfo{$full_rev};
4462 while (<$fd>) {
4463 last if (s/^\t//);
4464 if (/^(\S+) (.*)$/) {
4465 $meta->{$1} = $2;
4468 my $data = $_;
4469 chomp $data;
4470 my $rev = substr($full_rev, 0, 8);
4471 my $author = $meta->{'author'};
4472 my %date = parse_date($meta->{'author-time'},
4473 $meta->{'author-tz'});
4474 my $date = $date{'iso-tz'};
4475 if ($group_size) {
4476 $current_color = ++$current_color % $num_colors;
4478 print "<tr class=\"$rev_color[$current_color]\">\n";
4479 if ($group_size) {
4480 print "<td class=\"sha1\"";
4481 print " title=\"". esc_html($author) . ", $date\"";
4482 print " rowspan=\"$group_size\"" if ($group_size > 1);
4483 print ">";
4484 print $cgi->a({-href => href(action=>"commit",
4485 hash=>$full_rev,
4486 file_name=>$file_name)},
4487 esc_html($rev));
4488 print "</td>\n";
4490 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
4491 or die_error(500, "Open git-rev-parse failed");
4492 my $parent_commit = <$dd>;
4493 close $dd;
4494 chomp($parent_commit);
4495 my $blamed = href(action => 'blame',
4496 file_name => $meta->{'filename'},
4497 hash_base => $parent_commit);
4498 print "<td class=\"linenr\">";
4499 print $cgi->a({ -href => "$blamed#l$orig_lineno",
4500 -id => "l$lineno",
4501 -class => "linenr" },
4502 esc_html($lineno));
4503 print "</td>";
4504 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4505 print "</tr>\n";
4508 print "</table>\n";
4509 print "</div>";
4510 close $fd
4511 or print "Reading blob failed\n";
4513 if ($type eq 'incremental') {
4514 print "<script type=\"text/javascript\">\n";
4515 print "startBlame(\"" . href(action=>"blame_data", hash_base=>$hash_base, file_name=>$file_name) . "\", \"" .
4516 href(-partial_query=>1) . "\");\n";
4517 print "</script>\n";
4520 git_footer_html();
4523 sub git_blame_incremental {
4524 git_blame_common('incremental');
4527 sub git_blame {
4528 git_blame_common('oneshot');
4531 sub git_tags {
4532 my $head = git_get_head_hash($project);
4533 git_header_html();
4534 git_print_page_nav('','', $head,undef,$head);
4535 git_print_header_div('summary', $project);
4537 my @tagslist = git_get_tags_list();
4538 if (@tagslist) {
4539 git_tags_body(\@tagslist);
4541 git_footer_html();
4544 sub git_heads {
4545 my $head = git_get_head_hash($project);
4546 git_header_html();
4547 git_print_page_nav('','', $head,undef,$head);
4548 git_print_header_div('summary', $project);
4550 my @headslist = git_get_heads_list();
4551 if (@headslist) {
4552 git_heads_body(\@headslist, $head);
4554 git_footer_html();
4557 sub git_blob_plain {
4558 my $type = shift;
4559 my $expires;
4561 if (!defined $hash) {
4562 if (defined $file_name) {
4563 my $base = $hash_base || git_get_head_hash($project);
4564 $hash = git_get_hash_by_path($base, $file_name, "blob")
4565 or die_error(404, "Cannot find file");
4566 } else {
4567 die_error(400, "No file name defined");
4569 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4570 # blobs defined by non-textual hash id's can be cached
4571 $expires = "+1d";
4574 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4575 or die_error(500, "Open git-cat-file blob '$hash' failed");
4577 # content-type (can include charset)
4578 $type = blob_contenttype($fd, $file_name, $type);
4580 # "save as" filename, even when no $file_name is given
4581 my $save_as = "$hash";
4582 if (defined $file_name) {
4583 $save_as = $file_name;
4584 } elsif ($type =~ m/^text\//) {
4585 $save_as .= '.txt';
4588 print $cgi->header(
4589 -type => $type,
4590 -expires => $expires,
4591 -content_disposition => 'inline; filename="' . $save_as . '"');
4592 undef $/;
4593 binmode STDOUT, ':raw';
4594 print <$fd>;
4595 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4596 $/ = "\n";
4597 close $fd;
4600 sub git_blob {
4601 my $expires;
4603 if (!defined $hash) {
4604 if (defined $file_name) {
4605 my $base = $hash_base || git_get_head_hash($project);
4606 $hash = git_get_hash_by_path($base, $file_name, "blob")
4607 or die_error(404, "Cannot find file");
4608 } else {
4609 die_error(400, "No file name defined");
4611 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4612 # blobs defined by non-textual hash id's can be cached
4613 $expires = "+1d";
4616 my ($have_blame) = gitweb_check_feature('blame');
4617 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4618 or die_error(500, "Couldn't cat $file_name, $hash");
4619 my $mimetype = blob_mimetype($fd, $file_name);
4620 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
4621 close $fd;
4622 return git_blob_plain($mimetype);
4624 # we can have blame only for text/* mimetype
4625 $have_blame &&= ($mimetype =~ m!^text/!);
4627 git_header_html(undef, $expires);
4628 my $formats_nav = '';
4629 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4630 if (defined $file_name) {
4631 if ($have_blame) {
4632 $formats_nav .=
4633 $cgi->a({-href => href(action=>"blame", -replay=>1,
4634 -class => "blamelink")},
4635 "blame") .
4636 " | ";
4638 $formats_nav .=
4639 $cgi->a({-href => href(action=>"history", -replay=>1)},
4640 "history") .
4641 " | " .
4642 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4643 "raw") .
4644 " | " .
4645 $cgi->a({-href => href(action=>"blob",
4646 hash_base=>"HEAD", file_name=>$file_name)},
4647 "HEAD");
4648 } else {
4649 $formats_nav .=
4650 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4651 "raw");
4653 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4654 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4655 } else {
4656 print "<div class=\"page_nav\">\n" .
4657 "<br/><br/></div>\n" .
4658 "<div class=\"title\">$hash</div>\n";
4660 git_print_page_path($file_name, "blob", $hash_base);
4661 print "<div class=\"page_body\">\n";
4662 if ($mimetype =~ m!^image/!) {
4663 print qq!<img type="$mimetype"!;
4664 if ($file_name) {
4665 print qq! alt="$file_name" title="$file_name"!;
4667 print qq! src="! .
4668 href(action=>"blob_plain", hash=>$hash,
4669 hash_base=>$hash_base, file_name=>$file_name) .
4670 qq!" />\n!;
4671 } else {
4672 my $nr;
4673 while (my $line = <$fd>) {
4674 chomp $line;
4675 $nr++;
4676 $line = untabify($line);
4677 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4678 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4681 close $fd
4682 or print "Reading blob failed.\n";
4683 print "</div>";
4684 git_footer_html();
4687 sub git_tree {
4688 if (!defined $hash_base) {
4689 $hash_base = "HEAD";
4691 if (!defined $hash) {
4692 if (defined $file_name) {
4693 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4694 } else {
4695 $hash = $hash_base;
4698 die_error(404, "No such tree") unless defined($hash);
4699 $/ = "\0";
4700 open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4701 or die_error(500, "Open git-ls-tree failed");
4702 my @entries = map { chomp; $_ } <$fd>;
4703 close $fd or die_error(404, "Reading tree failed");
4704 $/ = "\n";
4706 my $refs = git_get_references();
4707 my $ref = format_ref_marker($refs, $hash_base);
4708 git_header_html();
4709 my $basedir = '';
4710 my ($have_blame) = gitweb_check_feature('blame');
4711 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4712 my @views_nav = ();
4713 if (defined $file_name) {
4714 push @views_nav,
4715 $cgi->a({-href => href(action=>"history", -replay=>1)},
4716 "history"),
4717 $cgi->a({-href => href(action=>"tree",
4718 hash_base=>"HEAD", file_name=>$file_name)},
4719 "HEAD"),
4721 my $snapshot_links = format_snapshot_links($hash);
4722 if (defined $snapshot_links) {
4723 # FIXME: Should be available when we have no hash base as well.
4724 push @views_nav, $snapshot_links;
4726 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4727 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4728 } else {
4729 undef $hash_base;
4730 print "<div class=\"page_nav\">\n";
4731 print "<br/><br/></div>\n";
4732 print "<div class=\"title\">$hash</div>\n";
4734 if (defined $file_name) {
4735 $basedir = $file_name;
4736 if ($basedir ne '' && substr($basedir, -1) ne '/') {
4737 $basedir .= '/';
4739 git_print_page_path($file_name, 'tree', $hash_base);
4741 print "<div class=\"page_body\">\n";
4742 print "<table class=\"tree\">\n";
4743 my $alternate = 1;
4744 # '..' (top directory) link if possible
4745 if (defined $hash_base &&
4746 defined $file_name && $file_name =~ m![^/]+$!) {
4747 if ($alternate) {
4748 print "<tr class=\"dark\">\n";
4749 } else {
4750 print "<tr class=\"light\">\n";
4752 $alternate ^= 1;
4754 my $up = $file_name;
4755 $up =~ s!/?[^/]+$!!;
4756 undef $up unless $up;
4757 # based on git_print_tree_entry
4758 print '<td class="mode">' . mode_str('040000') . "</td>\n";
4759 print '<td class="list">';
4760 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4761 file_name=>$up)},
4762 "..");
4763 print "</td>\n";
4764 print "<td class=\"link\"></td>\n";
4766 print "</tr>\n";
4768 foreach my $line (@entries) {
4769 my %t = parse_ls_tree_line($line, -z => 1);
4771 if ($alternate) {
4772 print "<tr class=\"dark\">\n";
4773 } else {
4774 print "<tr class=\"light\">\n";
4776 $alternate ^= 1;
4778 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4780 print "</tr>\n";
4782 print "</table>\n" .
4783 "</div>";
4784 git_footer_html();
4787 sub git_snapshot {
4788 my @supported_fmts = gitweb_check_feature('snapshot');
4789 @supported_fmts = filter_snapshot_fmts(@supported_fmts);
4791 my $format = $cgi->param('sf');
4792 if (!@supported_fmts) {
4793 die_error(403, "Snapshots not allowed");
4795 # default to first supported snapshot format
4796 $format ||= $supported_fmts[0];
4797 if ($format !~ m/^[a-z0-9]+$/) {
4798 die_error(400, "Invalid snapshot format parameter");
4799 } elsif (!exists($known_snapshot_formats{$format})) {
4800 die_error(400, "Unknown snapshot format");
4801 } elsif (!grep($_ eq $format, @supported_fmts)) {
4802 die_error(403, "Unsupported snapshot format");
4805 if (!defined $hash) {
4806 $hash = git_get_head_hash($project);
4809 my $name = $project;
4810 $name =~ s,([^/])/*\.git$,$1,;
4811 $name = basename($name);
4812 my $filename = to_utf8($name);
4813 $name =~ s/\047/\047\\\047\047/g;
4814 my $cmd;
4815 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
4816 $cmd = quote_command(
4817 git_cmd(), 'archive',
4818 "--format=$known_snapshot_formats{$format}{'format'}",
4819 "--prefix=$name/", $hash);
4820 if (exists $known_snapshot_formats{$format}{'compressor'}) {
4821 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
4824 print $cgi->header(
4825 -type => $known_snapshot_formats{$format}{'type'},
4826 -content_disposition => 'inline; filename="' . "$filename" . '"',
4827 -status => '200 OK');
4829 open my $fd, "-|", $cmd
4830 or die_error(500, "Execute git-archive failed");
4831 binmode STDOUT, ':raw';
4832 print <$fd>;
4833 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4834 close $fd;
4837 sub git_log {
4838 my $head = git_get_head_hash($project);
4839 if (!defined $hash) {
4840 $hash = $head;
4842 if (!defined $page) {
4843 $page = 0;
4845 my $refs = git_get_references();
4847 my @commitlist = parse_commits($hash, 101, (100 * $page));
4849 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
4851 git_header_html();
4852 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4854 if (!@commitlist) {
4855 my %co = parse_commit($hash);
4857 git_print_header_div('summary', $project);
4858 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4860 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4861 for (my $i = 0; $i <= $to; $i++) {
4862 my %co = %{$commitlist[$i]};
4863 next if !%co;
4864 my $commit = $co{'id'};
4865 my $ref = format_ref_marker($refs, $commit);
4866 my %ad = parse_date($co{'author_epoch'});
4867 git_print_header_div('commit',
4868 "<span class=\"age\">$co{'age_string'}</span>" .
4869 esc_html($co{'title'}) . $ref,
4870 $commit);
4871 print "<div class=\"title_text\">\n" .
4872 "<div class=\"log_link\">\n" .
4873 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4874 " | " .
4875 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4876 " | " .
4877 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4878 "<br/>\n" .
4879 "</div>\n" .
4880 "<i>" . esc_html($co{'author_name'}) . " [$ad{'rfc2822'}]</i><br/>\n" .
4881 "</div>\n";
4883 print "<div class=\"log_body\">\n";
4884 git_print_log($co{'comment'}, -final_empty_line=> 1);
4885 print "</div>\n";
4887 if ($#commitlist >= 100) {
4888 print "<div class=\"page_nav\">\n";
4889 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
4890 -accesskey => "n", -title => "Alt-n"}, "next");
4891 print "</div>\n";
4893 git_footer_html();
4896 sub git_commit {
4897 $hash ||= $hash_base || "HEAD";
4898 my %co = parse_commit($hash)
4899 or die_error(404, "Unknown commit object");
4900 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4901 my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4903 my $parent = $co{'parent'};
4904 my $parents = $co{'parents'}; # listref
4906 # we need to prepare $formats_nav before any parameter munging
4907 my $formats_nav;
4908 if (!defined $parent) {
4909 # --root commitdiff
4910 $formats_nav .= '(initial)';
4911 } elsif (@$parents == 1) {
4912 # single parent commit
4913 $formats_nav .=
4914 '(parent: ' .
4915 $cgi->a({-href => href(action=>"commit",
4916 hash=>$parent)},
4917 esc_html(substr($parent, 0, 7))) .
4918 ')';
4919 } else {
4920 # merge commit
4921 $formats_nav .=
4922 '(merge: ' .
4923 join(' ', map {
4924 $cgi->a({-href => href(action=>"commit",
4925 hash=>$_)},
4926 esc_html(substr($_, 0, 7)));
4927 } @$parents ) .
4928 ')';
4931 if (!defined $parent) {
4932 $parent = "--root";
4934 my @difftree;
4935 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4936 @diff_opts,
4937 (@$parents <= 1 ? $parent : '-c'),
4938 $hash, "--"
4939 or die_error(500, "Open git-diff-tree failed");
4940 @difftree = map { chomp; $_ } <$fd>;
4941 close $fd or die_error(404, "Reading git-diff-tree failed");
4943 # non-textual hash id's can be cached
4944 my $expires;
4945 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4946 $expires = "+1d";
4948 my $refs = git_get_references();
4949 my $ref = format_ref_marker($refs, $co{'id'});
4951 git_header_html(undef, $expires);
4952 git_print_page_nav('commit', '',
4953 $hash, $co{'tree'}, $hash,
4954 $formats_nav);
4956 if (defined $co{'parent'}) {
4957 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4958 } else {
4959 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4961 print "<div class=\"title_text\">\n" .
4962 "<table class=\"object_header\">\n";
4963 print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4964 "<tr>" .
4965 "<td></td><td> $ad{'rfc2822'}";
4966 if ($ad{'hour_local'} < 6) {
4967 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4968 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4969 } else {
4970 printf(" (%02d:%02d %s)",
4971 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4973 print "</td>" .
4974 "</tr>\n";
4975 print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4976 print "<tr><td></td><td> $cd{'rfc2822'}" .
4977 sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4978 "</td></tr>\n";
4979 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4980 print "<tr>" .
4981 "<td>tree</td>" .
4982 "<td class=\"sha1\">" .
4983 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4984 class => "list"}, $co{'tree'}) .
4985 "</td>" .
4986 "<td class=\"link\">" .
4987 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4988 "tree");
4989 my $snapshot_links = format_snapshot_links($hash);
4990 if (defined $snapshot_links) {
4991 print " | " . $snapshot_links;
4993 print "</td>" .
4994 "</tr>\n";
4996 foreach my $par (@$parents) {
4997 print "<tr>" .
4998 "<td>parent</td>" .
4999 "<td class=\"sha1\">" .
5000 $cgi->a({-href => href(action=>"commit", hash=>$par),
5001 class => "list"}, $par) .
5002 "</td>" .
5003 "<td class=\"link\">" .
5004 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5005 " | " .
5006 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5007 "</td>" .
5008 "</tr>\n";
5010 print "</table>".
5011 "</div>\n";
5013 print "<div class=\"page_body\">\n";
5014 git_print_log($co{'comment'});
5015 print "</div>\n";
5017 git_difftree_body(\@difftree, $hash, @$parents);
5019 git_footer_html();
5022 sub git_object {
5023 # object is defined by:
5024 # - hash or hash_base alone
5025 # - hash_base and file_name
5026 my $type;
5028 # - hash or hash_base alone
5029 if ($hash || ($hash_base && !defined $file_name)) {
5030 my $object_id = $hash || $hash_base;
5032 open my $fd, "-|", quote_command(
5033 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5034 or die_error(404, "Object does not exist");
5035 $type = <$fd>;
5036 chomp $type;
5037 close $fd
5038 or die_error(404, "Object does not exist");
5040 # - hash_base and file_name
5041 } elsif ($hash_base && defined $file_name) {
5042 $file_name =~ s,/+$,,;
5044 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5045 or die_error(404, "Base object does not exist");
5047 # here errors should not hapen
5048 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5049 or die_error(500, "Open git-ls-tree failed");
5050 my $line = <$fd>;
5051 close $fd;
5053 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5054 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5055 die_error(404, "File or directory for given base does not exist");
5057 $type = $2;
5058 $hash = $3;
5059 } else {
5060 die_error(400, "Not enough information to find object");
5063 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5064 hash=>$hash, hash_base=>$hash_base,
5065 file_name=>$file_name),
5066 -status => '302 Found');
5069 sub git_blobdiff {
5070 my $format = shift || 'html';
5072 my $fd;
5073 my @difftree;
5074 my %diffinfo;
5075 my $expires;
5077 # preparing $fd and %diffinfo for git_patchset_body
5078 # new style URI
5079 if (defined $hash_base && defined $hash_parent_base) {
5080 if (defined $file_name) {
5081 # read raw output
5082 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5083 $hash_parent_base, $hash_base,
5084 "--", (defined $file_parent ? $file_parent : ()), $file_name
5085 or die_error(500, "Open git-diff-tree failed");
5086 @difftree = map { chomp; $_ } <$fd>;
5087 close $fd
5088 or die_error(404, "Reading git-diff-tree failed");
5089 @difftree
5090 or die_error(404, "Blob diff not found");
5092 } elsif (defined $hash &&
5093 $hash =~ /[0-9a-fA-F]{40}/) {
5094 # try to find filename from $hash
5096 # read filtered raw output
5097 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5098 $hash_parent_base, $hash_base, "--"
5099 or die_error(500, "Open git-diff-tree failed");
5100 @difftree =
5101 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5102 # $hash == to_id
5103 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5104 map { chomp; $_ } <$fd>;
5105 close $fd
5106 or die_error(404, "Reading git-diff-tree failed");
5107 @difftree
5108 or die_error(404, "Blob diff not found");
5110 } else {
5111 die_error(400, "Missing one of the blob diff parameters");
5114 if (@difftree > 1) {
5115 die_error(400, "Ambiguous blob diff specification");
5118 %diffinfo = parse_difftree_raw_line($difftree[0]);
5119 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5120 $file_name ||= $diffinfo{'to_file'};
5122 $hash_parent ||= $diffinfo{'from_id'};
5123 $hash ||= $diffinfo{'to_id'};
5125 # non-textual hash id's can be cached
5126 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5127 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5128 $expires = '+1d';
5131 # open patch output
5132 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5133 '-p', ($format eq 'html' ? "--full-index" : ()),
5134 $hash_parent_base, $hash_base,
5135 "--", (defined $file_parent ? $file_parent : ()), $file_name
5136 or die_error(500, "Open git-diff-tree failed");
5139 # old/legacy style URI
5140 if (!%diffinfo && # if new style URI failed
5141 defined $hash && defined $hash_parent) {
5142 # fake git-diff-tree raw output
5143 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
5144 $diffinfo{'from_id'} = $hash_parent;
5145 $diffinfo{'to_id'} = $hash;
5146 if (defined $file_name) {
5147 if (defined $file_parent) {
5148 $diffinfo{'status'} = '2';
5149 $diffinfo{'from_file'} = $file_parent;
5150 $diffinfo{'to_file'} = $file_name;
5151 } else { # assume not renamed
5152 $diffinfo{'status'} = '1';
5153 $diffinfo{'from_file'} = $file_name;
5154 $diffinfo{'to_file'} = $file_name;
5156 } else { # no filename given
5157 $diffinfo{'status'} = '2';
5158 $diffinfo{'from_file'} = $hash_parent;
5159 $diffinfo{'to_file'} = $hash;
5162 # non-textual hash id's can be cached
5163 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
5164 $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5165 $expires = '+1d';
5168 # open patch output
5169 open $fd, "-|", git_cmd(), "diff", @diff_opts,
5170 '-p', ($format eq 'html' ? "--full-index" : ()),
5171 $hash_parent, $hash, "--"
5172 or die_error(500, "Open git-diff failed");
5173 } else {
5174 die_error(400, "Missing one of the blob diff parameters")
5175 unless %diffinfo;
5178 # header
5179 if ($format eq 'html') {
5180 my $formats_nav =
5181 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5182 "raw");
5183 git_header_html(undef, $expires);
5184 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5185 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5186 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5187 } else {
5188 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5189 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5191 if (defined $file_name) {
5192 git_print_page_path($file_name, "blob", $hash_base);
5193 } else {
5194 print "<div class=\"page_path\"></div>\n";
5197 } elsif ($format eq 'plain') {
5198 print $cgi->header(
5199 -type => 'text/plain',
5200 -charset => 'utf-8',
5201 -expires => $expires,
5202 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5204 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5206 } else {
5207 die_error(400, "Unknown blobdiff format");
5210 # patch
5211 if ($format eq 'html') {
5212 print "<div class=\"page_body\">\n";
5214 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5215 close $fd;
5217 print "</div>\n"; # class="page_body"
5218 git_footer_html();
5220 } else {
5221 while (my $line = <$fd>) {
5222 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5223 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5225 print $line;
5227 last if $line =~ m!^\+\+\+!;
5229 local $/ = undef;
5230 print <$fd>;
5231 close $fd;
5235 sub git_blobdiff_plain {
5236 git_blobdiff('plain');
5239 sub git_commitdiff {
5240 my $format = shift || 'html';
5241 $hash ||= $hash_base || "HEAD";
5242 my %co = parse_commit($hash)
5243 or die_error(404, "Unknown commit object");
5245 # choose format for commitdiff for merge
5246 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5247 $hash_parent = '--cc';
5249 # we need to prepare $formats_nav before almost any parameter munging
5250 my $formats_nav;
5251 if ($format eq 'html') {
5252 $formats_nav =
5253 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5254 "raw");
5256 if (defined $hash_parent &&
5257 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5258 # commitdiff with two commits given
5259 my $hash_parent_short = $hash_parent;
5260 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5261 $hash_parent_short = substr($hash_parent, 0, 7);
5263 $formats_nav .=
5264 ' (from';
5265 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5266 if ($co{'parents'}[$i] eq $hash_parent) {
5267 $formats_nav .= ' parent ' . ($i+1);
5268 last;
5271 $formats_nav .= ': ' .
5272 $cgi->a({-href => href(action=>"commitdiff",
5273 hash=>$hash_parent)},
5274 esc_html($hash_parent_short)) .
5275 ')';
5276 } elsif (!$co{'parent'}) {
5277 # --root commitdiff
5278 $formats_nav .= ' (initial)';
5279 } elsif (scalar @{$co{'parents'}} == 1) {
5280 # single parent commit
5281 $formats_nav .=
5282 ' (parent: ' .
5283 $cgi->a({-href => href(action=>"commitdiff",
5284 hash=>$co{'parent'})},
5285 esc_html(substr($co{'parent'}, 0, 7))) .
5286 ')';
5287 } else {
5288 # merge commit
5289 if ($hash_parent eq '--cc') {
5290 $formats_nav .= ' | ' .
5291 $cgi->a({-href => href(action=>"commitdiff",
5292 hash=>$hash, hash_parent=>'-c')},
5293 'combined');
5294 } else { # $hash_parent eq '-c'
5295 $formats_nav .= ' | ' .
5296 $cgi->a({-href => href(action=>"commitdiff",
5297 hash=>$hash, hash_parent=>'--cc')},
5298 'compact');
5300 $formats_nav .=
5301 ' (merge: ' .
5302 join(' ', map {
5303 $cgi->a({-href => href(action=>"commitdiff",
5304 hash=>$_)},
5305 esc_html(substr($_, 0, 7)));
5306 } @{$co{'parents'}} ) .
5307 ')';
5311 my $hash_parent_param = $hash_parent;
5312 if (!defined $hash_parent_param) {
5313 # --cc for multiple parents, --root for parentless
5314 $hash_parent_param =
5315 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5318 # read commitdiff
5319 my $fd;
5320 my @difftree;
5321 if ($format eq 'html') {
5322 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5323 "--no-commit-id", "--patch-with-raw", "--full-index",
5324 $hash_parent_param, $hash, "--"
5325 or die_error(500, "Open git-diff-tree failed");
5327 while (my $line = <$fd>) {
5328 chomp $line;
5329 # empty line ends raw part of diff-tree output
5330 last unless $line;
5331 push @difftree, scalar parse_difftree_raw_line($line);
5334 } elsif ($format eq 'plain') {
5335 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5336 '-p', $hash_parent_param, $hash, "--"
5337 or die_error(500, "Open git-diff-tree failed");
5339 } else {
5340 die_error(400, "Unknown commitdiff format");
5343 # non-textual hash id's can be cached
5344 my $expires;
5345 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5346 $expires = "+1d";
5349 # write commit message
5350 if ($format eq 'html') {
5351 my $refs = git_get_references();
5352 my $ref = format_ref_marker($refs, $co{'id'});
5354 git_header_html(undef, $expires);
5355 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5356 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5357 git_print_authorship(\%co);
5358 print "<div class=\"page_body\">\n";
5359 if (@{$co{'comment'}} > 1) {
5360 print "<div class=\"log\">\n";
5361 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5362 print "</div>\n"; # class="log"
5365 } elsif ($format eq 'plain') {
5366 my $refs = git_get_references("tags");
5367 my $tagname = git_get_rev_name_tags($hash);
5368 my $filename = basename($project) . "-$hash.patch";
5370 print $cgi->header(
5371 -type => 'text/plain',
5372 -charset => 'utf-8',
5373 -expires => $expires,
5374 -content_disposition => 'inline; filename="' . "$filename" . '"');
5375 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5376 print "From: " . to_utf8($co{'author'}) . "\n";
5377 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5378 print "Subject: " . to_utf8($co{'title'}) . "\n";
5380 print "X-Git-Tag: $tagname\n" if $tagname;
5381 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5383 foreach my $line (@{$co{'comment'}}) {
5384 print to_utf8($line) . "\n";
5386 print "---\n\n";
5389 # write patch
5390 if ($format eq 'html') {
5391 my $use_parents = !defined $hash_parent ||
5392 $hash_parent eq '-c' || $hash_parent eq '--cc';
5393 git_difftree_body(\@difftree, $hash,
5394 $use_parents ? @{$co{'parents'}} : $hash_parent);
5395 print "<br/>\n";
5397 git_patchset_body($fd, \@difftree, $hash,
5398 $use_parents ? @{$co{'parents'}} : $hash_parent);
5399 close $fd;
5400 print "</div>\n"; # class="page_body"
5401 git_footer_html();
5403 } elsif ($format eq 'plain') {
5404 local $/ = undef;
5405 print <$fd>;
5406 close $fd
5407 or print "Reading git-diff-tree failed\n";
5411 sub git_commitdiff_plain {
5412 git_commitdiff('plain');
5415 sub git_history {
5416 if (!defined $hash_base) {
5417 $hash_base = git_get_head_hash($project);
5419 if (!defined $page) {
5420 $page = 0;
5422 my $ftype;
5423 my %co = parse_commit($hash_base)
5424 or die_error(404, "Unknown commit object");
5426 my $refs = git_get_references();
5427 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5429 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5430 $file_name, "--full-history")
5431 or die_error(404, "No such file or directory on given branch");
5433 if (!defined $hash && defined $file_name) {
5434 # some commits could have deleted file in question,
5435 # and not have it in tree, but one of them has to have it
5436 for (my $i = 0; $i <= @commitlist; $i++) {
5437 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5438 last if defined $hash;
5441 if (defined $hash) {
5442 $ftype = git_get_type($hash);
5444 if (!defined $ftype) {
5445 die_error(500, "Unknown type of object");
5448 my $paging_nav = '';
5449 if ($page > 0) {
5450 $paging_nav .=
5451 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5452 file_name=>$file_name)},
5453 "first");
5454 $paging_nav .= " &sdot; " .
5455 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5456 -accesskey => "p", -title => "Alt-p"}, "prev");
5457 } else {
5458 $paging_nav .= "first";
5459 $paging_nav .= " &sdot; prev";
5461 my $next_link = '';
5462 if ($#commitlist >= 100) {
5463 $next_link =
5464 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5465 -accesskey => "n", -title => "Alt-n"}, "next");
5466 $paging_nav .= " &sdot; $next_link";
5467 } else {
5468 $paging_nav .= " &sdot; next";
5471 git_header_html();
5472 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5473 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5474 git_print_page_path($file_name, $ftype, $hash_base);
5476 git_history_body(\@commitlist, 0, 99,
5477 $refs, $hash_base, $ftype, $next_link);
5479 git_footer_html();
5482 sub git_search {
5483 gitweb_check_feature('search') or die_error(403, "Search is disabled");
5484 if (!defined $searchtext) {
5485 die_error(400, "Text field is empty");
5487 if (!defined $hash) {
5488 $hash = git_get_head_hash($project);
5490 my %co = parse_commit($hash);
5491 if (!%co) {
5492 die_error(404, "Unknown commit object");
5494 if (!defined $page) {
5495 $page = 0;
5498 $searchtype ||= 'commit';
5499 if ($searchtype eq 'pickaxe') {
5500 # pickaxe may take all resources of your box and run for several minutes
5501 # with every query - so decide by yourself how public you make this feature
5502 gitweb_check_feature('pickaxe')
5503 or die_error(403, "Pickaxe is disabled");
5505 if ($searchtype eq 'grep') {
5506 gitweb_check_feature('grep')
5507 or die_error(403, "Grep is disabled");
5510 git_header_html();
5512 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5513 my $greptype;
5514 if ($searchtype eq 'commit') {
5515 $greptype = "--grep=";
5516 } elsif ($searchtype eq 'author') {
5517 $greptype = "--author=";
5518 } elsif ($searchtype eq 'committer') {
5519 $greptype = "--committer=";
5521 $greptype .= $searchtext;
5522 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5523 $greptype, '--regexp-ignore-case',
5524 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5526 my $paging_nav = '';
5527 if ($page > 0) {
5528 $paging_nav .=
5529 $cgi->a({-href => href(action=>"search", hash=>$hash,
5530 searchtext=>$searchtext,
5531 searchtype=>$searchtype)},
5532 "first");
5533 $paging_nav .= " &sdot; " .
5534 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5535 -accesskey => "p", -title => "Alt-p"}, "prev");
5536 } else {
5537 $paging_nav .= "first";
5538 $paging_nav .= " &sdot; prev";
5540 my $next_link = '';
5541 if ($#commitlist >= 100) {
5542 $next_link =
5543 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5544 -accesskey => "n", -title => "Alt-n"}, "next");
5545 $paging_nav .= " &sdot; $next_link";
5546 } else {
5547 $paging_nav .= " &sdot; next";
5550 if ($#commitlist >= 100) {
5553 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5554 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5555 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5558 if ($searchtype eq 'pickaxe') {
5559 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5560 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5562 print "<table class=\"pickaxe search\">\n";
5563 my $alternate = 1;
5564 $/ = "\n";
5565 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5566 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5567 ($search_use_regexp ? '--pickaxe-regex' : ());
5568 undef %co;
5569 my @files;
5570 while (my $line = <$fd>) {
5571 chomp $line;
5572 next unless $line;
5574 my %set = parse_difftree_raw_line($line);
5575 if (defined $set{'commit'}) {
5576 # finish previous commit
5577 if (%co) {
5578 print "</td>\n" .
5579 "<td class=\"link\">" .
5580 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5581 " | " .
5582 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5583 print "</td>\n" .
5584 "</tr>\n";
5587 if ($alternate) {
5588 print "<tr class=\"dark\">\n";
5589 } else {
5590 print "<tr class=\"light\">\n";
5592 $alternate ^= 1;
5593 %co = parse_commit($set{'commit'});
5594 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5595 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5596 "<td><i>$author</i></td>\n" .
5597 "<td>" .
5598 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5599 -class => "list subject"},
5600 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5601 } elsif (defined $set{'to_id'}) {
5602 next if ($set{'to_id'} =~ m/^0{40}$/);
5604 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5605 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
5606 -class => "list"},
5607 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5608 "<br/>\n";
5611 close $fd;
5613 # finish last commit (warning: repetition!)
5614 if (%co) {
5615 print "</td>\n" .
5616 "<td class=\"link\">" .
5617 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5618 " | " .
5619 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5620 print "</td>\n" .
5621 "</tr>\n";
5624 print "</table>\n";
5627 if ($searchtype eq 'grep') {
5628 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5629 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5631 print "<table class=\"grep_search\">\n";
5632 my $alternate = 1;
5633 my $matches = 0;
5634 $/ = "\n";
5635 open my $fd, "-|", git_cmd(), 'grep', '-n',
5636 $search_use_regexp ? ('-E', '-i') : '-F',
5637 $searchtext, $co{'tree'};
5638 my $lastfile = '';
5639 while (my $line = <$fd>) {
5640 chomp $line;
5641 my ($file, $lno, $ltext, $binary);
5642 last if ($matches++ > 1000);
5643 if ($line =~ /^Binary file (.+) matches$/) {
5644 $file = $1;
5645 $binary = 1;
5646 } else {
5647 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5649 if ($file ne $lastfile) {
5650 $lastfile and print "</td></tr>\n";
5651 if ($alternate++) {
5652 print "<tr class=\"dark\">\n";
5653 } else {
5654 print "<tr class=\"light\">\n";
5656 print "<td class=\"list\">".
5657 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5658 file_name=>"$file"),
5659 -class => "list"}, esc_path($file));
5660 print "</td><td>\n";
5661 $lastfile = $file;
5663 if ($binary) {
5664 print "<div class=\"binary\">Binary file</div>\n";
5665 } else {
5666 $ltext = untabify($ltext);
5667 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
5668 $ltext = esc_html($1, -nbsp=>1);
5669 $ltext .= '<span class="match">';
5670 $ltext .= esc_html($2, -nbsp=>1);
5671 $ltext .= '</span>';
5672 $ltext .= esc_html($3, -nbsp=>1);
5673 } else {
5674 $ltext = esc_html($ltext, -nbsp=>1);
5676 print "<div class=\"pre\">" .
5677 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5678 file_name=>"$file").'#l'.$lno,
5679 -class => "linenr"}, sprintf('%4i', $lno))
5680 . ' ' . $ltext . "</div>\n";
5683 if ($lastfile) {
5684 print "</td></tr>\n";
5685 if ($matches > 1000) {
5686 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5688 } else {
5689 print "<div class=\"diff nodifferences\">No matches found</div>\n";
5691 close $fd;
5693 print "</table>\n";
5695 git_footer_html();
5698 sub git_search_help {
5699 git_header_html();
5700 git_print_page_nav('','', $hash,$hash,$hash);
5701 print <<EOT;
5702 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
5703 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
5704 the pattern entered is recognized as the POSIX extended
5705 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
5706 insensitive).</p>
5707 <dl>
5708 <dt><b>commit</b></dt>
5709 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
5711 my ($have_grep) = gitweb_check_feature('grep');
5712 if ($have_grep) {
5713 print <<EOT;
5714 <dt><b>grep</b></dt>
5715 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5716 a different one) are searched for the given pattern. On large trees, this search can take
5717 a while and put some strain on the server, so please use it with some consideration. Note that
5718 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
5719 case-sensitive.</dd>
5722 print <<EOT;
5723 <dt><b>author</b></dt>
5724 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
5725 <dt><b>committer</b></dt>
5726 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
5728 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5729 if ($have_pickaxe) {
5730 print <<EOT;
5731 <dt><b>pickaxe</b></dt>
5732 <dd>All commits that caused the string to appear or disappear from any file (changes that
5733 added, removed or "modified" the string) will be listed. This search can take a while and
5734 takes a lot of strain on the server, so please use it wisely. Note that since you may be
5735 interested even in changes just changing the case as well, this search is case sensitive.</dd>
5738 print "</dl>\n";
5739 git_footer_html();
5742 sub git_shortlog {
5743 my $head = git_get_head_hash($project);
5744 if (!defined $hash) {
5745 $hash = $head;
5747 if (!defined $page) {
5748 $page = 0;
5750 my $refs = git_get_references();
5752 my $commit_hash = $hash;
5753 if (defined $hash_parent) {
5754 $commit_hash = "$hash_parent..$hash";
5756 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
5758 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
5759 my $next_link = '';
5760 if ($#commitlist >= 100) {
5761 $next_link =
5762 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5763 -accesskey => "n", -title => "Alt-n"}, "next");
5766 git_header_html();
5767 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5768 git_print_header_div('summary', $project);
5770 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5772 git_footer_html();
5775 ## ......................................................................
5776 ## feeds (RSS, Atom; OPML)
5778 sub git_feed {
5779 my $format = shift || 'atom';
5780 my ($have_blame) = gitweb_check_feature('blame');
5782 # Atom: http://www.atomenabled.org/developers/syndication/
5783 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5784 if ($format ne 'rss' && $format ne 'atom') {
5785 die_error(400, "Unknown web feed format");
5788 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5789 my $head = $hash || 'HEAD';
5790 my @commitlist = parse_commits($head, 150, 0, $file_name);
5792 my %latest_commit;
5793 my %latest_date;
5794 my $content_type = "application/$format+xml";
5795 if (defined $cgi->http('HTTP_ACCEPT') &&
5796 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5797 # browser (feed reader) prefers text/xml
5798 $content_type = 'text/xml';
5800 if (defined($commitlist[0])) {
5801 %latest_commit = %{$commitlist[0]};
5802 %latest_date = parse_date($latest_commit{'author_epoch'});
5803 print $cgi->header(
5804 -type => $content_type,
5805 -charset => 'utf-8',
5806 -last_modified => $latest_date{'rfc2822'});
5807 } else {
5808 print $cgi->header(
5809 -type => $content_type,
5810 -charset => 'utf-8');
5813 # Optimization: skip generating the body if client asks only
5814 # for Last-Modified date.
5815 return if ($cgi->request_method() eq 'HEAD');
5817 # header variables
5818 my $title = "$site_name - $project/$action";
5819 my $feed_type = 'log';
5820 if (defined $hash) {
5821 $title .= " - '$hash'";
5822 $feed_type = 'branch log';
5823 if (defined $file_name) {
5824 $title .= " :: $file_name";
5825 $feed_type = 'history';
5827 } elsif (defined $file_name) {
5828 $title .= " - $file_name";
5829 $feed_type = 'history';
5831 $title .= " $feed_type";
5832 my $descr = git_get_project_description($project);
5833 if (defined $descr) {
5834 $descr = esc_html($descr);
5835 } else {
5836 $descr = "$project " .
5837 ($format eq 'rss' ? 'RSS' : 'Atom') .
5838 " feed";
5840 my $owner = git_get_project_owner($project);
5841 $owner = esc_html($owner);
5843 #header
5844 my $alt_url;
5845 if (defined $file_name) {
5846 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5847 } elsif (defined $hash) {
5848 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5849 } else {
5850 $alt_url = href(-full=>1, action=>"summary");
5852 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5853 if ($format eq 'rss') {
5854 print <<XML;
5855 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5856 <channel>
5858 print "<title>$title</title>\n" .
5859 "<link>$alt_url</link>\n" .
5860 "<description>$descr</description>\n" .
5861 "<language>en</language>\n";
5862 } elsif ($format eq 'atom') {
5863 print <<XML;
5864 <feed xmlns="http://www.w3.org/2005/Atom">
5866 print "<title>$title</title>\n" .
5867 "<subtitle>$descr</subtitle>\n" .
5868 '<link rel="alternate" type="text/html" href="' .
5869 $alt_url . '" />' . "\n" .
5870 '<link rel="self" type="' . $content_type . '" href="' .
5871 $cgi->self_url() . '" />' . "\n" .
5872 "<id>" . href(-full=>1) . "</id>\n" .
5873 # use project owner for feed author
5874 "<author><name>$owner</name></author>\n";
5875 if (defined $favicon) {
5876 print "<icon>" . esc_url($favicon) . "</icon>\n";
5878 if (defined $logo_url) {
5879 # not twice as wide as tall: 72 x 27 pixels
5880 print "<logo>" . esc_url($logo) . "</logo>\n";
5882 if (! %latest_date) {
5883 # dummy date to keep the feed valid until commits trickle in:
5884 print "<updated>1970-01-01T00:00:00Z</updated>\n";
5885 } else {
5886 print "<updated>$latest_date{'iso-8601'}</updated>\n";
5890 # contents
5891 for (my $i = 0; $i <= $#commitlist; $i++) {
5892 my %co = %{$commitlist[$i]};
5893 my $commit = $co{'id'};
5894 # we read 150, we always show 30 and the ones more recent than 48 hours
5895 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5896 last;
5898 my %cd = parse_date($co{'author_epoch'});
5900 # get list of changed files
5901 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5902 $co{'parent'} || "--root",
5903 $co{'id'}, "--", (defined $file_name ? $file_name : ())
5904 or next;
5905 my @difftree = map { chomp; $_ } <$fd>;
5906 close $fd
5907 or next;
5909 # print element (entry, item)
5910 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
5911 if ($format eq 'rss') {
5912 print "<item>\n" .
5913 "<title>" . esc_html($co{'title'}) . "</title>\n" .
5914 "<author>" . esc_html($co{'author'}) . "</author>\n" .
5915 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5916 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5917 "<link>$co_url</link>\n" .
5918 "<description>" . esc_html($co{'title'}) . "</description>\n" .
5919 "<content:encoded>" .
5920 "<![CDATA[\n";
5921 } elsif ($format eq 'atom') {
5922 print "<entry>\n" .
5923 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5924 "<updated>$cd{'iso-8601'}</updated>\n" .
5925 "<author>\n" .
5926 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
5927 if ($co{'author_email'}) {
5928 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
5930 print "</author>\n" .
5931 # use committer for contributor
5932 "<contributor>\n" .
5933 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5934 if ($co{'committer_email'}) {
5935 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5937 print "</contributor>\n" .
5938 "<published>$cd{'iso-8601'}</published>\n" .
5939 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5940 "<id>$co_url</id>\n" .
5941 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5942 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5944 my $comment = $co{'comment'};
5945 print "<pre>\n";
5946 foreach my $line (@$comment) {
5947 $line = esc_html($line);
5948 print "$line\n";
5950 print "</pre><ul>\n";
5951 foreach my $difftree_line (@difftree) {
5952 my %difftree = parse_difftree_raw_line($difftree_line);
5953 next if !$difftree{'from_id'};
5955 my $file = $difftree{'file'} || $difftree{'to_file'};
5957 print "<li>" .
5958 "[" .
5959 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5960 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5961 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5962 file_name=>$file, file_parent=>$difftree{'from_file'}),
5963 -title => "diff"}, 'D');
5964 if ($have_blame) {
5965 print $cgi->a({-href => href(-full=>1, action=>"blame",
5966 file_name=>$file, hash_base=>$commit), -class => "blamelink",
5967 -title => "blame"}, 'B');
5969 # if this is not a feed of a file history
5970 if (!defined $file_name || $file_name ne $file) {
5971 print $cgi->a({-href => href(-full=>1, action=>"history",
5972 file_name=>$file, hash=>$commit),
5973 -title => "history"}, 'H');
5975 $file = esc_path($file);
5976 print "] ".
5977 "$file</li>\n";
5979 if ($format eq 'rss') {
5980 print "</ul>]]>\n" .
5981 "</content:encoded>\n" .
5982 "</item>\n";
5983 } elsif ($format eq 'atom') {
5984 print "</ul>\n</div>\n" .
5985 "</content>\n" .
5986 "</entry>\n";
5990 # end of feed
5991 if ($format eq 'rss') {
5992 print "</channel>\n</rss>\n";
5993 } elsif ($format eq 'atom') {
5994 print "</feed>\n";
5998 sub git_rss {
5999 git_feed('rss');
6002 sub git_atom {
6003 git_feed('atom');
6006 sub git_opml {
6007 my @list = git_get_projects_list();
6009 print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
6010 print <<XML;
6011 <?xml version="1.0" encoding="utf-8"?>
6012 <opml version="1.0">
6013 <head>
6014 <title>$site_name OPML Export</title>
6015 </head>
6016 <body>
6017 <outline text="git RSS feeds">
6020 foreach my $pr (@list) {
6021 my %proj = %$pr;
6022 my $head = git_get_head_hash($proj{'path'});
6023 if (!defined $head) {
6024 next;
6026 $git_dir = "$projectroot/$proj{'path'}";
6027 my %co = parse_commit($head);
6028 if (!%co) {
6029 next;
6032 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6033 my $rss = "$my_url?p=$proj{'path'};a=rss";
6034 my $html = "$my_url?p=$proj{'path'};a=summary";
6035 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6037 print <<XML;
6038 </outline>
6039 </body>
6040 </opml>