Merge commit 'refs/top-bases/t/frontpage/separate' into t/frontpage/separate
[git/gitweb.git] / gitweb / gitweb.perl
blob365075475424056e0918e372a646a32716ba2084
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use strict;
11 use warnings;
12 use CGI qw(:standard :escapeHTML -nosticky);
13 use CGI::Util qw(unescape);
14 use CGI::Carp qw(fatalsToBrowser);
15 use Encode;
16 use Fcntl ':mode';
17 use File::Find qw();
18 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
21 BEGIN {
22 CGI->compile() if $ENV{'MOD_PERL'};
25 our $cgi = new CGI;
26 our $version = "++GIT_VERSION++";
27 our $my_url = $cgi->url();
28 our $my_uri = $cgi->url(-absolute => 1);
30 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
31 # needed and used only for URLs with nonempty PATH_INFO
32 our $base_url = $my_url;
34 # When the script is used as DirectoryIndex, the URL does not contain the name
35 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
36 # have to do it ourselves. We make $path_info global because it's also used
37 # later on.
39 # Another issue with the script being the DirectoryIndex is that the resulting
40 # $my_url data is not the full script URL: this is good, because we want
41 # generated links to keep implying the script name if it wasn't explicitly
42 # indicated in the URL we're handling, but it means that $my_url cannot be used
43 # as base URL.
44 # Therefore, if we needed to strip PATH_INFO, then we know that we have
45 # to build the base URL ourselves:
46 our $path_info = $ENV{"PATH_INFO"};
47 if ($path_info) {
48 if ($my_url =~ s,\Q$path_info\E$,, &&
49 $my_uri =~ s,\Q$path_info\E$,, &&
50 defined $ENV{'SCRIPT_NAME'}) {
51 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
55 # core git executable to use
56 # this can just be "git" if your webserver has a sensible PATH
57 our $GIT = "++GIT_BINDIR++/git";
59 # absolute fs-path which will be prepended to the project path
60 #our $projectroot = "/pub/scm";
61 our $projectroot = "++GITWEB_PROJECTROOT++";
63 # fs traversing limit for getting project list
64 # the number is relative to the projectroot
65 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
67 # target of the home link on top of all pages
68 our $home_link = $my_uri || "/";
70 # string of the home link on top of all pages
71 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
73 # name of your site or organization to appear in page titles
74 # replace this with something more descriptive for clearer bookmarks
75 our $site_name = "++GITWEB_SITENAME++"
76 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
78 # filename of html text to include at top of each page
79 our $site_header = "++GITWEB_SITE_HEADER++";
80 # html text to include at home page
81 our $home_text = "++GITWEB_HOMETEXT++";
82 # filename of html text to include at bottom of each page
83 our $site_footer = "++GITWEB_SITE_FOOTER++";
85 # URI of stylesheets
86 our @stylesheets = ("++GITWEB_CSS++");
87 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
88 our $stylesheet = undef;
89 # URI of GIT logo (72x27 size)
90 our $logo = "++GITWEB_LOGO++";
91 # URI of GIT favicon, assumed to be image/png type
92 our $favicon = "++GITWEB_FAVICON++";
94 # URI and label (title) of GIT logo link
95 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
96 #our $logo_label = "git documentation";
97 our $logo_url = "http://git-scm.com/";
98 our $logo_label = "git homepage";
100 # source of projects list
101 our $projects_list = "++GITWEB_LIST++";
103 # the width (in characters) of the projects list "Description" column
104 our $projects_list_description_width = 25;
106 # default order of projects list
107 # valid values are none, project, descr, owner, and age
108 our $default_projects_order = "project";
110 # show repository only if this file exists
111 # (only effective if this variable evaluates to true)
112 our $export_ok = "++GITWEB_EXPORT_OK++";
114 # show repository only if this subroutine returns true
115 # when given the path to the project, for example:
116 # sub { return -e "$_[0]/git-daemon-export-ok"; }
117 our $export_auth_hook = undef;
119 # only allow viewing of repositories also shown on the overview page
120 our $strict_export = "++GITWEB_STRICT_EXPORT++";
122 # list of git base URLs used for URL to where fetch project from,
123 # i.e. full URL is "$git_base_url/$project"
124 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
126 # default blob_plain mimetype and default charset for text/plain blob
127 our $default_blob_plain_mimetype = 'text/plain';
128 our $default_text_plain_charset = undef;
130 # file to use for guessing MIME types before trying /etc/mime.types
131 # (relative to the current git repository)
132 our $mimetypes_file = undef;
134 # assume this charset if line contains non-UTF-8 characters;
135 # it should be valid encoding (see Encoding::Supported(3pm) for list),
136 # for which encoding all byte sequences are valid, for example
137 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
138 # could be even 'utf-8' for the old behavior)
139 our $fallback_encoding = 'latin1';
141 # rename detection options for git-diff and git-diff-tree
142 # - default is '-M', with the cost proportional to
143 # (number of removed files) * (number of new files).
144 # - more costly is '-C' (which implies '-M'), with the cost proportional to
145 # (number of changed files + number of removed files) * (number of new files)
146 # - even more costly is '-C', '--find-copies-harder' with cost
147 # (number of files in the original tree) * (number of new files)
148 # - one might want to include '-B' option, e.g. '-B', '-M'
149 our @diff_opts = ('-M'); # taken from git_commit
151 # Disables features that would allow repository owners to inject script into
152 # the gitweb domain.
153 our $prevent_xss = 0;
155 # Whether to include project list on the gitweb front page; 0 means yes,
156 # 1 means no list but show tag cloud if enabled (all projects still need
157 # to be scanned), 2 means no list and no tag cloud (very fast)
158 our $frontpage_no_project_list = 0;
160 # information about snapshot formats that gitweb is capable of serving
161 our %known_snapshot_formats = (
162 # name => {
163 # 'display' => display name,
164 # 'type' => mime type,
165 # 'suffix' => filename suffix,
166 # 'format' => --format for git-archive,
167 # 'compressor' => [compressor command and arguments]
168 # (array reference, optional)
169 # 'disabled' => boolean (optional)}
171 'tgz' => {
172 'display' => 'tar.gz',
173 'type' => 'application/x-gzip',
174 'suffix' => '.tar.gz',
175 'format' => 'tar',
176 'compressor' => ['gzip']},
178 'tbz2' => {
179 'display' => 'tar.bz2',
180 'type' => 'application/x-bzip2',
181 'suffix' => '.tar.bz2',
182 'format' => 'tar',
183 'compressor' => ['bzip2']},
185 'txz' => {
186 'display' => 'tar.xz',
187 'type' => 'application/x-xz',
188 'suffix' => '.tar.xz',
189 'format' => 'tar',
190 'compressor' => ['xz'],
191 'disabled' => 1},
193 'zip' => {
194 'display' => 'zip',
195 'type' => 'application/x-zip',
196 'suffix' => '.zip',
197 'format' => 'zip'},
200 # Aliases so we understand old gitweb.snapshot values in repository
201 # configuration.
202 our %known_snapshot_format_aliases = (
203 'gzip' => 'tgz',
204 'bzip2' => 'tbz2',
205 'xz' => 'txz',
207 # backward compatibility: legacy gitweb config support
208 'x-gzip' => undef, 'gz' => undef,
209 'x-bzip2' => undef, 'bz2' => undef,
210 'x-zip' => undef, '' => undef,
213 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
214 # are changed, it may be appropriate to change these values too via
215 # $GITWEB_CONFIG.
216 our %avatar_size = (
217 'default' => 16,
218 'double' => 32
221 # You define site-wide feature defaults here; override them with
222 # $GITWEB_CONFIG as necessary.
223 our %feature = (
224 # feature => {
225 # 'sub' => feature-sub (subroutine),
226 # 'override' => allow-override (boolean),
227 # 'default' => [ default options...] (array reference)}
229 # if feature is overridable (it means that allow-override has true value),
230 # then feature-sub will be called with default options as parameters;
231 # return value of feature-sub indicates if to enable specified feature
233 # if there is no 'sub' key (no feature-sub), then feature cannot be
234 # overriden
236 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
237 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
238 # is enabled
240 # Enable the 'blame' blob view, showing the last commit that modified
241 # each line in the file. This can be very CPU-intensive.
243 # To enable system wide have in $GITWEB_CONFIG
244 # $feature{'blame'}{'default'} = [1];
245 # To have project specific config enable override in $GITWEB_CONFIG
246 # $feature{'blame'}{'override'} = 1;
247 # and in project config gitweb.blame = 0|1;
248 'blame' => {
249 'sub' => sub { feature_bool('blame', @_) },
250 'override' => 0,
251 'default' => [0]},
253 # Enable the 'snapshot' link, providing a compressed archive of any
254 # tree. This can potentially generate high traffic if you have large
255 # project.
257 # Value is a list of formats defined in %known_snapshot_formats that
258 # you wish to offer.
259 # To disable system wide have in $GITWEB_CONFIG
260 # $feature{'snapshot'}{'default'} = [];
261 # To have project specific config enable override in $GITWEB_CONFIG
262 # $feature{'snapshot'}{'override'} = 1;
263 # and in project config, a comma-separated list of formats or "none"
264 # to disable. Example: gitweb.snapshot = tbz2,zip;
265 'snapshot' => {
266 'sub' => \&feature_snapshot,
267 'override' => 0,
268 'default' => ['tgz']},
270 # Enable text search, which will list the commits which match author,
271 # committer or commit text to a given string. Enabled by default.
272 # Project specific override is not supported.
273 'search' => {
274 'override' => 0,
275 'default' => [1]},
277 # Enable grep search, which will list the files in currently selected
278 # tree containing the given string. Enabled by default. This can be
279 # potentially CPU-intensive, of course.
281 # To enable system wide have in $GITWEB_CONFIG
282 # $feature{'grep'}{'default'} = [1];
283 # To have project specific config enable override in $GITWEB_CONFIG
284 # $feature{'grep'}{'override'} = 1;
285 # and in project config gitweb.grep = 0|1;
286 'grep' => {
287 'sub' => sub { feature_bool('grep', @_) },
288 'override' => 0,
289 'default' => [1]},
291 # Enable the pickaxe search, which will list the commits that modified
292 # a given string in a file. This can be practical and quite faster
293 # alternative to 'blame', but still potentially CPU-intensive.
295 # To enable system wide have in $GITWEB_CONFIG
296 # $feature{'pickaxe'}{'default'} = [1];
297 # To have project specific config enable override in $GITWEB_CONFIG
298 # $feature{'pickaxe'}{'override'} = 1;
299 # and in project config gitweb.pickaxe = 0|1;
300 'pickaxe' => {
301 'sub' => sub { feature_bool('pickaxe', @_) },
302 'override' => 0,
303 'default' => [1]},
305 # Enable showing size of blobs in a 'tree' view, in a separate
306 # column, similar to what 'ls -l' does. This cost a bit of IO.
308 # To disable system wide have in $GITWEB_CONFIG
309 # $feature{'show-sizes'}{'default'} = [0];
310 # To have project specific config enable override in $GITWEB_CONFIG
311 # $feature{'show-sizes'}{'override'} = 1;
312 # and in project config gitweb.showsizes = 0|1;
313 'show-sizes' => {
314 'sub' => sub { feature_bool('showsizes', @_) },
315 'override' => 0,
316 'default' => [1]},
318 # Make gitweb use an alternative format of the URLs which can be
319 # more readable and natural-looking: project name is embedded
320 # directly in the path and the query string contains other
321 # auxiliary information. All gitweb installations recognize
322 # URL in either format; this configures in which formats gitweb
323 # generates links.
325 # To enable system wide have in $GITWEB_CONFIG
326 # $feature{'pathinfo'}{'default'} = [1];
327 # Project specific override is not supported.
329 # Note that you will need to change the default location of CSS,
330 # favicon, logo and possibly other files to an absolute URL. Also,
331 # if gitweb.cgi serves as your indexfile, you will need to force
332 # $my_uri to contain the script name in your $GITWEB_CONFIG.
333 'pathinfo' => {
334 'override' => 0,
335 'default' => [0]},
337 # Make gitweb consider projects in project root subdirectories
338 # to be forks of existing projects. Given project $projname.git,
339 # projects matching $projname/*.git will not be shown in the main
340 # projects list, instead a '+' mark will be added to $projname
341 # there and a 'forks' view will be enabled for the project, listing
342 # all the forks. If project list is taken from a file, forks have
343 # to be listed after the main project.
345 # To enable system wide have in $GITWEB_CONFIG
346 # $feature{'forks'}{'default'} = [1];
347 # Project specific override is not supported.
348 'forks' => {
349 'override' => 0,
350 'default' => [0]},
352 # Insert custom links to the action bar of all project pages.
353 # This enables you mainly to link to third-party scripts integrating
354 # into gitweb; e.g. git-browser for graphical history representation
355 # or custom web-based repository administration interface.
357 # The 'default' value consists of a list of triplets in the form
358 # (label, link, position) where position is the label after which
359 # to insert the link and link is a format string where %n expands
360 # to the project name, %f to the project path within the filesystem,
361 # %h to the current hash (h gitweb parameter) and %b to the current
362 # hash base (hb gitweb parameter); %% expands to %.
364 # To enable system wide have in $GITWEB_CONFIG e.g.
365 # $feature{'actions'}{'default'} = [('graphiclog',
366 # '/git-browser/by-commit.html?r=%n', 'summary')];
367 # Project specific override is not supported.
368 'actions' => {
369 'override' => 0,
370 'default' => []},
372 # Allow gitweb scan project content tags described in ctags/
373 # of project repository, and display the popular Web 2.0-ish
374 # "tag cloud" near the project list. Note that this is something
375 # COMPLETELY different from the normal Git tags.
377 # gitweb by itself can show existing tags, but it does not handle
378 # tagging itself; you need an external application for that.
379 # For an example script, check Girocco's cgi/tagproj.cgi.
380 # You may want to install the HTML::TagCloud Perl module to get
381 # a pretty tag cloud instead of just a list of tags.
383 # To enable system wide have in $GITWEB_CONFIG
384 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
385 # Project specific override is not supported.
386 'ctags' => {
387 'override' => 0,
388 'default' => [0]},
390 # The maximum number of patches in a patchset generated in patch
391 # view. Set this to 0 or undef to disable patch view, or to a
392 # negative number to remove any limit.
394 # To disable system wide have in $GITWEB_CONFIG
395 # $feature{'patches'}{'default'} = [0];
396 # To have project specific config enable override in $GITWEB_CONFIG
397 # $feature{'patches'}{'override'} = 1;
398 # and in project config gitweb.patches = 0|n;
399 # where n is the maximum number of patches allowed in a patchset.
400 'patches' => {
401 'sub' => \&feature_patches,
402 'override' => 0,
403 'default' => [16]},
405 # Avatar support. When this feature is enabled, views such as
406 # shortlog or commit will display an avatar associated with
407 # the email of the committer(s) and/or author(s).
409 # Currently available providers are gravatar and picon.
410 # If an unknown provider is specified, the feature is disabled.
412 # Gravatar depends on Digest::MD5.
413 # Picon currently relies on the indiana.edu database.
415 # To enable system wide have in $GITWEB_CONFIG
416 # $feature{'avatar'}{'default'} = ['<provider>'];
417 # where <provider> is either gravatar or picon.
418 # To have project specific config enable override in $GITWEB_CONFIG
419 # $feature{'avatar'}{'override'} = 1;
420 # and in project config gitweb.avatar = <provider>;
421 'avatar' => {
422 'sub' => \&feature_avatar,
423 'override' => 0,
424 'default' => ['']},
427 sub gitweb_get_feature {
428 my ($name) = @_;
429 return unless exists $feature{$name};
430 my ($sub, $override, @defaults) = (
431 $feature{$name}{'sub'},
432 $feature{$name}{'override'},
433 @{$feature{$name}{'default'}});
434 if (!$override) { return @defaults; }
435 if (!defined $sub) {
436 warn "feature $name is not overridable";
437 return @defaults;
439 return $sub->(@defaults);
442 # A wrapper to check if a given feature is enabled.
443 # With this, you can say
445 # my $bool_feat = gitweb_check_feature('bool_feat');
446 # gitweb_check_feature('bool_feat') or somecode;
448 # instead of
450 # my ($bool_feat) = gitweb_get_feature('bool_feat');
451 # (gitweb_get_feature('bool_feat'))[0] or somecode;
453 sub gitweb_check_feature {
454 return (gitweb_get_feature(@_))[0];
458 sub feature_bool {
459 my $key = shift;
460 my ($val) = git_get_project_config($key, '--bool');
462 if (!defined $val) {
463 return ($_[0]);
464 } elsif ($val eq 'true') {
465 return (1);
466 } elsif ($val eq 'false') {
467 return (0);
471 sub feature_snapshot {
472 my (@fmts) = @_;
474 my ($val) = git_get_project_config('snapshot');
476 if ($val) {
477 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
480 return @fmts;
483 sub feature_patches {
484 my @val = (git_get_project_config('patches', '--int'));
486 if (@val) {
487 return @val;
490 return ($_[0]);
493 sub feature_avatar {
494 my @val = (git_get_project_config('avatar'));
496 return @val ? @val : @_;
499 # checking HEAD file with -e is fragile if the repository was
500 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
501 # and then pruned.
502 sub check_head_link {
503 my ($dir) = @_;
504 my $headfile = "$dir/HEAD";
505 return ((-e $headfile) ||
506 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
509 sub check_export_ok {
510 my ($dir) = @_;
511 return (check_head_link($dir) &&
512 (!$export_ok || -e "$dir/$export_ok") &&
513 (!$export_auth_hook || $export_auth_hook->($dir)));
516 # process alternate names for backward compatibility
517 # filter out unsupported (unknown) snapshot formats
518 sub filter_snapshot_fmts {
519 my @fmts = @_;
521 @fmts = map {
522 exists $known_snapshot_format_aliases{$_} ?
523 $known_snapshot_format_aliases{$_} : $_} @fmts;
524 @fmts = grep {
525 exists $known_snapshot_formats{$_} &&
526 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
529 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
530 if (-e $GITWEB_CONFIG) {
531 do $GITWEB_CONFIG;
532 } else {
533 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
534 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
537 # version of the core git binary
538 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
540 $projects_list ||= $projectroot;
542 # ======================================================================
543 # input validation and dispatch
545 # input parameters can be collected from a variety of sources (presently, CGI
546 # and PATH_INFO), so we define an %input_params hash that collects them all
547 # together during validation: this allows subsequent uses (e.g. href()) to be
548 # agnostic of the parameter origin
550 our %input_params = ();
552 # input parameters are stored with the long parameter name as key. This will
553 # also be used in the href subroutine to convert parameters to their CGI
554 # equivalent, and since the href() usage is the most frequent one, we store
555 # the name -> CGI key mapping here, instead of the reverse.
557 # XXX: Warning: If you touch this, check the search form for updating,
558 # too.
560 our @cgi_param_mapping = (
561 project => "p",
562 action => "a",
563 file_name => "f",
564 file_parent => "fp",
565 hash => "h",
566 hash_parent => "hp",
567 hash_base => "hb",
568 hash_parent_base => "hpb",
569 page => "pg",
570 order => "o",
571 searchtext => "s",
572 searchtype => "st",
573 snapshot_format => "sf",
574 ctag_filter => 't',
575 extra_options => "opt",
576 search_use_regexp => "sr",
578 our %cgi_param_mapping = @cgi_param_mapping;
580 # we will also need to know the possible actions, for validation
581 our %actions = (
582 "blame" => \&git_blame,
583 "blobdiff" => \&git_blobdiff,
584 "blobdiff_plain" => \&git_blobdiff_plain,
585 "blob" => \&git_blob,
586 "blob_plain" => \&git_blob_plain,
587 "commitdiff" => \&git_commitdiff,
588 "commitdiff_plain" => \&git_commitdiff_plain,
589 "commit" => \&git_commit,
590 "forks" => \&git_forks,
591 "heads" => \&git_heads,
592 "history" => \&git_history,
593 "log" => \&git_log,
594 "patch" => \&git_patch,
595 "patches" => \&git_patches,
596 "rss" => \&git_rss,
597 "atom" => \&git_atom,
598 "search" => \&git_search,
599 "search_help" => \&git_search_help,
600 "shortlog" => \&git_shortlog,
601 "summary" => \&git_summary,
602 "tag" => \&git_tag,
603 "tags" => \&git_tags,
604 "tree" => \&git_tree,
605 "snapshot" => \&git_snapshot,
606 "object" => \&git_object,
607 # those below don't need $project
608 "opml" => \&git_opml,
609 "frontpage" => \&git_frontpage,
610 "project_list" => \&git_project_list,
611 "project_index" => \&git_project_index,
614 # finally, we have the hash of allowed extra_options for the commands that
615 # allow them
616 our %allowed_options = (
617 "--no-merges" => [ qw(rss atom log shortlog history) ],
620 # fill %input_params with the CGI parameters. All values except for 'opt'
621 # should be single values, but opt can be an array. We should probably
622 # build an array of parameters that can be multi-valued, but since for the time
623 # being it's only this one, we just single it out
624 while (my ($name, $symbol) = each %cgi_param_mapping) {
625 if ($symbol eq 'opt') {
626 $input_params{$name} = [ $cgi->param($symbol) ];
627 } else {
628 $input_params{$name} = $cgi->param($symbol);
632 # Backwards compatibility - by_tag= <=> t=
633 if ($cgi->param('by_tag')) {
634 $input_params{'ctag_filter'} = $cgi->param('by_tag');
637 # now read PATH_INFO and update the parameter list for missing parameters
638 sub evaluate_path_info {
639 return if defined $input_params{'project'};
640 return if !$path_info;
641 $path_info =~ s,^/+,,;
642 return if !$path_info;
644 # find which part of PATH_INFO is project
645 my $project = $path_info;
646 $project =~ s,/+$,,;
647 while ($project && !check_head_link("$projectroot/$project")) {
648 $project =~ s,/*[^/]*$,,;
650 return unless $project;
651 $input_params{'project'} = $project;
653 # do not change any parameters if an action is given using the query string
654 return if $input_params{'action'};
655 $path_info =~ s,^\Q$project\E/*,,;
657 # next, check if we have an action
658 my $action = $path_info;
659 $action =~ s,/.*$,,;
660 if (exists $actions{$action}) {
661 $path_info =~ s,^$action/*,,;
662 $input_params{'action'} = $action;
665 # list of actions that want hash_base instead of hash, but can have no
666 # pathname (f) parameter
667 my @wants_base = (
668 'tree',
669 'history',
672 # we want to catch
673 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
674 my ($parentrefname, $parentpathname, $refname, $pathname) =
675 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
677 # first, analyze the 'current' part
678 if (defined $pathname) {
679 # we got "branch:filename" or "branch:dir/"
680 # we could use git_get_type(branch:pathname), but:
681 # - it needs $git_dir
682 # - it does a git() call
683 # - the convention of terminating directories with a slash
684 # makes it superfluous
685 # - embedding the action in the PATH_INFO would make it even
686 # more superfluous
687 $pathname =~ s,^/+,,;
688 if (!$pathname || substr($pathname, -1) eq "/") {
689 $input_params{'action'} ||= "tree";
690 $pathname =~ s,/$,,;
691 } else {
692 # the default action depends on whether we had parent info
693 # or not
694 if ($parentrefname) {
695 $input_params{'action'} ||= "blobdiff_plain";
696 } else {
697 $input_params{'action'} ||= "blob_plain";
700 $input_params{'hash_base'} ||= $refname;
701 $input_params{'file_name'} ||= $pathname;
702 } elsif (defined $refname) {
703 # we got "branch". In this case we have to choose if we have to
704 # set hash or hash_base.
706 # Most of the actions without a pathname only want hash to be
707 # set, except for the ones specified in @wants_base that want
708 # hash_base instead. It should also be noted that hand-crafted
709 # links having 'history' as an action and no pathname or hash
710 # set will fail, but that happens regardless of PATH_INFO.
711 $input_params{'action'} ||= "shortlog";
712 if (grep { $_ eq $input_params{'action'} } @wants_base) {
713 $input_params{'hash_base'} ||= $refname;
714 } else {
715 $input_params{'hash'} ||= $refname;
719 # next, handle the 'parent' part, if present
720 if (defined $parentrefname) {
721 # a missing pathspec defaults to the 'current' filename, allowing e.g.
722 # someproject/blobdiff/oldrev..newrev:/filename
723 if ($parentpathname) {
724 $parentpathname =~ s,^/+,,;
725 $parentpathname =~ s,/$,,;
726 $input_params{'file_parent'} ||= $parentpathname;
727 } else {
728 $input_params{'file_parent'} ||= $input_params{'file_name'};
730 # we assume that hash_parent_base is wanted if a path was specified,
731 # or if the action wants hash_base instead of hash
732 if (defined $input_params{'file_parent'} ||
733 grep { $_ eq $input_params{'action'} } @wants_base) {
734 $input_params{'hash_parent_base'} ||= $parentrefname;
735 } else {
736 $input_params{'hash_parent'} ||= $parentrefname;
740 # for the snapshot action, we allow URLs in the form
741 # $project/snapshot/$hash.ext
742 # where .ext determines the snapshot and gets removed from the
743 # passed $refname to provide the $hash.
745 # To be able to tell that $refname includes the format extension, we
746 # require the following two conditions to be satisfied:
747 # - the hash input parameter MUST have been set from the $refname part
748 # of the URL (i.e. they must be equal)
749 # - the snapshot format MUST NOT have been defined already (e.g. from
750 # CGI parameter sf)
751 # It's also useless to try any matching unless $refname has a dot,
752 # so we check for that too
753 if (defined $input_params{'action'} &&
754 $input_params{'action'} eq 'snapshot' &&
755 defined $refname && index($refname, '.') != -1 &&
756 $refname eq $input_params{'hash'} &&
757 !defined $input_params{'snapshot_format'}) {
758 # We loop over the known snapshot formats, checking for
759 # extensions. Allowed extensions are both the defined suffix
760 # (which includes the initial dot already) and the snapshot
761 # format key itself, with a prepended dot
762 while (my ($fmt, $opt) = each %known_snapshot_formats) {
763 my $hash = $refname;
764 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
765 next;
767 my $sfx = $1;
768 # a valid suffix was found, so set the snapshot format
769 # and reset the hash parameter
770 $input_params{'snapshot_format'} = $fmt;
771 $input_params{'hash'} = $hash;
772 # we also set the format suffix to the one requested
773 # in the URL: this way a request for e.g. .tgz returns
774 # a .tgz instead of a .tar.gz
775 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
776 last;
780 evaluate_path_info();
782 our $action = $input_params{'action'};
783 if (defined $action) {
784 if (!validate_action($action)) {
785 die_error(400, "Invalid action parameter");
789 # parameters which are pathnames
790 our $project = $input_params{'project'};
791 if (defined $project) {
792 if (!validate_project($project)) {
793 undef $project;
794 die_error(404, "No such project");
798 our $file_name = $input_params{'file_name'};
799 if (defined $file_name) {
800 if (!validate_pathname($file_name)) {
801 die_error(400, "Invalid file parameter");
805 our $file_parent = $input_params{'file_parent'};
806 if (defined $file_parent) {
807 if (!validate_pathname($file_parent)) {
808 die_error(400, "Invalid file parent parameter");
812 # parameters which are refnames
813 our $hash = $input_params{'hash'};
814 if (defined $hash) {
815 if (!validate_refname($hash)) {
816 die_error(400, "Invalid hash parameter");
820 our $hash_parent = $input_params{'hash_parent'};
821 if (defined $hash_parent) {
822 if (!validate_refname($hash_parent)) {
823 die_error(400, "Invalid hash parent parameter");
827 our $hash_base = $input_params{'hash_base'};
828 if (defined $hash_base) {
829 if (!validate_refname($hash_base)) {
830 die_error(400, "Invalid hash base parameter");
834 our @extra_options = @{$input_params{'extra_options'}};
835 # @extra_options is always defined, since it can only be (currently) set from
836 # CGI, and $cgi->param() returns the empty array in array context if the param
837 # is not set
838 foreach my $opt (@extra_options) {
839 if (not exists $allowed_options{$opt}) {
840 die_error(400, "Invalid option parameter");
842 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
843 die_error(400, "Invalid option parameter for this action");
847 our $hash_parent_base = $input_params{'hash_parent_base'};
848 if (defined $hash_parent_base) {
849 if (!validate_refname($hash_parent_base)) {
850 die_error(400, "Invalid hash parent base parameter");
854 # other parameters
855 our $page = $input_params{'page'};
856 if (defined $page) {
857 if ($page =~ m/[^0-9]/) {
858 die_error(400, "Invalid page parameter");
862 our $searchtype = $input_params{'searchtype'};
863 if (defined $searchtype) {
864 if ($searchtype =~ m/[^a-z]/) {
865 die_error(400, "Invalid searchtype parameter");
869 our $search_use_regexp = $input_params{'search_use_regexp'};
871 our $searchtext = $input_params{'searchtext'};
872 our $search_regexp;
873 if (defined $searchtext) {
874 if (length($searchtext) < 2) {
875 die_error(403, "At least two characters are required for search parameter");
877 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
880 # path to the current git repository
881 our $git_dir;
882 $git_dir = "$projectroot/$project" if $project;
884 # list of supported snapshot formats
885 our @snapshot_fmts = gitweb_get_feature('snapshot');
886 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
888 # check that the avatar feature is set to a known provider name,
889 # and for each provider check if the dependencies are satisfied.
890 # if the provider name is invalid or the dependencies are not met,
891 # reset $git_avatar to the empty string.
892 our ($git_avatar) = gitweb_get_feature('avatar');
893 if ($git_avatar eq 'gravatar') {
894 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
895 } elsif ($git_avatar eq 'picon') {
896 # no dependencies
897 } else {
898 $git_avatar = '';
901 # dispatch
902 if (!defined $action) {
903 if (defined $hash) {
904 $action = git_get_type($hash);
905 } elsif (defined $hash_base && defined $file_name) {
906 $action = git_get_type("$hash_base:$file_name");
907 } elsif (defined $project) {
908 $action = 'summary';
909 } else {
910 $action = 'frontpage';
913 if (!defined($actions{$action})) {
914 die_error(400, "Unknown action");
916 if ($action !~ m/^(?:opml|frontpage|project_list|project_index)$/ &&
917 !$project) {
918 die_error(400, "Project needed");
920 $actions{$action}->();
921 exit;
923 ## ======================================================================
924 ## action links
926 sub href {
927 my %params = @_;
928 # default is to use -absolute url() i.e. $my_uri
929 my $href = $params{-full} ? $my_url : $my_uri;
931 $params{'project'} = $project unless exists $params{'project'};
933 if ($params{-replay}) {
934 while (my ($name, $symbol) = each %cgi_param_mapping) {
935 if (!exists $params{$name}) {
936 $params{$name} = $input_params{$name};
941 my $use_pathinfo = gitweb_check_feature('pathinfo');
942 if ($use_pathinfo and defined $params{'project'}) {
943 # try to put as many parameters as possible in PATH_INFO:
944 # - project name
945 # - action
946 # - hash_parent or hash_parent_base:/file_parent
947 # - hash or hash_base:/filename
948 # - the snapshot_format as an appropriate suffix
950 # When the script is the root DirectoryIndex for the domain,
951 # $href here would be something like http://gitweb.example.com/
952 # Thus, we strip any trailing / from $href, to spare us double
953 # slashes in the final URL
954 $href =~ s,/$,,;
956 # Then add the project name, if present
957 $href .= "/".esc_url($params{'project'});
958 delete $params{'project'};
960 # since we destructively absorb parameters, we keep this
961 # boolean that remembers if we're handling a snapshot
962 my $is_snapshot = $params{'action'} eq 'snapshot';
964 # Summary just uses the project path URL, any other action is
965 # added to the URL
966 if (defined $params{'action'}) {
967 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
968 delete $params{'action'};
971 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
972 # stripping nonexistent or useless pieces
973 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
974 || $params{'hash_parent'} || $params{'hash'});
975 if (defined $params{'hash_base'}) {
976 if (defined $params{'hash_parent_base'}) {
977 $href .= esc_url($params{'hash_parent_base'});
978 # skip the file_parent if it's the same as the file_name
979 if (defined $params{'file_parent'}) {
980 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
981 delete $params{'file_parent'};
982 } elsif ($params{'file_parent'} !~ /\.\./) {
983 $href .= ":/".esc_url($params{'file_parent'});
984 delete $params{'file_parent'};
987 $href .= "..";
988 delete $params{'hash_parent'};
989 delete $params{'hash_parent_base'};
990 } elsif (defined $params{'hash_parent'}) {
991 $href .= esc_url($params{'hash_parent'}). "..";
992 delete $params{'hash_parent'};
995 $href .= esc_url($params{'hash_base'});
996 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
997 $href .= ":/".esc_url($params{'file_name'});
998 delete $params{'file_name'};
1000 delete $params{'hash'};
1001 delete $params{'hash_base'};
1002 } elsif (defined $params{'hash'}) {
1003 $href .= esc_url($params{'hash'});
1004 delete $params{'hash'};
1007 # If the action was a snapshot, we can absorb the
1008 # snapshot_format parameter too
1009 if ($is_snapshot) {
1010 my $fmt = $params{'snapshot_format'};
1011 # snapshot_format should always be defined when href()
1012 # is called, but just in case some code forgets, we
1013 # fall back to the default
1014 $fmt ||= $snapshot_fmts[0];
1015 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1016 delete $params{'snapshot_format'};
1020 # now encode the parameters explicitly
1021 my @result = ();
1022 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1023 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1024 if (defined $params{$name}) {
1025 if (ref($params{$name}) eq "ARRAY") {
1026 foreach my $par (@{$params{$name}}) {
1027 push @result, $symbol . "=" . esc_param($par);
1029 } else {
1030 push @result, $symbol . "=" . esc_param($params{$name});
1034 $href .= "?" . join(';', @result) if scalar @result;
1036 return $href;
1040 ## ======================================================================
1041 ## validation, quoting/unquoting and escaping
1043 sub validate_action {
1044 my $input = shift || return undef;
1045 return undef unless exists $actions{$input};
1046 return $input;
1049 sub validate_project {
1050 my $input = shift || return undef;
1051 if (!validate_pathname($input) ||
1052 !(-d "$projectroot/$input") ||
1053 !check_export_ok("$projectroot/$input") ||
1054 ($strict_export && !project_in_list($input))) {
1055 return undef;
1056 } else {
1057 return $input;
1061 sub validate_pathname {
1062 my $input = shift || return undef;
1064 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1065 # at the beginning, at the end, and between slashes.
1066 # also this catches doubled slashes
1067 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1068 return undef;
1070 # no null characters
1071 if ($input =~ m!\0!) {
1072 return undef;
1074 return $input;
1077 sub validate_refname {
1078 my $input = shift || return undef;
1080 # textual hashes are O.K.
1081 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1082 return $input;
1084 # it must be correct pathname
1085 $input = validate_pathname($input)
1086 or return undef;
1087 # restrictions on ref name according to git-check-ref-format
1088 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1089 return undef;
1091 return $input;
1094 # decode sequences of octets in utf8 into Perl's internal form,
1095 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1096 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1097 sub to_utf8 {
1098 my $str = shift;
1099 if (utf8::valid($str)) {
1100 utf8::decode($str);
1101 return $str;
1102 } else {
1103 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1107 # quote unsafe chars, but keep the slash, even when it's not
1108 # correct, but quoted slashes look too horrible in bookmarks
1109 sub esc_param {
1110 my $str = shift;
1111 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1112 $str =~ s/ /\+/g;
1113 return $str;
1116 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1117 sub esc_url {
1118 my $str = shift;
1119 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1120 $str =~ s/\+/%2B/g;
1121 $str =~ s/ /\+/g;
1122 return $str;
1125 # replace invalid utf8 character with SUBSTITUTION sequence
1126 sub esc_html {
1127 my $str = shift;
1128 my %opts = @_;
1130 $str = to_utf8($str);
1131 $str = $cgi->escapeHTML($str);
1132 if ($opts{'-nbsp'}) {
1133 $str =~ s/ /&nbsp;/g;
1135 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1136 return $str;
1139 # quote control characters and escape filename to HTML
1140 sub esc_path {
1141 my $str = shift;
1142 my %opts = @_;
1144 $str = to_utf8($str);
1145 $str = $cgi->escapeHTML($str);
1146 if ($opts{'-nbsp'}) {
1147 $str =~ s/ /&nbsp;/g;
1149 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1150 return $str;
1153 # Make control characters "printable", using character escape codes (CEC)
1154 sub quot_cec {
1155 my $cntrl = shift;
1156 my %opts = @_;
1157 my %es = ( # character escape codes, aka escape sequences
1158 "\t" => '\t', # tab (HT)
1159 "\n" => '\n', # line feed (LF)
1160 "\r" => '\r', # carrige return (CR)
1161 "\f" => '\f', # form feed (FF)
1162 "\b" => '\b', # backspace (BS)
1163 "\a" => '\a', # alarm (bell) (BEL)
1164 "\e" => '\e', # escape (ESC)
1165 "\013" => '\v', # vertical tab (VT)
1166 "\000" => '\0', # nul character (NUL)
1168 my $chr = ( (exists $es{$cntrl})
1169 ? $es{$cntrl}
1170 : sprintf('\%2x', ord($cntrl)) );
1171 if ($opts{-nohtml}) {
1172 return $chr;
1173 } else {
1174 return "<span class=\"cntrl\">$chr</span>";
1178 # Alternatively use unicode control pictures codepoints,
1179 # Unicode "printable representation" (PR)
1180 sub quot_upr {
1181 my $cntrl = shift;
1182 my %opts = @_;
1184 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1185 if ($opts{-nohtml}) {
1186 return $chr;
1187 } else {
1188 return "<span class=\"cntrl\">$chr</span>";
1192 # git may return quoted and escaped filenames
1193 sub unquote {
1194 my $str = shift;
1196 sub unq {
1197 my $seq = shift;
1198 my %es = ( # character escape codes, aka escape sequences
1199 't' => "\t", # tab (HT, TAB)
1200 'n' => "\n", # newline (NL)
1201 'r' => "\r", # return (CR)
1202 'f' => "\f", # form feed (FF)
1203 'b' => "\b", # backspace (BS)
1204 'a' => "\a", # alarm (bell) (BEL)
1205 'e' => "\e", # escape (ESC)
1206 'v' => "\013", # vertical tab (VT)
1209 if ($seq =~ m/^[0-7]{1,3}$/) {
1210 # octal char sequence
1211 return chr(oct($seq));
1212 } elsif (exists $es{$seq}) {
1213 # C escape sequence, aka character escape code
1214 return $es{$seq};
1216 # quoted ordinary character
1217 return $seq;
1220 if ($str =~ m/^"(.*)"$/) {
1221 # needs unquoting
1222 $str = $1;
1223 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1225 return $str;
1228 # escape tabs (convert tabs to spaces)
1229 sub untabify {
1230 my $line = shift;
1232 while ((my $pos = index($line, "\t")) != -1) {
1233 if (my $count = (8 - ($pos % 8))) {
1234 my $spaces = ' ' x $count;
1235 $line =~ s/\t/$spaces/;
1239 return $line;
1242 sub project_in_list {
1243 my $project = shift;
1244 my @list = git_get_projects_list();
1245 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1248 ## ----------------------------------------------------------------------
1249 ## HTML aware string manipulation
1251 # Try to chop given string on a word boundary between position
1252 # $len and $len+$add_len. If there is no word boundary there,
1253 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1254 # (marking chopped part) would be longer than given string.
1255 sub chop_str {
1256 my $str = shift;
1257 my $len = shift;
1258 my $add_len = shift || 10;
1259 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1261 # Make sure perl knows it is utf8 encoded so we don't
1262 # cut in the middle of a utf8 multibyte char.
1263 $str = to_utf8($str);
1265 # allow only $len chars, but don't cut a word if it would fit in $add_len
1266 # if it doesn't fit, cut it if it's still longer than the dots we would add
1267 # remove chopped character entities entirely
1269 # when chopping in the middle, distribute $len into left and right part
1270 # return early if chopping wouldn't make string shorter
1271 if ($where eq 'center') {
1272 return $str if ($len + 5 >= length($str)); # filler is length 5
1273 $len = int($len/2);
1274 } else {
1275 return $str if ($len + 4 >= length($str)); # filler is length 4
1278 # regexps: ending and beginning with word part up to $add_len
1279 my $endre = qr/.{$len}\w{0,$add_len}/;
1280 my $begre = qr/\w{0,$add_len}.{$len}/;
1282 if ($where eq 'left') {
1283 $str =~ m/^(.*?)($begre)$/;
1284 my ($lead, $body) = ($1, $2);
1285 if (length($lead) > 4) {
1286 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1287 $lead = " ...";
1289 return "$lead$body";
1291 } elsif ($where eq 'center') {
1292 $str =~ m/^($endre)(.*)$/;
1293 my ($left, $str) = ($1, $2);
1294 $str =~ m/^(.*?)($begre)$/;
1295 my ($mid, $right) = ($1, $2);
1296 if (length($mid) > 5) {
1297 $left =~ s/&[^;]*$//;
1298 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1299 $mid = " ... ";
1301 return "$left$mid$right";
1303 } else {
1304 $str =~ m/^($endre)(.*)$/;
1305 my $body = $1;
1306 my $tail = $2;
1307 if (length($tail) > 4) {
1308 $body =~ s/&[^;]*$//;
1309 $tail = "... ";
1311 return "$body$tail";
1315 # takes the same arguments as chop_str, but also wraps a <span> around the
1316 # result with a title attribute if it does get chopped. Additionally, the
1317 # string is HTML-escaped.
1318 sub chop_and_escape_str {
1319 my ($str) = @_;
1321 my $chopped = chop_str(@_);
1322 if ($chopped eq $str) {
1323 return esc_html($chopped);
1324 } else {
1325 $str =~ s/[[:cntrl:]]/?/g;
1326 return $cgi->span({-title=>$str}, esc_html($chopped));
1330 ## ----------------------------------------------------------------------
1331 ## functions returning short strings
1333 # CSS class for given age value (in seconds)
1334 sub age_class {
1335 my $age = shift;
1337 if (!defined $age) {
1338 return "noage";
1339 } elsif ($age < 60*60*2) {
1340 return "age0";
1341 } elsif ($age < 60*60*24*2) {
1342 return "age1";
1343 } else {
1344 return "age2";
1348 # convert age in seconds to "nn units ago" string
1349 sub age_string {
1350 my $age = shift;
1351 my $age_str;
1353 if ($age > 60*60*24*365*2) {
1354 $age_str = (int $age/60/60/24/365);
1355 $age_str .= " years ago";
1356 } elsif ($age > 60*60*24*(365/12)*2) {
1357 $age_str = int $age/60/60/24/(365/12);
1358 $age_str .= " months ago";
1359 } elsif ($age > 60*60*24*7*2) {
1360 $age_str = int $age/60/60/24/7;
1361 $age_str .= " weeks ago";
1362 } elsif ($age > 60*60*24*2) {
1363 $age_str = int $age/60/60/24;
1364 $age_str .= " days ago";
1365 } elsif ($age > 60*60*2) {
1366 $age_str = int $age/60/60;
1367 $age_str .= " hours ago";
1368 } elsif ($age > 60*2) {
1369 $age_str = int $age/60;
1370 $age_str .= " min ago";
1371 } elsif ($age > 2) {
1372 $age_str = int $age;
1373 $age_str .= " sec ago";
1374 } else {
1375 $age_str .= " right now";
1377 return $age_str;
1380 use constant {
1381 S_IFINVALID => 0030000,
1382 S_IFGITLINK => 0160000,
1385 # submodule/subproject, a commit object reference
1386 sub S_ISGITLINK {
1387 my $mode = shift;
1389 return (($mode & S_IFMT) == S_IFGITLINK)
1392 # convert file mode in octal to symbolic file mode string
1393 sub mode_str {
1394 my $mode = oct shift;
1396 if (S_ISGITLINK($mode)) {
1397 return 'm---------';
1398 } elsif (S_ISDIR($mode & S_IFMT)) {
1399 return 'drwxr-xr-x';
1400 } elsif (S_ISLNK($mode)) {
1401 return 'lrwxrwxrwx';
1402 } elsif (S_ISREG($mode)) {
1403 # git cares only about the executable bit
1404 if ($mode & S_IXUSR) {
1405 return '-rwxr-xr-x';
1406 } else {
1407 return '-rw-r--r--';
1409 } else {
1410 return '----------';
1414 # convert file mode in octal to file type string
1415 sub file_type {
1416 my $mode = shift;
1418 if ($mode !~ m/^[0-7]+$/) {
1419 return $mode;
1420 } else {
1421 $mode = oct $mode;
1424 if (S_ISGITLINK($mode)) {
1425 return "submodule";
1426 } elsif (S_ISDIR($mode & S_IFMT)) {
1427 return "directory";
1428 } elsif (S_ISLNK($mode)) {
1429 return "symlink";
1430 } elsif (S_ISREG($mode)) {
1431 return "file";
1432 } else {
1433 return "unknown";
1437 # convert file mode in octal to file type description string
1438 sub file_type_long {
1439 my $mode = shift;
1441 if ($mode !~ m/^[0-7]+$/) {
1442 return $mode;
1443 } else {
1444 $mode = oct $mode;
1447 if (S_ISGITLINK($mode)) {
1448 return "submodule";
1449 } elsif (S_ISDIR($mode & S_IFMT)) {
1450 return "directory";
1451 } elsif (S_ISLNK($mode)) {
1452 return "symlink";
1453 } elsif (S_ISREG($mode)) {
1454 if ($mode & S_IXUSR) {
1455 return "executable";
1456 } else {
1457 return "file";
1459 } else {
1460 return "unknown";
1465 ## ----------------------------------------------------------------------
1466 ## functions returning short HTML fragments, or transforming HTML fragments
1467 ## which don't belong to other sections
1469 # format line of commit message.
1470 sub format_log_line_html {
1471 my $line = shift;
1473 $line = esc_html($line, -nbsp=>1);
1474 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1475 $cgi->a({-href => href(action=>"object", hash=>$1),
1476 -class => "text"}, $1);
1477 }eg;
1479 return $line;
1482 # format marker of refs pointing to given object
1484 # the destination action is chosen based on object type and current context:
1485 # - for annotated tags, we choose the tag view unless it's the current view
1486 # already, in which case we go to shortlog view
1487 # - for other refs, we keep the current view if we're in history, shortlog or
1488 # log view, and select shortlog otherwise
1489 sub format_ref_marker {
1490 my ($refs, $id) = @_;
1491 my $markers = '';
1493 if (defined $refs->{$id}) {
1494 foreach my $ref (@{$refs->{$id}}) {
1495 # this code exploits the fact that non-lightweight tags are the
1496 # only indirect objects, and that they are the only objects for which
1497 # we want to use tag instead of shortlog as action
1498 my ($type, $name) = qw();
1499 my $indirect = ($ref =~ s/\^\{\}$//);
1500 # e.g. tags/v2.6.11 or heads/next
1501 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1502 $type = $1;
1503 $name = $2;
1504 } else {
1505 $type = "ref";
1506 $name = $ref;
1509 my $class = $type;
1510 $class .= " indirect" if $indirect;
1512 my $dest_action = "shortlog";
1514 if ($indirect) {
1515 $dest_action = "tag" unless $action eq "tag";
1516 } elsif ($action =~ /^(history|(short)?log)$/) {
1517 $dest_action = $action;
1520 my $dest = "";
1521 $dest .= "refs/" unless $ref =~ m!^refs/!;
1522 $dest .= $ref;
1524 my $link = $cgi->a({
1525 -href => href(
1526 action=>$dest_action,
1527 hash=>$dest
1528 )}, $name);
1530 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1531 $link . "</span>";
1535 if ($markers) {
1536 return ' <span class="refs">'. $markers . '</span>';
1537 } else {
1538 return "";
1542 # format, perhaps shortened and with markers, title line
1543 sub format_subject_html {
1544 my ($long, $short, $href, $extra) = @_;
1545 $extra = '' unless defined($extra);
1547 if (length($short) < length($long)) {
1548 $long =~ s/[[:cntrl:]]/?/g;
1549 return $cgi->a({-href => $href, -class => "list subject",
1550 -title => to_utf8($long)},
1551 esc_html($short)) . $extra;
1552 } else {
1553 return $cgi->a({-href => $href, -class => "list subject"},
1554 esc_html($long)) . $extra;
1558 # Rather than recomputing the url for an email multiple times, we cache it
1559 # after the first hit. This gives a visible benefit in views where the avatar
1560 # for the same email is used repeatedly (e.g. shortlog).
1561 # The cache is shared by all avatar engines (currently gravatar only), which
1562 # are free to use it as preferred. Since only one avatar engine is used for any
1563 # given page, there's no risk for cache conflicts.
1564 our %avatar_cache = ();
1566 # Compute the picon url for a given email, by using the picon search service over at
1567 # http://www.cs.indiana.edu/picons/search.html
1568 sub picon_url {
1569 my $email = lc shift;
1570 if (!$avatar_cache{$email}) {
1571 my ($user, $domain) = split('@', $email);
1572 $avatar_cache{$email} =
1573 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1574 "$domain/$user/" .
1575 "users+domains+unknown/up/single";
1577 return $avatar_cache{$email};
1580 # Compute the gravatar url for a given email, if it's not in the cache already.
1581 # Gravatar stores only the part of the URL before the size, since that's the
1582 # one computationally more expensive. This also allows reuse of the cache for
1583 # different sizes (for this particular engine).
1584 sub gravatar_url {
1585 my $email = lc shift;
1586 my $size = shift;
1587 $avatar_cache{$email} ||=
1588 "http://www.gravatar.com/avatar/" .
1589 Digest::MD5::md5_hex($email) . "?s=";
1590 return $avatar_cache{$email} . $size;
1593 # Insert an avatar for the given $email at the given $size if the feature
1594 # is enabled.
1595 sub git_get_avatar {
1596 my ($email, %opts) = @_;
1597 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1598 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1599 $opts{-size} ||= 'default';
1600 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1601 my $url = "";
1602 if ($git_avatar eq 'gravatar') {
1603 $url = gravatar_url($email, $size);
1604 } elsif ($git_avatar eq 'picon') {
1605 $url = picon_url($email);
1607 # Other providers can be added by extending the if chain, defining $url
1608 # as needed. If no variant puts something in $url, we assume avatars
1609 # are completely disabled/unavailable.
1610 if ($url) {
1611 return $pre_white .
1612 "<img width=\"$size\" " .
1613 "class=\"avatar\" " .
1614 "src=\"$url\" " .
1615 "alt=\"\" " .
1616 "/>" . $post_white;
1617 } else {
1618 return "";
1622 sub format_search_author {
1623 my ($author, $searchtype, $displaytext) = @_;
1624 my $have_search = gitweb_check_feature('search');
1626 if ($have_search) {
1627 my $performed = "";
1628 if ($searchtype eq 'author') {
1629 $performed = "authored";
1630 } elsif ($searchtype eq 'committer') {
1631 $performed = "committed";
1634 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1635 searchtext=>$author,
1636 searchtype=>$searchtype), class=>"list",
1637 title=>"Search for commits $performed by $author"},
1638 $displaytext);
1640 } else {
1641 return $displaytext;
1645 # format the author name of the given commit with the given tag
1646 # the author name is chopped and escaped according to the other
1647 # optional parameters (see chop_str).
1648 sub format_author_html {
1649 my $tag = shift;
1650 my $co = shift;
1651 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1652 return "<$tag class=\"author\">" .
1653 format_search_author($co->{'author_name'}, "author",
1654 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1655 $author) .
1656 "</$tag>";
1659 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1660 sub format_git_diff_header_line {
1661 my $line = shift;
1662 my $diffinfo = shift;
1663 my ($from, $to) = @_;
1665 if ($diffinfo->{'nparents'}) {
1666 # combined diff
1667 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1668 if ($to->{'href'}) {
1669 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1670 esc_path($to->{'file'}));
1671 } else { # file was deleted (no href)
1672 $line .= esc_path($to->{'file'});
1674 } else {
1675 # "ordinary" diff
1676 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1677 if ($from->{'href'}) {
1678 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1679 'a/' . esc_path($from->{'file'}));
1680 } else { # file was added (no href)
1681 $line .= 'a/' . esc_path($from->{'file'});
1683 $line .= ' ';
1684 if ($to->{'href'}) {
1685 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1686 'b/' . esc_path($to->{'file'}));
1687 } else { # file was deleted
1688 $line .= 'b/' . esc_path($to->{'file'});
1692 return "<div class=\"diff header\">$line</div>\n";
1695 # format extended diff header line, before patch itself
1696 sub format_extended_diff_header_line {
1697 my $line = shift;
1698 my $diffinfo = shift;
1699 my ($from, $to) = @_;
1701 # match <path>
1702 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1703 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1704 esc_path($from->{'file'}));
1706 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1707 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1708 esc_path($to->{'file'}));
1710 # match single <mode>
1711 if ($line =~ m/\s(\d{6})$/) {
1712 $line .= '<span class="info"> (' .
1713 file_type_long($1) .
1714 ')</span>';
1716 # match <hash>
1717 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1718 # can match only for combined diff
1719 $line = 'index ';
1720 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1721 if ($from->{'href'}[$i]) {
1722 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1723 -class=>"hash"},
1724 substr($diffinfo->{'from_id'}[$i],0,7));
1725 } else {
1726 $line .= '0' x 7;
1728 # separator
1729 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1731 $line .= '..';
1732 if ($to->{'href'}) {
1733 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1734 substr($diffinfo->{'to_id'},0,7));
1735 } else {
1736 $line .= '0' x 7;
1739 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1740 # can match only for ordinary diff
1741 my ($from_link, $to_link);
1742 if ($from->{'href'}) {
1743 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1744 substr($diffinfo->{'from_id'},0,7));
1745 } else {
1746 $from_link = '0' x 7;
1748 if ($to->{'href'}) {
1749 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1750 substr($diffinfo->{'to_id'},0,7));
1751 } else {
1752 $to_link = '0' x 7;
1754 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1755 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1758 return $line . "<br/>\n";
1761 # format from-file/to-file diff header
1762 sub format_diff_from_to_header {
1763 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1764 my $line;
1765 my $result = '';
1767 $line = $from_line;
1768 #assert($line =~ m/^---/) if DEBUG;
1769 # no extra formatting for "^--- /dev/null"
1770 if (! $diffinfo->{'nparents'}) {
1771 # ordinary (single parent) diff
1772 if ($line =~ m!^--- "?a/!) {
1773 if ($from->{'href'}) {
1774 $line = '--- a/' .
1775 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1776 esc_path($from->{'file'}));
1777 } else {
1778 $line = '--- a/' .
1779 esc_path($from->{'file'});
1782 $result .= qq!<div class="diff from_file">$line</div>\n!;
1784 } else {
1785 # combined diff (merge commit)
1786 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1787 if ($from->{'href'}[$i]) {
1788 $line = '--- ' .
1789 $cgi->a({-href=>href(action=>"blobdiff",
1790 hash_parent=>$diffinfo->{'from_id'}[$i],
1791 hash_parent_base=>$parents[$i],
1792 file_parent=>$from->{'file'}[$i],
1793 hash=>$diffinfo->{'to_id'},
1794 hash_base=>$hash,
1795 file_name=>$to->{'file'}),
1796 -class=>"path",
1797 -title=>"diff" . ($i+1)},
1798 $i+1) .
1799 '/' .
1800 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1801 esc_path($from->{'file'}[$i]));
1802 } else {
1803 $line = '--- /dev/null';
1805 $result .= qq!<div class="diff from_file">$line</div>\n!;
1809 $line = $to_line;
1810 #assert($line =~ m/^\+\+\+/) if DEBUG;
1811 # no extra formatting for "^+++ /dev/null"
1812 if ($line =~ m!^\+\+\+ "?b/!) {
1813 if ($to->{'href'}) {
1814 $line = '+++ b/' .
1815 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1816 esc_path($to->{'file'}));
1817 } else {
1818 $line = '+++ b/' .
1819 esc_path($to->{'file'});
1822 $result .= qq!<div class="diff to_file">$line</div>\n!;
1824 return $result;
1827 # create note for patch simplified by combined diff
1828 sub format_diff_cc_simplified {
1829 my ($diffinfo, @parents) = @_;
1830 my $result = '';
1832 $result .= "<div class=\"diff header\">" .
1833 "diff --cc ";
1834 if (!is_deleted($diffinfo)) {
1835 $result .= $cgi->a({-href => href(action=>"blob",
1836 hash_base=>$hash,
1837 hash=>$diffinfo->{'to_id'},
1838 file_name=>$diffinfo->{'to_file'}),
1839 -class => "path"},
1840 esc_path($diffinfo->{'to_file'}));
1841 } else {
1842 $result .= esc_path($diffinfo->{'to_file'});
1844 $result .= "</div>\n" . # class="diff header"
1845 "<div class=\"diff nodifferences\">" .
1846 "Simple merge" .
1847 "</div>\n"; # class="diff nodifferences"
1849 return $result;
1852 # format patch (diff) line (not to be used for diff headers)
1853 sub format_diff_line {
1854 my $line = shift;
1855 my ($from, $to) = @_;
1856 my $diff_class = "";
1858 chomp $line;
1860 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1861 # combined diff
1862 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1863 if ($line =~ m/^\@{3}/) {
1864 $diff_class = " chunk_header";
1865 } elsif ($line =~ m/^\\/) {
1866 $diff_class = " incomplete";
1867 } elsif ($prefix =~ tr/+/+/) {
1868 $diff_class = " add";
1869 } elsif ($prefix =~ tr/-/-/) {
1870 $diff_class = " rem";
1872 } else {
1873 # assume ordinary diff
1874 my $char = substr($line, 0, 1);
1875 if ($char eq '+') {
1876 $diff_class = " add";
1877 } elsif ($char eq '-') {
1878 $diff_class = " rem";
1879 } elsif ($char eq '@') {
1880 $diff_class = " chunk_header";
1881 } elsif ($char eq "\\") {
1882 $diff_class = " incomplete";
1885 $line = untabify($line);
1886 if ($from && $to && $line =~ m/^\@{2} /) {
1887 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1888 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1890 $from_lines = 0 unless defined $from_lines;
1891 $to_lines = 0 unless defined $to_lines;
1893 if ($from->{'href'}) {
1894 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1895 -class=>"list"}, $from_text);
1897 if ($to->{'href'}) {
1898 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1899 -class=>"list"}, $to_text);
1901 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1902 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1903 return "<div class=\"diff$diff_class\">$line</div>\n";
1904 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1905 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1906 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1908 @from_text = split(' ', $ranges);
1909 for (my $i = 0; $i < @from_text; ++$i) {
1910 ($from_start[$i], $from_nlines[$i]) =
1911 (split(',', substr($from_text[$i], 1)), 0);
1914 $to_text = pop @from_text;
1915 $to_start = pop @from_start;
1916 $to_nlines = pop @from_nlines;
1918 $line = "<span class=\"chunk_info\">$prefix ";
1919 for (my $i = 0; $i < @from_text; ++$i) {
1920 if ($from->{'href'}[$i]) {
1921 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1922 -class=>"list"}, $from_text[$i]);
1923 } else {
1924 $line .= $from_text[$i];
1926 $line .= " ";
1928 if ($to->{'href'}) {
1929 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1930 -class=>"list"}, $to_text);
1931 } else {
1932 $line .= $to_text;
1934 $line .= " $prefix</span>" .
1935 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1936 return "<div class=\"diff$diff_class\">$line</div>\n";
1938 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1941 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1942 # linked. Pass the hash of the tree/commit to snapshot.
1943 sub format_snapshot_links {
1944 my ($hash) = @_;
1945 my $num_fmts = @snapshot_fmts;
1946 if ($num_fmts > 1) {
1947 # A parenthesized list of links bearing format names.
1948 # e.g. "snapshot (_tar.gz_ _zip_)"
1949 return "snapshot (" . join(' ', map
1950 $cgi->a({
1951 -href => href(
1952 action=>"snapshot",
1953 hash=>$hash,
1954 snapshot_format=>$_
1956 }, $known_snapshot_formats{$_}{'display'})
1957 , @snapshot_fmts) . ")";
1958 } elsif ($num_fmts == 1) {
1959 # A single "snapshot" link whose tooltip bears the format name.
1960 # i.e. "_snapshot_"
1961 my ($fmt) = @snapshot_fmts;
1962 return
1963 $cgi->a({
1964 -href => href(
1965 action=>"snapshot",
1966 hash=>$hash,
1967 snapshot_format=>$fmt
1969 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1970 }, "snapshot");
1971 } else { # $num_fmts == 0
1972 return undef;
1976 ## ......................................................................
1977 ## functions returning values to be passed, perhaps after some
1978 ## transformation, to other functions; e.g. returning arguments to href()
1980 # returns hash to be passed to href to generate gitweb URL
1981 # in -title key it returns description of link
1982 sub get_feed_info {
1983 my $format = shift || 'Atom';
1984 my %res = (action => lc($format));
1986 # feed links are possible only for project views
1987 return unless (defined $project);
1988 # some views should link to OPML, or to generic project feed,
1989 # or don't have specific feed yet (so they should use generic)
1990 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1992 my $branch;
1993 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1994 # from tag links; this also makes possible to detect branch links
1995 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1996 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1997 $branch = $1;
1999 # find log type for feed description (title)
2000 my $type = 'log';
2001 if (defined $file_name) {
2002 $type = "history of $file_name";
2003 $type .= "/" if ($action eq 'tree');
2004 $type .= " on '$branch'" if (defined $branch);
2005 } else {
2006 $type = "log of $branch" if (defined $branch);
2009 $res{-title} = $type;
2010 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2011 $res{'file_name'} = $file_name;
2013 return %res;
2016 ## ----------------------------------------------------------------------
2017 ## git utility subroutines, invoking git commands
2019 # returns path to the core git executable and the --git-dir parameter as list
2020 sub git_cmd {
2021 return $GIT, '--git-dir='.$git_dir;
2024 # quote the given arguments for passing them to the shell
2025 # quote_command("command", "arg 1", "arg with ' and ! characters")
2026 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2027 # Try to avoid using this function wherever possible.
2028 sub quote_command {
2029 return join(' ',
2030 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2033 # get HEAD ref of given project as hash
2034 sub git_get_head_hash {
2035 my $project = shift;
2036 my $o_git_dir = $git_dir;
2037 my $retval = undef;
2038 $git_dir = "$projectroot/$project";
2039 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
2040 my $head = <$fd>;
2041 close $fd;
2042 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
2043 $retval = $1;
2046 if (defined $o_git_dir) {
2047 $git_dir = $o_git_dir;
2049 return $retval;
2052 # get type of given object
2053 sub git_get_type {
2054 my $hash = shift;
2056 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2057 my $type = <$fd>;
2058 close $fd or return;
2059 chomp $type;
2060 return $type;
2063 # repository configuration
2064 our $config_file = '';
2065 our %config;
2067 # store multiple values for single key as anonymous array reference
2068 # single values stored directly in the hash, not as [ <value> ]
2069 sub hash_set_multi {
2070 my ($hash, $key, $value) = @_;
2072 if (!exists $hash->{$key}) {
2073 $hash->{$key} = $value;
2074 } elsif (!ref $hash->{$key}) {
2075 $hash->{$key} = [ $hash->{$key}, $value ];
2076 } else {
2077 push @{$hash->{$key}}, $value;
2081 # return hash of git project configuration
2082 # optionally limited to some section, e.g. 'gitweb'
2083 sub git_parse_project_config {
2084 my $section_regexp = shift;
2085 my %config;
2087 local $/ = "\0";
2089 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2090 or return;
2092 while (my $keyval = <$fh>) {
2093 chomp $keyval;
2094 my ($key, $value) = split(/\n/, $keyval, 2);
2096 hash_set_multi(\%config, $key, $value)
2097 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2099 close $fh;
2101 return %config;
2104 # convert config value to boolean: 'true' or 'false'
2105 # no value, number > 0, 'true' and 'yes' values are true
2106 # rest of values are treated as false (never as error)
2107 sub config_to_bool {
2108 my $val = shift;
2110 return 1 if !defined $val; # section.key
2112 # strip leading and trailing whitespace
2113 $val =~ s/^\s+//;
2114 $val =~ s/\s+$//;
2116 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2117 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2120 # convert config value to simple decimal number
2121 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2122 # to be multiplied by 1024, 1048576, or 1073741824
2123 sub config_to_int {
2124 my $val = shift;
2126 # strip leading and trailing whitespace
2127 $val =~ s/^\s+//;
2128 $val =~ s/\s+$//;
2130 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2131 $unit = lc($unit);
2132 # unknown unit is treated as 1
2133 return $num * ($unit eq 'g' ? 1073741824 :
2134 $unit eq 'm' ? 1048576 :
2135 $unit eq 'k' ? 1024 : 1);
2137 return $val;
2140 # convert config value to array reference, if needed
2141 sub config_to_multi {
2142 my $val = shift;
2144 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2147 sub git_get_project_config {
2148 my ($key, $type) = @_;
2150 # key sanity check
2151 return unless ($key);
2152 $key =~ s/^gitweb\.//;
2153 return if ($key =~ m/\W/);
2155 # type sanity check
2156 if (defined $type) {
2157 $type =~ s/^--//;
2158 $type = undef
2159 unless ($type eq 'bool' || $type eq 'int');
2162 # get config
2163 if (!defined $config_file ||
2164 $config_file ne "$git_dir/config") {
2165 %config = git_parse_project_config('gitweb');
2166 $config_file = "$git_dir/config";
2169 # check if config variable (key) exists
2170 return unless exists $config{"gitweb.$key"};
2172 # ensure given type
2173 if (!defined $type) {
2174 return $config{"gitweb.$key"};
2175 } elsif ($type eq 'bool') {
2176 # backward compatibility: 'git config --bool' returns true/false
2177 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2178 } elsif ($type eq 'int') {
2179 return config_to_int($config{"gitweb.$key"});
2181 return $config{"gitweb.$key"};
2184 # get hash of given path at given ref
2185 sub git_get_hash_by_path {
2186 my $base = shift;
2187 my $path = shift || return undef;
2188 my $type = shift;
2190 $path =~ s,/+$,,;
2192 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2193 or die_error(500, "Open git-ls-tree failed");
2194 my $line = <$fd>;
2195 close $fd or return undef;
2197 if (!defined $line) {
2198 # there is no tree or hash given by $path at $base
2199 return undef;
2202 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2203 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2204 if (defined $type && $type ne $2) {
2205 # type doesn't match
2206 return undef;
2208 return $3;
2211 # get path of entry with given hash at given tree-ish (ref)
2212 # used to get 'from' filename for combined diff (merge commit) for renames
2213 sub git_get_path_by_hash {
2214 my $base = shift || return;
2215 my $hash = shift || return;
2217 local $/ = "\0";
2219 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2220 or return undef;
2221 while (my $line = <$fd>) {
2222 chomp $line;
2224 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2225 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2226 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2227 close $fd;
2228 return $1;
2231 close $fd;
2232 return undef;
2235 ## ......................................................................
2236 ## git utility functions, directly accessing git repository
2238 sub git_get_project_description {
2239 my $path = shift;
2241 $git_dir = "$projectroot/$path";
2242 open my $fd, '<', "$git_dir/description"
2243 or return git_get_project_config('description');
2244 my $descr = <$fd>;
2245 close $fd;
2246 if (defined $descr) {
2247 chomp $descr;
2249 return $descr;
2252 sub git_get_project_ctags {
2253 my $path = shift;
2254 my $ctags = {};
2256 $git_dir = "$projectroot/$path";
2257 opendir my $dh, "$git_dir/ctags"
2258 or return $ctags;
2259 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2260 open my $ct, '<', $_ or next;
2261 my $val = <$ct>;
2262 chomp $val;
2263 close $ct;
2264 my $ctag = $_; $ctag =~ s#.*/##;
2265 $ctags->{$ctag} = $val;
2267 closedir $dh;
2268 $ctags;
2271 sub git_populate_project_tagcloud {
2272 my ($ctags, $action) = @_;
2274 # First, merge different-cased tags; tags vote on casing
2275 my %ctags_lc;
2276 foreach (keys %$ctags) {
2277 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2278 if (not $ctags_lc{lc $_}->{topcount}
2279 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2280 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2281 $ctags_lc{lc $_}->{topname} = $_;
2285 my $cloud;
2286 if (eval { require HTML::TagCloud; 1; }) {
2287 $cloud = HTML::TagCloud->new;
2288 foreach (sort keys %ctags_lc) {
2289 # Pad the title with spaces so that the cloud looks
2290 # less crammed.
2291 my $title = $ctags_lc{$_}->{topname};
2292 $title =~ s/ /&nbsp;/g;
2293 $title =~ s/^/&nbsp;/g;
2294 $title =~ s/$/&nbsp;/g;
2295 $cloud->add($title, href(action=>$action, ctag_filter=>$_),
2296 $ctags_lc{$_}->{count});
2298 } else {
2299 $cloud = \%ctags_lc;
2301 $cloud;
2304 sub git_show_project_tagcloud {
2305 my ($cloud, $count, $action) = @_;
2306 print STDERR ref($cloud)."..\n";
2307 if (ref $cloud eq 'HTML::TagCloud') {
2308 return $cloud->html_and_css($count);
2309 } else {
2310 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2311 return '<p align="center">' . join (', ', map {
2312 $cgi->a({-href => href(action=>$action, ctag_filter=>$_)},
2313 $cloud->{$_}->{topname});
2314 } splice(@tags, 0, $count)) . '</p>';
2318 sub git_get_project_url_list {
2319 my $path = shift;
2321 $git_dir = "$projectroot/$path";
2322 open my $fd, '<', "$git_dir/cloneurl"
2323 or return wantarray ?
2324 @{ config_to_multi(git_get_project_config('url')) } :
2325 config_to_multi(git_get_project_config('url'));
2326 my @git_project_url_list = map { chomp; $_ } <$fd>;
2327 close $fd;
2329 return wantarray ? @git_project_url_list : \@git_project_url_list;
2332 sub git_get_projects_list {
2333 my ($filter) = @_;
2334 my @list;
2336 $filter ||= '';
2337 $filter =~ s/\.git$//;
2339 my $check_forks = gitweb_check_feature('forks');
2341 if (-d $projects_list) {
2342 # search in directory
2343 my $dir = $projects_list . ($filter ? "/$filter" : '');
2344 # remove the trailing "/"
2345 $dir =~ s!/+$!!;
2346 my $pfxlen = length("$dir");
2347 my $pfxdepth = ($dir =~ tr!/!!);
2349 File::Find::find({
2350 follow_fast => 1, # follow symbolic links
2351 follow_skip => 2, # ignore duplicates
2352 dangling_symlinks => 0, # ignore dangling symlinks, silently
2353 wanted => sub {
2354 # skip project-list toplevel, if we get it.
2355 return if (m!^[/.]$!);
2356 # only directories can be git repositories
2357 return unless (-d $_);
2358 # don't traverse too deep (Find is super slow on os x)
2359 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2360 $File::Find::prune = 1;
2361 return;
2364 my $subdir = substr($File::Find::name, $pfxlen + 1);
2365 # we check related file in $projectroot
2366 my $path = ($filter ? "$filter/" : '') . $subdir;
2367 if (check_export_ok("$projectroot/$path")) {
2368 push @list, { path => $path };
2369 $File::Find::prune = 1;
2372 }, "$dir");
2374 } elsif (-f $projects_list) {
2375 # read from file(url-encoded):
2376 # 'git%2Fgit.git Linus+Torvalds'
2377 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2378 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2379 my %paths;
2380 open my $fd, '<', $projects_list or return;
2381 PROJECT:
2382 while (my $line = <$fd>) {
2383 chomp $line;
2384 my ($path, $owner) = split ' ', $line;
2385 $path = unescape($path);
2386 $owner = unescape($owner);
2387 if (!defined $path) {
2388 next;
2390 if ($filter ne '') {
2391 # looking for forks;
2392 my $pfx = substr($path, 0, length($filter));
2393 if ($pfx ne $filter) {
2394 next PROJECT;
2396 my $sfx = substr($path, length($filter));
2397 if ($sfx !~ /^\/.*\.git$/) {
2398 next PROJECT;
2400 } elsif ($check_forks) {
2401 PATH:
2402 foreach my $filter (keys %paths) {
2403 # looking for forks;
2404 my $pfx = substr($path, 0, length($filter));
2405 if ($pfx ne $filter) {
2406 next PATH;
2408 my $sfx = substr($path, length($filter));
2409 if ($sfx !~ /^\/.*\.git$/) {
2410 next PATH;
2412 # is a fork, don't include it in
2413 # the list
2414 next PROJECT;
2417 if (check_export_ok("$projectroot/$path")) {
2418 my $pr = {
2419 path => $path,
2420 owner => to_utf8($owner),
2422 push @list, $pr;
2423 (my $forks_path = $path) =~ s/\.git$//;
2424 $paths{$forks_path}++;
2427 close $fd;
2429 return @list;
2432 our $gitweb_project_owner = undef;
2433 sub git_get_project_list_from_file {
2435 return if (defined $gitweb_project_owner);
2437 $gitweb_project_owner = {};
2438 # read from file (url-encoded):
2439 # 'git%2Fgit.git Linus+Torvalds'
2440 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2441 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2442 if (-f $projects_list) {
2443 open(my $fd, '<', $projects_list);
2444 while (my $line = <$fd>) {
2445 chomp $line;
2446 my ($pr, $ow) = split ' ', $line;
2447 $pr = unescape($pr);
2448 $ow = unescape($ow);
2449 $gitweb_project_owner->{$pr} = to_utf8($ow);
2451 close $fd;
2455 sub git_get_project_owner {
2456 my $project = shift;
2457 my $owner;
2459 return undef unless $project;
2460 $git_dir = "$projectroot/$project";
2462 if (!defined $gitweb_project_owner) {
2463 git_get_project_list_from_file();
2466 if (exists $gitweb_project_owner->{$project}) {
2467 $owner = $gitweb_project_owner->{$project};
2469 if (!defined $owner){
2470 $owner = git_get_project_config('owner');
2472 if (!defined $owner) {
2473 $owner = get_file_owner("$git_dir");
2476 return $owner;
2479 sub git_get_last_activity {
2480 my ($path) = @_;
2481 my $fd;
2483 $git_dir = "$projectroot/$path";
2484 open($fd, "-|", git_cmd(), 'for-each-ref',
2485 '--format=%(committer)',
2486 '--sort=-committerdate',
2487 '--count=1',
2488 'refs/heads') or return;
2489 my $most_recent = <$fd>;
2490 close $fd or return;
2491 if (defined $most_recent &&
2492 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2493 my $timestamp = $1;
2494 my $age = time - $timestamp;
2495 return ($age, age_string($age));
2497 return (undef, undef);
2500 sub git_get_references {
2501 my $type = shift || "";
2502 my %refs;
2503 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2504 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2505 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2506 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2507 or return;
2509 while (my $line = <$fd>) {
2510 chomp $line;
2511 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2512 if (defined $refs{$1}) {
2513 push @{$refs{$1}}, $2;
2514 } else {
2515 $refs{$1} = [ $2 ];
2519 close $fd or return;
2520 return \%refs;
2523 sub git_get_rev_name_tags {
2524 my $hash = shift || return undef;
2526 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2527 or return;
2528 my $name_rev = <$fd>;
2529 close $fd;
2531 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2532 return $1;
2533 } else {
2534 # catches also '$hash undefined' output
2535 return undef;
2539 ## ----------------------------------------------------------------------
2540 ## parse to hash functions
2542 sub parse_date {
2543 my $epoch = shift;
2544 my $tz = shift || "-0000";
2546 my %date;
2547 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2548 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2549 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2550 $date{'hour'} = $hour;
2551 $date{'minute'} = $min;
2552 $date{'mday'} = $mday;
2553 $date{'day'} = $days[$wday];
2554 $date{'month'} = $months[$mon];
2555 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2556 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2557 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2558 $mday, $months[$mon], $hour ,$min;
2559 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2560 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2562 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2563 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2564 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2565 $date{'hour_local'} = $hour;
2566 $date{'minute_local'} = $min;
2567 $date{'tz_local'} = $tz;
2568 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2569 1900+$year, $mon+1, $mday,
2570 $hour, $min, $sec, $tz);
2571 return %date;
2574 sub parse_tag {
2575 my $tag_id = shift;
2576 my %tag;
2577 my @comment;
2579 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2580 $tag{'id'} = $tag_id;
2581 while (my $line = <$fd>) {
2582 chomp $line;
2583 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2584 $tag{'object'} = $1;
2585 } elsif ($line =~ m/^type (.+)$/) {
2586 $tag{'type'} = $1;
2587 } elsif ($line =~ m/^tag (.+)$/) {
2588 $tag{'name'} = $1;
2589 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2590 $tag{'author'} = $1;
2591 $tag{'author_epoch'} = $2;
2592 $tag{'author_tz'} = $3;
2593 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2594 $tag{'author_name'} = $1;
2595 $tag{'author_email'} = $2;
2596 } else {
2597 $tag{'author_name'} = $tag{'author'};
2599 } elsif ($line =~ m/--BEGIN/) {
2600 push @comment, $line;
2601 last;
2602 } elsif ($line eq "") {
2603 last;
2606 push @comment, <$fd>;
2607 $tag{'comment'} = \@comment;
2608 close $fd or return;
2609 if (!defined $tag{'name'}) {
2610 return
2612 return %tag
2615 sub parse_commit_text {
2616 my ($commit_text, $withparents) = @_;
2617 my @commit_lines = split '\n', $commit_text;
2618 my %co;
2620 pop @commit_lines; # Remove '\0'
2622 if (! @commit_lines) {
2623 return;
2626 my $header = shift @commit_lines;
2627 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2628 return;
2630 ($co{'id'}, my @parents) = split ' ', $header;
2631 while (my $line = shift @commit_lines) {
2632 last if $line eq "\n";
2633 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2634 $co{'tree'} = $1;
2635 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2636 push @parents, $1;
2637 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2638 $co{'author'} = to_utf8($1);
2639 $co{'author_epoch'} = $2;
2640 $co{'author_tz'} = $3;
2641 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2642 $co{'author_name'} = $1;
2643 $co{'author_email'} = $2;
2644 } else {
2645 $co{'author_name'} = $co{'author'};
2647 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2648 $co{'committer'} = to_utf8($1);
2649 $co{'committer_epoch'} = $2;
2650 $co{'committer_tz'} = $3;
2651 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2652 $co{'committer_name'} = $1;
2653 $co{'committer_email'} = $2;
2654 } else {
2655 $co{'committer_name'} = $co{'committer'};
2659 if (!defined $co{'tree'}) {
2660 return;
2662 $co{'parents'} = \@parents;
2663 $co{'parent'} = $parents[0];
2665 foreach my $title (@commit_lines) {
2666 $title =~ s/^ //;
2667 if ($title ne "") {
2668 $co{'title'} = chop_str($title, 80, 5);
2669 # remove leading stuff of merges to make the interesting part visible
2670 if (length($title) > 50) {
2671 $title =~ s/^Automatic //;
2672 $title =~ s/^merge (of|with) /Merge ... /i;
2673 if (length($title) > 50) {
2674 $title =~ s/(http|rsync):\/\///;
2676 if (length($title) > 50) {
2677 $title =~ s/(master|www|rsync)\.//;
2679 if (length($title) > 50) {
2680 $title =~ s/kernel.org:?//;
2682 if (length($title) > 50) {
2683 $title =~ s/\/pub\/scm//;
2686 $co{'title_short'} = chop_str($title, 50, 5);
2687 last;
2690 if (! defined $co{'title'} || $co{'title'} eq "") {
2691 $co{'title'} = $co{'title_short'} = '(no commit message)';
2693 # remove added spaces
2694 foreach my $line (@commit_lines) {
2695 $line =~ s/^ //;
2697 $co{'comment'} = \@commit_lines;
2699 my $age = time - $co{'committer_epoch'};
2700 $co{'age'} = $age;
2701 $co{'age_string'} = age_string($age);
2702 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2703 if ($age > 60*60*24*7*2) {
2704 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2705 $co{'age_string_age'} = $co{'age_string'};
2706 } else {
2707 $co{'age_string_date'} = $co{'age_string'};
2708 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2710 return %co;
2713 sub parse_commit {
2714 my ($commit_id) = @_;
2715 my %co;
2717 local $/ = "\0";
2719 open my $fd, "-|", git_cmd(), "rev-list",
2720 "--parents",
2721 "--header",
2722 "--max-count=1",
2723 $commit_id,
2724 "--",
2725 or die_error(500, "Open git-rev-list failed");
2726 %co = parse_commit_text(<$fd>, 1);
2727 close $fd;
2729 return %co;
2732 sub parse_commits {
2733 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2734 my @cos;
2736 $maxcount ||= 1;
2737 $skip ||= 0;
2739 local $/ = "\0";
2741 open my $fd, "-|", git_cmd(), "rev-list",
2742 "--header",
2743 @args,
2744 ("--max-count=" . $maxcount),
2745 ("--skip=" . $skip),
2746 @extra_options,
2747 $commit_id,
2748 "--",
2749 ($filename ? ($filename) : ())
2750 or die_error(500, "Open git-rev-list failed");
2751 while (my $line = <$fd>) {
2752 my %co = parse_commit_text($line);
2753 push @cos, \%co;
2755 close $fd;
2757 return wantarray ? @cos : \@cos;
2760 # parse line of git-diff-tree "raw" output
2761 sub parse_difftree_raw_line {
2762 my $line = shift;
2763 my %res;
2765 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2766 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2767 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2768 $res{'from_mode'} = $1;
2769 $res{'to_mode'} = $2;
2770 $res{'from_id'} = $3;
2771 $res{'to_id'} = $4;
2772 $res{'status'} = $5;
2773 $res{'similarity'} = $6;
2774 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2775 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2776 } else {
2777 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2780 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2781 # combined diff (for merge commit)
2782 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2783 $res{'nparents'} = length($1);
2784 $res{'from_mode'} = [ split(' ', $2) ];
2785 $res{'to_mode'} = pop @{$res{'from_mode'}};
2786 $res{'from_id'} = [ split(' ', $3) ];
2787 $res{'to_id'} = pop @{$res{'from_id'}};
2788 $res{'status'} = [ split('', $4) ];
2789 $res{'to_file'} = unquote($5);
2791 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2792 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2793 $res{'commit'} = $1;
2796 return wantarray ? %res : \%res;
2799 # wrapper: return parsed line of git-diff-tree "raw" output
2800 # (the argument might be raw line, or parsed info)
2801 sub parsed_difftree_line {
2802 my $line_or_ref = shift;
2804 if (ref($line_or_ref) eq "HASH") {
2805 # pre-parsed (or generated by hand)
2806 return $line_or_ref;
2807 } else {
2808 return parse_difftree_raw_line($line_or_ref);
2812 # parse line of git-ls-tree output
2813 sub parse_ls_tree_line {
2814 my $line = shift;
2815 my %opts = @_;
2816 my %res;
2818 if ($opts{'-l'}) {
2819 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
2820 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
2822 $res{'mode'} = $1;
2823 $res{'type'} = $2;
2824 $res{'hash'} = $3;
2825 $res{'size'} = $4;
2826 if ($opts{'-z'}) {
2827 $res{'name'} = $5;
2828 } else {
2829 $res{'name'} = unquote($5);
2831 } else {
2832 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2833 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2835 $res{'mode'} = $1;
2836 $res{'type'} = $2;
2837 $res{'hash'} = $3;
2838 if ($opts{'-z'}) {
2839 $res{'name'} = $4;
2840 } else {
2841 $res{'name'} = unquote($4);
2845 return wantarray ? %res : \%res;
2848 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2849 sub parse_from_to_diffinfo {
2850 my ($diffinfo, $from, $to, @parents) = @_;
2852 if ($diffinfo->{'nparents'}) {
2853 # combined diff
2854 $from->{'file'} = [];
2855 $from->{'href'} = [];
2856 fill_from_file_info($diffinfo, @parents)
2857 unless exists $diffinfo->{'from_file'};
2858 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2859 $from->{'file'}[$i] =
2860 defined $diffinfo->{'from_file'}[$i] ?
2861 $diffinfo->{'from_file'}[$i] :
2862 $diffinfo->{'to_file'};
2863 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2864 $from->{'href'}[$i] = href(action=>"blob",
2865 hash_base=>$parents[$i],
2866 hash=>$diffinfo->{'from_id'}[$i],
2867 file_name=>$from->{'file'}[$i]);
2868 } else {
2869 $from->{'href'}[$i] = undef;
2872 } else {
2873 # ordinary (not combined) diff
2874 $from->{'file'} = $diffinfo->{'from_file'};
2875 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2876 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2877 hash=>$diffinfo->{'from_id'},
2878 file_name=>$from->{'file'});
2879 } else {
2880 delete $from->{'href'};
2884 $to->{'file'} = $diffinfo->{'to_file'};
2885 if (!is_deleted($diffinfo)) { # file exists in result
2886 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2887 hash=>$diffinfo->{'to_id'},
2888 file_name=>$to->{'file'});
2889 } else {
2890 delete $to->{'href'};
2894 ## ......................................................................
2895 ## parse to array of hashes functions
2897 sub git_get_heads_list {
2898 my $limit = shift;
2899 my @headslist;
2901 open my $fd, '-|', git_cmd(), 'for-each-ref',
2902 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2903 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2904 'refs/heads'
2905 or return;
2906 while (my $line = <$fd>) {
2907 my %ref_item;
2909 chomp $line;
2910 my ($refinfo, $committerinfo) = split(/\0/, $line);
2911 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2912 my ($committer, $epoch, $tz) =
2913 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2914 $ref_item{'fullname'} = $name;
2915 $name =~ s!^refs/heads/!!;
2917 $ref_item{'name'} = $name;
2918 $ref_item{'id'} = $hash;
2919 $ref_item{'title'} = $title || '(no commit message)';
2920 $ref_item{'epoch'} = $epoch;
2921 if ($epoch) {
2922 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2923 } else {
2924 $ref_item{'age'} = "unknown";
2927 push @headslist, \%ref_item;
2929 close $fd;
2931 return wantarray ? @headslist : \@headslist;
2934 sub git_get_tags_list {
2935 my $limit = shift;
2936 my @tagslist;
2938 open my $fd, '-|', git_cmd(), 'for-each-ref',
2939 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2940 '--format=%(objectname) %(objecttype) %(refname) '.
2941 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2942 'refs/tags'
2943 or return;
2944 while (my $line = <$fd>) {
2945 my %ref_item;
2947 chomp $line;
2948 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2949 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2950 my ($creator, $epoch, $tz) =
2951 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2952 $ref_item{'fullname'} = $name;
2953 $name =~ s!^refs/tags/!!;
2955 $ref_item{'type'} = $type;
2956 $ref_item{'id'} = $id;
2957 $ref_item{'name'} = $name;
2958 if ($type eq "tag") {
2959 $ref_item{'subject'} = $title;
2960 $ref_item{'reftype'} = $reftype;
2961 $ref_item{'refid'} = $refid;
2962 } else {
2963 $ref_item{'reftype'} = $type;
2964 $ref_item{'refid'} = $id;
2967 if ($type eq "tag" || $type eq "commit") {
2968 $ref_item{'epoch'} = $epoch;
2969 if ($epoch) {
2970 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2971 } else {
2972 $ref_item{'age'} = "unknown";
2976 push @tagslist, \%ref_item;
2978 close $fd;
2980 return wantarray ? @tagslist : \@tagslist;
2983 ## ----------------------------------------------------------------------
2984 ## filesystem-related functions
2986 sub get_file_owner {
2987 my $path = shift;
2989 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2990 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2991 if (!defined $gcos) {
2992 return undef;
2994 my $owner = $gcos;
2995 $owner =~ s/[,;].*$//;
2996 return to_utf8($owner);
2999 # assume that file exists
3000 sub insert_file {
3001 my $filename = shift;
3003 open my $fd, '<', $filename;
3004 print map { to_utf8($_) } <$fd>;
3005 close $fd;
3008 ## ......................................................................
3009 ## mimetype related functions
3011 sub mimetype_guess_file {
3012 my $filename = shift;
3013 my $mimemap = shift;
3014 -r $mimemap or return undef;
3016 my %mimemap;
3017 open(my $mh, '<', $mimemap) or return undef;
3018 while (<$mh>) {
3019 next if m/^#/; # skip comments
3020 my ($mimetype, $exts) = split(/\t+/);
3021 if (defined $exts) {
3022 my @exts = split(/\s+/, $exts);
3023 foreach my $ext (@exts) {
3024 $mimemap{$ext} = $mimetype;
3028 close($mh);
3030 $filename =~ /\.([^.]*)$/;
3031 return $mimemap{$1};
3034 sub mimetype_guess {
3035 my $filename = shift;
3036 my $mime;
3037 $filename =~ /\./ or return undef;
3039 if ($mimetypes_file) {
3040 my $file = $mimetypes_file;
3041 if ($file !~ m!^/!) { # if it is relative path
3042 # it is relative to project
3043 $file = "$projectroot/$project/$file";
3045 $mime = mimetype_guess_file($filename, $file);
3047 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3048 return $mime;
3051 sub blob_mimetype {
3052 my $fd = shift;
3053 my $filename = shift;
3055 if ($filename) {
3056 my $mime = mimetype_guess($filename);
3057 $mime and return $mime;
3060 # just in case
3061 return $default_blob_plain_mimetype unless $fd;
3063 if (-T $fd) {
3064 return 'text/plain';
3065 } elsif (! $filename) {
3066 return 'application/octet-stream';
3067 } elsif ($filename =~ m/\.png$/i) {
3068 return 'image/png';
3069 } elsif ($filename =~ m/\.gif$/i) {
3070 return 'image/gif';
3071 } elsif ($filename =~ m/\.jpe?g$/i) {
3072 return 'image/jpeg';
3073 } else {
3074 return 'application/octet-stream';
3078 sub blob_contenttype {
3079 my ($fd, $file_name, $type) = @_;
3081 $type ||= blob_mimetype($fd, $file_name);
3082 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3083 $type .= "; charset=$default_text_plain_charset";
3086 return $type;
3089 ## ======================================================================
3090 ## functions printing HTML: header, footer, error page
3092 sub git_header_html {
3093 my $status = shift || "200 OK";
3094 my $expires = shift;
3096 my $title = "$site_name";
3097 if (defined $project) {
3098 $title .= " - " . to_utf8($project);
3099 if (defined $action) {
3100 $title .= "/$action";
3101 if (defined $file_name) {
3102 $title .= " - " . esc_path($file_name);
3103 if ($action eq "tree" && $file_name !~ m|/$|) {
3104 $title .= "/";
3109 my $content_type;
3110 # require explicit support from the UA if we are to send the page as
3111 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3112 # we have to do this because MSIE sometimes globs '*/*', pretending to
3113 # support xhtml+xml but choking when it gets what it asked for.
3114 if (defined $cgi->http('HTTP_ACCEPT') &&
3115 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3116 $cgi->Accept('application/xhtml+xml') != 0) {
3117 $content_type = 'application/xhtml+xml';
3118 } else {
3119 $content_type = 'text/html';
3121 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3122 -status=> $status, -expires => $expires);
3123 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3124 print <<EOF;
3125 <?xml version="1.0" encoding="utf-8"?>
3126 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3127 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3128 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3129 <!-- git core binaries version $git_version -->
3130 <head>
3131 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3132 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3133 <meta name="robots" content="index, nofollow"/>
3134 <title>$title</title>
3136 # the stylesheet, favicon etc urls won't work correctly with path_info
3137 # unless we set the appropriate base URL
3138 if ($ENV{'PATH_INFO'}) {
3139 print "<base href=\"".esc_url($base_url)."\" />\n";
3141 # print out each stylesheet that exist, providing backwards capability
3142 # for those people who defined $stylesheet in a config file
3143 if (defined $stylesheet) {
3144 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3145 } else {
3146 foreach my $stylesheet (@stylesheets) {
3147 next unless $stylesheet;
3148 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3151 if (defined $project) {
3152 my %href_params = get_feed_info();
3153 if (!exists $href_params{'-title'}) {
3154 $href_params{'-title'} = 'log';
3157 foreach my $format qw(RSS Atom) {
3158 my $type = lc($format);
3159 my %link_attr = (
3160 '-rel' => 'alternate',
3161 '-title' => "$project - $href_params{'-title'} - $format feed",
3162 '-type' => "application/$type+xml"
3165 $href_params{'action'} = $type;
3166 $link_attr{'-href'} = href(%href_params);
3167 print "<link ".
3168 "rel=\"$link_attr{'-rel'}\" ".
3169 "title=\"$link_attr{'-title'}\" ".
3170 "href=\"$link_attr{'-href'}\" ".
3171 "type=\"$link_attr{'-type'}\" ".
3172 "/>\n";
3174 $href_params{'extra_options'} = '--no-merges';
3175 $link_attr{'-href'} = href(%href_params);
3176 $link_attr{'-title'} .= ' (no merges)';
3177 print "<link ".
3178 "rel=\"$link_attr{'-rel'}\" ".
3179 "title=\"$link_attr{'-title'}\" ".
3180 "href=\"$link_attr{'-href'}\" ".
3181 "type=\"$link_attr{'-type'}\" ".
3182 "/>\n";
3185 } else {
3186 printf('<link rel="alternate" title="%s projects list" '.
3187 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3188 $site_name, href(project=>undef, action=>"project_index"));
3189 printf('<link rel="alternate" title="%s projects feeds" '.
3190 'href="%s" type="text/x-opml" />'."\n",
3191 $site_name, href(project=>undef, action=>"opml"));
3193 if (defined $favicon) {
3194 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3197 print "</head>\n" .
3198 "<body>\n";
3200 if (-f $site_header) {
3201 insert_file($site_header);
3204 print "<div class=\"page_header\">\n" .
3205 $cgi->a({-href => esc_url($logo_url),
3206 -title => $logo_label},
3207 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3208 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3209 if (defined $project) {
3210 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3211 if (defined $action) {
3212 print " / $action";
3214 print "\n";
3216 print "</div>\n";
3218 my $have_search = gitweb_check_feature('search');
3219 if (defined $project && $have_search) {
3220 if (!defined $searchtext) {
3221 $searchtext = "";
3223 my $search_hash;
3224 if (defined $hash_base) {
3225 $search_hash = $hash_base;
3226 } elsif (defined $hash) {
3227 $search_hash = $hash;
3228 } else {
3229 $search_hash = "HEAD";
3231 my $action = $my_uri;
3232 my $use_pathinfo = gitweb_check_feature('pathinfo');
3233 if ($use_pathinfo) {
3234 $action .= "/".esc_url($project);
3236 print $cgi->startform(-method => "get", -action => $action) .
3237 "<div class=\"search\">\n" .
3238 (!$use_pathinfo &&
3239 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3240 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3241 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3242 $cgi->popup_menu(-name => 'st', -default => 'commit',
3243 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3244 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3245 " search:\n",
3246 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3247 "<span title=\"Extended regular expression\">" .
3248 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3249 -checked => $search_use_regexp) .
3250 "</span>" .
3251 "</div>" .
3252 $cgi->end_form() . "\n";
3256 sub git_footer_html {
3257 my $feed_class = 'rss_logo';
3259 print "<div class=\"page_footer\">\n";
3260 if (defined $project) {
3261 my $descr = git_get_project_description($project);
3262 if (defined $descr) {
3263 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3266 my %href_params = get_feed_info();
3267 if (!%href_params) {
3268 $feed_class .= ' generic';
3270 $href_params{'-title'} ||= 'log';
3272 foreach my $format qw(RSS Atom) {
3273 $href_params{'action'} = lc($format);
3274 print $cgi->a({-href => href(%href_params),
3275 -title => "$href_params{'-title'} $format feed",
3276 -class => $feed_class}, $format)."\n";
3279 } else {
3280 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3281 -class => $feed_class}, "OPML") . " ";
3282 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3283 -class => $feed_class}, "TXT") . "\n";
3285 print "</div>\n"; # class="page_footer"
3287 if (-f $site_footer) {
3288 insert_file($site_footer);
3291 print "</body>\n" .
3292 "</html>";
3295 # die_error(<http_status_code>, <error_message>)
3296 # Example: die_error(404, 'Hash not found')
3297 # By convention, use the following status codes (as defined in RFC 2616):
3298 # 400: Invalid or missing CGI parameters, or
3299 # requested object exists but has wrong type.
3300 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3301 # this server or project.
3302 # 404: Requested object/revision/project doesn't exist.
3303 # 500: The server isn't configured properly, or
3304 # an internal error occurred (e.g. failed assertions caused by bugs), or
3305 # an unknown error occurred (e.g. the git binary died unexpectedly).
3306 sub die_error {
3307 my $status = shift || 500;
3308 my $error = shift || "Internal server error";
3310 my %http_responses = (400 => '400 Bad Request',
3311 403 => '403 Forbidden',
3312 404 => '404 Not Found',
3313 500 => '500 Internal Server Error');
3314 git_header_html($http_responses{$status});
3315 print <<EOF;
3316 <div class="page_body">
3317 <br /><br />
3318 $status - $error
3319 <br />
3320 </div>
3322 git_footer_html();
3323 exit;
3326 ## ----------------------------------------------------------------------
3327 ## functions printing or outputting HTML: navigation
3329 sub git_print_page_nav {
3330 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3331 $extra = '' if !defined $extra; # pager or formats
3333 my @navs = qw(summary shortlog log commit commitdiff tree);
3334 if ($suppress) {
3335 @navs = grep { $_ ne $suppress } @navs;
3338 my %arg = map { $_ => {action=>$_} } @navs;
3339 if (defined $head) {
3340 for (qw(commit commitdiff)) {
3341 $arg{$_}{'hash'} = $head;
3343 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3344 for (qw(shortlog log)) {
3345 $arg{$_}{'hash'} = $head;
3350 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3351 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3353 my @actions = gitweb_get_feature('actions');
3354 my %repl = (
3355 '%' => '%',
3356 'n' => $project, # project name
3357 'f' => $git_dir, # project path within filesystem
3358 'h' => $treehead || '', # current hash ('h' parameter)
3359 'b' => $treebase || '', # hash base ('hb' parameter)
3361 while (@actions) {
3362 my ($label, $link, $pos) = splice(@actions,0,3);
3363 # insert
3364 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3365 # munch munch
3366 $link =~ s/%([%nfhb])/$repl{$1}/g;
3367 $arg{$label}{'_href'} = $link;
3370 print "<div class=\"page_nav\">\n" .
3371 (join " | ",
3372 map { $_ eq $current ?
3373 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3374 } @navs);
3375 print "<br/>\n$extra<br/>\n" .
3376 "</div>\n";
3379 sub format_paging_nav {
3380 my ($action, $hash, $head, $page, $has_next_link) = @_;
3381 my $paging_nav;
3384 if ($hash ne $head || $page) {
3385 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3386 } else {
3387 $paging_nav .= "HEAD";
3390 if ($page > 0) {
3391 $paging_nav .= " &sdot; " .
3392 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3393 -accesskey => "p", -title => "Alt-p"}, "prev");
3394 } else {
3395 $paging_nav .= " &sdot; prev";
3398 if ($has_next_link) {
3399 $paging_nav .= " &sdot; " .
3400 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3401 -accesskey => "n", -title => "Alt-n"}, "next");
3402 } else {
3403 $paging_nav .= " &sdot; next";
3406 return $paging_nav;
3409 ## ......................................................................
3410 ## functions printing or outputting HTML: div
3412 sub git_print_header_div {
3413 my ($action, $title, $hash, $hash_base) = @_;
3414 my %args = ();
3416 $args{'action'} = $action;
3417 $args{'hash'} = $hash if $hash;
3418 $args{'hash_base'} = $hash_base if $hash_base;
3420 print "<div class=\"header\">\n" .
3421 $cgi->a({-href => href(%args), -class => "title"},
3422 $title ? $title : $action) .
3423 "\n</div>\n";
3426 sub print_local_time {
3427 my %date = @_;
3428 if ($date{'hour_local'} < 6) {
3429 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3430 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3431 } else {
3432 printf(" (%02d:%02d %s)",
3433 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3437 # Outputs the author name and date in long form
3438 sub git_print_authorship {
3439 my $co = shift;
3440 my %opts = @_;
3441 my $tag = $opts{-tag} || 'div';
3442 my $author = $co->{'author_name'};
3444 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3445 print "<$tag class=\"author_date\">" .
3446 format_search_author($author, "author", esc_html($author)) .
3447 " [$ad{'rfc2822'}";
3448 print_local_time(%ad) if ($opts{-localtime});
3449 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3450 . "</$tag>\n";
3453 # Outputs table rows containing the full author or committer information,
3454 # in the format expected for 'commit' view (& similia).
3455 # Parameters are a commit hash reference, followed by the list of people
3456 # to output information for. If the list is empty it defalts to both
3457 # author and committer.
3458 sub git_print_authorship_rows {
3459 my $co = shift;
3460 # too bad we can't use @people = @_ || ('author', 'committer')
3461 my @people = @_;
3462 @people = ('author', 'committer') unless @people;
3463 foreach my $who (@people) {
3464 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3465 print "<tr><td>$who</td><td>" .
3466 format_search_author($co->{"${who}_name"}, $who,
3467 esc_html($co->{"${who}_name"})) . " " .
3468 format_search_author($co->{"${who}_email"}, $who,
3469 esc_html("<" . $co->{"${who}_email"} . ">")) .
3470 "</td><td rowspan=\"2\">" .
3471 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3472 "</td></tr>\n" .
3473 "<tr>" .
3474 "<td></td><td> $wd{'rfc2822'}";
3475 print_local_time(%wd);
3476 print "</td>" .
3477 "</tr>\n";
3481 sub git_print_page_path {
3482 my $name = shift;
3483 my $type = shift;
3484 my $hb = shift;
3487 print "<div class=\"page_path\">";
3488 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3489 -title => 'tree root'}, to_utf8("[$project]"));
3490 print " / ";
3491 if (defined $name) {
3492 my @dirname = split '/', $name;
3493 my $basename = pop @dirname;
3494 my $fullname = '';
3496 foreach my $dir (@dirname) {
3497 $fullname .= ($fullname ? '/' : '') . $dir;
3498 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3499 hash_base=>$hb),
3500 -title => $fullname}, esc_path($dir));
3501 print " / ";
3503 if (defined $type && $type eq 'blob') {
3504 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3505 hash_base=>$hb),
3506 -title => $name}, esc_path($basename));
3507 } elsif (defined $type && $type eq 'tree') {
3508 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3509 hash_base=>$hb),
3510 -title => $name}, esc_path($basename));
3511 print " / ";
3512 } else {
3513 print esc_path($basename);
3516 print "<br/></div>\n";
3519 sub git_print_log {
3520 my $log = shift;
3521 my %opts = @_;
3523 if ($opts{'-remove_title'}) {
3524 # remove title, i.e. first line of log
3525 shift @$log;
3527 # remove leading empty lines
3528 while (defined $log->[0] && $log->[0] eq "") {
3529 shift @$log;
3532 # print log
3533 my $signoff = 0;
3534 my $empty = 0;
3535 foreach my $line (@$log) {
3536 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3537 $signoff = 1;
3538 $empty = 0;
3539 if (! $opts{'-remove_signoff'}) {
3540 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3541 next;
3542 } else {
3543 # remove signoff lines
3544 next;
3546 } else {
3547 $signoff = 0;
3550 # print only one empty line
3551 # do not print empty line after signoff
3552 if ($line eq "") {
3553 next if ($empty || $signoff);
3554 $empty = 1;
3555 } else {
3556 $empty = 0;
3559 print format_log_line_html($line) . "<br/>\n";
3562 if ($opts{'-final_empty_line'}) {
3563 # end with single empty line
3564 print "<br/>\n" unless $empty;
3568 # return link target (what link points to)
3569 sub git_get_link_target {
3570 my $hash = shift;
3571 my $link_target;
3573 # read link
3574 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3575 or return;
3577 local $/ = undef;
3578 $link_target = <$fd>;
3580 close $fd
3581 or return;
3583 return $link_target;
3586 # given link target, and the directory (basedir) the link is in,
3587 # return target of link relative to top directory (top tree);
3588 # return undef if it is not possible (including absolute links).
3589 sub normalize_link_target {
3590 my ($link_target, $basedir) = @_;
3592 # absolute symlinks (beginning with '/') cannot be normalized
3593 return if (substr($link_target, 0, 1) eq '/');
3595 # normalize link target to path from top (root) tree (dir)
3596 my $path;
3597 if ($basedir) {
3598 $path = $basedir . '/' . $link_target;
3599 } else {
3600 # we are in top (root) tree (dir)
3601 $path = $link_target;
3604 # remove //, /./, and /../
3605 my @path_parts;
3606 foreach my $part (split('/', $path)) {
3607 # discard '.' and ''
3608 next if (!$part || $part eq '.');
3609 # handle '..'
3610 if ($part eq '..') {
3611 if (@path_parts) {
3612 pop @path_parts;
3613 } else {
3614 # link leads outside repository (outside top dir)
3615 return;
3617 } else {
3618 push @path_parts, $part;
3621 $path = join('/', @path_parts);
3623 return $path;
3626 # print tree entry (row of git_tree), but without encompassing <tr> element
3627 sub git_print_tree_entry {
3628 my ($t, $basedir, $hash_base, $have_blame) = @_;
3630 my %base_key = ();
3631 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3633 # The format of a table row is: mode list link. Where mode is
3634 # the mode of the entry, list is the name of the entry, an href,
3635 # and link is the action links of the entry.
3637 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3638 if (exists $t->{'size'}) {
3639 print "<td class=\"size\">$t->{'size'}</td>\n";
3641 if ($t->{'type'} eq "blob") {
3642 print "<td class=\"list\">" .
3643 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3644 file_name=>"$basedir$t->{'name'}", %base_key),
3645 -class => "list"}, esc_path($t->{'name'}));
3646 if (S_ISLNK(oct $t->{'mode'})) {
3647 my $link_target = git_get_link_target($t->{'hash'});
3648 if ($link_target) {
3649 my $norm_target = normalize_link_target($link_target, $basedir);
3650 if (defined $norm_target) {
3651 print " -> " .
3652 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3653 file_name=>$norm_target),
3654 -title => $norm_target}, esc_path($link_target));
3655 } else {
3656 print " -> " . esc_path($link_target);
3660 print "</td>\n";
3661 print "<td class=\"link\">";
3662 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3663 file_name=>"$basedir$t->{'name'}", %base_key)},
3664 "blob");
3665 if ($have_blame) {
3666 print " | " .
3667 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3668 file_name=>"$basedir$t->{'name'}", %base_key)},
3669 "blame");
3671 if (defined $hash_base) {
3672 print " | " .
3673 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3674 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3675 "history");
3677 print " | " .
3678 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3679 file_name=>"$basedir$t->{'name'}")},
3680 "raw");
3681 print "</td>\n";
3683 } elsif ($t->{'type'} eq "tree") {
3684 print "<td class=\"list\">";
3685 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3686 file_name=>"$basedir$t->{'name'}",
3687 %base_key)},
3688 esc_path($t->{'name'}));
3689 print "</td>\n";
3690 print "<td class=\"link\">";
3691 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3692 file_name=>"$basedir$t->{'name'}",
3693 %base_key)},
3694 "tree");
3695 if (defined $hash_base) {
3696 print " | " .
3697 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3698 file_name=>"$basedir$t->{'name'}")},
3699 "history");
3701 print "</td>\n";
3702 } else {
3703 # unknown object: we can only present history for it
3704 # (this includes 'commit' object, i.e. submodule support)
3705 print "<td class=\"list\">" .
3706 esc_path($t->{'name'}) .
3707 "</td>\n";
3708 print "<td class=\"link\">";
3709 if (defined $hash_base) {
3710 print $cgi->a({-href => href(action=>"history",
3711 hash_base=>$hash_base,
3712 file_name=>"$basedir$t->{'name'}")},
3713 "history");
3715 print "</td>\n";
3719 ## ......................................................................
3720 ## functions printing large fragments of HTML
3722 # get pre-image filenames for merge (combined) diff
3723 sub fill_from_file_info {
3724 my ($diff, @parents) = @_;
3726 $diff->{'from_file'} = [ ];
3727 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3728 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3729 if ($diff->{'status'}[$i] eq 'R' ||
3730 $diff->{'status'}[$i] eq 'C') {
3731 $diff->{'from_file'}[$i] =
3732 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3736 return $diff;
3739 # is current raw difftree line of file deletion
3740 sub is_deleted {
3741 my $diffinfo = shift;
3743 return $diffinfo->{'to_id'} eq ('0' x 40);
3746 # does patch correspond to [previous] difftree raw line
3747 # $diffinfo - hashref of parsed raw diff format
3748 # $patchinfo - hashref of parsed patch diff format
3749 # (the same keys as in $diffinfo)
3750 sub is_patch_split {
3751 my ($diffinfo, $patchinfo) = @_;
3753 return defined $diffinfo && defined $patchinfo
3754 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3758 sub git_difftree_body {
3759 my ($difftree, $hash, @parents) = @_;
3760 my ($parent) = $parents[0];
3761 my $have_blame = gitweb_check_feature('blame');
3762 print "<div class=\"list_head\">\n";
3763 if ($#{$difftree} > 10) {
3764 print(($#{$difftree} + 1) . " files changed:\n");
3766 print "</div>\n";
3768 print "<table class=\"" .
3769 (@parents > 1 ? "combined " : "") .
3770 "diff_tree\">\n";
3772 # header only for combined diff in 'commitdiff' view
3773 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3774 if ($has_header) {
3775 # table header
3776 print "<thead><tr>\n" .
3777 "<th></th><th></th>\n"; # filename, patchN link
3778 for (my $i = 0; $i < @parents; $i++) {
3779 my $par = $parents[$i];
3780 print "<th>" .
3781 $cgi->a({-href => href(action=>"commitdiff",
3782 hash=>$hash, hash_parent=>$par),
3783 -title => 'commitdiff to parent number ' .
3784 ($i+1) . ': ' . substr($par,0,7)},
3785 $i+1) .
3786 "&nbsp;</th>\n";
3788 print "</tr></thead>\n<tbody>\n";
3791 my $alternate = 1;
3792 my $patchno = 0;
3793 foreach my $line (@{$difftree}) {
3794 my $diff = parsed_difftree_line($line);
3796 if ($alternate) {
3797 print "<tr class=\"dark\">\n";
3798 } else {
3799 print "<tr class=\"light\">\n";
3801 $alternate ^= 1;
3803 if (exists $diff->{'nparents'}) { # combined diff
3805 fill_from_file_info($diff, @parents)
3806 unless exists $diff->{'from_file'};
3808 if (!is_deleted($diff)) {
3809 # file exists in the result (child) commit
3810 print "<td>" .
3811 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3812 file_name=>$diff->{'to_file'},
3813 hash_base=>$hash),
3814 -class => "list"}, esc_path($diff->{'to_file'})) .
3815 "</td>\n";
3816 } else {
3817 print "<td>" .
3818 esc_path($diff->{'to_file'}) .
3819 "</td>\n";
3822 if ($action eq 'commitdiff') {
3823 # link to patch
3824 $patchno++;
3825 print "<td class=\"link\">" .
3826 $cgi->a({-href => "#patch$patchno"}, "patch") .
3827 " | " .
3828 "</td>\n";
3831 my $has_history = 0;
3832 my $not_deleted = 0;
3833 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3834 my $hash_parent = $parents[$i];
3835 my $from_hash = $diff->{'from_id'}[$i];
3836 my $from_path = $diff->{'from_file'}[$i];
3837 my $status = $diff->{'status'}[$i];
3839 $has_history ||= ($status ne 'A');
3840 $not_deleted ||= ($status ne 'D');
3842 if ($status eq 'A') {
3843 print "<td class=\"link\" align=\"right\"> | </td>\n";
3844 } elsif ($status eq 'D') {
3845 print "<td class=\"link\">" .
3846 $cgi->a({-href => href(action=>"blob",
3847 hash_base=>$hash,
3848 hash=>$from_hash,
3849 file_name=>$from_path)},
3850 "blob" . ($i+1)) .
3851 " | </td>\n";
3852 } else {
3853 if ($diff->{'to_id'} eq $from_hash) {
3854 print "<td class=\"link nochange\">";
3855 } else {
3856 print "<td class=\"link\">";
3858 print $cgi->a({-href => href(action=>"blobdiff",
3859 hash=>$diff->{'to_id'},
3860 hash_parent=>$from_hash,
3861 hash_base=>$hash,
3862 hash_parent_base=>$hash_parent,
3863 file_name=>$diff->{'to_file'},
3864 file_parent=>$from_path)},
3865 "diff" . ($i+1)) .
3866 " | </td>\n";
3870 print "<td class=\"link\">";
3871 if ($not_deleted) {
3872 print $cgi->a({-href => href(action=>"blob",
3873 hash=>$diff->{'to_id'},
3874 file_name=>$diff->{'to_file'},
3875 hash_base=>$hash)},
3876 "blob");
3877 print " | " if ($has_history);
3879 if ($has_history) {
3880 print $cgi->a({-href => href(action=>"history",
3881 file_name=>$diff->{'to_file'},
3882 hash_base=>$hash)},
3883 "history");
3885 print "</td>\n";
3887 print "</tr>\n";
3888 next; # instead of 'else' clause, to avoid extra indent
3890 # else ordinary diff
3892 my ($to_mode_oct, $to_mode_str, $to_file_type);
3893 my ($from_mode_oct, $from_mode_str, $from_file_type);
3894 if ($diff->{'to_mode'} ne ('0' x 6)) {
3895 $to_mode_oct = oct $diff->{'to_mode'};
3896 if (S_ISREG($to_mode_oct)) { # only for regular file
3897 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3899 $to_file_type = file_type($diff->{'to_mode'});
3901 if ($diff->{'from_mode'} ne ('0' x 6)) {
3902 $from_mode_oct = oct $diff->{'from_mode'};
3903 if (S_ISREG($to_mode_oct)) { # only for regular file
3904 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3906 $from_file_type = file_type($diff->{'from_mode'});
3909 if ($diff->{'status'} eq "A") { # created
3910 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3911 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3912 $mode_chng .= "]</span>";
3913 print "<td>";
3914 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3915 hash_base=>$hash, file_name=>$diff->{'file'}),
3916 -class => "list"}, esc_path($diff->{'file'}));
3917 print "</td>\n";
3918 print "<td>$mode_chng</td>\n";
3919 print "<td class=\"link\">";
3920 if ($action eq 'commitdiff') {
3921 # link to patch
3922 $patchno++;
3923 print $cgi->a({-href => "#patch$patchno"}, "patch");
3924 print " | ";
3926 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3927 hash_base=>$hash, file_name=>$diff->{'file'})},
3928 "blob");
3929 print "</td>\n";
3931 } elsif ($diff->{'status'} eq "D") { # deleted
3932 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3933 print "<td>";
3934 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3935 hash_base=>$parent, file_name=>$diff->{'file'}),
3936 -class => "list"}, esc_path($diff->{'file'}));
3937 print "</td>\n";
3938 print "<td>$mode_chng</td>\n";
3939 print "<td class=\"link\">";
3940 if ($action eq 'commitdiff') {
3941 # link to patch
3942 $patchno++;
3943 print $cgi->a({-href => "#patch$patchno"}, "patch");
3944 print " | ";
3946 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3947 hash_base=>$parent, file_name=>$diff->{'file'})},
3948 "blob") . " | ";
3949 if ($have_blame) {
3950 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3951 file_name=>$diff->{'file'})},
3952 "blame") . " | ";
3954 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3955 file_name=>$diff->{'file'})},
3956 "history");
3957 print "</td>\n";
3959 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3960 my $mode_chnge = "";
3961 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3962 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3963 if ($from_file_type ne $to_file_type) {
3964 $mode_chnge .= " from $from_file_type to $to_file_type";
3966 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3967 if ($from_mode_str && $to_mode_str) {
3968 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3969 } elsif ($to_mode_str) {
3970 $mode_chnge .= " mode: $to_mode_str";
3973 $mode_chnge .= "]</span>\n";
3975 print "<td>";
3976 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3977 hash_base=>$hash, file_name=>$diff->{'file'}),
3978 -class => "list"}, esc_path($diff->{'file'}));
3979 print "</td>\n";
3980 print "<td>$mode_chnge</td>\n";
3981 print "<td class=\"link\">";
3982 if ($action eq 'commitdiff') {
3983 # link to patch
3984 $patchno++;
3985 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3986 " | ";
3987 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3988 # "commit" view and modified file (not onlu mode changed)
3989 print $cgi->a({-href => href(action=>"blobdiff",
3990 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3991 hash_base=>$hash, hash_parent_base=>$parent,
3992 file_name=>$diff->{'file'})},
3993 "diff") .
3994 " | ";
3996 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3997 hash_base=>$hash, file_name=>$diff->{'file'})},
3998 "blob") . " | ";
3999 if ($have_blame) {
4000 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4001 file_name=>$diff->{'file'})},
4002 "blame") . " | ";
4004 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4005 file_name=>$diff->{'file'})},
4006 "history");
4007 print "</td>\n";
4009 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4010 my %status_name = ('R' => 'moved', 'C' => 'copied');
4011 my $nstatus = $status_name{$diff->{'status'}};
4012 my $mode_chng = "";
4013 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4014 # mode also for directories, so we cannot use $to_mode_str
4015 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4017 print "<td>" .
4018 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4019 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4020 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4021 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4022 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4023 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4024 -class => "list"}, esc_path($diff->{'from_file'})) .
4025 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4026 "<td class=\"link\">";
4027 if ($action eq 'commitdiff') {
4028 # link to patch
4029 $patchno++;
4030 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4031 " | ";
4032 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4033 # "commit" view and modified file (not only pure rename or copy)
4034 print $cgi->a({-href => href(action=>"blobdiff",
4035 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4036 hash_base=>$hash, hash_parent_base=>$parent,
4037 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4038 "diff") .
4039 " | ";
4041 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4042 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4043 "blob") . " | ";
4044 if ($have_blame) {
4045 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4046 file_name=>$diff->{'to_file'})},
4047 "blame") . " | ";
4049 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4050 file_name=>$diff->{'to_file'})},
4051 "history");
4052 print "</td>\n";
4054 } # we should not encounter Unmerged (U) or Unknown (X) status
4055 print "</tr>\n";
4057 print "</tbody>" if $has_header;
4058 print "</table>\n";
4061 sub git_patchset_body {
4062 my ($fd, $difftree, $hash, @hash_parents) = @_;
4063 my ($hash_parent) = $hash_parents[0];
4065 my $is_combined = (@hash_parents > 1);
4066 my $patch_idx = 0;
4067 my $patch_number = 0;
4068 my $patch_line;
4069 my $diffinfo;
4070 my $to_name;
4071 my (%from, %to);
4073 print "<div class=\"patchset\">\n";
4075 # skip to first patch
4076 while ($patch_line = <$fd>) {
4077 chomp $patch_line;
4079 last if ($patch_line =~ m/^diff /);
4082 PATCH:
4083 while ($patch_line) {
4085 # parse "git diff" header line
4086 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4087 # $1 is from_name, which we do not use
4088 $to_name = unquote($2);
4089 $to_name =~ s!^b/!!;
4090 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4091 # $1 is 'cc' or 'combined', which we do not use
4092 $to_name = unquote($2);
4093 } else {
4094 $to_name = undef;
4097 # check if current patch belong to current raw line
4098 # and parse raw git-diff line if needed
4099 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4100 # this is continuation of a split patch
4101 print "<div class=\"patch cont\">\n";
4102 } else {
4103 # advance raw git-diff output if needed
4104 $patch_idx++ if defined $diffinfo;
4106 # read and prepare patch information
4107 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4109 # compact combined diff output can have some patches skipped
4110 # find which patch (using pathname of result) we are at now;
4111 if ($is_combined) {
4112 while ($to_name ne $diffinfo->{'to_file'}) {
4113 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4114 format_diff_cc_simplified($diffinfo, @hash_parents) .
4115 "</div>\n"; # class="patch"
4117 $patch_idx++;
4118 $patch_number++;
4120 last if $patch_idx > $#$difftree;
4121 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4125 # modifies %from, %to hashes
4126 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4128 # this is first patch for raw difftree line with $patch_idx index
4129 # we index @$difftree array from 0, but number patches from 1
4130 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4133 # git diff header
4134 #assert($patch_line =~ m/^diff /) if DEBUG;
4135 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4136 $patch_number++;
4137 # print "git diff" header
4138 print format_git_diff_header_line($patch_line, $diffinfo,
4139 \%from, \%to);
4141 # print extended diff header
4142 print "<div class=\"diff extended_header\">\n";
4143 EXTENDED_HEADER:
4144 while ($patch_line = <$fd>) {
4145 chomp $patch_line;
4147 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4149 print format_extended_diff_header_line($patch_line, $diffinfo,
4150 \%from, \%to);
4152 print "</div>\n"; # class="diff extended_header"
4154 # from-file/to-file diff header
4155 if (! $patch_line) {
4156 print "</div>\n"; # class="patch"
4157 last PATCH;
4159 next PATCH if ($patch_line =~ m/^diff /);
4160 #assert($patch_line =~ m/^---/) if DEBUG;
4162 my $last_patch_line = $patch_line;
4163 $patch_line = <$fd>;
4164 chomp $patch_line;
4165 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4167 print format_diff_from_to_header($last_patch_line, $patch_line,
4168 $diffinfo, \%from, \%to,
4169 @hash_parents);
4171 # the patch itself
4172 LINE:
4173 while ($patch_line = <$fd>) {
4174 chomp $patch_line;
4176 next PATCH if ($patch_line =~ m/^diff /);
4178 print format_diff_line($patch_line, \%from, \%to);
4181 } continue {
4182 print "</div>\n"; # class="patch"
4185 # for compact combined (--cc) format, with chunk and patch simpliciaction
4186 # patchset might be empty, but there might be unprocessed raw lines
4187 for (++$patch_idx if $patch_number > 0;
4188 $patch_idx < @$difftree;
4189 ++$patch_idx) {
4190 # read and prepare patch information
4191 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4193 # generate anchor for "patch" links in difftree / whatchanged part
4194 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4195 format_diff_cc_simplified($diffinfo, @hash_parents) .
4196 "</div>\n"; # class="patch"
4198 $patch_number++;
4201 if ($patch_number == 0) {
4202 if (@hash_parents > 1) {
4203 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4204 } else {
4205 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4209 print "</div>\n"; # class="patchset"
4212 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4214 # fills project list info (age, description, owner, forks) for each
4215 # project in the list, removing invalid projects from returned list
4216 # NOTE: modifies $projlist, but does not remove entries from it
4217 sub fill_project_list_info {
4218 my ($projlist, $check_forks, $show_ctags) = @_;
4219 my @projects;
4221 PROJECT:
4222 foreach my $pr (@$projlist) {
4223 my (@activity) = git_get_last_activity($pr->{'path'});
4224 unless (@activity) {
4225 next PROJECT;
4227 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4228 if (!defined $pr->{'descr'}) {
4229 my $descr = git_get_project_description($pr->{'path'}) || "";
4230 $descr = to_utf8($descr);
4231 $pr->{'descr_long'} = $descr;
4232 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4234 if (!defined $pr->{'owner'}) {
4235 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4237 if ($check_forks) {
4238 my $pname = $pr->{'path'};
4239 if (($pname =~ s/\.git$//) &&
4240 ($pname !~ /\/$/) &&
4241 (-d "$projectroot/$pname")) {
4242 $pr->{'forks'} = "-d $projectroot/$pname";
4243 } else {
4244 $pr->{'forks'} = 0;
4247 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4248 push @projects, $pr;
4251 return @projects;
4254 # print 'sort by' <th> element, generating 'sort by $name' replay link
4255 # if that order is not selected
4256 sub print_sort_th {
4257 my ($name, $order, $header) = @_;
4258 $header ||= ucfirst($name);
4260 if ($order eq $name) {
4261 print "<th>$header</th>\n";
4262 } else {
4263 print "<th>" .
4264 $cgi->a({-href => href(-replay=>1, order=>$name),
4265 -class => "header"}, $header) .
4266 "</th>\n";
4270 sub git_project_list_ctags {
4271 my ($projects, $action) = @_;
4272 $action ||= 'project_list';
4274 my %ctags;
4275 foreach my $p (@$projects) {
4276 foreach my $ct (keys %{$p->{'ctags'}}) {
4277 $ctags{$ct} += $p->{'ctags'}->{$ct};
4280 my $cloud = git_populate_project_tagcloud(\%ctags, $action);
4281 print git_show_project_tagcloud($cloud, 64, $action);
4284 sub git_project_list_body {
4285 # actually uses global variable $project
4286 my ($projlist, $order, $from, $to, $extra, $no_header, $ctags_action) = @_;
4288 my $check_forks = gitweb_check_feature('forks');
4289 my $show_ctags = gitweb_check_feature('ctags');
4290 my @projects = fill_project_list_info($projlist, $check_forks, $show_ctags);
4292 $order ||= $default_projects_order;
4293 $from = 0 unless defined $from;
4294 $to = $#projects if (!defined $to || $#projects < $to);
4296 my %order_info = (
4297 project => { key => 'path', type => 'str' },
4298 descr => { key => 'descr_long', type => 'str' },
4299 owner => { key => 'owner', type => 'str' },
4300 age => { key => 'age', type => 'num' }
4302 my $oi = $order_info{$order};
4303 if ($oi->{'type'} eq 'str') {
4304 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4305 } else {
4306 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4309 if ($show_ctags) {
4310 git_project_list_ctags(\@projects, $ctags_action);
4313 print "<table class=\"project_list\">\n";
4314 unless ($no_header) {
4315 print "<tr>\n";
4316 if ($check_forks) {
4317 print "<th></th>\n";
4319 print_sort_th('project', $order, 'Project');
4320 print_sort_th('descr', $order, 'Description');
4321 print_sort_th('owner', $order, 'Owner');
4322 print_sort_th('age', $order, 'Last Change');
4323 print "<th></th>\n" . # for links
4324 "</tr>\n";
4326 my $alternate = 1;
4327 my $tagfilter = $input_params{'ctag_filter'};
4328 for (my $i = $from; $i <= $to; $i++) {
4329 my $pr = $projects[$i];
4331 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4332 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4333 and not $pr->{'descr_long'} =~ /$searchtext/;
4334 # Weed out forks or non-matching entries of search
4335 if ($check_forks) {
4336 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4337 $forkbase="^$forkbase" if $forkbase;
4338 next if not $searchtext and not $tagfilter and $show_ctags
4339 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4342 if ($alternate) {
4343 print "<tr class=\"dark\">\n";
4344 } else {
4345 print "<tr class=\"light\">\n";
4347 $alternate ^= 1;
4348 if ($check_forks) {
4349 print "<td>";
4350 if ($pr->{'forks'}) {
4351 print "<!-- $pr->{'forks'} -->\n";
4352 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4354 print "</td>\n";
4356 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4357 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4358 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4359 -class => "list", -title => $pr->{'descr_long'}},
4360 esc_html($pr->{'descr'})) . "</td>\n" .
4361 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4362 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4363 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4364 "<td class=\"link\">" .
4365 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4366 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4367 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4368 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4369 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4370 "</td>\n" .
4371 "</tr>\n";
4373 if (defined $extra) {
4374 print "<tr>\n";
4375 if ($check_forks) {
4376 print "<td></td>\n";
4378 print "<td colspan=\"5\">$extra</td>\n" .
4379 "</tr>\n";
4381 print "</table>\n";
4384 sub git_project_search_form {
4385 print $cgi->startform(-method => "get") .
4386 $cgi->hidden({-name=>"a", -value=>"project_list"}) . "\n" .
4387 "<p class=\"projsearch\">Search:\n" .
4388 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4389 "</p>" .
4390 $cgi->end_form() . "\n";
4393 sub git_project_list_all {
4394 my $order = $input_params{'order'};
4395 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4396 die_error(400, "Unknown order parameter");
4399 my @list = git_get_projects_list();
4400 if (!@list) {
4401 die_error(404, "No projects found");
4404 git_project_list_body(\@list, $order);
4407 sub git_shortlog_body {
4408 # uses global variable $project
4409 my ($commitlist, $from, $to, $refs, $extra) = @_;
4411 $from = 0 unless defined $from;
4412 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4414 print "<table class=\"shortlog\">\n";
4415 my $alternate = 1;
4416 for (my $i = $from; $i <= $to; $i++) {
4417 my %co = %{$commitlist->[$i]};
4418 my $commit = $co{'id'};
4419 my $ref = format_ref_marker($refs, $commit);
4420 if ($alternate) {
4421 print "<tr class=\"dark\">\n";
4422 } else {
4423 print "<tr class=\"light\">\n";
4425 $alternate ^= 1;
4426 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4427 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4428 format_author_html('td', \%co, 10) . "<td>";
4429 print format_subject_html($co{'title'}, $co{'title_short'},
4430 href(action=>"commit", hash=>$commit), $ref);
4431 print "</td>\n" .
4432 "<td class=\"link\">" .
4433 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4434 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4435 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4436 my $snapshot_links = format_snapshot_links($commit);
4437 if (defined $snapshot_links) {
4438 print " | " . $snapshot_links;
4440 print "</td>\n" .
4441 "</tr>\n";
4443 if (defined $extra) {
4444 print "<tr>\n" .
4445 "<td colspan=\"4\">$extra</td>\n" .
4446 "</tr>\n";
4448 print "</table>\n";
4451 sub git_history_body {
4452 # Warning: assumes constant type (blob or tree) during history
4453 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4455 $from = 0 unless defined $from;
4456 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4458 print "<table class=\"history\">\n";
4459 my $alternate = 1;
4460 for (my $i = $from; $i <= $to; $i++) {
4461 my %co = %{$commitlist->[$i]};
4462 if (!%co) {
4463 next;
4465 my $commit = $co{'id'};
4467 my $ref = format_ref_marker($refs, $commit);
4469 if ($alternate) {
4470 print "<tr class=\"dark\">\n";
4471 } else {
4472 print "<tr class=\"light\">\n";
4474 $alternate ^= 1;
4475 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4476 # shortlog: format_author_html('td', \%co, 10)
4477 format_author_html('td', \%co, 15, 3) . "<td>";
4478 # originally git_history used chop_str($co{'title'}, 50)
4479 print format_subject_html($co{'title'}, $co{'title_short'},
4480 href(action=>"commit", hash=>$commit), $ref);
4481 print "</td>\n" .
4482 "<td class=\"link\">" .
4483 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4484 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4486 if ($ftype eq 'blob') {
4487 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4488 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4489 if (defined $blob_current && defined $blob_parent &&
4490 $blob_current ne $blob_parent) {
4491 print " | " .
4492 $cgi->a({-href => href(action=>"blobdiff",
4493 hash=>$blob_current, hash_parent=>$blob_parent,
4494 hash_base=>$hash_base, hash_parent_base=>$commit,
4495 file_name=>$file_name)},
4496 "diff to current");
4499 print "</td>\n" .
4500 "</tr>\n";
4502 if (defined $extra) {
4503 print "<tr>\n" .
4504 "<td colspan=\"4\">$extra</td>\n" .
4505 "</tr>\n";
4507 print "</table>\n";
4510 sub git_tags_body {
4511 # uses global variable $project
4512 my ($taglist, $from, $to, $extra) = @_;
4513 $from = 0 unless defined $from;
4514 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4516 print "<table class=\"tags\">\n";
4517 my $alternate = 1;
4518 for (my $i = $from; $i <= $to; $i++) {
4519 my $entry = $taglist->[$i];
4520 my %tag = %$entry;
4521 my $comment = $tag{'subject'};
4522 my $comment_short;
4523 if (defined $comment) {
4524 $comment_short = chop_str($comment, 30, 5);
4526 if ($alternate) {
4527 print "<tr class=\"dark\">\n";
4528 } else {
4529 print "<tr class=\"light\">\n";
4531 $alternate ^= 1;
4532 if (defined $tag{'age'}) {
4533 print "<td><i>$tag{'age'}</i></td>\n";
4534 } else {
4535 print "<td></td>\n";
4537 print "<td>" .
4538 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4539 -class => "list name"}, esc_html($tag{'name'})) .
4540 "</td>\n" .
4541 "<td>";
4542 if (defined $comment) {
4543 print format_subject_html($comment, $comment_short,
4544 href(action=>"tag", hash=>$tag{'id'}));
4546 print "</td>\n" .
4547 "<td class=\"selflink\">";
4548 if ($tag{'type'} eq "tag") {
4549 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4550 } else {
4551 print "&nbsp;";
4553 print "</td>\n" .
4554 "<td class=\"link\">" . " | " .
4555 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4556 if ($tag{'reftype'} eq "commit") {
4557 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4558 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4559 } elsif ($tag{'reftype'} eq "blob") {
4560 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4562 print "</td>\n" .
4563 "</tr>";
4565 if (defined $extra) {
4566 print "<tr>\n" .
4567 "<td colspan=\"5\">$extra</td>\n" .
4568 "</tr>\n";
4570 print "</table>\n";
4573 sub git_heads_body {
4574 # uses global variable $project
4575 my ($headlist, $head, $from, $to, $extra) = @_;
4576 $from = 0 unless defined $from;
4577 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4579 print "<table class=\"heads\">\n";
4580 my $alternate = 1;
4581 for (my $i = $from; $i <= $to; $i++) {
4582 my $entry = $headlist->[$i];
4583 my %ref = %$entry;
4584 my $curr = $ref{'id'} eq $head;
4585 if ($alternate) {
4586 print "<tr class=\"dark\">\n";
4587 } else {
4588 print "<tr class=\"light\">\n";
4590 $alternate ^= 1;
4591 print "<td><i>$ref{'age'}</i></td>\n" .
4592 ($curr ? "<td class=\"current_head\">" : "<td>") .
4593 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4594 -class => "list name"},esc_html($ref{'name'})) .
4595 "</td>\n" .
4596 "<td class=\"link\">" .
4597 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4598 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4599 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4600 "</td>\n" .
4601 "</tr>";
4603 if (defined $extra) {
4604 print "<tr>\n" .
4605 "<td colspan=\"3\">$extra</td>\n" .
4606 "</tr>\n";
4608 print "</table>\n";
4611 sub git_search_grep_body {
4612 my ($commitlist, $from, $to, $extra) = @_;
4613 $from = 0 unless defined $from;
4614 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4616 print "<table class=\"commit_search\">\n";
4617 my $alternate = 1;
4618 for (my $i = $from; $i <= $to; $i++) {
4619 my %co = %{$commitlist->[$i]};
4620 if (!%co) {
4621 next;
4623 my $commit = $co{'id'};
4624 if ($alternate) {
4625 print "<tr class=\"dark\">\n";
4626 } else {
4627 print "<tr class=\"light\">\n";
4629 $alternate ^= 1;
4630 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4631 format_author_html('td', \%co, 15, 5) .
4632 "<td>" .
4633 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4634 -class => "list subject"},
4635 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4636 my $comment = $co{'comment'};
4637 foreach my $line (@$comment) {
4638 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4639 my ($lead, $match, $trail) = ($1, $2, $3);
4640 $match = chop_str($match, 70, 5, 'center');
4641 my $contextlen = int((80 - length($match))/2);
4642 $contextlen = 30 if ($contextlen > 30);
4643 $lead = chop_str($lead, $contextlen, 10, 'left');
4644 $trail = chop_str($trail, $contextlen, 10, 'right');
4646 $lead = esc_html($lead);
4647 $match = esc_html($match);
4648 $trail = esc_html($trail);
4650 print "$lead<span class=\"match\">$match</span>$trail<br />";
4653 print "</td>\n" .
4654 "<td class=\"link\">" .
4655 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4656 " | " .
4657 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4658 " | " .
4659 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4660 print "</td>\n" .
4661 "</tr>\n";
4663 if (defined $extra) {
4664 print "<tr>\n" .
4665 "<td colspan=\"3\">$extra</td>\n" .
4666 "</tr>\n";
4668 print "</table>\n";
4671 ## ======================================================================
4672 ## ======================================================================
4673 ## actions
4675 sub git_frontpage {
4676 git_header_html();
4677 if (-f $home_text) {
4678 print "<div class=\"index_include\">\n";
4679 insert_file($home_text);
4680 print "</div>\n";
4682 git_project_search_form();
4683 if (not $frontpage_no_project_list) {
4684 git_project_list_all();
4685 } else {
4686 my $show_ctags = gitweb_check_feature('ctags');
4687 if ($frontpage_no_project_list == 1 and $show_ctags) {
4688 my @list = git_get_projects_list();
4689 my @projects = fill_project_list_info(\@list, gitweb_check_feature('forks'), $show_ctags);
4690 git_project_list_ctags(\@projects);
4692 print "<p class=\"projectlist_link\">" .
4693 $cgi->a({-href => href(action=>'project_list')}, "Browse all projects") .
4694 "</p>\n";
4696 git_footer_html();
4699 sub git_project_list {
4700 git_header_html();
4701 git_project_search_form();
4702 git_project_list_all();
4703 git_footer_html();
4706 sub git_forks {
4707 my $order = $input_params{'order'};
4708 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4709 die_error(400, "Unknown order parameter");
4712 my @list = git_get_projects_list($project);
4713 if (!@list) {
4714 die_error(404, "No forks found");
4717 git_header_html();
4718 git_print_page_nav('','');
4719 git_print_header_div('summary', "$project forks");
4720 git_project_list_body(\@list, $order, undef, undef, undef, undef, 'forks');
4721 git_footer_html();
4724 sub git_project_index {
4725 my @projects = git_get_projects_list($project);
4727 print $cgi->header(
4728 -type => 'text/plain',
4729 -charset => 'utf-8',
4730 -content_disposition => 'inline; filename="index.aux"');
4732 foreach my $pr (@projects) {
4733 if (!exists $pr->{'owner'}) {
4734 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4737 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4738 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4739 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4740 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4741 $path =~ s/ /\+/g;
4742 $owner =~ s/ /\+/g;
4744 print "$path $owner\n";
4748 sub git_summary {
4749 my $descr = git_get_project_description($project) || "none";
4750 my %co = parse_commit("HEAD");
4751 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4752 my $head = $co{'id'};
4754 my $owner = git_get_project_owner($project);
4756 my $refs = git_get_references();
4757 # These get_*_list functions return one more to allow us to see if
4758 # there are more ...
4759 my @taglist = git_get_tags_list(16);
4760 my @headlist = git_get_heads_list(16);
4761 my @forklist;
4762 my $check_forks = gitweb_check_feature('forks');
4764 if ($check_forks) {
4765 @forklist = git_get_projects_list($project);
4768 git_header_html();
4769 git_print_page_nav('summary','', $head);
4771 print "<div class=\"title\">&nbsp;</div>\n";
4772 print "<table class=\"projects_list\">\n" .
4773 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4774 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4775 if (defined $cd{'rfc2822'}) {
4776 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4779 # use per project git URL list in $projectroot/$project/cloneurl
4780 # or make project git URL from git base URL and project name
4781 my $url_tag = "URL";
4782 my @url_list = git_get_project_url_list($project);
4783 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4784 foreach my $git_url (@url_list) {
4785 next unless $git_url;
4786 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4787 $url_tag = "";
4790 # Tag cloud
4791 my $show_ctags = gitweb_check_feature('ctags');
4792 if ($show_ctags) {
4793 my $ctags = git_get_project_ctags($project);
4794 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
4795 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4796 print "</td>\n<td>" unless %$ctags;
4797 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4798 print "</td>\n<td>" if %$ctags;
4799 print git_show_project_tagcloud($cloud, 48, 'project_list');
4800 print "</td></tr>";
4803 print "</table>\n";
4805 # If XSS prevention is on, we don't include README.html.
4806 # TODO: Allow a readme in some safe format.
4807 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4808 print "<div class=\"title\">readme</div>\n" .
4809 "<div class=\"readme\">\n";
4810 insert_file("$projectroot/$project/README.html");
4811 print "\n</div>\n"; # class="readme"
4814 # we need to request one more than 16 (0..15) to check if
4815 # those 16 are all
4816 my @commitlist = $head ? parse_commits($head, 17) : ();
4817 if (@commitlist) {
4818 git_print_header_div('shortlog');
4819 git_shortlog_body(\@commitlist, 0, 15, $refs,
4820 $#commitlist <= 15 ? undef :
4821 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4824 if (@taglist) {
4825 git_print_header_div('tags');
4826 git_tags_body(\@taglist, 0, 15,
4827 $#taglist <= 15 ? undef :
4828 $cgi->a({-href => href(action=>"tags")}, "..."));
4831 if (@headlist) {
4832 git_print_header_div('heads');
4833 git_heads_body(\@headlist, $head, 0, 15,
4834 $#headlist <= 15 ? undef :
4835 $cgi->a({-href => href(action=>"heads")}, "..."));
4838 if (@forklist) {
4839 git_print_header_div('forks');
4840 git_project_list_body(\@forklist, 'age', 0, 15,
4841 $#forklist <= 15 ? undef :
4842 $cgi->a({-href => href(action=>"forks")}, "..."),
4843 'no_header', 'forks');
4846 git_footer_html();
4849 sub git_tag {
4850 my $head = git_get_head_hash($project);
4851 git_header_html();
4852 git_print_page_nav('','', $head,undef,$head);
4853 my %tag = parse_tag($hash);
4855 if (! %tag) {
4856 die_error(404, "Unknown tag object");
4859 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4860 print "<div class=\"title_text\">\n" .
4861 "<table class=\"object_header\">\n" .
4862 "<tr>\n" .
4863 "<td>object</td>\n" .
4864 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4865 $tag{'object'}) . "</td>\n" .
4866 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4867 $tag{'type'}) . "</td>\n" .
4868 "</tr>\n";
4869 if (defined($tag{'author'})) {
4870 git_print_authorship_rows(\%tag, 'author');
4872 print "</table>\n\n" .
4873 "</div>\n";
4874 print "<div class=\"page_body\">";
4875 my $comment = $tag{'comment'};
4876 foreach my $line (@$comment) {
4877 chomp $line;
4878 print esc_html($line, -nbsp=>1) . "<br/>\n";
4880 print "</div>\n";
4881 git_footer_html();
4884 sub git_blame {
4885 # permissions
4886 gitweb_check_feature('blame')
4887 or die_error(403, "Blame view not allowed");
4889 # error checking
4890 die_error(400, "No file name given") unless $file_name;
4891 $hash_base ||= git_get_head_hash($project);
4892 die_error(404, "Couldn't find base commit") unless $hash_base;
4893 my %co = parse_commit($hash_base)
4894 or die_error(404, "Commit not found");
4895 my $ftype = "blob";
4896 if (!defined $hash) {
4897 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4898 or die_error(404, "Error looking up file");
4899 } else {
4900 $ftype = git_get_type($hash);
4901 if ($ftype !~ "blob") {
4902 die_error(400, "Object is not a blob");
4906 # run git-blame --porcelain
4907 open my $fd, "-|", git_cmd(), "blame", '-p',
4908 $hash_base, '--', $file_name
4909 or die_error(500, "Open git-blame failed");
4911 # page header
4912 git_header_html();
4913 my $formats_nav =
4914 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4915 "blob") .
4916 " | " .
4917 $cgi->a({-href => href(action=>"history", -replay=>1)},
4918 "history") .
4919 " | " .
4920 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4921 "HEAD");
4922 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4923 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4924 git_print_page_path($file_name, $ftype, $hash_base);
4926 # page body
4927 my @rev_color = qw(light dark);
4928 my $num_colors = scalar(@rev_color);
4929 my $current_color = 0;
4930 my %metainfo = ();
4932 print <<HTML;
4933 <div class="page_body">
4934 <table class="blame">
4935 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4936 HTML
4937 LINE:
4938 while (my $line = <$fd>) {
4939 chomp $line;
4940 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4941 # no <lines in group> for subsequent lines in group of lines
4942 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4943 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
4944 if (!exists $metainfo{$full_rev}) {
4945 $metainfo{$full_rev} = { 'nprevious' => 0 };
4947 my $meta = $metainfo{$full_rev};
4948 my $data;
4949 while ($data = <$fd>) {
4950 chomp $data;
4951 last if ($data =~ s/^\t//); # contents of line
4952 if ($data =~ /^(\S+)(?: (.*))?$/) {
4953 $meta->{$1} = $2 unless exists $meta->{$1};
4955 if ($data =~ /^previous /) {
4956 $meta->{'nprevious'}++;
4959 my $short_rev = substr($full_rev, 0, 8);
4960 my $author = $meta->{'author'};
4961 my %date =
4962 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
4963 my $date = $date{'iso-tz'};
4964 if ($group_size) {
4965 $current_color = ($current_color + 1) % $num_colors;
4967 my $tr_class = $rev_color[$current_color];
4968 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
4969 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
4970 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
4971 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
4972 if ($group_size) {
4973 print "<td class=\"sha1\"";
4974 print " title=\"". esc_html($author) . ", $date\"";
4975 print " rowspan=\"$group_size\"" if ($group_size > 1);
4976 print ">";
4977 print $cgi->a({-href => href(action=>"commit",
4978 hash=>$full_rev,
4979 file_name=>$file_name)},
4980 esc_html($short_rev));
4981 if ($group_size >= 2) {
4982 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
4983 if (@author_initials) {
4984 print "<br />" .
4985 esc_html(join('', @author_initials));
4986 # or join('.', ...)
4989 print "</td>\n";
4991 # 'previous' <sha1 of parent commit> <filename at commit>
4992 if (exists $meta->{'previous'} &&
4993 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
4994 $meta->{'parent'} = $1;
4995 $meta->{'file_parent'} = unquote($2);
4997 my $linenr_commit =
4998 exists($meta->{'parent'}) ?
4999 $meta->{'parent'} : $full_rev;
5000 my $linenr_filename =
5001 exists($meta->{'file_parent'}) ?
5002 $meta->{'file_parent'} : unquote($meta->{'filename'});
5003 my $blamed = href(action => 'blame',
5004 file_name => $linenr_filename,
5005 hash_base => $linenr_commit);
5006 print "<td class=\"linenr\">";
5007 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5008 -class => "linenr" },
5009 esc_html($lineno));
5010 print "</td>";
5011 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5012 print "</tr>\n";
5014 print "</table>\n";
5015 print "</div>";
5016 close $fd
5017 or print "Reading blob failed\n";
5019 # page footer
5020 git_footer_html();
5023 sub git_tags {
5024 my $head = git_get_head_hash($project);
5025 git_header_html();
5026 git_print_page_nav('','', $head,undef,$head);
5027 git_print_header_div('summary', $project);
5029 my @tagslist = git_get_tags_list();
5030 if (@tagslist) {
5031 git_tags_body(\@tagslist);
5033 git_footer_html();
5036 sub git_heads {
5037 my $head = git_get_head_hash($project);
5038 git_header_html();
5039 git_print_page_nav('','', $head,undef,$head);
5040 git_print_header_div('summary', $project);
5042 my @headslist = git_get_heads_list();
5043 if (@headslist) {
5044 git_heads_body(\@headslist, $head);
5046 git_footer_html();
5049 sub git_blob_plain {
5050 my $type = shift;
5051 my $expires;
5053 if (!defined $hash) {
5054 if (defined $file_name) {
5055 my $base = $hash_base || git_get_head_hash($project);
5056 $hash = git_get_hash_by_path($base, $file_name, "blob")
5057 or die_error(404, "Cannot find file");
5058 } else {
5059 die_error(400, "No file name defined");
5061 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5062 # blobs defined by non-textual hash id's can be cached
5063 $expires = "+1d";
5066 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5067 or die_error(500, "Open git-cat-file blob '$hash' failed");
5069 # content-type (can include charset)
5070 $type = blob_contenttype($fd, $file_name, $type);
5072 # "save as" filename, even when no $file_name is given
5073 my $save_as = "$hash";
5074 if (defined $file_name) {
5075 $save_as = $file_name;
5076 } elsif ($type =~ m/^text\//) {
5077 $save_as .= '.txt';
5080 # With XSS prevention on, blobs of all types except a few known safe
5081 # ones are served with "Content-Disposition: attachment" to make sure
5082 # they don't run in our security domain. For certain image types,
5083 # blob view writes an <img> tag referring to blob_plain view, and we
5084 # want to be sure not to break that by serving the image as an
5085 # attachment (though Firefox 3 doesn't seem to care).
5086 my $sandbox = $prevent_xss &&
5087 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5089 print $cgi->header(
5090 -type => $type,
5091 -expires => $expires,
5092 -content_disposition =>
5093 ($sandbox ? 'attachment' : 'inline')
5094 . '; filename="' . $save_as . '"');
5095 local $/ = undef;
5096 binmode STDOUT, ':raw';
5097 print <$fd>;
5098 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5099 close $fd;
5102 sub git_blob {
5103 my $expires;
5105 if (!defined $hash) {
5106 if (defined $file_name) {
5107 my $base = $hash_base || git_get_head_hash($project);
5108 $hash = git_get_hash_by_path($base, $file_name, "blob")
5109 or die_error(404, "Cannot find file");
5110 } else {
5111 die_error(400, "No file name defined");
5113 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5114 # blobs defined by non-textual hash id's can be cached
5115 $expires = "+1d";
5118 my $have_blame = gitweb_check_feature('blame');
5119 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5120 or die_error(500, "Couldn't cat $file_name, $hash");
5121 my $mimetype = blob_mimetype($fd, $file_name);
5122 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5123 close $fd;
5124 return git_blob_plain($mimetype);
5126 # we can have blame only for text/* mimetype
5127 $have_blame &&= ($mimetype =~ m!^text/!);
5129 git_header_html(undef, $expires);
5130 my $formats_nav = '';
5131 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5132 if (defined $file_name) {
5133 if ($have_blame) {
5134 $formats_nav .=
5135 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5136 "blame") .
5137 " | ";
5139 $formats_nav .=
5140 $cgi->a({-href => href(action=>"history", -replay=>1)},
5141 "history") .
5142 " | " .
5143 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5144 "raw") .
5145 " | " .
5146 $cgi->a({-href => href(action=>"blob",
5147 hash_base=>"HEAD", file_name=>$file_name)},
5148 "HEAD");
5149 } else {
5150 $formats_nav .=
5151 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5152 "raw");
5154 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5155 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5156 } else {
5157 print "<div class=\"page_nav\">\n" .
5158 "<br/><br/></div>\n" .
5159 "<div class=\"title\">$hash</div>\n";
5161 git_print_page_path($file_name, "blob", $hash_base);
5162 print "<div class=\"page_body\">\n";
5163 if ($mimetype =~ m!^image/!) {
5164 print qq!<img type="$mimetype"!;
5165 if ($file_name) {
5166 print qq! alt="$file_name" title="$file_name"!;
5168 print qq! src="! .
5169 href(action=>"blob_plain", hash=>$hash,
5170 hash_base=>$hash_base, file_name=>$file_name) .
5171 qq!" />\n!;
5172 } else {
5173 my $nr;
5174 while (my $line = <$fd>) {
5175 chomp $line;
5176 $nr++;
5177 $line = untabify($line);
5178 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5179 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5182 close $fd
5183 or print "Reading blob failed.\n";
5184 print "</div>";
5185 git_footer_html();
5188 sub git_tree {
5189 if (!defined $hash_base) {
5190 $hash_base = "HEAD";
5192 if (!defined $hash) {
5193 if (defined $file_name) {
5194 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5195 } else {
5196 $hash = $hash_base;
5199 die_error(404, "No such tree") unless defined($hash);
5201 my $show_sizes = gitweb_check_feature('show-sizes');
5202 my $have_blame = gitweb_check_feature('blame');
5204 my @entries = ();
5206 local $/ = "\0";
5207 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5208 ($show_sizes ? '-l' : ()), @extra_options, $hash
5209 or die_error(500, "Open git-ls-tree failed");
5210 @entries = map { chomp; $_ } <$fd>;
5211 close $fd
5212 or die_error(404, "Reading tree failed");
5215 my $refs = git_get_references();
5216 my $ref = format_ref_marker($refs, $hash_base);
5217 git_header_html();
5218 my $basedir = '';
5219 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5220 my @views_nav = ();
5221 if (defined $file_name) {
5222 push @views_nav,
5223 $cgi->a({-href => href(action=>"history", -replay=>1)},
5224 "history"),
5225 $cgi->a({-href => href(action=>"tree",
5226 hash_base=>"HEAD", file_name=>$file_name)},
5227 "HEAD"),
5229 my $snapshot_links = format_snapshot_links($hash);
5230 if (defined $snapshot_links) {
5231 # FIXME: Should be available when we have no hash base as well.
5232 push @views_nav, $snapshot_links;
5234 git_print_page_nav('tree','', $hash_base, undef, undef,
5235 join(' | ', @views_nav));
5236 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5237 } else {
5238 undef $hash_base;
5239 print "<div class=\"page_nav\">\n";
5240 print "<br/><br/></div>\n";
5241 print "<div class=\"title\">$hash</div>\n";
5243 if (defined $file_name) {
5244 $basedir = $file_name;
5245 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5246 $basedir .= '/';
5248 git_print_page_path($file_name, 'tree', $hash_base);
5250 print "<div class=\"page_body\">\n";
5251 print "<table class=\"tree\">\n";
5252 my $alternate = 1;
5253 # '..' (top directory) link if possible
5254 if (defined $hash_base &&
5255 defined $file_name && $file_name =~ m![^/]+$!) {
5256 if ($alternate) {
5257 print "<tr class=\"dark\">\n";
5258 } else {
5259 print "<tr class=\"light\">\n";
5261 $alternate ^= 1;
5263 my $up = $file_name;
5264 $up =~ s!/?[^/]+$!!;
5265 undef $up unless $up;
5266 # based on git_print_tree_entry
5267 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5268 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5269 print '<td class="list">';
5270 print $cgi->a({-href => href(action=>"tree",
5271 hash_base=>$hash_base,
5272 file_name=>$up)},
5273 "..");
5274 print "</td>\n";
5275 print "<td class=\"link\"></td>\n";
5277 print "</tr>\n";
5279 foreach my $line (@entries) {
5280 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5282 if ($alternate) {
5283 print "<tr class=\"dark\">\n";
5284 } else {
5285 print "<tr class=\"light\">\n";
5287 $alternate ^= 1;
5289 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5291 print "</tr>\n";
5293 print "</table>\n" .
5294 "</div>";
5295 git_footer_html();
5298 sub git_snapshot {
5299 my $format = $input_params{'snapshot_format'};
5300 if (!@snapshot_fmts) {
5301 die_error(403, "Snapshots not allowed");
5303 # default to first supported snapshot format
5304 $format ||= $snapshot_fmts[0];
5305 if ($format !~ m/^[a-z0-9]+$/) {
5306 die_error(400, "Invalid snapshot format parameter");
5307 } elsif (!exists($known_snapshot_formats{$format})) {
5308 die_error(400, "Unknown snapshot format");
5309 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5310 die_error(403, "Snapshot format not allowed");
5311 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5312 die_error(403, "Unsupported snapshot format");
5315 if (!defined $hash) {
5316 $hash = git_get_head_hash($project);
5319 my $name = $project;
5320 $name =~ s,([^/])/*\.git$,$1,;
5321 $name = basename($name);
5322 my $filename = to_utf8($name);
5323 $name =~ s/\047/\047\\\047\047/g;
5324 my $cmd;
5325 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5326 $cmd = quote_command(
5327 git_cmd(), 'archive',
5328 "--format=$known_snapshot_formats{$format}{'format'}",
5329 "--prefix=$name/", $hash);
5330 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5331 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5334 print $cgi->header(
5335 -type => $known_snapshot_formats{$format}{'type'},
5336 -content_disposition => 'inline; filename="' . "$filename" . '"',
5337 -status => '200 OK');
5339 open my $fd, "-|", $cmd
5340 or die_error(500, "Execute git-archive failed");
5341 binmode STDOUT, ':raw';
5342 print <$fd>;
5343 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5344 close $fd;
5347 sub git_log {
5348 my $head = git_get_head_hash($project);
5349 if (!defined $hash) {
5350 $hash = $head;
5352 if (!defined $page) {
5353 $page = 0;
5355 my $refs = git_get_references();
5357 my @commitlist = parse_commits($hash, 101, (100 * $page));
5359 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
5361 my ($patch_max) = gitweb_get_feature('patches');
5362 if ($patch_max) {
5363 if ($patch_max < 0 || @commitlist <= $patch_max) {
5364 $paging_nav .= " &sdot; " .
5365 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5366 "patches");
5370 git_header_html();
5371 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5373 if (!@commitlist) {
5374 my %co = parse_commit($hash);
5376 git_print_header_div('summary', $project);
5377 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5379 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5380 for (my $i = 0; $i <= $to; $i++) {
5381 my %co = %{$commitlist[$i]};
5382 next if !%co;
5383 my $commit = $co{'id'};
5384 my $ref = format_ref_marker($refs, $commit);
5385 my %ad = parse_date($co{'author_epoch'});
5386 git_print_header_div('commit',
5387 "<span class=\"age\">$co{'age_string'}</span>" .
5388 esc_html($co{'title'}) . $ref,
5389 $commit);
5390 print "<div class=\"title_text\">\n" .
5391 "<div class=\"log_link\">\n" .
5392 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5393 " | " .
5394 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5395 " | " .
5396 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5397 "<br/>\n" .
5398 "</div>\n";
5399 git_print_authorship(\%co, -tag => 'span');
5400 print "<br/>\n</div>\n";
5402 print "<div class=\"log_body\">\n";
5403 git_print_log($co{'comment'}, -final_empty_line=> 1);
5404 print "</div>\n";
5406 if ($#commitlist >= 100) {
5407 print "<div class=\"page_nav\">\n";
5408 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5409 -accesskey => "n", -title => "Alt-n"}, "next");
5410 print "</div>\n";
5412 git_footer_html();
5415 sub git_commit {
5416 $hash ||= $hash_base || "HEAD";
5417 my %co = parse_commit($hash)
5418 or die_error(404, "Unknown commit object");
5420 my $parent = $co{'parent'};
5421 my $parents = $co{'parents'}; # listref
5423 # we need to prepare $formats_nav before any parameter munging
5424 my $formats_nav;
5425 if (!defined $parent) {
5426 # --root commitdiff
5427 $formats_nav .= '(initial)';
5428 } elsif (@$parents == 1) {
5429 # single parent commit
5430 $formats_nav .=
5431 '(parent: ' .
5432 $cgi->a({-href => href(action=>"commit",
5433 hash=>$parent)},
5434 esc_html(substr($parent, 0, 7))) .
5435 ')';
5436 } else {
5437 # merge commit
5438 $formats_nav .=
5439 '(merge: ' .
5440 join(' ', map {
5441 $cgi->a({-href => href(action=>"commit",
5442 hash=>$_)},
5443 esc_html(substr($_, 0, 7)));
5444 } @$parents ) .
5445 ')';
5447 if (gitweb_check_feature('patches') && @$parents <= 1) {
5448 $formats_nav .= " | " .
5449 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5450 "patch");
5453 if (!defined $parent) {
5454 $parent = "--root";
5456 my @difftree;
5457 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5458 @diff_opts,
5459 (@$parents <= 1 ? $parent : '-c'),
5460 $hash, "--"
5461 or die_error(500, "Open git-diff-tree failed");
5462 @difftree = map { chomp; $_ } <$fd>;
5463 close $fd or die_error(404, "Reading git-diff-tree failed");
5465 # non-textual hash id's can be cached
5466 my $expires;
5467 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5468 $expires = "+1d";
5470 my $refs = git_get_references();
5471 my $ref = format_ref_marker($refs, $co{'id'});
5473 git_header_html(undef, $expires);
5474 git_print_page_nav('commit', '',
5475 $hash, $co{'tree'}, $hash,
5476 $formats_nav);
5478 if (defined $co{'parent'}) {
5479 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5480 } else {
5481 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5483 print "<div class=\"title_text\">\n" .
5484 "<table class=\"object_header\">\n";
5485 git_print_authorship_rows(\%co);
5486 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5487 print "<tr>" .
5488 "<td>tree</td>" .
5489 "<td class=\"sha1\">" .
5490 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5491 class => "list"}, $co{'tree'}) .
5492 "</td>" .
5493 "<td class=\"link\">" .
5494 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5495 "tree");
5496 my $snapshot_links = format_snapshot_links($hash);
5497 if (defined $snapshot_links) {
5498 print " | " . $snapshot_links;
5500 print "</td>" .
5501 "</tr>\n";
5503 foreach my $par (@$parents) {
5504 print "<tr>" .
5505 "<td>parent</td>" .
5506 "<td class=\"sha1\">" .
5507 $cgi->a({-href => href(action=>"commit", hash=>$par),
5508 class => "list"}, $par) .
5509 "</td>" .
5510 "<td class=\"link\">" .
5511 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5512 " | " .
5513 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5514 "</td>" .
5515 "</tr>\n";
5517 print "</table>".
5518 "</div>\n";
5520 print "<div class=\"page_body\">\n";
5521 git_print_log($co{'comment'});
5522 print "</div>\n";
5524 git_difftree_body(\@difftree, $hash, @$parents);
5526 git_footer_html();
5529 sub git_object {
5530 # object is defined by:
5531 # - hash or hash_base alone
5532 # - hash_base and file_name
5533 my $type;
5535 # - hash or hash_base alone
5536 if ($hash || ($hash_base && !defined $file_name)) {
5537 my $object_id = $hash || $hash_base;
5539 open my $fd, "-|", quote_command(
5540 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5541 or die_error(404, "Object does not exist");
5542 $type = <$fd>;
5543 chomp $type;
5544 close $fd
5545 or die_error(404, "Object does not exist");
5547 # - hash_base and file_name
5548 } elsif ($hash_base && defined $file_name) {
5549 $file_name =~ s,/+$,,;
5551 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5552 or die_error(404, "Base object does not exist");
5554 # here errors should not hapen
5555 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5556 or die_error(500, "Open git-ls-tree failed");
5557 my $line = <$fd>;
5558 close $fd;
5560 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5561 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5562 die_error(404, "File or directory for given base does not exist");
5564 $type = $2;
5565 $hash = $3;
5566 } else {
5567 die_error(400, "Not enough information to find object");
5570 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5571 hash=>$hash, hash_base=>$hash_base,
5572 file_name=>$file_name),
5573 -status => '302 Found');
5576 sub git_blobdiff {
5577 my $format = shift || 'html';
5579 my $fd;
5580 my @difftree;
5581 my %diffinfo;
5582 my $expires;
5584 # preparing $fd and %diffinfo for git_patchset_body
5585 # new style URI
5586 if (defined $hash_base && defined $hash_parent_base) {
5587 if (defined $file_name) {
5588 # read raw output
5589 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5590 $hash_parent_base, $hash_base,
5591 "--", (defined $file_parent ? $file_parent : ()), $file_name
5592 or die_error(500, "Open git-diff-tree failed");
5593 @difftree = map { chomp; $_ } <$fd>;
5594 close $fd
5595 or die_error(404, "Reading git-diff-tree failed");
5596 @difftree
5597 or die_error(404, "Blob diff not found");
5599 } elsif (defined $hash &&
5600 $hash =~ /[0-9a-fA-F]{40}/) {
5601 # try to find filename from $hash
5603 # read filtered raw output
5604 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5605 $hash_parent_base, $hash_base, "--"
5606 or die_error(500, "Open git-diff-tree failed");
5607 @difftree =
5608 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5609 # $hash == to_id
5610 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5611 map { chomp; $_ } <$fd>;
5612 close $fd
5613 or die_error(404, "Reading git-diff-tree failed");
5614 @difftree
5615 or die_error(404, "Blob diff not found");
5617 } else {
5618 die_error(400, "Missing one of the blob diff parameters");
5621 if (@difftree > 1) {
5622 die_error(400, "Ambiguous blob diff specification");
5625 %diffinfo = parse_difftree_raw_line($difftree[0]);
5626 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5627 $file_name ||= $diffinfo{'to_file'};
5629 $hash_parent ||= $diffinfo{'from_id'};
5630 $hash ||= $diffinfo{'to_id'};
5632 # non-textual hash id's can be cached
5633 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5634 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5635 $expires = '+1d';
5638 # open patch output
5639 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5640 '-p', ($format eq 'html' ? "--full-index" : ()),
5641 $hash_parent_base, $hash_base,
5642 "--", (defined $file_parent ? $file_parent : ()), $file_name
5643 or die_error(500, "Open git-diff-tree failed");
5646 # old/legacy style URI -- not generated anymore since 1.4.3.
5647 if (!%diffinfo) {
5648 die_error('404 Not Found', "Missing one of the blob diff parameters")
5651 # header
5652 if ($format eq 'html') {
5653 my $formats_nav =
5654 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5655 "raw");
5656 git_header_html(undef, $expires);
5657 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5658 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5659 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5660 } else {
5661 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5662 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5664 if (defined $file_name) {
5665 git_print_page_path($file_name, "blob", $hash_base);
5666 } else {
5667 print "<div class=\"page_path\"></div>\n";
5670 } elsif ($format eq 'plain') {
5671 print $cgi->header(
5672 -type => 'text/plain',
5673 -charset => 'utf-8',
5674 -expires => $expires,
5675 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5677 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5679 } else {
5680 die_error(400, "Unknown blobdiff format");
5683 # patch
5684 if ($format eq 'html') {
5685 print "<div class=\"page_body\">\n";
5687 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5688 close $fd;
5690 print "</div>\n"; # class="page_body"
5691 git_footer_html();
5693 } else {
5694 while (my $line = <$fd>) {
5695 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5696 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5698 print $line;
5700 last if $line =~ m!^\+\+\+!;
5702 local $/ = undef;
5703 print <$fd>;
5704 close $fd;
5708 sub git_blobdiff_plain {
5709 git_blobdiff('plain');
5712 sub git_commitdiff {
5713 my %params = @_;
5714 my $format = $params{-format} || 'html';
5716 my ($patch_max) = gitweb_get_feature('patches');
5717 if ($format eq 'patch') {
5718 die_error(403, "Patch view not allowed") unless $patch_max;
5721 $hash ||= $hash_base || "HEAD";
5722 my %co = parse_commit($hash)
5723 or die_error(404, "Unknown commit object");
5725 # choose format for commitdiff for merge
5726 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5727 $hash_parent = '--cc';
5729 # we need to prepare $formats_nav before almost any parameter munging
5730 my $formats_nav;
5731 if ($format eq 'html') {
5732 $formats_nav =
5733 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5734 "raw");
5735 if ($patch_max && @{$co{'parents'}} <= 1) {
5736 $formats_nav .= " | " .
5737 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5738 "patch");
5741 if (defined $hash_parent &&
5742 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5743 # commitdiff with two commits given
5744 my $hash_parent_short = $hash_parent;
5745 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5746 $hash_parent_short = substr($hash_parent, 0, 7);
5748 $formats_nav .=
5749 ' (from';
5750 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5751 if ($co{'parents'}[$i] eq $hash_parent) {
5752 $formats_nav .= ' parent ' . ($i+1);
5753 last;
5756 $formats_nav .= ': ' .
5757 $cgi->a({-href => href(action=>"commitdiff",
5758 hash=>$hash_parent)},
5759 esc_html($hash_parent_short)) .
5760 ')';
5761 } elsif (!$co{'parent'}) {
5762 # --root commitdiff
5763 $formats_nav .= ' (initial)';
5764 } elsif (scalar @{$co{'parents'}} == 1) {
5765 # single parent commit
5766 $formats_nav .=
5767 ' (parent: ' .
5768 $cgi->a({-href => href(action=>"commitdiff",
5769 hash=>$co{'parent'})},
5770 esc_html(substr($co{'parent'}, 0, 7))) .
5771 ')';
5772 } else {
5773 # merge commit
5774 if ($hash_parent eq '--cc') {
5775 $formats_nav .= ' | ' .
5776 $cgi->a({-href => href(action=>"commitdiff",
5777 hash=>$hash, hash_parent=>'-c')},
5778 'combined');
5779 } else { # $hash_parent eq '-c'
5780 $formats_nav .= ' | ' .
5781 $cgi->a({-href => href(action=>"commitdiff",
5782 hash=>$hash, hash_parent=>'--cc')},
5783 'compact');
5785 $formats_nav .=
5786 ' (merge: ' .
5787 join(' ', map {
5788 $cgi->a({-href => href(action=>"commitdiff",
5789 hash=>$_)},
5790 esc_html(substr($_, 0, 7)));
5791 } @{$co{'parents'}} ) .
5792 ')';
5796 my $hash_parent_param = $hash_parent;
5797 if (!defined $hash_parent_param) {
5798 # --cc for multiple parents, --root for parentless
5799 $hash_parent_param =
5800 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5803 # read commitdiff
5804 my $fd;
5805 my @difftree;
5806 if ($format eq 'html') {
5807 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5808 "--no-commit-id", "--patch-with-raw", "--full-index",
5809 $hash_parent_param, $hash, "--"
5810 or die_error(500, "Open git-diff-tree failed");
5812 while (my $line = <$fd>) {
5813 chomp $line;
5814 # empty line ends raw part of diff-tree output
5815 last unless $line;
5816 push @difftree, scalar parse_difftree_raw_line($line);
5819 } elsif ($format eq 'plain') {
5820 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5821 '-p', $hash_parent_param, $hash, "--"
5822 or die_error(500, "Open git-diff-tree failed");
5823 } elsif ($format eq 'patch') {
5824 # For commit ranges, we limit the output to the number of
5825 # patches specified in the 'patches' feature.
5826 # For single commits, we limit the output to a single patch,
5827 # diverging from the git-format-patch default.
5828 my @commit_spec = ();
5829 if ($hash_parent) {
5830 if ($patch_max > 0) {
5831 push @commit_spec, "-$patch_max";
5833 push @commit_spec, '-n', "$hash_parent..$hash";
5834 } else {
5835 if ($params{-single}) {
5836 push @commit_spec, '-1';
5837 } else {
5838 if ($patch_max > 0) {
5839 push @commit_spec, "-$patch_max";
5841 push @commit_spec, "-n";
5843 push @commit_spec, '--root', $hash;
5845 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5846 '--stdout', @commit_spec
5847 or die_error(500, "Open git-format-patch failed");
5848 } else {
5849 die_error(400, "Unknown commitdiff format");
5852 # non-textual hash id's can be cached
5853 my $expires;
5854 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5855 $expires = "+1d";
5858 # write commit message
5859 if ($format eq 'html') {
5860 my $refs = git_get_references();
5861 my $ref = format_ref_marker($refs, $co{'id'});
5863 git_header_html(undef, $expires);
5864 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5865 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5866 print "<div class=\"title_text\">\n" .
5867 "<table class=\"object_header\">\n";
5868 git_print_authorship_rows(\%co);
5869 print "</table>".
5870 "</div>\n";
5871 print "<div class=\"page_body\">\n";
5872 if (@{$co{'comment'}} > 1) {
5873 print "<div class=\"log\">\n";
5874 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5875 print "</div>\n"; # class="log"
5878 } elsif ($format eq 'plain') {
5879 my $refs = git_get_references("tags");
5880 my $tagname = git_get_rev_name_tags($hash);
5881 my $filename = basename($project) . "-$hash.patch";
5883 print $cgi->header(
5884 -type => 'text/plain',
5885 -charset => 'utf-8',
5886 -expires => $expires,
5887 -content_disposition => 'inline; filename="' . "$filename" . '"');
5888 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5889 print "From: " . to_utf8($co{'author'}) . "\n";
5890 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5891 print "Subject: " . to_utf8($co{'title'}) . "\n";
5893 print "X-Git-Tag: $tagname\n" if $tagname;
5894 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5896 foreach my $line (@{$co{'comment'}}) {
5897 print to_utf8($line) . "\n";
5899 print "---\n\n";
5900 } elsif ($format eq 'patch') {
5901 my $filename = basename($project) . "-$hash.patch";
5903 print $cgi->header(
5904 -type => 'text/plain',
5905 -charset => 'utf-8',
5906 -expires => $expires,
5907 -content_disposition => 'inline; filename="' . "$filename" . '"');
5910 # write patch
5911 if ($format eq 'html') {
5912 my $use_parents = !defined $hash_parent ||
5913 $hash_parent eq '-c' || $hash_parent eq '--cc';
5914 git_difftree_body(\@difftree, $hash,
5915 $use_parents ? @{$co{'parents'}} : $hash_parent);
5916 print "<br/>\n";
5918 git_patchset_body($fd, \@difftree, $hash,
5919 $use_parents ? @{$co{'parents'}} : $hash_parent);
5920 close $fd;
5921 print "</div>\n"; # class="page_body"
5922 git_footer_html();
5924 } elsif ($format eq 'plain') {
5925 local $/ = undef;
5926 print <$fd>;
5927 close $fd
5928 or print "Reading git-diff-tree failed\n";
5929 } elsif ($format eq 'patch') {
5930 local $/ = undef;
5931 print <$fd>;
5932 close $fd
5933 or print "Reading git-format-patch failed\n";
5937 sub git_commitdiff_plain {
5938 git_commitdiff(-format => 'plain');
5941 # format-patch-style patches
5942 sub git_patch {
5943 git_commitdiff(-format => 'patch', -single => 1);
5946 sub git_patches {
5947 git_commitdiff(-format => 'patch');
5950 sub git_history {
5951 if (!defined $hash_base) {
5952 $hash_base = git_get_head_hash($project);
5954 if (!defined $page) {
5955 $page = 0;
5957 my $ftype;
5958 my %co = parse_commit($hash_base)
5959 or die_error(404, "Unknown commit object");
5961 my $refs = git_get_references();
5962 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5964 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5965 $file_name, "--full-history")
5966 or die_error(404, "No such file or directory on given branch");
5968 if (!defined $hash && defined $file_name) {
5969 # some commits could have deleted file in question,
5970 # and not have it in tree, but one of them has to have it
5971 for (my $i = 0; $i <= @commitlist; $i++) {
5972 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5973 last if defined $hash;
5976 if (defined $hash) {
5977 $ftype = git_get_type($hash);
5979 if (!defined $ftype) {
5980 die_error(500, "Unknown type of object");
5983 my $paging_nav = '';
5984 if ($page > 0) {
5985 $paging_nav .=
5986 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5987 file_name=>$file_name)},
5988 "first");
5989 $paging_nav .= " &sdot; " .
5990 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5991 -accesskey => "p", -title => "Alt-p"}, "prev");
5992 } else {
5993 $paging_nav .= "first";
5994 $paging_nav .= " &sdot; prev";
5996 my $next_link = '';
5997 if ($#commitlist >= 100) {
5998 $next_link =
5999 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6000 -accesskey => "n", -title => "Alt-n"}, "next");
6001 $paging_nav .= " &sdot; $next_link";
6002 } else {
6003 $paging_nav .= " &sdot; next";
6006 git_header_html();
6007 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
6008 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6009 git_print_page_path($file_name, $ftype, $hash_base);
6011 git_history_body(\@commitlist, 0, 99,
6012 $refs, $hash_base, $ftype, $next_link);
6014 git_footer_html();
6017 sub git_search {
6018 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6019 if (!defined $searchtext) {
6020 die_error(400, "Text field is empty");
6022 if (!defined $hash) {
6023 $hash = git_get_head_hash($project);
6025 my %co = parse_commit($hash);
6026 if (!%co) {
6027 die_error(404, "Unknown commit object");
6029 if (!defined $page) {
6030 $page = 0;
6033 $searchtype ||= 'commit';
6034 if ($searchtype eq 'pickaxe') {
6035 # pickaxe may take all resources of your box and run for several minutes
6036 # with every query - so decide by yourself how public you make this feature
6037 gitweb_check_feature('pickaxe')
6038 or die_error(403, "Pickaxe is disabled");
6040 if ($searchtype eq 'grep') {
6041 gitweb_check_feature('grep')
6042 or die_error(403, "Grep is disabled");
6045 git_header_html();
6047 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6048 my $greptype;
6049 if ($searchtype eq 'commit') {
6050 $greptype = "--grep=";
6051 } elsif ($searchtype eq 'author') {
6052 $greptype = "--author=";
6053 } elsif ($searchtype eq 'committer') {
6054 $greptype = "--committer=";
6056 $greptype .= $searchtext;
6057 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6058 $greptype, '--regexp-ignore-case',
6059 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6061 my $paging_nav = '';
6062 if ($page > 0) {
6063 $paging_nav .=
6064 $cgi->a({-href => href(action=>"search", hash=>$hash,
6065 searchtext=>$searchtext,
6066 searchtype=>$searchtype)},
6067 "first");
6068 $paging_nav .= " &sdot; " .
6069 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6070 -accesskey => "p", -title => "Alt-p"}, "prev");
6071 } else {
6072 $paging_nav .= "first";
6073 $paging_nav .= " &sdot; prev";
6075 my $next_link = '';
6076 if ($#commitlist >= 100) {
6077 $next_link =
6078 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6079 -accesskey => "n", -title => "Alt-n"}, "next");
6080 $paging_nav .= " &sdot; $next_link";
6081 } else {
6082 $paging_nav .= " &sdot; next";
6085 if ($#commitlist >= 100) {
6088 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6089 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6090 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6093 if ($searchtype eq 'pickaxe') {
6094 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6095 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6097 print "<table class=\"pickaxe search\">\n";
6098 my $alternate = 1;
6099 local $/ = "\n";
6100 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6101 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6102 ($search_use_regexp ? '--pickaxe-regex' : ());
6103 undef %co;
6104 my @files;
6105 while (my $line = <$fd>) {
6106 chomp $line;
6107 next unless $line;
6109 my %set = parse_difftree_raw_line($line);
6110 if (defined $set{'commit'}) {
6111 # finish previous commit
6112 if (%co) {
6113 print "</td>\n" .
6114 "<td class=\"link\">" .
6115 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6116 " | " .
6117 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6118 print "</td>\n" .
6119 "</tr>\n";
6122 if ($alternate) {
6123 print "<tr class=\"dark\">\n";
6124 } else {
6125 print "<tr class=\"light\">\n";
6127 $alternate ^= 1;
6128 %co = parse_commit($set{'commit'});
6129 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6130 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6131 "<td><i>$author</i></td>\n" .
6132 "<td>" .
6133 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6134 -class => "list subject"},
6135 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6136 } elsif (defined $set{'to_id'}) {
6137 next if ($set{'to_id'} =~ m/^0{40}$/);
6139 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6140 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6141 -class => "list"},
6142 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6143 "<br/>\n";
6146 close $fd;
6148 # finish last commit (warning: repetition!)
6149 if (%co) {
6150 print "</td>\n" .
6151 "<td class=\"link\">" .
6152 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6153 " | " .
6154 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6155 print "</td>\n" .
6156 "</tr>\n";
6159 print "</table>\n";
6162 if ($searchtype eq 'grep') {
6163 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6164 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6166 print "<table class=\"grep_search\">\n";
6167 my $alternate = 1;
6168 my $matches = 0;
6169 local $/ = "\n";
6170 open my $fd, "-|", git_cmd(), 'grep', '-n',
6171 $search_use_regexp ? ('-E', '-i') : '-F',
6172 $searchtext, $co{'tree'};
6173 my $lastfile = '';
6174 while (my $line = <$fd>) {
6175 chomp $line;
6176 my ($file, $lno, $ltext, $binary);
6177 last if ($matches++ > 1000);
6178 if ($line =~ /^Binary file (.+) matches$/) {
6179 $file = $1;
6180 $binary = 1;
6181 } else {
6182 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6184 if ($file ne $lastfile) {
6185 $lastfile and print "</td></tr>\n";
6186 if ($alternate++) {
6187 print "<tr class=\"dark\">\n";
6188 } else {
6189 print "<tr class=\"light\">\n";
6191 print "<td class=\"list\">".
6192 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6193 file_name=>"$file"),
6194 -class => "list"}, esc_path($file));
6195 print "</td><td>\n";
6196 $lastfile = $file;
6198 if ($binary) {
6199 print "<div class=\"binary\">Binary file</div>\n";
6200 } else {
6201 $ltext = untabify($ltext);
6202 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6203 $ltext = esc_html($1, -nbsp=>1);
6204 $ltext .= '<span class="match">';
6205 $ltext .= esc_html($2, -nbsp=>1);
6206 $ltext .= '</span>';
6207 $ltext .= esc_html($3, -nbsp=>1);
6208 } else {
6209 $ltext = esc_html($ltext, -nbsp=>1);
6211 print "<div class=\"pre\">" .
6212 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6213 file_name=>"$file").'#l'.$lno,
6214 -class => "linenr"}, sprintf('%4i', $lno))
6215 . ' ' . $ltext . "</div>\n";
6218 if ($lastfile) {
6219 print "</td></tr>\n";
6220 if ($matches > 1000) {
6221 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6223 } else {
6224 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6226 close $fd;
6228 print "</table>\n";
6230 git_footer_html();
6233 sub git_search_help {
6234 git_header_html();
6235 git_print_page_nav('','', $hash,$hash,$hash);
6236 print <<EOT;
6237 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6238 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6239 the pattern entered is recognized as the POSIX extended
6240 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6241 insensitive).</p>
6242 <dl>
6243 <dt><b>commit</b></dt>
6244 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6246 my $have_grep = gitweb_check_feature('grep');
6247 if ($have_grep) {
6248 print <<EOT;
6249 <dt><b>grep</b></dt>
6250 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6251 a different one) are searched for the given pattern. On large trees, this search can take
6252 a while and put some strain on the server, so please use it with some consideration. Note that
6253 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6254 case-sensitive.</dd>
6257 print <<EOT;
6258 <dt><b>author</b></dt>
6259 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6260 <dt><b>committer</b></dt>
6261 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6263 my $have_pickaxe = gitweb_check_feature('pickaxe');
6264 if ($have_pickaxe) {
6265 print <<EOT;
6266 <dt><b>pickaxe</b></dt>
6267 <dd>All commits that caused the string to appear or disappear from any file (changes that
6268 added, removed or "modified" the string) will be listed. This search can take a while and
6269 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6270 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6273 print "</dl>\n";
6274 git_footer_html();
6277 sub git_shortlog {
6278 my $head = git_get_head_hash($project);
6279 if (!defined $hash) {
6280 $hash = $head;
6282 if (!defined $page) {
6283 $page = 0;
6285 my $refs = git_get_references();
6287 my $commit_hash = $hash;
6288 if (defined $hash_parent) {
6289 $commit_hash = "$hash_parent..$hash";
6291 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6293 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6294 my $next_link = '';
6295 if ($#commitlist >= 100) {
6296 $next_link =
6297 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6298 -accesskey => "n", -title => "Alt-n"}, "next");
6300 my $patch_max = gitweb_check_feature('patches');
6301 if ($patch_max) {
6302 if ($patch_max < 0 || @commitlist <= $patch_max) {
6303 $paging_nav .= " &sdot; " .
6304 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6305 "patches");
6309 git_header_html();
6310 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6311 git_print_header_div('summary', $project);
6313 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6315 git_footer_html();
6318 ## ......................................................................
6319 ## feeds (RSS, Atom; OPML)
6321 sub git_feed {
6322 my $format = shift || 'atom';
6323 my $have_blame = gitweb_check_feature('blame');
6325 # Atom: http://www.atomenabled.org/developers/syndication/
6326 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6327 if ($format ne 'rss' && $format ne 'atom') {
6328 die_error(400, "Unknown web feed format");
6331 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6332 my $head = $hash || 'HEAD';
6333 my @commitlist = parse_commits($head, 150, 0, $file_name);
6335 my %latest_commit;
6336 my %latest_date;
6337 my $content_type = "application/$format+xml";
6338 if (defined $cgi->http('HTTP_ACCEPT') &&
6339 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6340 # browser (feed reader) prefers text/xml
6341 $content_type = 'text/xml';
6343 if (defined($commitlist[0])) {
6344 %latest_commit = %{$commitlist[0]};
6345 my $latest_epoch = $latest_commit{'committer_epoch'};
6346 %latest_date = parse_date($latest_epoch);
6347 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6348 if (defined $if_modified) {
6349 my $since;
6350 if (eval { require HTTP::Date; 1; }) {
6351 $since = HTTP::Date::str2time($if_modified);
6352 } elsif (eval { require Time::ParseDate; 1; }) {
6353 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6355 if (defined $since && $latest_epoch <= $since) {
6356 print $cgi->header(
6357 -type => $content_type,
6358 -charset => 'utf-8',
6359 -last_modified => $latest_date{'rfc2822'},
6360 -status => '304 Not Modified');
6361 return;
6364 print $cgi->header(
6365 -type => $content_type,
6366 -charset => 'utf-8',
6367 -last_modified => $latest_date{'rfc2822'});
6368 } else {
6369 print $cgi->header(
6370 -type => $content_type,
6371 -charset => 'utf-8');
6374 # Optimization: skip generating the body if client asks only
6375 # for Last-Modified date.
6376 return if ($cgi->request_method() eq 'HEAD');
6378 # header variables
6379 my $title = "$site_name - $project/$action";
6380 my $feed_type = 'log';
6381 if (defined $hash) {
6382 $title .= " - '$hash'";
6383 $feed_type = 'branch log';
6384 if (defined $file_name) {
6385 $title .= " :: $file_name";
6386 $feed_type = 'history';
6388 } elsif (defined $file_name) {
6389 $title .= " - $file_name";
6390 $feed_type = 'history';
6392 $title .= " $feed_type";
6393 my $descr = git_get_project_description($project);
6394 if (defined $descr) {
6395 $descr = esc_html($descr);
6396 } else {
6397 $descr = "$project " .
6398 ($format eq 'rss' ? 'RSS' : 'Atom') .
6399 " feed";
6401 my $owner = git_get_project_owner($project);
6402 $owner = esc_html($owner);
6404 #header
6405 my $alt_url;
6406 if (defined $file_name) {
6407 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6408 } elsif (defined $hash) {
6409 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6410 } else {
6411 $alt_url = href(-full=>1, action=>"summary");
6413 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6414 if ($format eq 'rss') {
6415 print <<XML;
6416 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6417 <channel>
6419 print "<title>$title</title>\n" .
6420 "<link>$alt_url</link>\n" .
6421 "<description>$descr</description>\n" .
6422 "<language>en</language>\n" .
6423 # project owner is responsible for 'editorial' content
6424 "<managingEditor>$owner</managingEditor>\n";
6425 if (defined $logo || defined $favicon) {
6426 # prefer the logo to the favicon, since RSS
6427 # doesn't allow both
6428 my $img = esc_url($logo || $favicon);
6429 print "<image>\n" .
6430 "<url>$img</url>\n" .
6431 "<title>$title</title>\n" .
6432 "<link>$alt_url</link>\n" .
6433 "</image>\n";
6435 if (%latest_date) {
6436 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6437 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6439 print "<generator>gitweb v.$version/$git_version</generator>\n";
6440 } elsif ($format eq 'atom') {
6441 print <<XML;
6442 <feed xmlns="http://www.w3.org/2005/Atom">
6444 print "<title>$title</title>\n" .
6445 "<subtitle>$descr</subtitle>\n" .
6446 '<link rel="alternate" type="text/html" href="' .
6447 $alt_url . '" />' . "\n" .
6448 '<link rel="self" type="' . $content_type . '" href="' .
6449 $cgi->self_url() . '" />' . "\n" .
6450 "<id>" . href(-full=>1) . "</id>\n" .
6451 # use project owner for feed author
6452 "<author><name>$owner</name></author>\n";
6453 if (defined $favicon) {
6454 print "<icon>" . esc_url($favicon) . "</icon>\n";
6456 if (defined $logo_url) {
6457 # not twice as wide as tall: 72 x 27 pixels
6458 print "<logo>" . esc_url($logo) . "</logo>\n";
6460 if (! %latest_date) {
6461 # dummy date to keep the feed valid until commits trickle in:
6462 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6463 } else {
6464 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6466 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6469 # contents
6470 for (my $i = 0; $i <= $#commitlist; $i++) {
6471 my %co = %{$commitlist[$i]};
6472 my $commit = $co{'id'};
6473 # we read 150, we always show 30 and the ones more recent than 48 hours
6474 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6475 last;
6477 my %cd = parse_date($co{'author_epoch'});
6479 # get list of changed files
6480 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6481 $co{'parent'} || "--root",
6482 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6483 or next;
6484 my @difftree = map { chomp; $_ } <$fd>;
6485 close $fd
6486 or next;
6488 # print element (entry, item)
6489 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6490 if ($format eq 'rss') {
6491 print "<item>\n" .
6492 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6493 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6494 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6495 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6496 "<link>$co_url</link>\n" .
6497 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6498 "<content:encoded>" .
6499 "<![CDATA[\n";
6500 } elsif ($format eq 'atom') {
6501 print "<entry>\n" .
6502 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6503 "<updated>$cd{'iso-8601'}</updated>\n" .
6504 "<author>\n" .
6505 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6506 if ($co{'author_email'}) {
6507 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6509 print "</author>\n" .
6510 # use committer for contributor
6511 "<contributor>\n" .
6512 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6513 if ($co{'committer_email'}) {
6514 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6516 print "</contributor>\n" .
6517 "<published>$cd{'iso-8601'}</published>\n" .
6518 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6519 "<id>$co_url</id>\n" .
6520 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6521 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6523 my $comment = $co{'comment'};
6524 print "<pre>\n";
6525 foreach my $line (@$comment) {
6526 $line = esc_html($line);
6527 print "$line\n";
6529 print "</pre><ul>\n";
6530 foreach my $difftree_line (@difftree) {
6531 my %difftree = parse_difftree_raw_line($difftree_line);
6532 next if !$difftree{'from_id'};
6534 my $file = $difftree{'file'} || $difftree{'to_file'};
6536 print "<li>" .
6537 "[" .
6538 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6539 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6540 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6541 file_name=>$file, file_parent=>$difftree{'from_file'}),
6542 -title => "diff"}, 'D');
6543 if ($have_blame) {
6544 print $cgi->a({-href => href(-full=>1, action=>"blame",
6545 file_name=>$file, hash_base=>$commit),
6546 -title => "blame"}, 'B');
6548 # if this is not a feed of a file history
6549 if (!defined $file_name || $file_name ne $file) {
6550 print $cgi->a({-href => href(-full=>1, action=>"history",
6551 file_name=>$file, hash=>$commit),
6552 -title => "history"}, 'H');
6554 $file = esc_path($file);
6555 print "] ".
6556 "$file</li>\n";
6558 if ($format eq 'rss') {
6559 print "</ul>]]>\n" .
6560 "</content:encoded>\n" .
6561 "</item>\n";
6562 } elsif ($format eq 'atom') {
6563 print "</ul>\n</div>\n" .
6564 "</content>\n" .
6565 "</entry>\n";
6569 # end of feed
6570 if ($format eq 'rss') {
6571 print "</channel>\n</rss>\n";
6572 } elsif ($format eq 'atom') {
6573 print "</feed>\n";
6577 sub git_rss {
6578 git_feed('rss');
6581 sub git_atom {
6582 git_feed('atom');
6585 sub git_opml {
6586 my @list = git_get_projects_list();
6588 print $cgi->header(
6589 -type => 'text/xml',
6590 -charset => 'utf-8',
6591 -content_disposition => 'inline; filename="opml.xml"');
6593 print <<XML;
6594 <?xml version="1.0" encoding="utf-8"?>
6595 <opml version="1.0">
6596 <head>
6597 <title>$site_name OPML Export</title>
6598 </head>
6599 <body>
6600 <outline text="git RSS feeds">
6603 foreach my $pr (@list) {
6604 my %proj = %$pr;
6605 my $head = git_get_head_hash($proj{'path'});
6606 if (!defined $head) {
6607 next;
6609 $git_dir = "$projectroot/$proj{'path'}";
6610 my %co = parse_commit($head);
6611 if (!%co) {
6612 next;
6615 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6616 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6617 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6618 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6620 print <<XML;
6621 </outline>
6622 </body>
6623 </opml>