Merge commit 'refs/top-bases/t/blame/extra-columns' into t/blame/extra-columns
[git/gitweb.git] / gitweb / gitweb.perl
blob18f054a610f6554d47bda47325ea323ab9f9f934
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;
4439 <div class="page_body">
4440 <table class="blame">
4441 <tr><th>Commit&nbsp;<a href="javascript:extra_blame_columns()" id="columns_expander">[+]</a></th>
4442 <th class="extra_column">Author</th>
4443 <th class="extra_column">Date</th>
4444 <th>Line</th>
4445 <th>Data</th></tr>
4446 HTML
4447 my %metainfo = ();
4448 my $linenr = 0;
4449 while (<$fd>) {
4450 chomp;
4451 if ($type eq 'incremental') {
4452 # Empty stage with just the file contents
4453 $linenr += 1;
4454 print "<tr id=\"l$linenr\" class=\"light2\">";
4455 print '<td class="sha1"><a href=""></a></td>';
4456 print "<td class=\"extra_column\"></td>";
4457 print "<td class=\"extra_column\"></td>";
4458 print "<td class=\"linenr\"><a class=\"linenr\" href=\"\">$linenr</a></td><td class=\"pre\">" . esc_html($_) . "</td>\n";
4459 print "</tr>\n";
4460 next;
4463 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4464 /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
4465 if (!exists $metainfo{$full_rev}) {
4466 $metainfo{$full_rev} = {};
4468 my $meta = $metainfo{$full_rev};
4469 while (<$fd>) {
4470 last if (s/^\t//);
4471 if (/^(\S+) (.*)$/) {
4472 $meta->{$1} = $2;
4475 my $data = $_;
4476 chomp $data;
4477 my $rev = substr($full_rev, 0, 8);
4478 my $author = $meta->{'author'};
4479 my %date = parse_date($meta->{'author-time'},
4480 $meta->{'author-tz'});
4481 my $date = $date{'iso-tz'};
4482 if ($group_size) {
4483 $current_color = ++$current_color % $num_colors;
4485 print "<tr class=\"$rev_color[$current_color]\">\n";
4486 if ($group_size) {
4487 my $rowspan = $group_size > 1 ? " rowspan=\"$group_size\"" : "";
4488 print "<td class=\"sha1\"";
4489 print " title=\"". esc_html($author) . ", $date\"";
4490 print "$rowspan>";
4491 print $cgi->a({-href => href(action=>"commit",
4492 hash=>$full_rev,
4493 file_name=>$file_name)},
4494 esc_html($rev));
4495 print "</td>\n";
4496 print "<td class=\"extra_column\" $rowspan>". esc_html($author) . "</td>";
4497 print "<td class=\"extra_column\" $rowspan>". $date . "</td>";
4499 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
4500 or die_error(500, "Open git-rev-parse failed");
4501 my $parent_commit = <$dd>;
4502 close $dd;
4503 chomp($parent_commit);
4504 my $blamed = href(action => 'blame',
4505 file_name => $meta->{'filename'},
4506 hash_base => $parent_commit);
4507 print "<td class=\"linenr\">";
4508 print $cgi->a({ -href => "$blamed#l$orig_lineno",
4509 -id => "l$lineno",
4510 -class => "linenr" },
4511 esc_html($lineno));
4512 print "</td>";
4513 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4514 print "</tr>\n";
4517 print "</table>\n";
4518 print "</div>";
4519 close $fd
4520 or print "Reading blob failed\n";
4522 if ($type eq 'incremental') {
4523 print "<script type=\"text/javascript\">\n";
4524 print "startBlame(\"" . href(action=>"blame_data", hash_base=>$hash_base, file_name=>$file_name) . "\", \"" .
4525 href(-partial_query=>1) . "\");\n";
4526 print "</script>\n";
4529 git_footer_html();
4532 sub git_blame_incremental {
4533 git_blame_common('incremental');
4536 sub git_blame {
4537 git_blame_common('oneshot');
4540 sub git_tags {
4541 my $head = git_get_head_hash($project);
4542 git_header_html();
4543 git_print_page_nav('','', $head,undef,$head);
4544 git_print_header_div('summary', $project);
4546 my @tagslist = git_get_tags_list();
4547 if (@tagslist) {
4548 git_tags_body(\@tagslist);
4550 git_footer_html();
4553 sub git_heads {
4554 my $head = git_get_head_hash($project);
4555 git_header_html();
4556 git_print_page_nav('','', $head,undef,$head);
4557 git_print_header_div('summary', $project);
4559 my @headslist = git_get_heads_list();
4560 if (@headslist) {
4561 git_heads_body(\@headslist, $head);
4563 git_footer_html();
4566 sub git_blob_plain {
4567 my $type = shift;
4568 my $expires;
4570 if (!defined $hash) {
4571 if (defined $file_name) {
4572 my $base = $hash_base || git_get_head_hash($project);
4573 $hash = git_get_hash_by_path($base, $file_name, "blob")
4574 or die_error(404, "Cannot find file");
4575 } else {
4576 die_error(400, "No file name defined");
4578 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4579 # blobs defined by non-textual hash id's can be cached
4580 $expires = "+1d";
4583 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4584 or die_error(500, "Open git-cat-file blob '$hash' failed");
4586 # content-type (can include charset)
4587 $type = blob_contenttype($fd, $file_name, $type);
4589 # "save as" filename, even when no $file_name is given
4590 my $save_as = "$hash";
4591 if (defined $file_name) {
4592 $save_as = $file_name;
4593 } elsif ($type =~ m/^text\//) {
4594 $save_as .= '.txt';
4597 print $cgi->header(
4598 -type => $type,
4599 -expires => $expires,
4600 -content_disposition => 'inline; filename="' . $save_as . '"');
4601 undef $/;
4602 binmode STDOUT, ':raw';
4603 print <$fd>;
4604 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4605 $/ = "\n";
4606 close $fd;
4609 sub git_blob {
4610 my $expires;
4612 if (!defined $hash) {
4613 if (defined $file_name) {
4614 my $base = $hash_base || git_get_head_hash($project);
4615 $hash = git_get_hash_by_path($base, $file_name, "blob")
4616 or die_error(404, "Cannot find file");
4617 } else {
4618 die_error(400, "No file name defined");
4620 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4621 # blobs defined by non-textual hash id's can be cached
4622 $expires = "+1d";
4625 my ($have_blame) = gitweb_check_feature('blame');
4626 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4627 or die_error(500, "Couldn't cat $file_name, $hash");
4628 my $mimetype = blob_mimetype($fd, $file_name);
4629 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
4630 close $fd;
4631 return git_blob_plain($mimetype);
4633 # we can have blame only for text/* mimetype
4634 $have_blame &&= ($mimetype =~ m!^text/!);
4636 git_header_html(undef, $expires);
4637 my $formats_nav = '';
4638 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4639 if (defined $file_name) {
4640 if ($have_blame) {
4641 $formats_nav .=
4642 $cgi->a({-href => href(action=>"blame", -replay=>1,
4643 -class => "blamelink")},
4644 "blame") .
4645 " | ";
4647 $formats_nav .=
4648 $cgi->a({-href => href(action=>"history", -replay=>1)},
4649 "history") .
4650 " | " .
4651 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4652 "raw") .
4653 " | " .
4654 $cgi->a({-href => href(action=>"blob",
4655 hash_base=>"HEAD", file_name=>$file_name)},
4656 "HEAD");
4657 } else {
4658 $formats_nav .=
4659 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4660 "raw");
4662 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4663 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4664 } else {
4665 print "<div class=\"page_nav\">\n" .
4666 "<br/><br/></div>\n" .
4667 "<div class=\"title\">$hash</div>\n";
4669 git_print_page_path($file_name, "blob", $hash_base);
4670 print "<div class=\"page_body\">\n";
4671 if ($mimetype =~ m!^image/!) {
4672 print qq!<img type="$mimetype"!;
4673 if ($file_name) {
4674 print qq! alt="$file_name" title="$file_name"!;
4676 print qq! src="! .
4677 href(action=>"blob_plain", hash=>$hash,
4678 hash_base=>$hash_base, file_name=>$file_name) .
4679 qq!" />\n!;
4680 } else {
4681 my $nr;
4682 while (my $line = <$fd>) {
4683 chomp $line;
4684 $nr++;
4685 $line = untabify($line);
4686 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4687 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4690 close $fd
4691 or print "Reading blob failed.\n";
4692 print "</div>";
4693 git_footer_html();
4696 sub git_tree {
4697 if (!defined $hash_base) {
4698 $hash_base = "HEAD";
4700 if (!defined $hash) {
4701 if (defined $file_name) {
4702 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4703 } else {
4704 $hash = $hash_base;
4707 die_error(404, "No such tree") unless defined($hash);
4708 $/ = "\0";
4709 open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4710 or die_error(500, "Open git-ls-tree failed");
4711 my @entries = map { chomp; $_ } <$fd>;
4712 close $fd or die_error(404, "Reading tree failed");
4713 $/ = "\n";
4715 my $refs = git_get_references();
4716 my $ref = format_ref_marker($refs, $hash_base);
4717 git_header_html();
4718 my $basedir = '';
4719 my ($have_blame) = gitweb_check_feature('blame');
4720 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4721 my @views_nav = ();
4722 if (defined $file_name) {
4723 push @views_nav,
4724 $cgi->a({-href => href(action=>"history", -replay=>1)},
4725 "history"),
4726 $cgi->a({-href => href(action=>"tree",
4727 hash_base=>"HEAD", file_name=>$file_name)},
4728 "HEAD"),
4730 my $snapshot_links = format_snapshot_links($hash);
4731 if (defined $snapshot_links) {
4732 # FIXME: Should be available when we have no hash base as well.
4733 push @views_nav, $snapshot_links;
4735 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4736 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4737 } else {
4738 undef $hash_base;
4739 print "<div class=\"page_nav\">\n";
4740 print "<br/><br/></div>\n";
4741 print "<div class=\"title\">$hash</div>\n";
4743 if (defined $file_name) {
4744 $basedir = $file_name;
4745 if ($basedir ne '' && substr($basedir, -1) ne '/') {
4746 $basedir .= '/';
4748 git_print_page_path($file_name, 'tree', $hash_base);
4750 print "<div class=\"page_body\">\n";
4751 print "<table class=\"tree\">\n";
4752 my $alternate = 1;
4753 # '..' (top directory) link if possible
4754 if (defined $hash_base &&
4755 defined $file_name && $file_name =~ m![^/]+$!) {
4756 if ($alternate) {
4757 print "<tr class=\"dark\">\n";
4758 } else {
4759 print "<tr class=\"light\">\n";
4761 $alternate ^= 1;
4763 my $up = $file_name;
4764 $up =~ s!/?[^/]+$!!;
4765 undef $up unless $up;
4766 # based on git_print_tree_entry
4767 print '<td class="mode">' . mode_str('040000') . "</td>\n";
4768 print '<td class="list">';
4769 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4770 file_name=>$up)},
4771 "..");
4772 print "</td>\n";
4773 print "<td class=\"link\"></td>\n";
4775 print "</tr>\n";
4777 foreach my $line (@entries) {
4778 my %t = parse_ls_tree_line($line, -z => 1);
4780 if ($alternate) {
4781 print "<tr class=\"dark\">\n";
4782 } else {
4783 print "<tr class=\"light\">\n";
4785 $alternate ^= 1;
4787 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4789 print "</tr>\n";
4791 print "</table>\n" .
4792 "</div>";
4793 git_footer_html();
4796 sub git_snapshot {
4797 my @supported_fmts = gitweb_check_feature('snapshot');
4798 @supported_fmts = filter_snapshot_fmts(@supported_fmts);
4800 my $format = $cgi->param('sf');
4801 if (!@supported_fmts) {
4802 die_error(403, "Snapshots not allowed");
4804 # default to first supported snapshot format
4805 $format ||= $supported_fmts[0];
4806 if ($format !~ m/^[a-z0-9]+$/) {
4807 die_error(400, "Invalid snapshot format parameter");
4808 } elsif (!exists($known_snapshot_formats{$format})) {
4809 die_error(400, "Unknown snapshot format");
4810 } elsif (!grep($_ eq $format, @supported_fmts)) {
4811 die_error(403, "Unsupported snapshot format");
4814 if (!defined $hash) {
4815 $hash = git_get_head_hash($project);
4818 my $name = $project;
4819 $name =~ s,([^/])/*\.git$,$1,;
4820 $name = basename($name);
4821 my $filename = to_utf8($name);
4822 $name =~ s/\047/\047\\\047\047/g;
4823 my $cmd;
4824 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
4825 $cmd = quote_command(
4826 git_cmd(), 'archive',
4827 "--format=$known_snapshot_formats{$format}{'format'}",
4828 "--prefix=$name/", $hash);
4829 if (exists $known_snapshot_formats{$format}{'compressor'}) {
4830 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
4833 print $cgi->header(
4834 -type => $known_snapshot_formats{$format}{'type'},
4835 -content_disposition => 'inline; filename="' . "$filename" . '"',
4836 -status => '200 OK');
4838 open my $fd, "-|", $cmd
4839 or die_error(500, "Execute git-archive failed");
4840 binmode STDOUT, ':raw';
4841 print <$fd>;
4842 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4843 close $fd;
4846 sub git_log {
4847 my $head = git_get_head_hash($project);
4848 if (!defined $hash) {
4849 $hash = $head;
4851 if (!defined $page) {
4852 $page = 0;
4854 my $refs = git_get_references();
4856 my @commitlist = parse_commits($hash, 101, (100 * $page));
4858 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
4860 git_header_html();
4861 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4863 if (!@commitlist) {
4864 my %co = parse_commit($hash);
4866 git_print_header_div('summary', $project);
4867 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4869 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4870 for (my $i = 0; $i <= $to; $i++) {
4871 my %co = %{$commitlist[$i]};
4872 next if !%co;
4873 my $commit = $co{'id'};
4874 my $ref = format_ref_marker($refs, $commit);
4875 my %ad = parse_date($co{'author_epoch'});
4876 git_print_header_div('commit',
4877 "<span class=\"age\">$co{'age_string'}</span>" .
4878 esc_html($co{'title'}) . $ref,
4879 $commit);
4880 print "<div class=\"title_text\">\n" .
4881 "<div class=\"log_link\">\n" .
4882 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4883 " | " .
4884 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4885 " | " .
4886 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4887 "<br/>\n" .
4888 "</div>\n" .
4889 "<i>" . esc_html($co{'author_name'}) . " [$ad{'rfc2822'}]</i><br/>\n" .
4890 "</div>\n";
4892 print "<div class=\"log_body\">\n";
4893 git_print_log($co{'comment'}, -final_empty_line=> 1);
4894 print "</div>\n";
4896 if ($#commitlist >= 100) {
4897 print "<div class=\"page_nav\">\n";
4898 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
4899 -accesskey => "n", -title => "Alt-n"}, "next");
4900 print "</div>\n";
4902 git_footer_html();
4905 sub git_commit {
4906 $hash ||= $hash_base || "HEAD";
4907 my %co = parse_commit($hash)
4908 or die_error(404, "Unknown commit object");
4909 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4910 my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4912 my $parent = $co{'parent'};
4913 my $parents = $co{'parents'}; # listref
4915 # we need to prepare $formats_nav before any parameter munging
4916 my $formats_nav;
4917 if (!defined $parent) {
4918 # --root commitdiff
4919 $formats_nav .= '(initial)';
4920 } elsif (@$parents == 1) {
4921 # single parent commit
4922 $formats_nav .=
4923 '(parent: ' .
4924 $cgi->a({-href => href(action=>"commit",
4925 hash=>$parent)},
4926 esc_html(substr($parent, 0, 7))) .
4927 ')';
4928 } else {
4929 # merge commit
4930 $formats_nav .=
4931 '(merge: ' .
4932 join(' ', map {
4933 $cgi->a({-href => href(action=>"commit",
4934 hash=>$_)},
4935 esc_html(substr($_, 0, 7)));
4936 } @$parents ) .
4937 ')';
4940 if (!defined $parent) {
4941 $parent = "--root";
4943 my @difftree;
4944 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4945 @diff_opts,
4946 (@$parents <= 1 ? $parent : '-c'),
4947 $hash, "--"
4948 or die_error(500, "Open git-diff-tree failed");
4949 @difftree = map { chomp; $_ } <$fd>;
4950 close $fd or die_error(404, "Reading git-diff-tree failed");
4952 # non-textual hash id's can be cached
4953 my $expires;
4954 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4955 $expires = "+1d";
4957 my $refs = git_get_references();
4958 my $ref = format_ref_marker($refs, $co{'id'});
4960 git_header_html(undef, $expires);
4961 git_print_page_nav('commit', '',
4962 $hash, $co{'tree'}, $hash,
4963 $formats_nav);
4965 if (defined $co{'parent'}) {
4966 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4967 } else {
4968 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4970 print "<div class=\"title_text\">\n" .
4971 "<table class=\"object_header\">\n";
4972 print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4973 "<tr>" .
4974 "<td></td><td> $ad{'rfc2822'}";
4975 if ($ad{'hour_local'} < 6) {
4976 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4977 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4978 } else {
4979 printf(" (%02d:%02d %s)",
4980 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4982 print "</td>" .
4983 "</tr>\n";
4984 print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4985 print "<tr><td></td><td> $cd{'rfc2822'}" .
4986 sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4987 "</td></tr>\n";
4988 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4989 print "<tr>" .
4990 "<td>tree</td>" .
4991 "<td class=\"sha1\">" .
4992 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4993 class => "list"}, $co{'tree'}) .
4994 "</td>" .
4995 "<td class=\"link\">" .
4996 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4997 "tree");
4998 my $snapshot_links = format_snapshot_links($hash);
4999 if (defined $snapshot_links) {
5000 print " | " . $snapshot_links;
5002 print "</td>" .
5003 "</tr>\n";
5005 foreach my $par (@$parents) {
5006 print "<tr>" .
5007 "<td>parent</td>" .
5008 "<td class=\"sha1\">" .
5009 $cgi->a({-href => href(action=>"commit", hash=>$par),
5010 class => "list"}, $par) .
5011 "</td>" .
5012 "<td class=\"link\">" .
5013 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5014 " | " .
5015 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5016 "</td>" .
5017 "</tr>\n";
5019 print "</table>".
5020 "</div>\n";
5022 print "<div class=\"page_body\">\n";
5023 git_print_log($co{'comment'});
5024 print "</div>\n";
5026 git_difftree_body(\@difftree, $hash, @$parents);
5028 git_footer_html();
5031 sub git_object {
5032 # object is defined by:
5033 # - hash or hash_base alone
5034 # - hash_base and file_name
5035 my $type;
5037 # - hash or hash_base alone
5038 if ($hash || ($hash_base && !defined $file_name)) {
5039 my $object_id = $hash || $hash_base;
5041 open my $fd, "-|", quote_command(
5042 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5043 or die_error(404, "Object does not exist");
5044 $type = <$fd>;
5045 chomp $type;
5046 close $fd
5047 or die_error(404, "Object does not exist");
5049 # - hash_base and file_name
5050 } elsif ($hash_base && defined $file_name) {
5051 $file_name =~ s,/+$,,;
5053 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5054 or die_error(404, "Base object does not exist");
5056 # here errors should not hapen
5057 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5058 or die_error(500, "Open git-ls-tree failed");
5059 my $line = <$fd>;
5060 close $fd;
5062 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5063 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5064 die_error(404, "File or directory for given base does not exist");
5066 $type = $2;
5067 $hash = $3;
5068 } else {
5069 die_error(400, "Not enough information to find object");
5072 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5073 hash=>$hash, hash_base=>$hash_base,
5074 file_name=>$file_name),
5075 -status => '302 Found');
5078 sub git_blobdiff {
5079 my $format = shift || 'html';
5081 my $fd;
5082 my @difftree;
5083 my %diffinfo;
5084 my $expires;
5086 # preparing $fd and %diffinfo for git_patchset_body
5087 # new style URI
5088 if (defined $hash_base && defined $hash_parent_base) {
5089 if (defined $file_name) {
5090 # read raw output
5091 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5092 $hash_parent_base, $hash_base,
5093 "--", (defined $file_parent ? $file_parent : ()), $file_name
5094 or die_error(500, "Open git-diff-tree failed");
5095 @difftree = map { chomp; $_ } <$fd>;
5096 close $fd
5097 or die_error(404, "Reading git-diff-tree failed");
5098 @difftree
5099 or die_error(404, "Blob diff not found");
5101 } elsif (defined $hash &&
5102 $hash =~ /[0-9a-fA-F]{40}/) {
5103 # try to find filename from $hash
5105 # read filtered raw output
5106 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5107 $hash_parent_base, $hash_base, "--"
5108 or die_error(500, "Open git-diff-tree failed");
5109 @difftree =
5110 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5111 # $hash == to_id
5112 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5113 map { chomp; $_ } <$fd>;
5114 close $fd
5115 or die_error(404, "Reading git-diff-tree failed");
5116 @difftree
5117 or die_error(404, "Blob diff not found");
5119 } else {
5120 die_error(400, "Missing one of the blob diff parameters");
5123 if (@difftree > 1) {
5124 die_error(400, "Ambiguous blob diff specification");
5127 %diffinfo = parse_difftree_raw_line($difftree[0]);
5128 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5129 $file_name ||= $diffinfo{'to_file'};
5131 $hash_parent ||= $diffinfo{'from_id'};
5132 $hash ||= $diffinfo{'to_id'};
5134 # non-textual hash id's can be cached
5135 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5136 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5137 $expires = '+1d';
5140 # open patch output
5141 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5142 '-p', ($format eq 'html' ? "--full-index" : ()),
5143 $hash_parent_base, $hash_base,
5144 "--", (defined $file_parent ? $file_parent : ()), $file_name
5145 or die_error(500, "Open git-diff-tree failed");
5148 # old/legacy style URI
5149 if (!%diffinfo && # if new style URI failed
5150 defined $hash && defined $hash_parent) {
5151 # fake git-diff-tree raw output
5152 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
5153 $diffinfo{'from_id'} = $hash_parent;
5154 $diffinfo{'to_id'} = $hash;
5155 if (defined $file_name) {
5156 if (defined $file_parent) {
5157 $diffinfo{'status'} = '2';
5158 $diffinfo{'from_file'} = $file_parent;
5159 $diffinfo{'to_file'} = $file_name;
5160 } else { # assume not renamed
5161 $diffinfo{'status'} = '1';
5162 $diffinfo{'from_file'} = $file_name;
5163 $diffinfo{'to_file'} = $file_name;
5165 } else { # no filename given
5166 $diffinfo{'status'} = '2';
5167 $diffinfo{'from_file'} = $hash_parent;
5168 $diffinfo{'to_file'} = $hash;
5171 # non-textual hash id's can be cached
5172 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
5173 $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5174 $expires = '+1d';
5177 # open patch output
5178 open $fd, "-|", git_cmd(), "diff", @diff_opts,
5179 '-p', ($format eq 'html' ? "--full-index" : ()),
5180 $hash_parent, $hash, "--"
5181 or die_error(500, "Open git-diff failed");
5182 } else {
5183 die_error(400, "Missing one of the blob diff parameters")
5184 unless %diffinfo;
5187 # header
5188 if ($format eq 'html') {
5189 my $formats_nav =
5190 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5191 "raw");
5192 git_header_html(undef, $expires);
5193 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5194 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5195 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5196 } else {
5197 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5198 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5200 if (defined $file_name) {
5201 git_print_page_path($file_name, "blob", $hash_base);
5202 } else {
5203 print "<div class=\"page_path\"></div>\n";
5206 } elsif ($format eq 'plain') {
5207 print $cgi->header(
5208 -type => 'text/plain',
5209 -charset => 'utf-8',
5210 -expires => $expires,
5211 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5213 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5215 } else {
5216 die_error(400, "Unknown blobdiff format");
5219 # patch
5220 if ($format eq 'html') {
5221 print "<div class=\"page_body\">\n";
5223 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5224 close $fd;
5226 print "</div>\n"; # class="page_body"
5227 git_footer_html();
5229 } else {
5230 while (my $line = <$fd>) {
5231 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5232 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5234 print $line;
5236 last if $line =~ m!^\+\+\+!;
5238 local $/ = undef;
5239 print <$fd>;
5240 close $fd;
5244 sub git_blobdiff_plain {
5245 git_blobdiff('plain');
5248 sub git_commitdiff {
5249 my $format = shift || 'html';
5250 $hash ||= $hash_base || "HEAD";
5251 my %co = parse_commit($hash)
5252 or die_error(404, "Unknown commit object");
5254 # choose format for commitdiff for merge
5255 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5256 $hash_parent = '--cc';
5258 # we need to prepare $formats_nav before almost any parameter munging
5259 my $formats_nav;
5260 if ($format eq 'html') {
5261 $formats_nav =
5262 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5263 "raw");
5265 if (defined $hash_parent &&
5266 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5267 # commitdiff with two commits given
5268 my $hash_parent_short = $hash_parent;
5269 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5270 $hash_parent_short = substr($hash_parent, 0, 7);
5272 $formats_nav .=
5273 ' (from';
5274 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5275 if ($co{'parents'}[$i] eq $hash_parent) {
5276 $formats_nav .= ' parent ' . ($i+1);
5277 last;
5280 $formats_nav .= ': ' .
5281 $cgi->a({-href => href(action=>"commitdiff",
5282 hash=>$hash_parent)},
5283 esc_html($hash_parent_short)) .
5284 ')';
5285 } elsif (!$co{'parent'}) {
5286 # --root commitdiff
5287 $formats_nav .= ' (initial)';
5288 } elsif (scalar @{$co{'parents'}} == 1) {
5289 # single parent commit
5290 $formats_nav .=
5291 ' (parent: ' .
5292 $cgi->a({-href => href(action=>"commitdiff",
5293 hash=>$co{'parent'})},
5294 esc_html(substr($co{'parent'}, 0, 7))) .
5295 ')';
5296 } else {
5297 # merge commit
5298 if ($hash_parent eq '--cc') {
5299 $formats_nav .= ' | ' .
5300 $cgi->a({-href => href(action=>"commitdiff",
5301 hash=>$hash, hash_parent=>'-c')},
5302 'combined');
5303 } else { # $hash_parent eq '-c'
5304 $formats_nav .= ' | ' .
5305 $cgi->a({-href => href(action=>"commitdiff",
5306 hash=>$hash, hash_parent=>'--cc')},
5307 'compact');
5309 $formats_nav .=
5310 ' (merge: ' .
5311 join(' ', map {
5312 $cgi->a({-href => href(action=>"commitdiff",
5313 hash=>$_)},
5314 esc_html(substr($_, 0, 7)));
5315 } @{$co{'parents'}} ) .
5316 ')';
5320 my $hash_parent_param = $hash_parent;
5321 if (!defined $hash_parent_param) {
5322 # --cc for multiple parents, --root for parentless
5323 $hash_parent_param =
5324 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5327 # read commitdiff
5328 my $fd;
5329 my @difftree;
5330 if ($format eq 'html') {
5331 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5332 "--no-commit-id", "--patch-with-raw", "--full-index",
5333 $hash_parent_param, $hash, "--"
5334 or die_error(500, "Open git-diff-tree failed");
5336 while (my $line = <$fd>) {
5337 chomp $line;
5338 # empty line ends raw part of diff-tree output
5339 last unless $line;
5340 push @difftree, scalar parse_difftree_raw_line($line);
5343 } elsif ($format eq 'plain') {
5344 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5345 '-p', $hash_parent_param, $hash, "--"
5346 or die_error(500, "Open git-diff-tree failed");
5348 } else {
5349 die_error(400, "Unknown commitdiff format");
5352 # non-textual hash id's can be cached
5353 my $expires;
5354 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5355 $expires = "+1d";
5358 # write commit message
5359 if ($format eq 'html') {
5360 my $refs = git_get_references();
5361 my $ref = format_ref_marker($refs, $co{'id'});
5363 git_header_html(undef, $expires);
5364 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5365 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5366 git_print_authorship(\%co);
5367 print "<div class=\"page_body\">\n";
5368 if (@{$co{'comment'}} > 1) {
5369 print "<div class=\"log\">\n";
5370 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5371 print "</div>\n"; # class="log"
5374 } elsif ($format eq 'plain') {
5375 my $refs = git_get_references("tags");
5376 my $tagname = git_get_rev_name_tags($hash);
5377 my $filename = basename($project) . "-$hash.patch";
5379 print $cgi->header(
5380 -type => 'text/plain',
5381 -charset => 'utf-8',
5382 -expires => $expires,
5383 -content_disposition => 'inline; filename="' . "$filename" . '"');
5384 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5385 print "From: " . to_utf8($co{'author'}) . "\n";
5386 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5387 print "Subject: " . to_utf8($co{'title'}) . "\n";
5389 print "X-Git-Tag: $tagname\n" if $tagname;
5390 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5392 foreach my $line (@{$co{'comment'}}) {
5393 print to_utf8($line) . "\n";
5395 print "---\n\n";
5398 # write patch
5399 if ($format eq 'html') {
5400 my $use_parents = !defined $hash_parent ||
5401 $hash_parent eq '-c' || $hash_parent eq '--cc';
5402 git_difftree_body(\@difftree, $hash,
5403 $use_parents ? @{$co{'parents'}} : $hash_parent);
5404 print "<br/>\n";
5406 git_patchset_body($fd, \@difftree, $hash,
5407 $use_parents ? @{$co{'parents'}} : $hash_parent);
5408 close $fd;
5409 print "</div>\n"; # class="page_body"
5410 git_footer_html();
5412 } elsif ($format eq 'plain') {
5413 local $/ = undef;
5414 print <$fd>;
5415 close $fd
5416 or print "Reading git-diff-tree failed\n";
5420 sub git_commitdiff_plain {
5421 git_commitdiff('plain');
5424 sub git_history {
5425 if (!defined $hash_base) {
5426 $hash_base = git_get_head_hash($project);
5428 if (!defined $page) {
5429 $page = 0;
5431 my $ftype;
5432 my %co = parse_commit($hash_base)
5433 or die_error(404, "Unknown commit object");
5435 my $refs = git_get_references();
5436 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5438 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5439 $file_name, "--full-history")
5440 or die_error(404, "No such file or directory on given branch");
5442 if (!defined $hash && defined $file_name) {
5443 # some commits could have deleted file in question,
5444 # and not have it in tree, but one of them has to have it
5445 for (my $i = 0; $i <= @commitlist; $i++) {
5446 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5447 last if defined $hash;
5450 if (defined $hash) {
5451 $ftype = git_get_type($hash);
5453 if (!defined $ftype) {
5454 die_error(500, "Unknown type of object");
5457 my $paging_nav = '';
5458 if ($page > 0) {
5459 $paging_nav .=
5460 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5461 file_name=>$file_name)},
5462 "first");
5463 $paging_nav .= " &sdot; " .
5464 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5465 -accesskey => "p", -title => "Alt-p"}, "prev");
5466 } else {
5467 $paging_nav .= "first";
5468 $paging_nav .= " &sdot; prev";
5470 my $next_link = '';
5471 if ($#commitlist >= 100) {
5472 $next_link =
5473 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5474 -accesskey => "n", -title => "Alt-n"}, "next");
5475 $paging_nav .= " &sdot; $next_link";
5476 } else {
5477 $paging_nav .= " &sdot; next";
5480 git_header_html();
5481 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5482 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5483 git_print_page_path($file_name, $ftype, $hash_base);
5485 git_history_body(\@commitlist, 0, 99,
5486 $refs, $hash_base, $ftype, $next_link);
5488 git_footer_html();
5491 sub git_search {
5492 gitweb_check_feature('search') or die_error(403, "Search is disabled");
5493 if (!defined $searchtext) {
5494 die_error(400, "Text field is empty");
5496 if (!defined $hash) {
5497 $hash = git_get_head_hash($project);
5499 my %co = parse_commit($hash);
5500 if (!%co) {
5501 die_error(404, "Unknown commit object");
5503 if (!defined $page) {
5504 $page = 0;
5507 $searchtype ||= 'commit';
5508 if ($searchtype eq 'pickaxe') {
5509 # pickaxe may take all resources of your box and run for several minutes
5510 # with every query - so decide by yourself how public you make this feature
5511 gitweb_check_feature('pickaxe')
5512 or die_error(403, "Pickaxe is disabled");
5514 if ($searchtype eq 'grep') {
5515 gitweb_check_feature('grep')
5516 or die_error(403, "Grep is disabled");
5519 git_header_html();
5521 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5522 my $greptype;
5523 if ($searchtype eq 'commit') {
5524 $greptype = "--grep=";
5525 } elsif ($searchtype eq 'author') {
5526 $greptype = "--author=";
5527 } elsif ($searchtype eq 'committer') {
5528 $greptype = "--committer=";
5530 $greptype .= $searchtext;
5531 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5532 $greptype, '--regexp-ignore-case',
5533 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5535 my $paging_nav = '';
5536 if ($page > 0) {
5537 $paging_nav .=
5538 $cgi->a({-href => href(action=>"search", hash=>$hash,
5539 searchtext=>$searchtext,
5540 searchtype=>$searchtype)},
5541 "first");
5542 $paging_nav .= " &sdot; " .
5543 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5544 -accesskey => "p", -title => "Alt-p"}, "prev");
5545 } else {
5546 $paging_nav .= "first";
5547 $paging_nav .= " &sdot; prev";
5549 my $next_link = '';
5550 if ($#commitlist >= 100) {
5551 $next_link =
5552 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5553 -accesskey => "n", -title => "Alt-n"}, "next");
5554 $paging_nav .= " &sdot; $next_link";
5555 } else {
5556 $paging_nav .= " &sdot; next";
5559 if ($#commitlist >= 100) {
5562 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5563 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5564 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5567 if ($searchtype eq 'pickaxe') {
5568 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5569 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5571 print "<table class=\"pickaxe search\">\n";
5572 my $alternate = 1;
5573 $/ = "\n";
5574 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5575 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5576 ($search_use_regexp ? '--pickaxe-regex' : ());
5577 undef %co;
5578 my @files;
5579 while (my $line = <$fd>) {
5580 chomp $line;
5581 next unless $line;
5583 my %set = parse_difftree_raw_line($line);
5584 if (defined $set{'commit'}) {
5585 # finish previous commit
5586 if (%co) {
5587 print "</td>\n" .
5588 "<td class=\"link\">" .
5589 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5590 " | " .
5591 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5592 print "</td>\n" .
5593 "</tr>\n";
5596 if ($alternate) {
5597 print "<tr class=\"dark\">\n";
5598 } else {
5599 print "<tr class=\"light\">\n";
5601 $alternate ^= 1;
5602 %co = parse_commit($set{'commit'});
5603 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5604 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5605 "<td><i>$author</i></td>\n" .
5606 "<td>" .
5607 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5608 -class => "list subject"},
5609 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5610 } elsif (defined $set{'to_id'}) {
5611 next if ($set{'to_id'} =~ m/^0{40}$/);
5613 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5614 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
5615 -class => "list"},
5616 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5617 "<br/>\n";
5620 close $fd;
5622 # finish last commit (warning: repetition!)
5623 if (%co) {
5624 print "</td>\n" .
5625 "<td class=\"link\">" .
5626 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5627 " | " .
5628 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5629 print "</td>\n" .
5630 "</tr>\n";
5633 print "</table>\n";
5636 if ($searchtype eq 'grep') {
5637 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5638 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5640 print "<table class=\"grep_search\">\n";
5641 my $alternate = 1;
5642 my $matches = 0;
5643 $/ = "\n";
5644 open my $fd, "-|", git_cmd(), 'grep', '-n',
5645 $search_use_regexp ? ('-E', '-i') : '-F',
5646 $searchtext, $co{'tree'};
5647 my $lastfile = '';
5648 while (my $line = <$fd>) {
5649 chomp $line;
5650 my ($file, $lno, $ltext, $binary);
5651 last if ($matches++ > 1000);
5652 if ($line =~ /^Binary file (.+) matches$/) {
5653 $file = $1;
5654 $binary = 1;
5655 } else {
5656 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5658 if ($file ne $lastfile) {
5659 $lastfile and print "</td></tr>\n";
5660 if ($alternate++) {
5661 print "<tr class=\"dark\">\n";
5662 } else {
5663 print "<tr class=\"light\">\n";
5665 print "<td class=\"list\">".
5666 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5667 file_name=>"$file"),
5668 -class => "list"}, esc_path($file));
5669 print "</td><td>\n";
5670 $lastfile = $file;
5672 if ($binary) {
5673 print "<div class=\"binary\">Binary file</div>\n";
5674 } else {
5675 $ltext = untabify($ltext);
5676 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
5677 $ltext = esc_html($1, -nbsp=>1);
5678 $ltext .= '<span class="match">';
5679 $ltext .= esc_html($2, -nbsp=>1);
5680 $ltext .= '</span>';
5681 $ltext .= esc_html($3, -nbsp=>1);
5682 } else {
5683 $ltext = esc_html($ltext, -nbsp=>1);
5685 print "<div class=\"pre\">" .
5686 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5687 file_name=>"$file").'#l'.$lno,
5688 -class => "linenr"}, sprintf('%4i', $lno))
5689 . ' ' . $ltext . "</div>\n";
5692 if ($lastfile) {
5693 print "</td></tr>\n";
5694 if ($matches > 1000) {
5695 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5697 } else {
5698 print "<div class=\"diff nodifferences\">No matches found</div>\n";
5700 close $fd;
5702 print "</table>\n";
5704 git_footer_html();
5707 sub git_search_help {
5708 git_header_html();
5709 git_print_page_nav('','', $hash,$hash,$hash);
5710 print <<EOT;
5711 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
5712 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
5713 the pattern entered is recognized as the POSIX extended
5714 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
5715 insensitive).</p>
5716 <dl>
5717 <dt><b>commit</b></dt>
5718 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
5720 my ($have_grep) = gitweb_check_feature('grep');
5721 if ($have_grep) {
5722 print <<EOT;
5723 <dt><b>grep</b></dt>
5724 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5725 a different one) are searched for the given pattern. On large trees, this search can take
5726 a while and put some strain on the server, so please use it with some consideration. Note that
5727 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
5728 case-sensitive.</dd>
5731 print <<EOT;
5732 <dt><b>author</b></dt>
5733 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
5734 <dt><b>committer</b></dt>
5735 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
5737 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5738 if ($have_pickaxe) {
5739 print <<EOT;
5740 <dt><b>pickaxe</b></dt>
5741 <dd>All commits that caused the string to appear or disappear from any file (changes that
5742 added, removed or "modified" the string) will be listed. This search can take a while and
5743 takes a lot of strain on the server, so please use it wisely. Note that since you may be
5744 interested even in changes just changing the case as well, this search is case sensitive.</dd>
5747 print "</dl>\n";
5748 git_footer_html();
5751 sub git_shortlog {
5752 my $head = git_get_head_hash($project);
5753 if (!defined $hash) {
5754 $hash = $head;
5756 if (!defined $page) {
5757 $page = 0;
5759 my $refs = git_get_references();
5761 my $commit_hash = $hash;
5762 if (defined $hash_parent) {
5763 $commit_hash = "$hash_parent..$hash";
5765 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
5767 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
5768 my $next_link = '';
5769 if ($#commitlist >= 100) {
5770 $next_link =
5771 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5772 -accesskey => "n", -title => "Alt-n"}, "next");
5775 git_header_html();
5776 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5777 git_print_header_div('summary', $project);
5779 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5781 git_footer_html();
5784 ## ......................................................................
5785 ## feeds (RSS, Atom; OPML)
5787 sub git_feed {
5788 my $format = shift || 'atom';
5789 my ($have_blame) = gitweb_check_feature('blame');
5791 # Atom: http://www.atomenabled.org/developers/syndication/
5792 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5793 if ($format ne 'rss' && $format ne 'atom') {
5794 die_error(400, "Unknown web feed format");
5797 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5798 my $head = $hash || 'HEAD';
5799 my @commitlist = parse_commits($head, 150, 0, $file_name);
5801 my %latest_commit;
5802 my %latest_date;
5803 my $content_type = "application/$format+xml";
5804 if (defined $cgi->http('HTTP_ACCEPT') &&
5805 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5806 # browser (feed reader) prefers text/xml
5807 $content_type = 'text/xml';
5809 if (defined($commitlist[0])) {
5810 %latest_commit = %{$commitlist[0]};
5811 %latest_date = parse_date($latest_commit{'author_epoch'});
5812 print $cgi->header(
5813 -type => $content_type,
5814 -charset => 'utf-8',
5815 -last_modified => $latest_date{'rfc2822'});
5816 } else {
5817 print $cgi->header(
5818 -type => $content_type,
5819 -charset => 'utf-8');
5822 # Optimization: skip generating the body if client asks only
5823 # for Last-Modified date.
5824 return if ($cgi->request_method() eq 'HEAD');
5826 # header variables
5827 my $title = "$site_name - $project/$action";
5828 my $feed_type = 'log';
5829 if (defined $hash) {
5830 $title .= " - '$hash'";
5831 $feed_type = 'branch log';
5832 if (defined $file_name) {
5833 $title .= " :: $file_name";
5834 $feed_type = 'history';
5836 } elsif (defined $file_name) {
5837 $title .= " - $file_name";
5838 $feed_type = 'history';
5840 $title .= " $feed_type";
5841 my $descr = git_get_project_description($project);
5842 if (defined $descr) {
5843 $descr = esc_html($descr);
5844 } else {
5845 $descr = "$project " .
5846 ($format eq 'rss' ? 'RSS' : 'Atom') .
5847 " feed";
5849 my $owner = git_get_project_owner($project);
5850 $owner = esc_html($owner);
5852 #header
5853 my $alt_url;
5854 if (defined $file_name) {
5855 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5856 } elsif (defined $hash) {
5857 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5858 } else {
5859 $alt_url = href(-full=>1, action=>"summary");
5861 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5862 if ($format eq 'rss') {
5863 print <<XML;
5864 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5865 <channel>
5867 print "<title>$title</title>\n" .
5868 "<link>$alt_url</link>\n" .
5869 "<description>$descr</description>\n" .
5870 "<language>en</language>\n";
5871 } elsif ($format eq 'atom') {
5872 print <<XML;
5873 <feed xmlns="http://www.w3.org/2005/Atom">
5875 print "<title>$title</title>\n" .
5876 "<subtitle>$descr</subtitle>\n" .
5877 '<link rel="alternate" type="text/html" href="' .
5878 $alt_url . '" />' . "\n" .
5879 '<link rel="self" type="' . $content_type . '" href="' .
5880 $cgi->self_url() . '" />' . "\n" .
5881 "<id>" . href(-full=>1) . "</id>\n" .
5882 # use project owner for feed author
5883 "<author><name>$owner</name></author>\n";
5884 if (defined $favicon) {
5885 print "<icon>" . esc_url($favicon) . "</icon>\n";
5887 if (defined $logo_url) {
5888 # not twice as wide as tall: 72 x 27 pixels
5889 print "<logo>" . esc_url($logo) . "</logo>\n";
5891 if (! %latest_date) {
5892 # dummy date to keep the feed valid until commits trickle in:
5893 print "<updated>1970-01-01T00:00:00Z</updated>\n";
5894 } else {
5895 print "<updated>$latest_date{'iso-8601'}</updated>\n";
5899 # contents
5900 for (my $i = 0; $i <= $#commitlist; $i++) {
5901 my %co = %{$commitlist[$i]};
5902 my $commit = $co{'id'};
5903 # we read 150, we always show 30 and the ones more recent than 48 hours
5904 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5905 last;
5907 my %cd = parse_date($co{'author_epoch'});
5909 # get list of changed files
5910 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5911 $co{'parent'} || "--root",
5912 $co{'id'}, "--", (defined $file_name ? $file_name : ())
5913 or next;
5914 my @difftree = map { chomp; $_ } <$fd>;
5915 close $fd
5916 or next;
5918 # print element (entry, item)
5919 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
5920 if ($format eq 'rss') {
5921 print "<item>\n" .
5922 "<title>" . esc_html($co{'title'}) . "</title>\n" .
5923 "<author>" . esc_html($co{'author'}) . "</author>\n" .
5924 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5925 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5926 "<link>$co_url</link>\n" .
5927 "<description>" . esc_html($co{'title'}) . "</description>\n" .
5928 "<content:encoded>" .
5929 "<![CDATA[\n";
5930 } elsif ($format eq 'atom') {
5931 print "<entry>\n" .
5932 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5933 "<updated>$cd{'iso-8601'}</updated>\n" .
5934 "<author>\n" .
5935 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
5936 if ($co{'author_email'}) {
5937 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
5939 print "</author>\n" .
5940 # use committer for contributor
5941 "<contributor>\n" .
5942 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5943 if ($co{'committer_email'}) {
5944 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5946 print "</contributor>\n" .
5947 "<published>$cd{'iso-8601'}</published>\n" .
5948 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5949 "<id>$co_url</id>\n" .
5950 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5951 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5953 my $comment = $co{'comment'};
5954 print "<pre>\n";
5955 foreach my $line (@$comment) {
5956 $line = esc_html($line);
5957 print "$line\n";
5959 print "</pre><ul>\n";
5960 foreach my $difftree_line (@difftree) {
5961 my %difftree = parse_difftree_raw_line($difftree_line);
5962 next if !$difftree{'from_id'};
5964 my $file = $difftree{'file'} || $difftree{'to_file'};
5966 print "<li>" .
5967 "[" .
5968 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5969 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5970 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5971 file_name=>$file, file_parent=>$difftree{'from_file'}),
5972 -title => "diff"}, 'D');
5973 if ($have_blame) {
5974 print $cgi->a({-href => href(-full=>1, action=>"blame",
5975 file_name=>$file, hash_base=>$commit), -class => "blamelink",
5976 -title => "blame"}, 'B');
5978 # if this is not a feed of a file history
5979 if (!defined $file_name || $file_name ne $file) {
5980 print $cgi->a({-href => href(-full=>1, action=>"history",
5981 file_name=>$file, hash=>$commit),
5982 -title => "history"}, 'H');
5984 $file = esc_path($file);
5985 print "] ".
5986 "$file</li>\n";
5988 if ($format eq 'rss') {
5989 print "</ul>]]>\n" .
5990 "</content:encoded>\n" .
5991 "</item>\n";
5992 } elsif ($format eq 'atom') {
5993 print "</ul>\n</div>\n" .
5994 "</content>\n" .
5995 "</entry>\n";
5999 # end of feed
6000 if ($format eq 'rss') {
6001 print "</channel>\n</rss>\n";
6002 } elsif ($format eq 'atom') {
6003 print "</feed>\n";
6007 sub git_rss {
6008 git_feed('rss');
6011 sub git_atom {
6012 git_feed('atom');
6015 sub git_opml {
6016 my @list = git_get_projects_list();
6018 print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
6019 print <<XML;
6020 <?xml version="1.0" encoding="utf-8"?>
6021 <opml version="1.0">
6022 <head>
6023 <title>$site_name OPML Export</title>
6024 </head>
6025 <body>
6026 <outline text="git RSS feeds">
6029 foreach my $pr (@list) {
6030 my %proj = %$pr;
6031 my $head = git_get_head_hash($proj{'path'});
6032 if (!defined $head) {
6033 next;
6035 $git_dir = "$projectroot/$proj{'path'}";
6036 my %co = parse_commit($head);
6037 if (!%co) {
6038 next;
6041 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6042 my $rss = "$my_url?p=$proj{'path'};a=rss";
6043 my $html = "$my_url?p=$proj{'path'};a=summary";
6044 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6046 print <<XML;
6047 </outline>
6048 </body>
6049 </opml>