[PATCH] gitweb: Support for no project list on gitweb front page
[git/gitweb.git] / gitweb / gitweb.perl
blob00e48891818b6150f6196ecf68b64164af5ec34c
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 extra_options => "opt",
575 search_use_regexp => "sr",
577 our %cgi_param_mapping = @cgi_param_mapping;
579 # we will also need to know the possible actions, for validation
580 our %actions = (
581 "blame" => \&git_blame,
582 "blobdiff" => \&git_blobdiff,
583 "blobdiff_plain" => \&git_blobdiff_plain,
584 "blob" => \&git_blob,
585 "blob_plain" => \&git_blob_plain,
586 "commitdiff" => \&git_commitdiff,
587 "commitdiff_plain" => \&git_commitdiff_plain,
588 "commit" => \&git_commit,
589 "forks" => \&git_forks,
590 "heads" => \&git_heads,
591 "history" => \&git_history,
592 "log" => \&git_log,
593 "patch" => \&git_patch,
594 "patches" => \&git_patches,
595 "rss" => \&git_rss,
596 "atom" => \&git_atom,
597 "search" => \&git_search,
598 "search_help" => \&git_search_help,
599 "shortlog" => \&git_shortlog,
600 "summary" => \&git_summary,
601 "tag" => \&git_tag,
602 "tags" => \&git_tags,
603 "tree" => \&git_tree,
604 "snapshot" => \&git_snapshot,
605 "object" => \&git_object,
606 # those below don't need $project
607 "opml" => \&git_opml,
608 "frontpage" => \&git_frontpage,
609 "project_list" => \&git_project_list,
610 "project_index" => \&git_project_index,
613 # finally, we have the hash of allowed extra_options for the commands that
614 # allow them
615 our %allowed_options = (
616 "--no-merges" => [ qw(rss atom log shortlog history) ],
619 # fill %input_params with the CGI parameters. All values except for 'opt'
620 # should be single values, but opt can be an array. We should probably
621 # build an array of parameters that can be multi-valued, but since for the time
622 # being it's only this one, we just single it out
623 while (my ($name, $symbol) = each %cgi_param_mapping) {
624 if ($symbol eq 'opt') {
625 $input_params{$name} = [ $cgi->param($symbol) ];
626 } else {
627 $input_params{$name} = $cgi->param($symbol);
631 # now read PATH_INFO and update the parameter list for missing parameters
632 sub evaluate_path_info {
633 return if defined $input_params{'project'};
634 return if !$path_info;
635 $path_info =~ s,^/+,,;
636 return if !$path_info;
638 # find which part of PATH_INFO is project
639 my $project = $path_info;
640 $project =~ s,/+$,,;
641 while ($project && !check_head_link("$projectroot/$project")) {
642 $project =~ s,/*[^/]*$,,;
644 return unless $project;
645 $input_params{'project'} = $project;
647 # do not change any parameters if an action is given using the query string
648 return if $input_params{'action'};
649 $path_info =~ s,^\Q$project\E/*,,;
651 # next, check if we have an action
652 my $action = $path_info;
653 $action =~ s,/.*$,,;
654 if (exists $actions{$action}) {
655 $path_info =~ s,^$action/*,,;
656 $input_params{'action'} = $action;
659 # list of actions that want hash_base instead of hash, but can have no
660 # pathname (f) parameter
661 my @wants_base = (
662 'tree',
663 'history',
666 # we want to catch
667 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
668 my ($parentrefname, $parentpathname, $refname, $pathname) =
669 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
671 # first, analyze the 'current' part
672 if (defined $pathname) {
673 # we got "branch:filename" or "branch:dir/"
674 # we could use git_get_type(branch:pathname), but:
675 # - it needs $git_dir
676 # - it does a git() call
677 # - the convention of terminating directories with a slash
678 # makes it superfluous
679 # - embedding the action in the PATH_INFO would make it even
680 # more superfluous
681 $pathname =~ s,^/+,,;
682 if (!$pathname || substr($pathname, -1) eq "/") {
683 $input_params{'action'} ||= "tree";
684 $pathname =~ s,/$,,;
685 } else {
686 # the default action depends on whether we had parent info
687 # or not
688 if ($parentrefname) {
689 $input_params{'action'} ||= "blobdiff_plain";
690 } else {
691 $input_params{'action'} ||= "blob_plain";
694 $input_params{'hash_base'} ||= $refname;
695 $input_params{'file_name'} ||= $pathname;
696 } elsif (defined $refname) {
697 # we got "branch". In this case we have to choose if we have to
698 # set hash or hash_base.
700 # Most of the actions without a pathname only want hash to be
701 # set, except for the ones specified in @wants_base that want
702 # hash_base instead. It should also be noted that hand-crafted
703 # links having 'history' as an action and no pathname or hash
704 # set will fail, but that happens regardless of PATH_INFO.
705 $input_params{'action'} ||= "shortlog";
706 if (grep { $_ eq $input_params{'action'} } @wants_base) {
707 $input_params{'hash_base'} ||= $refname;
708 } else {
709 $input_params{'hash'} ||= $refname;
713 # next, handle the 'parent' part, if present
714 if (defined $parentrefname) {
715 # a missing pathspec defaults to the 'current' filename, allowing e.g.
716 # someproject/blobdiff/oldrev..newrev:/filename
717 if ($parentpathname) {
718 $parentpathname =~ s,^/+,,;
719 $parentpathname =~ s,/$,,;
720 $input_params{'file_parent'} ||= $parentpathname;
721 } else {
722 $input_params{'file_parent'} ||= $input_params{'file_name'};
724 # we assume that hash_parent_base is wanted if a path was specified,
725 # or if the action wants hash_base instead of hash
726 if (defined $input_params{'file_parent'} ||
727 grep { $_ eq $input_params{'action'} } @wants_base) {
728 $input_params{'hash_parent_base'} ||= $parentrefname;
729 } else {
730 $input_params{'hash_parent'} ||= $parentrefname;
734 # for the snapshot action, we allow URLs in the form
735 # $project/snapshot/$hash.ext
736 # where .ext determines the snapshot and gets removed from the
737 # passed $refname to provide the $hash.
739 # To be able to tell that $refname includes the format extension, we
740 # require the following two conditions to be satisfied:
741 # - the hash input parameter MUST have been set from the $refname part
742 # of the URL (i.e. they must be equal)
743 # - the snapshot format MUST NOT have been defined already (e.g. from
744 # CGI parameter sf)
745 # It's also useless to try any matching unless $refname has a dot,
746 # so we check for that too
747 if (defined $input_params{'action'} &&
748 $input_params{'action'} eq 'snapshot' &&
749 defined $refname && index($refname, '.') != -1 &&
750 $refname eq $input_params{'hash'} &&
751 !defined $input_params{'snapshot_format'}) {
752 # We loop over the known snapshot formats, checking for
753 # extensions. Allowed extensions are both the defined suffix
754 # (which includes the initial dot already) and the snapshot
755 # format key itself, with a prepended dot
756 while (my ($fmt, $opt) = each %known_snapshot_formats) {
757 my $hash = $refname;
758 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
759 next;
761 my $sfx = $1;
762 # a valid suffix was found, so set the snapshot format
763 # and reset the hash parameter
764 $input_params{'snapshot_format'} = $fmt;
765 $input_params{'hash'} = $hash;
766 # we also set the format suffix to the one requested
767 # in the URL: this way a request for e.g. .tgz returns
768 # a .tgz instead of a .tar.gz
769 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
770 last;
774 evaluate_path_info();
776 our $action = $input_params{'action'};
777 if (defined $action) {
778 if (!validate_action($action)) {
779 die_error(400, "Invalid action parameter");
783 # parameters which are pathnames
784 our $project = $input_params{'project'};
785 if (defined $project) {
786 if (!validate_project($project)) {
787 undef $project;
788 die_error(404, "No such project");
792 our $file_name = $input_params{'file_name'};
793 if (defined $file_name) {
794 if (!validate_pathname($file_name)) {
795 die_error(400, "Invalid file parameter");
799 our $file_parent = $input_params{'file_parent'};
800 if (defined $file_parent) {
801 if (!validate_pathname($file_parent)) {
802 die_error(400, "Invalid file parent parameter");
806 # parameters which are refnames
807 our $hash = $input_params{'hash'};
808 if (defined $hash) {
809 if (!validate_refname($hash)) {
810 die_error(400, "Invalid hash parameter");
814 our $hash_parent = $input_params{'hash_parent'};
815 if (defined $hash_parent) {
816 if (!validate_refname($hash_parent)) {
817 die_error(400, "Invalid hash parent parameter");
821 our $hash_base = $input_params{'hash_base'};
822 if (defined $hash_base) {
823 if (!validate_refname($hash_base)) {
824 die_error(400, "Invalid hash base parameter");
828 our @extra_options = @{$input_params{'extra_options'}};
829 # @extra_options is always defined, since it can only be (currently) set from
830 # CGI, and $cgi->param() returns the empty array in array context if the param
831 # is not set
832 foreach my $opt (@extra_options) {
833 if (not exists $allowed_options{$opt}) {
834 die_error(400, "Invalid option parameter");
836 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
837 die_error(400, "Invalid option parameter for this action");
841 our $hash_parent_base = $input_params{'hash_parent_base'};
842 if (defined $hash_parent_base) {
843 if (!validate_refname($hash_parent_base)) {
844 die_error(400, "Invalid hash parent base parameter");
848 # other parameters
849 our $page = $input_params{'page'};
850 if (defined $page) {
851 if ($page =~ m/[^0-9]/) {
852 die_error(400, "Invalid page parameter");
856 our $searchtype = $input_params{'searchtype'};
857 if (defined $searchtype) {
858 if ($searchtype =~ m/[^a-z]/) {
859 die_error(400, "Invalid searchtype parameter");
863 our $search_use_regexp = $input_params{'search_use_regexp'};
865 our $searchtext = $input_params{'searchtext'};
866 our $search_regexp;
867 if (defined $searchtext) {
868 if (length($searchtext) < 2) {
869 die_error(403, "At least two characters are required for search parameter");
871 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
874 # path to the current git repository
875 our $git_dir;
876 $git_dir = "$projectroot/$project" if $project;
878 # list of supported snapshot formats
879 our @snapshot_fmts = gitweb_get_feature('snapshot');
880 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
882 # check that the avatar feature is set to a known provider name,
883 # and for each provider check if the dependencies are satisfied.
884 # if the provider name is invalid or the dependencies are not met,
885 # reset $git_avatar to the empty string.
886 our ($git_avatar) = gitweb_get_feature('avatar');
887 if ($git_avatar eq 'gravatar') {
888 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
889 } elsif ($git_avatar eq 'picon') {
890 # no dependencies
891 } else {
892 $git_avatar = '';
895 # dispatch
896 if (!defined $action) {
897 if (defined $hash) {
898 $action = git_get_type($hash);
899 } elsif (defined $hash_base && defined $file_name) {
900 $action = git_get_type("$hash_base:$file_name");
901 } elsif (defined $project) {
902 $action = 'summary';
903 } else {
904 $action = 'frontpage';
907 if (!defined($actions{$action})) {
908 die_error(400, "Unknown action");
910 if ($action !~ m/^(?:opml|frontpage|project_list|project_index)$/ &&
911 !$project) {
912 die_error(400, "Project needed");
914 $actions{$action}->();
915 exit;
917 ## ======================================================================
918 ## action links
920 sub href {
921 my %params = @_;
922 # default is to use -absolute url() i.e. $my_uri
923 my $href = $params{-full} ? $my_url : $my_uri;
925 $params{'project'} = $project unless exists $params{'project'};
927 if ($params{-replay}) {
928 while (my ($name, $symbol) = each %cgi_param_mapping) {
929 if (!exists $params{$name}) {
930 $params{$name} = $input_params{$name};
935 my $use_pathinfo = gitweb_check_feature('pathinfo');
936 if ($use_pathinfo and defined $params{'project'}) {
937 # try to put as many parameters as possible in PATH_INFO:
938 # - project name
939 # - action
940 # - hash_parent or hash_parent_base:/file_parent
941 # - hash or hash_base:/filename
942 # - the snapshot_format as an appropriate suffix
944 # When the script is the root DirectoryIndex for the domain,
945 # $href here would be something like http://gitweb.example.com/
946 # Thus, we strip any trailing / from $href, to spare us double
947 # slashes in the final URL
948 $href =~ s,/$,,;
950 # Then add the project name, if present
951 $href .= "/".esc_url($params{'project'});
952 delete $params{'project'};
954 # since we destructively absorb parameters, we keep this
955 # boolean that remembers if we're handling a snapshot
956 my $is_snapshot = $params{'action'} eq 'snapshot';
958 # Summary just uses the project path URL, any other action is
959 # added to the URL
960 if (defined $params{'action'}) {
961 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
962 delete $params{'action'};
965 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
966 # stripping nonexistent or useless pieces
967 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
968 || $params{'hash_parent'} || $params{'hash'});
969 if (defined $params{'hash_base'}) {
970 if (defined $params{'hash_parent_base'}) {
971 $href .= esc_url($params{'hash_parent_base'});
972 # skip the file_parent if it's the same as the file_name
973 if (defined $params{'file_parent'}) {
974 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
975 delete $params{'file_parent'};
976 } elsif ($params{'file_parent'} !~ /\.\./) {
977 $href .= ":/".esc_url($params{'file_parent'});
978 delete $params{'file_parent'};
981 $href .= "..";
982 delete $params{'hash_parent'};
983 delete $params{'hash_parent_base'};
984 } elsif (defined $params{'hash_parent'}) {
985 $href .= esc_url($params{'hash_parent'}). "..";
986 delete $params{'hash_parent'};
989 $href .= esc_url($params{'hash_base'});
990 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
991 $href .= ":/".esc_url($params{'file_name'});
992 delete $params{'file_name'};
994 delete $params{'hash'};
995 delete $params{'hash_base'};
996 } elsif (defined $params{'hash'}) {
997 $href .= esc_url($params{'hash'});
998 delete $params{'hash'};
1001 # If the action was a snapshot, we can absorb the
1002 # snapshot_format parameter too
1003 if ($is_snapshot) {
1004 my $fmt = $params{'snapshot_format'};
1005 # snapshot_format should always be defined when href()
1006 # is called, but just in case some code forgets, we
1007 # fall back to the default
1008 $fmt ||= $snapshot_fmts[0];
1009 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1010 delete $params{'snapshot_format'};
1014 # now encode the parameters explicitly
1015 my @result = ();
1016 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1017 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1018 if (defined $params{$name}) {
1019 if (ref($params{$name}) eq "ARRAY") {
1020 foreach my $par (@{$params{$name}}) {
1021 push @result, $symbol . "=" . esc_param($par);
1023 } else {
1024 push @result, $symbol . "=" . esc_param($params{$name});
1028 $href .= "?" . join(';', @result) if scalar @result;
1030 return $href;
1034 ## ======================================================================
1035 ## validation, quoting/unquoting and escaping
1037 sub validate_action {
1038 my $input = shift || return undef;
1039 return undef unless exists $actions{$input};
1040 return $input;
1043 sub validate_project {
1044 my $input = shift || return undef;
1045 if (!validate_pathname($input) ||
1046 !(-d "$projectroot/$input") ||
1047 !check_export_ok("$projectroot/$input") ||
1048 ($strict_export && !project_in_list($input))) {
1049 return undef;
1050 } else {
1051 return $input;
1055 sub validate_pathname {
1056 my $input = shift || return undef;
1058 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1059 # at the beginning, at the end, and between slashes.
1060 # also this catches doubled slashes
1061 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1062 return undef;
1064 # no null characters
1065 if ($input =~ m!\0!) {
1066 return undef;
1068 return $input;
1071 sub validate_refname {
1072 my $input = shift || return undef;
1074 # textual hashes are O.K.
1075 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1076 return $input;
1078 # it must be correct pathname
1079 $input = validate_pathname($input)
1080 or return undef;
1081 # restrictions on ref name according to git-check-ref-format
1082 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1083 return undef;
1085 return $input;
1088 # decode sequences of octets in utf8 into Perl's internal form,
1089 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1090 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1091 sub to_utf8 {
1092 my $str = shift;
1093 if (utf8::valid($str)) {
1094 utf8::decode($str);
1095 return $str;
1096 } else {
1097 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1101 # quote unsafe chars, but keep the slash, even when it's not
1102 # correct, but quoted slashes look too horrible in bookmarks
1103 sub esc_param {
1104 my $str = shift;
1105 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1106 $str =~ s/ /\+/g;
1107 return $str;
1110 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1111 sub esc_url {
1112 my $str = shift;
1113 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1114 $str =~ s/\+/%2B/g;
1115 $str =~ s/ /\+/g;
1116 return $str;
1119 # replace invalid utf8 character with SUBSTITUTION sequence
1120 sub esc_html {
1121 my $str = shift;
1122 my %opts = @_;
1124 $str = to_utf8($str);
1125 $str = $cgi->escapeHTML($str);
1126 if ($opts{'-nbsp'}) {
1127 $str =~ s/ /&nbsp;/g;
1129 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1130 return $str;
1133 # quote control characters and escape filename to HTML
1134 sub esc_path {
1135 my $str = shift;
1136 my %opts = @_;
1138 $str = to_utf8($str);
1139 $str = $cgi->escapeHTML($str);
1140 if ($opts{'-nbsp'}) {
1141 $str =~ s/ /&nbsp;/g;
1143 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1144 return $str;
1147 # Make control characters "printable", using character escape codes (CEC)
1148 sub quot_cec {
1149 my $cntrl = shift;
1150 my %opts = @_;
1151 my %es = ( # character escape codes, aka escape sequences
1152 "\t" => '\t', # tab (HT)
1153 "\n" => '\n', # line feed (LF)
1154 "\r" => '\r', # carrige return (CR)
1155 "\f" => '\f', # form feed (FF)
1156 "\b" => '\b', # backspace (BS)
1157 "\a" => '\a', # alarm (bell) (BEL)
1158 "\e" => '\e', # escape (ESC)
1159 "\013" => '\v', # vertical tab (VT)
1160 "\000" => '\0', # nul character (NUL)
1162 my $chr = ( (exists $es{$cntrl})
1163 ? $es{$cntrl}
1164 : sprintf('\%2x', ord($cntrl)) );
1165 if ($opts{-nohtml}) {
1166 return $chr;
1167 } else {
1168 return "<span class=\"cntrl\">$chr</span>";
1172 # Alternatively use unicode control pictures codepoints,
1173 # Unicode "printable representation" (PR)
1174 sub quot_upr {
1175 my $cntrl = shift;
1176 my %opts = @_;
1178 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1179 if ($opts{-nohtml}) {
1180 return $chr;
1181 } else {
1182 return "<span class=\"cntrl\">$chr</span>";
1186 # git may return quoted and escaped filenames
1187 sub unquote {
1188 my $str = shift;
1190 sub unq {
1191 my $seq = shift;
1192 my %es = ( # character escape codes, aka escape sequences
1193 't' => "\t", # tab (HT, TAB)
1194 'n' => "\n", # newline (NL)
1195 'r' => "\r", # return (CR)
1196 'f' => "\f", # form feed (FF)
1197 'b' => "\b", # backspace (BS)
1198 'a' => "\a", # alarm (bell) (BEL)
1199 'e' => "\e", # escape (ESC)
1200 'v' => "\013", # vertical tab (VT)
1203 if ($seq =~ m/^[0-7]{1,3}$/) {
1204 # octal char sequence
1205 return chr(oct($seq));
1206 } elsif (exists $es{$seq}) {
1207 # C escape sequence, aka character escape code
1208 return $es{$seq};
1210 # quoted ordinary character
1211 return $seq;
1214 if ($str =~ m/^"(.*)"$/) {
1215 # needs unquoting
1216 $str = $1;
1217 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1219 return $str;
1222 # escape tabs (convert tabs to spaces)
1223 sub untabify {
1224 my $line = shift;
1226 while ((my $pos = index($line, "\t")) != -1) {
1227 if (my $count = (8 - ($pos % 8))) {
1228 my $spaces = ' ' x $count;
1229 $line =~ s/\t/$spaces/;
1233 return $line;
1236 sub project_in_list {
1237 my $project = shift;
1238 my @list = git_get_projects_list();
1239 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1242 ## ----------------------------------------------------------------------
1243 ## HTML aware string manipulation
1245 # Try to chop given string on a word boundary between position
1246 # $len and $len+$add_len. If there is no word boundary there,
1247 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1248 # (marking chopped part) would be longer than given string.
1249 sub chop_str {
1250 my $str = shift;
1251 my $len = shift;
1252 my $add_len = shift || 10;
1253 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1255 # Make sure perl knows it is utf8 encoded so we don't
1256 # cut in the middle of a utf8 multibyte char.
1257 $str = to_utf8($str);
1259 # allow only $len chars, but don't cut a word if it would fit in $add_len
1260 # if it doesn't fit, cut it if it's still longer than the dots we would add
1261 # remove chopped character entities entirely
1263 # when chopping in the middle, distribute $len into left and right part
1264 # return early if chopping wouldn't make string shorter
1265 if ($where eq 'center') {
1266 return $str if ($len + 5 >= length($str)); # filler is length 5
1267 $len = int($len/2);
1268 } else {
1269 return $str if ($len + 4 >= length($str)); # filler is length 4
1272 # regexps: ending and beginning with word part up to $add_len
1273 my $endre = qr/.{$len}\w{0,$add_len}/;
1274 my $begre = qr/\w{0,$add_len}.{$len}/;
1276 if ($where eq 'left') {
1277 $str =~ m/^(.*?)($begre)$/;
1278 my ($lead, $body) = ($1, $2);
1279 if (length($lead) > 4) {
1280 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1281 $lead = " ...";
1283 return "$lead$body";
1285 } elsif ($where eq 'center') {
1286 $str =~ m/^($endre)(.*)$/;
1287 my ($left, $str) = ($1, $2);
1288 $str =~ m/^(.*?)($begre)$/;
1289 my ($mid, $right) = ($1, $2);
1290 if (length($mid) > 5) {
1291 $left =~ s/&[^;]*$//;
1292 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1293 $mid = " ... ";
1295 return "$left$mid$right";
1297 } else {
1298 $str =~ m/^($endre)(.*)$/;
1299 my $body = $1;
1300 my $tail = $2;
1301 if (length($tail) > 4) {
1302 $body =~ s/&[^;]*$//;
1303 $tail = "... ";
1305 return "$body$tail";
1309 # takes the same arguments as chop_str, but also wraps a <span> around the
1310 # result with a title attribute if it does get chopped. Additionally, the
1311 # string is HTML-escaped.
1312 sub chop_and_escape_str {
1313 my ($str) = @_;
1315 my $chopped = chop_str(@_);
1316 if ($chopped eq $str) {
1317 return esc_html($chopped);
1318 } else {
1319 $str =~ s/[[:cntrl:]]/?/g;
1320 return $cgi->span({-title=>$str}, esc_html($chopped));
1324 ## ----------------------------------------------------------------------
1325 ## functions returning short strings
1327 # CSS class for given age value (in seconds)
1328 sub age_class {
1329 my $age = shift;
1331 if (!defined $age) {
1332 return "noage";
1333 } elsif ($age < 60*60*2) {
1334 return "age0";
1335 } elsif ($age < 60*60*24*2) {
1336 return "age1";
1337 } else {
1338 return "age2";
1342 # convert age in seconds to "nn units ago" string
1343 sub age_string {
1344 my $age = shift;
1345 my $age_str;
1347 if ($age > 60*60*24*365*2) {
1348 $age_str = (int $age/60/60/24/365);
1349 $age_str .= " years ago";
1350 } elsif ($age > 60*60*24*(365/12)*2) {
1351 $age_str = int $age/60/60/24/(365/12);
1352 $age_str .= " months ago";
1353 } elsif ($age > 60*60*24*7*2) {
1354 $age_str = int $age/60/60/24/7;
1355 $age_str .= " weeks ago";
1356 } elsif ($age > 60*60*24*2) {
1357 $age_str = int $age/60/60/24;
1358 $age_str .= " days ago";
1359 } elsif ($age > 60*60*2) {
1360 $age_str = int $age/60/60;
1361 $age_str .= " hours ago";
1362 } elsif ($age > 60*2) {
1363 $age_str = int $age/60;
1364 $age_str .= " min ago";
1365 } elsif ($age > 2) {
1366 $age_str = int $age;
1367 $age_str .= " sec ago";
1368 } else {
1369 $age_str .= " right now";
1371 return $age_str;
1374 use constant {
1375 S_IFINVALID => 0030000,
1376 S_IFGITLINK => 0160000,
1379 # submodule/subproject, a commit object reference
1380 sub S_ISGITLINK {
1381 my $mode = shift;
1383 return (($mode & S_IFMT) == S_IFGITLINK)
1386 # convert file mode in octal to symbolic file mode string
1387 sub mode_str {
1388 my $mode = oct shift;
1390 if (S_ISGITLINK($mode)) {
1391 return 'm---------';
1392 } elsif (S_ISDIR($mode & S_IFMT)) {
1393 return 'drwxr-xr-x';
1394 } elsif (S_ISLNK($mode)) {
1395 return 'lrwxrwxrwx';
1396 } elsif (S_ISREG($mode)) {
1397 # git cares only about the executable bit
1398 if ($mode & S_IXUSR) {
1399 return '-rwxr-xr-x';
1400 } else {
1401 return '-rw-r--r--';
1403 } else {
1404 return '----------';
1408 # convert file mode in octal to file type string
1409 sub file_type {
1410 my $mode = shift;
1412 if ($mode !~ m/^[0-7]+$/) {
1413 return $mode;
1414 } else {
1415 $mode = oct $mode;
1418 if (S_ISGITLINK($mode)) {
1419 return "submodule";
1420 } elsif (S_ISDIR($mode & S_IFMT)) {
1421 return "directory";
1422 } elsif (S_ISLNK($mode)) {
1423 return "symlink";
1424 } elsif (S_ISREG($mode)) {
1425 return "file";
1426 } else {
1427 return "unknown";
1431 # convert file mode in octal to file type description string
1432 sub file_type_long {
1433 my $mode = shift;
1435 if ($mode !~ m/^[0-7]+$/) {
1436 return $mode;
1437 } else {
1438 $mode = oct $mode;
1441 if (S_ISGITLINK($mode)) {
1442 return "submodule";
1443 } elsif (S_ISDIR($mode & S_IFMT)) {
1444 return "directory";
1445 } elsif (S_ISLNK($mode)) {
1446 return "symlink";
1447 } elsif (S_ISREG($mode)) {
1448 if ($mode & S_IXUSR) {
1449 return "executable";
1450 } else {
1451 return "file";
1453 } else {
1454 return "unknown";
1459 ## ----------------------------------------------------------------------
1460 ## functions returning short HTML fragments, or transforming HTML fragments
1461 ## which don't belong to other sections
1463 # format line of commit message.
1464 sub format_log_line_html {
1465 my $line = shift;
1467 $line = esc_html($line, -nbsp=>1);
1468 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1469 $cgi->a({-href => href(action=>"object", hash=>$1),
1470 -class => "text"}, $1);
1471 }eg;
1473 return $line;
1476 # format marker of refs pointing to given object
1478 # the destination action is chosen based on object type and current context:
1479 # - for annotated tags, we choose the tag view unless it's the current view
1480 # already, in which case we go to shortlog view
1481 # - for other refs, we keep the current view if we're in history, shortlog or
1482 # log view, and select shortlog otherwise
1483 sub format_ref_marker {
1484 my ($refs, $id) = @_;
1485 my $markers = '';
1487 if (defined $refs->{$id}) {
1488 foreach my $ref (@{$refs->{$id}}) {
1489 # this code exploits the fact that non-lightweight tags are the
1490 # only indirect objects, and that they are the only objects for which
1491 # we want to use tag instead of shortlog as action
1492 my ($type, $name) = qw();
1493 my $indirect = ($ref =~ s/\^\{\}$//);
1494 # e.g. tags/v2.6.11 or heads/next
1495 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1496 $type = $1;
1497 $name = $2;
1498 } else {
1499 $type = "ref";
1500 $name = $ref;
1503 my $class = $type;
1504 $class .= " indirect" if $indirect;
1506 my $dest_action = "shortlog";
1508 if ($indirect) {
1509 $dest_action = "tag" unless $action eq "tag";
1510 } elsif ($action =~ /^(history|(short)?log)$/) {
1511 $dest_action = $action;
1514 my $dest = "";
1515 $dest .= "refs/" unless $ref =~ m!^refs/!;
1516 $dest .= $ref;
1518 my $link = $cgi->a({
1519 -href => href(
1520 action=>$dest_action,
1521 hash=>$dest
1522 )}, $name);
1524 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1525 $link . "</span>";
1529 if ($markers) {
1530 return ' <span class="refs">'. $markers . '</span>';
1531 } else {
1532 return "";
1536 # format, perhaps shortened and with markers, title line
1537 sub format_subject_html {
1538 my ($long, $short, $href, $extra) = @_;
1539 $extra = '' unless defined($extra);
1541 if (length($short) < length($long)) {
1542 $long =~ s/[[:cntrl:]]/?/g;
1543 return $cgi->a({-href => $href, -class => "list subject",
1544 -title => to_utf8($long)},
1545 esc_html($short)) . $extra;
1546 } else {
1547 return $cgi->a({-href => $href, -class => "list subject"},
1548 esc_html($long)) . $extra;
1552 # Rather than recomputing the url for an email multiple times, we cache it
1553 # after the first hit. This gives a visible benefit in views where the avatar
1554 # for the same email is used repeatedly (e.g. shortlog).
1555 # The cache is shared by all avatar engines (currently gravatar only), which
1556 # are free to use it as preferred. Since only one avatar engine is used for any
1557 # given page, there's no risk for cache conflicts.
1558 our %avatar_cache = ();
1560 # Compute the picon url for a given email, by using the picon search service over at
1561 # http://www.cs.indiana.edu/picons/search.html
1562 sub picon_url {
1563 my $email = lc shift;
1564 if (!$avatar_cache{$email}) {
1565 my ($user, $domain) = split('@', $email);
1566 $avatar_cache{$email} =
1567 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1568 "$domain/$user/" .
1569 "users+domains+unknown/up/single";
1571 return $avatar_cache{$email};
1574 # Compute the gravatar url for a given email, if it's not in the cache already.
1575 # Gravatar stores only the part of the URL before the size, since that's the
1576 # one computationally more expensive. This also allows reuse of the cache for
1577 # different sizes (for this particular engine).
1578 sub gravatar_url {
1579 my $email = lc shift;
1580 my $size = shift;
1581 $avatar_cache{$email} ||=
1582 "http://www.gravatar.com/avatar/" .
1583 Digest::MD5::md5_hex($email) . "?s=";
1584 return $avatar_cache{$email} . $size;
1587 # Insert an avatar for the given $email at the given $size if the feature
1588 # is enabled.
1589 sub git_get_avatar {
1590 my ($email, %opts) = @_;
1591 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1592 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1593 $opts{-size} ||= 'default';
1594 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1595 my $url = "";
1596 if ($git_avatar eq 'gravatar') {
1597 $url = gravatar_url($email, $size);
1598 } elsif ($git_avatar eq 'picon') {
1599 $url = picon_url($email);
1601 # Other providers can be added by extending the if chain, defining $url
1602 # as needed. If no variant puts something in $url, we assume avatars
1603 # are completely disabled/unavailable.
1604 if ($url) {
1605 return $pre_white .
1606 "<img width=\"$size\" " .
1607 "class=\"avatar\" " .
1608 "src=\"$url\" " .
1609 "alt=\"\" " .
1610 "/>" . $post_white;
1611 } else {
1612 return "";
1616 sub format_search_author {
1617 my ($author, $searchtype, $displaytext) = @_;
1618 my $have_search = gitweb_check_feature('search');
1620 if ($have_search) {
1621 my $performed = "";
1622 if ($searchtype eq 'author') {
1623 $performed = "authored";
1624 } elsif ($searchtype eq 'committer') {
1625 $performed = "committed";
1628 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1629 searchtext=>$author,
1630 searchtype=>$searchtype), class=>"list",
1631 title=>"Search for commits $performed by $author"},
1632 $displaytext);
1634 } else {
1635 return $displaytext;
1639 # format the author name of the given commit with the given tag
1640 # the author name is chopped and escaped according to the other
1641 # optional parameters (see chop_str).
1642 sub format_author_html {
1643 my $tag = shift;
1644 my $co = shift;
1645 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1646 return "<$tag class=\"author\">" .
1647 format_search_author($co->{'author_name'}, "author",
1648 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1649 $author) .
1650 "</$tag>";
1653 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1654 sub format_git_diff_header_line {
1655 my $line = shift;
1656 my $diffinfo = shift;
1657 my ($from, $to) = @_;
1659 if ($diffinfo->{'nparents'}) {
1660 # combined diff
1661 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1662 if ($to->{'href'}) {
1663 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1664 esc_path($to->{'file'}));
1665 } else { # file was deleted (no href)
1666 $line .= esc_path($to->{'file'});
1668 } else {
1669 # "ordinary" diff
1670 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1671 if ($from->{'href'}) {
1672 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1673 'a/' . esc_path($from->{'file'}));
1674 } else { # file was added (no href)
1675 $line .= 'a/' . esc_path($from->{'file'});
1677 $line .= ' ';
1678 if ($to->{'href'}) {
1679 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1680 'b/' . esc_path($to->{'file'}));
1681 } else { # file was deleted
1682 $line .= 'b/' . esc_path($to->{'file'});
1686 return "<div class=\"diff header\">$line</div>\n";
1689 # format extended diff header line, before patch itself
1690 sub format_extended_diff_header_line {
1691 my $line = shift;
1692 my $diffinfo = shift;
1693 my ($from, $to) = @_;
1695 # match <path>
1696 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1697 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1698 esc_path($from->{'file'}));
1700 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1701 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1702 esc_path($to->{'file'}));
1704 # match single <mode>
1705 if ($line =~ m/\s(\d{6})$/) {
1706 $line .= '<span class="info"> (' .
1707 file_type_long($1) .
1708 ')</span>';
1710 # match <hash>
1711 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1712 # can match only for combined diff
1713 $line = 'index ';
1714 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1715 if ($from->{'href'}[$i]) {
1716 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1717 -class=>"hash"},
1718 substr($diffinfo->{'from_id'}[$i],0,7));
1719 } else {
1720 $line .= '0' x 7;
1722 # separator
1723 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1725 $line .= '..';
1726 if ($to->{'href'}) {
1727 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1728 substr($diffinfo->{'to_id'},0,7));
1729 } else {
1730 $line .= '0' x 7;
1733 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1734 # can match only for ordinary diff
1735 my ($from_link, $to_link);
1736 if ($from->{'href'}) {
1737 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1738 substr($diffinfo->{'from_id'},0,7));
1739 } else {
1740 $from_link = '0' x 7;
1742 if ($to->{'href'}) {
1743 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1744 substr($diffinfo->{'to_id'},0,7));
1745 } else {
1746 $to_link = '0' x 7;
1748 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1749 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1752 return $line . "<br/>\n";
1755 # format from-file/to-file diff header
1756 sub format_diff_from_to_header {
1757 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1758 my $line;
1759 my $result = '';
1761 $line = $from_line;
1762 #assert($line =~ m/^---/) if DEBUG;
1763 # no extra formatting for "^--- /dev/null"
1764 if (! $diffinfo->{'nparents'}) {
1765 # ordinary (single parent) diff
1766 if ($line =~ m!^--- "?a/!) {
1767 if ($from->{'href'}) {
1768 $line = '--- a/' .
1769 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1770 esc_path($from->{'file'}));
1771 } else {
1772 $line = '--- a/' .
1773 esc_path($from->{'file'});
1776 $result .= qq!<div class="diff from_file">$line</div>\n!;
1778 } else {
1779 # combined diff (merge commit)
1780 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1781 if ($from->{'href'}[$i]) {
1782 $line = '--- ' .
1783 $cgi->a({-href=>href(action=>"blobdiff",
1784 hash_parent=>$diffinfo->{'from_id'}[$i],
1785 hash_parent_base=>$parents[$i],
1786 file_parent=>$from->{'file'}[$i],
1787 hash=>$diffinfo->{'to_id'},
1788 hash_base=>$hash,
1789 file_name=>$to->{'file'}),
1790 -class=>"path",
1791 -title=>"diff" . ($i+1)},
1792 $i+1) .
1793 '/' .
1794 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1795 esc_path($from->{'file'}[$i]));
1796 } else {
1797 $line = '--- /dev/null';
1799 $result .= qq!<div class="diff from_file">$line</div>\n!;
1803 $line = $to_line;
1804 #assert($line =~ m/^\+\+\+/) if DEBUG;
1805 # no extra formatting for "^+++ /dev/null"
1806 if ($line =~ m!^\+\+\+ "?b/!) {
1807 if ($to->{'href'}) {
1808 $line = '+++ b/' .
1809 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1810 esc_path($to->{'file'}));
1811 } else {
1812 $line = '+++ b/' .
1813 esc_path($to->{'file'});
1816 $result .= qq!<div class="diff to_file">$line</div>\n!;
1818 return $result;
1821 # create note for patch simplified by combined diff
1822 sub format_diff_cc_simplified {
1823 my ($diffinfo, @parents) = @_;
1824 my $result = '';
1826 $result .= "<div class=\"diff header\">" .
1827 "diff --cc ";
1828 if (!is_deleted($diffinfo)) {
1829 $result .= $cgi->a({-href => href(action=>"blob",
1830 hash_base=>$hash,
1831 hash=>$diffinfo->{'to_id'},
1832 file_name=>$diffinfo->{'to_file'}),
1833 -class => "path"},
1834 esc_path($diffinfo->{'to_file'}));
1835 } else {
1836 $result .= esc_path($diffinfo->{'to_file'});
1838 $result .= "</div>\n" . # class="diff header"
1839 "<div class=\"diff nodifferences\">" .
1840 "Simple merge" .
1841 "</div>\n"; # class="diff nodifferences"
1843 return $result;
1846 # format patch (diff) line (not to be used for diff headers)
1847 sub format_diff_line {
1848 my $line = shift;
1849 my ($from, $to) = @_;
1850 my $diff_class = "";
1852 chomp $line;
1854 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1855 # combined diff
1856 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1857 if ($line =~ m/^\@{3}/) {
1858 $diff_class = " chunk_header";
1859 } elsif ($line =~ m/^\\/) {
1860 $diff_class = " incomplete";
1861 } elsif ($prefix =~ tr/+/+/) {
1862 $diff_class = " add";
1863 } elsif ($prefix =~ tr/-/-/) {
1864 $diff_class = " rem";
1866 } else {
1867 # assume ordinary diff
1868 my $char = substr($line, 0, 1);
1869 if ($char eq '+') {
1870 $diff_class = " add";
1871 } elsif ($char eq '-') {
1872 $diff_class = " rem";
1873 } elsif ($char eq '@') {
1874 $diff_class = " chunk_header";
1875 } elsif ($char eq "\\") {
1876 $diff_class = " incomplete";
1879 $line = untabify($line);
1880 if ($from && $to && $line =~ m/^\@{2} /) {
1881 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1882 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1884 $from_lines = 0 unless defined $from_lines;
1885 $to_lines = 0 unless defined $to_lines;
1887 if ($from->{'href'}) {
1888 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1889 -class=>"list"}, $from_text);
1891 if ($to->{'href'}) {
1892 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1893 -class=>"list"}, $to_text);
1895 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1896 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1897 return "<div class=\"diff$diff_class\">$line</div>\n";
1898 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1899 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1900 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1902 @from_text = split(' ', $ranges);
1903 for (my $i = 0; $i < @from_text; ++$i) {
1904 ($from_start[$i], $from_nlines[$i]) =
1905 (split(',', substr($from_text[$i], 1)), 0);
1908 $to_text = pop @from_text;
1909 $to_start = pop @from_start;
1910 $to_nlines = pop @from_nlines;
1912 $line = "<span class=\"chunk_info\">$prefix ";
1913 for (my $i = 0; $i < @from_text; ++$i) {
1914 if ($from->{'href'}[$i]) {
1915 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1916 -class=>"list"}, $from_text[$i]);
1917 } else {
1918 $line .= $from_text[$i];
1920 $line .= " ";
1922 if ($to->{'href'}) {
1923 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1924 -class=>"list"}, $to_text);
1925 } else {
1926 $line .= $to_text;
1928 $line .= " $prefix</span>" .
1929 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1930 return "<div class=\"diff$diff_class\">$line</div>\n";
1932 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1935 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1936 # linked. Pass the hash of the tree/commit to snapshot.
1937 sub format_snapshot_links {
1938 my ($hash) = @_;
1939 my $num_fmts = @snapshot_fmts;
1940 if ($num_fmts > 1) {
1941 # A parenthesized list of links bearing format names.
1942 # e.g. "snapshot (_tar.gz_ _zip_)"
1943 return "snapshot (" . join(' ', map
1944 $cgi->a({
1945 -href => href(
1946 action=>"snapshot",
1947 hash=>$hash,
1948 snapshot_format=>$_
1950 }, $known_snapshot_formats{$_}{'display'})
1951 , @snapshot_fmts) . ")";
1952 } elsif ($num_fmts == 1) {
1953 # A single "snapshot" link whose tooltip bears the format name.
1954 # i.e. "_snapshot_"
1955 my ($fmt) = @snapshot_fmts;
1956 return
1957 $cgi->a({
1958 -href => href(
1959 action=>"snapshot",
1960 hash=>$hash,
1961 snapshot_format=>$fmt
1963 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1964 }, "snapshot");
1965 } else { # $num_fmts == 0
1966 return undef;
1970 ## ......................................................................
1971 ## functions returning values to be passed, perhaps after some
1972 ## transformation, to other functions; e.g. returning arguments to href()
1974 # returns hash to be passed to href to generate gitweb URL
1975 # in -title key it returns description of link
1976 sub get_feed_info {
1977 my $format = shift || 'Atom';
1978 my %res = (action => lc($format));
1980 # feed links are possible only for project views
1981 return unless (defined $project);
1982 # some views should link to OPML, or to generic project feed,
1983 # or don't have specific feed yet (so they should use generic)
1984 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1986 my $branch;
1987 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1988 # from tag links; this also makes possible to detect branch links
1989 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1990 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1991 $branch = $1;
1993 # find log type for feed description (title)
1994 my $type = 'log';
1995 if (defined $file_name) {
1996 $type = "history of $file_name";
1997 $type .= "/" if ($action eq 'tree');
1998 $type .= " on '$branch'" if (defined $branch);
1999 } else {
2000 $type = "log of $branch" if (defined $branch);
2003 $res{-title} = $type;
2004 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2005 $res{'file_name'} = $file_name;
2007 return %res;
2010 ## ----------------------------------------------------------------------
2011 ## git utility subroutines, invoking git commands
2013 # returns path to the core git executable and the --git-dir parameter as list
2014 sub git_cmd {
2015 return $GIT, '--git-dir='.$git_dir;
2018 # quote the given arguments for passing them to the shell
2019 # quote_command("command", "arg 1", "arg with ' and ! characters")
2020 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2021 # Try to avoid using this function wherever possible.
2022 sub quote_command {
2023 return join(' ',
2024 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2027 # get HEAD ref of given project as hash
2028 sub git_get_head_hash {
2029 my $project = shift;
2030 my $o_git_dir = $git_dir;
2031 my $retval = undef;
2032 $git_dir = "$projectroot/$project";
2033 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
2034 my $head = <$fd>;
2035 close $fd;
2036 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
2037 $retval = $1;
2040 if (defined $o_git_dir) {
2041 $git_dir = $o_git_dir;
2043 return $retval;
2046 # get type of given object
2047 sub git_get_type {
2048 my $hash = shift;
2050 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2051 my $type = <$fd>;
2052 close $fd or return;
2053 chomp $type;
2054 return $type;
2057 # repository configuration
2058 our $config_file = '';
2059 our %config;
2061 # store multiple values for single key as anonymous array reference
2062 # single values stored directly in the hash, not as [ <value> ]
2063 sub hash_set_multi {
2064 my ($hash, $key, $value) = @_;
2066 if (!exists $hash->{$key}) {
2067 $hash->{$key} = $value;
2068 } elsif (!ref $hash->{$key}) {
2069 $hash->{$key} = [ $hash->{$key}, $value ];
2070 } else {
2071 push @{$hash->{$key}}, $value;
2075 # return hash of git project configuration
2076 # optionally limited to some section, e.g. 'gitweb'
2077 sub git_parse_project_config {
2078 my $section_regexp = shift;
2079 my %config;
2081 local $/ = "\0";
2083 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2084 or return;
2086 while (my $keyval = <$fh>) {
2087 chomp $keyval;
2088 my ($key, $value) = split(/\n/, $keyval, 2);
2090 hash_set_multi(\%config, $key, $value)
2091 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2093 close $fh;
2095 return %config;
2098 # convert config value to boolean: 'true' or 'false'
2099 # no value, number > 0, 'true' and 'yes' values are true
2100 # rest of values are treated as false (never as error)
2101 sub config_to_bool {
2102 my $val = shift;
2104 return 1 if !defined $val; # section.key
2106 # strip leading and trailing whitespace
2107 $val =~ s/^\s+//;
2108 $val =~ s/\s+$//;
2110 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2111 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2114 # convert config value to simple decimal number
2115 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2116 # to be multiplied by 1024, 1048576, or 1073741824
2117 sub config_to_int {
2118 my $val = shift;
2120 # strip leading and trailing whitespace
2121 $val =~ s/^\s+//;
2122 $val =~ s/\s+$//;
2124 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2125 $unit = lc($unit);
2126 # unknown unit is treated as 1
2127 return $num * ($unit eq 'g' ? 1073741824 :
2128 $unit eq 'm' ? 1048576 :
2129 $unit eq 'k' ? 1024 : 1);
2131 return $val;
2134 # convert config value to array reference, if needed
2135 sub config_to_multi {
2136 my $val = shift;
2138 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2141 sub git_get_project_config {
2142 my ($key, $type) = @_;
2144 # key sanity check
2145 return unless ($key);
2146 $key =~ s/^gitweb\.//;
2147 return if ($key =~ m/\W/);
2149 # type sanity check
2150 if (defined $type) {
2151 $type =~ s/^--//;
2152 $type = undef
2153 unless ($type eq 'bool' || $type eq 'int');
2156 # get config
2157 if (!defined $config_file ||
2158 $config_file ne "$git_dir/config") {
2159 %config = git_parse_project_config('gitweb');
2160 $config_file = "$git_dir/config";
2163 # check if config variable (key) exists
2164 return unless exists $config{"gitweb.$key"};
2166 # ensure given type
2167 if (!defined $type) {
2168 return $config{"gitweb.$key"};
2169 } elsif ($type eq 'bool') {
2170 # backward compatibility: 'git config --bool' returns true/false
2171 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2172 } elsif ($type eq 'int') {
2173 return config_to_int($config{"gitweb.$key"});
2175 return $config{"gitweb.$key"};
2178 # get hash of given path at given ref
2179 sub git_get_hash_by_path {
2180 my $base = shift;
2181 my $path = shift || return undef;
2182 my $type = shift;
2184 $path =~ s,/+$,,;
2186 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2187 or die_error(500, "Open git-ls-tree failed");
2188 my $line = <$fd>;
2189 close $fd or return undef;
2191 if (!defined $line) {
2192 # there is no tree or hash given by $path at $base
2193 return undef;
2196 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2197 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2198 if (defined $type && $type ne $2) {
2199 # type doesn't match
2200 return undef;
2202 return $3;
2205 # get path of entry with given hash at given tree-ish (ref)
2206 # used to get 'from' filename for combined diff (merge commit) for renames
2207 sub git_get_path_by_hash {
2208 my $base = shift || return;
2209 my $hash = shift || return;
2211 local $/ = "\0";
2213 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2214 or return undef;
2215 while (my $line = <$fd>) {
2216 chomp $line;
2218 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2219 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2220 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2221 close $fd;
2222 return $1;
2225 close $fd;
2226 return undef;
2229 ## ......................................................................
2230 ## git utility functions, directly accessing git repository
2232 sub git_get_project_description {
2233 my $path = shift;
2235 $git_dir = "$projectroot/$path";
2236 open my $fd, '<', "$git_dir/description"
2237 or return git_get_project_config('description');
2238 my $descr = <$fd>;
2239 close $fd;
2240 if (defined $descr) {
2241 chomp $descr;
2243 return $descr;
2246 sub git_get_project_ctags {
2247 my $path = shift;
2248 my $ctags = {};
2250 $git_dir = "$projectroot/$path";
2251 opendir my $dh, "$git_dir/ctags"
2252 or return $ctags;
2253 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2254 open my $ct, '<', $_ or next;
2255 my $val = <$ct>;
2256 chomp $val;
2257 close $ct;
2258 my $ctag = $_; $ctag =~ s#.*/##;
2259 $ctags->{$ctag} = $val;
2261 closedir $dh;
2262 $ctags;
2265 sub git_populate_project_tagcloud {
2266 my $ctags = shift;
2268 # First, merge different-cased tags; tags vote on casing
2269 my %ctags_lc;
2270 foreach (keys %$ctags) {
2271 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2272 if (not $ctags_lc{lc $_}->{topcount}
2273 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2274 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2275 $ctags_lc{lc $_}->{topname} = $_;
2279 my $cloud;
2280 if (eval { require HTML::TagCloud; 1; }) {
2281 $cloud = HTML::TagCloud->new;
2282 foreach (sort keys %ctags_lc) {
2283 # Pad the title with spaces so that the cloud looks
2284 # less crammed.
2285 my $title = $ctags_lc{$_}->{topname};
2286 $title =~ s/ /&nbsp;/g;
2287 $title =~ s/^/&nbsp;/g;
2288 $title =~ s/$/&nbsp;/g;
2289 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2291 } else {
2292 $cloud = \%ctags_lc;
2294 $cloud;
2297 sub git_show_project_tagcloud {
2298 my ($cloud, $count) = @_;
2299 print STDERR ref($cloud)."..\n";
2300 if (ref $cloud eq 'HTML::TagCloud') {
2301 return $cloud->html_and_css($count);
2302 } else {
2303 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2304 return '<p align="center">' . join (', ', map {
2305 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2306 } splice(@tags, 0, $count)) . '</p>';
2310 sub git_get_project_url_list {
2311 my $path = shift;
2313 $git_dir = "$projectroot/$path";
2314 open my $fd, '<', "$git_dir/cloneurl"
2315 or return wantarray ?
2316 @{ config_to_multi(git_get_project_config('url')) } :
2317 config_to_multi(git_get_project_config('url'));
2318 my @git_project_url_list = map { chomp; $_ } <$fd>;
2319 close $fd;
2321 return wantarray ? @git_project_url_list : \@git_project_url_list;
2324 sub git_get_projects_list {
2325 my ($filter) = @_;
2326 my @list;
2328 $filter ||= '';
2329 $filter =~ s/\.git$//;
2331 my $check_forks = gitweb_check_feature('forks');
2333 if (-d $projects_list) {
2334 # search in directory
2335 my $dir = $projects_list . ($filter ? "/$filter" : '');
2336 # remove the trailing "/"
2337 $dir =~ s!/+$!!;
2338 my $pfxlen = length("$dir");
2339 my $pfxdepth = ($dir =~ tr!/!!);
2341 File::Find::find({
2342 follow_fast => 1, # follow symbolic links
2343 follow_skip => 2, # ignore duplicates
2344 dangling_symlinks => 0, # ignore dangling symlinks, silently
2345 wanted => sub {
2346 # skip project-list toplevel, if we get it.
2347 return if (m!^[/.]$!);
2348 # only directories can be git repositories
2349 return unless (-d $_);
2350 # don't traverse too deep (Find is super slow on os x)
2351 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2352 $File::Find::prune = 1;
2353 return;
2356 my $subdir = substr($File::Find::name, $pfxlen + 1);
2357 # we check related file in $projectroot
2358 my $path = ($filter ? "$filter/" : '') . $subdir;
2359 if (check_export_ok("$projectroot/$path")) {
2360 push @list, { path => $path };
2361 $File::Find::prune = 1;
2364 }, "$dir");
2366 } elsif (-f $projects_list) {
2367 # read from file(url-encoded):
2368 # 'git%2Fgit.git Linus+Torvalds'
2369 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2370 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2371 my %paths;
2372 open my $fd, '<', $projects_list or return;
2373 PROJECT:
2374 while (my $line = <$fd>) {
2375 chomp $line;
2376 my ($path, $owner) = split ' ', $line;
2377 $path = unescape($path);
2378 $owner = unescape($owner);
2379 if (!defined $path) {
2380 next;
2382 if ($filter ne '') {
2383 # looking for forks;
2384 my $pfx = substr($path, 0, length($filter));
2385 if ($pfx ne $filter) {
2386 next PROJECT;
2388 my $sfx = substr($path, length($filter));
2389 if ($sfx !~ /^\/.*\.git$/) {
2390 next PROJECT;
2392 } elsif ($check_forks) {
2393 PATH:
2394 foreach my $filter (keys %paths) {
2395 # looking for forks;
2396 my $pfx = substr($path, 0, length($filter));
2397 if ($pfx ne $filter) {
2398 next PATH;
2400 my $sfx = substr($path, length($filter));
2401 if ($sfx !~ /^\/.*\.git$/) {
2402 next PATH;
2404 # is a fork, don't include it in
2405 # the list
2406 next PROJECT;
2409 if (check_export_ok("$projectroot/$path")) {
2410 my $pr = {
2411 path => $path,
2412 owner => to_utf8($owner),
2414 push @list, $pr;
2415 (my $forks_path = $path) =~ s/\.git$//;
2416 $paths{$forks_path}++;
2419 close $fd;
2421 return @list;
2424 our $gitweb_project_owner = undef;
2425 sub git_get_project_list_from_file {
2427 return if (defined $gitweb_project_owner);
2429 $gitweb_project_owner = {};
2430 # read from file (url-encoded):
2431 # 'git%2Fgit.git Linus+Torvalds'
2432 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2433 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2434 if (-f $projects_list) {
2435 open(my $fd, '<', $projects_list);
2436 while (my $line = <$fd>) {
2437 chomp $line;
2438 my ($pr, $ow) = split ' ', $line;
2439 $pr = unescape($pr);
2440 $ow = unescape($ow);
2441 $gitweb_project_owner->{$pr} = to_utf8($ow);
2443 close $fd;
2447 sub git_get_project_owner {
2448 my $project = shift;
2449 my $owner;
2451 return undef unless $project;
2452 $git_dir = "$projectroot/$project";
2454 if (!defined $gitweb_project_owner) {
2455 git_get_project_list_from_file();
2458 if (exists $gitweb_project_owner->{$project}) {
2459 $owner = $gitweb_project_owner->{$project};
2461 if (!defined $owner){
2462 $owner = git_get_project_config('owner');
2464 if (!defined $owner) {
2465 $owner = get_file_owner("$git_dir");
2468 return $owner;
2471 sub git_get_last_activity {
2472 my ($path) = @_;
2473 my $fd;
2475 $git_dir = "$projectroot/$path";
2476 open($fd, "-|", git_cmd(), 'for-each-ref',
2477 '--format=%(committer)',
2478 '--sort=-committerdate',
2479 '--count=1',
2480 'refs/heads') or return;
2481 my $most_recent = <$fd>;
2482 close $fd or return;
2483 if (defined $most_recent &&
2484 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2485 my $timestamp = $1;
2486 my $age = time - $timestamp;
2487 return ($age, age_string($age));
2489 return (undef, undef);
2492 sub git_get_references {
2493 my $type = shift || "";
2494 my %refs;
2495 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2496 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2497 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2498 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2499 or return;
2501 while (my $line = <$fd>) {
2502 chomp $line;
2503 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2504 if (defined $refs{$1}) {
2505 push @{$refs{$1}}, $2;
2506 } else {
2507 $refs{$1} = [ $2 ];
2511 close $fd or return;
2512 return \%refs;
2515 sub git_get_rev_name_tags {
2516 my $hash = shift || return undef;
2518 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2519 or return;
2520 my $name_rev = <$fd>;
2521 close $fd;
2523 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2524 return $1;
2525 } else {
2526 # catches also '$hash undefined' output
2527 return undef;
2531 ## ----------------------------------------------------------------------
2532 ## parse to hash functions
2534 sub parse_date {
2535 my $epoch = shift;
2536 my $tz = shift || "-0000";
2538 my %date;
2539 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2540 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2541 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2542 $date{'hour'} = $hour;
2543 $date{'minute'} = $min;
2544 $date{'mday'} = $mday;
2545 $date{'day'} = $days[$wday];
2546 $date{'month'} = $months[$mon];
2547 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2548 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2549 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2550 $mday, $months[$mon], $hour ,$min;
2551 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2552 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2554 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2555 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2556 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2557 $date{'hour_local'} = $hour;
2558 $date{'minute_local'} = $min;
2559 $date{'tz_local'} = $tz;
2560 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2561 1900+$year, $mon+1, $mday,
2562 $hour, $min, $sec, $tz);
2563 return %date;
2566 sub parse_tag {
2567 my $tag_id = shift;
2568 my %tag;
2569 my @comment;
2571 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2572 $tag{'id'} = $tag_id;
2573 while (my $line = <$fd>) {
2574 chomp $line;
2575 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2576 $tag{'object'} = $1;
2577 } elsif ($line =~ m/^type (.+)$/) {
2578 $tag{'type'} = $1;
2579 } elsif ($line =~ m/^tag (.+)$/) {
2580 $tag{'name'} = $1;
2581 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2582 $tag{'author'} = $1;
2583 $tag{'author_epoch'} = $2;
2584 $tag{'author_tz'} = $3;
2585 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2586 $tag{'author_name'} = $1;
2587 $tag{'author_email'} = $2;
2588 } else {
2589 $tag{'author_name'} = $tag{'author'};
2591 } elsif ($line =~ m/--BEGIN/) {
2592 push @comment, $line;
2593 last;
2594 } elsif ($line eq "") {
2595 last;
2598 push @comment, <$fd>;
2599 $tag{'comment'} = \@comment;
2600 close $fd or return;
2601 if (!defined $tag{'name'}) {
2602 return
2604 return %tag
2607 sub parse_commit_text {
2608 my ($commit_text, $withparents) = @_;
2609 my @commit_lines = split '\n', $commit_text;
2610 my %co;
2612 pop @commit_lines; # Remove '\0'
2614 if (! @commit_lines) {
2615 return;
2618 my $header = shift @commit_lines;
2619 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2620 return;
2622 ($co{'id'}, my @parents) = split ' ', $header;
2623 while (my $line = shift @commit_lines) {
2624 last if $line eq "\n";
2625 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2626 $co{'tree'} = $1;
2627 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2628 push @parents, $1;
2629 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2630 $co{'author'} = to_utf8($1);
2631 $co{'author_epoch'} = $2;
2632 $co{'author_tz'} = $3;
2633 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2634 $co{'author_name'} = $1;
2635 $co{'author_email'} = $2;
2636 } else {
2637 $co{'author_name'} = $co{'author'};
2639 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2640 $co{'committer'} = to_utf8($1);
2641 $co{'committer_epoch'} = $2;
2642 $co{'committer_tz'} = $3;
2643 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2644 $co{'committer_name'} = $1;
2645 $co{'committer_email'} = $2;
2646 } else {
2647 $co{'committer_name'} = $co{'committer'};
2651 if (!defined $co{'tree'}) {
2652 return;
2654 $co{'parents'} = \@parents;
2655 $co{'parent'} = $parents[0];
2657 foreach my $title (@commit_lines) {
2658 $title =~ s/^ //;
2659 if ($title ne "") {
2660 $co{'title'} = chop_str($title, 80, 5);
2661 # remove leading stuff of merges to make the interesting part visible
2662 if (length($title) > 50) {
2663 $title =~ s/^Automatic //;
2664 $title =~ s/^merge (of|with) /Merge ... /i;
2665 if (length($title) > 50) {
2666 $title =~ s/(http|rsync):\/\///;
2668 if (length($title) > 50) {
2669 $title =~ s/(master|www|rsync)\.//;
2671 if (length($title) > 50) {
2672 $title =~ s/kernel.org:?//;
2674 if (length($title) > 50) {
2675 $title =~ s/\/pub\/scm//;
2678 $co{'title_short'} = chop_str($title, 50, 5);
2679 last;
2682 if (! defined $co{'title'} || $co{'title'} eq "") {
2683 $co{'title'} = $co{'title_short'} = '(no commit message)';
2685 # remove added spaces
2686 foreach my $line (@commit_lines) {
2687 $line =~ s/^ //;
2689 $co{'comment'} = \@commit_lines;
2691 my $age = time - $co{'committer_epoch'};
2692 $co{'age'} = $age;
2693 $co{'age_string'} = age_string($age);
2694 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2695 if ($age > 60*60*24*7*2) {
2696 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2697 $co{'age_string_age'} = $co{'age_string'};
2698 } else {
2699 $co{'age_string_date'} = $co{'age_string'};
2700 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2702 return %co;
2705 sub parse_commit {
2706 my ($commit_id) = @_;
2707 my %co;
2709 local $/ = "\0";
2711 open my $fd, "-|", git_cmd(), "rev-list",
2712 "--parents",
2713 "--header",
2714 "--max-count=1",
2715 $commit_id,
2716 "--",
2717 or die_error(500, "Open git-rev-list failed");
2718 %co = parse_commit_text(<$fd>, 1);
2719 close $fd;
2721 return %co;
2724 sub parse_commits {
2725 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2726 my @cos;
2728 $maxcount ||= 1;
2729 $skip ||= 0;
2731 local $/ = "\0";
2733 open my $fd, "-|", git_cmd(), "rev-list",
2734 "--header",
2735 @args,
2736 ("--max-count=" . $maxcount),
2737 ("--skip=" . $skip),
2738 @extra_options,
2739 $commit_id,
2740 "--",
2741 ($filename ? ($filename) : ())
2742 or die_error(500, "Open git-rev-list failed");
2743 while (my $line = <$fd>) {
2744 my %co = parse_commit_text($line);
2745 push @cos, \%co;
2747 close $fd;
2749 return wantarray ? @cos : \@cos;
2752 # parse line of git-diff-tree "raw" output
2753 sub parse_difftree_raw_line {
2754 my $line = shift;
2755 my %res;
2757 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2758 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2759 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2760 $res{'from_mode'} = $1;
2761 $res{'to_mode'} = $2;
2762 $res{'from_id'} = $3;
2763 $res{'to_id'} = $4;
2764 $res{'status'} = $5;
2765 $res{'similarity'} = $6;
2766 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2767 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2768 } else {
2769 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2772 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2773 # combined diff (for merge commit)
2774 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2775 $res{'nparents'} = length($1);
2776 $res{'from_mode'} = [ split(' ', $2) ];
2777 $res{'to_mode'} = pop @{$res{'from_mode'}};
2778 $res{'from_id'} = [ split(' ', $3) ];
2779 $res{'to_id'} = pop @{$res{'from_id'}};
2780 $res{'status'} = [ split('', $4) ];
2781 $res{'to_file'} = unquote($5);
2783 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2784 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2785 $res{'commit'} = $1;
2788 return wantarray ? %res : \%res;
2791 # wrapper: return parsed line of git-diff-tree "raw" output
2792 # (the argument might be raw line, or parsed info)
2793 sub parsed_difftree_line {
2794 my $line_or_ref = shift;
2796 if (ref($line_or_ref) eq "HASH") {
2797 # pre-parsed (or generated by hand)
2798 return $line_or_ref;
2799 } else {
2800 return parse_difftree_raw_line($line_or_ref);
2804 # parse line of git-ls-tree output
2805 sub parse_ls_tree_line {
2806 my $line = shift;
2807 my %opts = @_;
2808 my %res;
2810 if ($opts{'-l'}) {
2811 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
2812 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
2814 $res{'mode'} = $1;
2815 $res{'type'} = $2;
2816 $res{'hash'} = $3;
2817 $res{'size'} = $4;
2818 if ($opts{'-z'}) {
2819 $res{'name'} = $5;
2820 } else {
2821 $res{'name'} = unquote($5);
2823 } else {
2824 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2825 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2827 $res{'mode'} = $1;
2828 $res{'type'} = $2;
2829 $res{'hash'} = $3;
2830 if ($opts{'-z'}) {
2831 $res{'name'} = $4;
2832 } else {
2833 $res{'name'} = unquote($4);
2837 return wantarray ? %res : \%res;
2840 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2841 sub parse_from_to_diffinfo {
2842 my ($diffinfo, $from, $to, @parents) = @_;
2844 if ($diffinfo->{'nparents'}) {
2845 # combined diff
2846 $from->{'file'} = [];
2847 $from->{'href'} = [];
2848 fill_from_file_info($diffinfo, @parents)
2849 unless exists $diffinfo->{'from_file'};
2850 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2851 $from->{'file'}[$i] =
2852 defined $diffinfo->{'from_file'}[$i] ?
2853 $diffinfo->{'from_file'}[$i] :
2854 $diffinfo->{'to_file'};
2855 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2856 $from->{'href'}[$i] = href(action=>"blob",
2857 hash_base=>$parents[$i],
2858 hash=>$diffinfo->{'from_id'}[$i],
2859 file_name=>$from->{'file'}[$i]);
2860 } else {
2861 $from->{'href'}[$i] = undef;
2864 } else {
2865 # ordinary (not combined) diff
2866 $from->{'file'} = $diffinfo->{'from_file'};
2867 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2868 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2869 hash=>$diffinfo->{'from_id'},
2870 file_name=>$from->{'file'});
2871 } else {
2872 delete $from->{'href'};
2876 $to->{'file'} = $diffinfo->{'to_file'};
2877 if (!is_deleted($diffinfo)) { # file exists in result
2878 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2879 hash=>$diffinfo->{'to_id'},
2880 file_name=>$to->{'file'});
2881 } else {
2882 delete $to->{'href'};
2886 ## ......................................................................
2887 ## parse to array of hashes functions
2889 sub git_get_heads_list {
2890 my $limit = shift;
2891 my @headslist;
2893 open my $fd, '-|', git_cmd(), 'for-each-ref',
2894 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2895 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2896 'refs/heads'
2897 or return;
2898 while (my $line = <$fd>) {
2899 my %ref_item;
2901 chomp $line;
2902 my ($refinfo, $committerinfo) = split(/\0/, $line);
2903 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2904 my ($committer, $epoch, $tz) =
2905 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2906 $ref_item{'fullname'} = $name;
2907 $name =~ s!^refs/heads/!!;
2909 $ref_item{'name'} = $name;
2910 $ref_item{'id'} = $hash;
2911 $ref_item{'title'} = $title || '(no commit message)';
2912 $ref_item{'epoch'} = $epoch;
2913 if ($epoch) {
2914 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2915 } else {
2916 $ref_item{'age'} = "unknown";
2919 push @headslist, \%ref_item;
2921 close $fd;
2923 return wantarray ? @headslist : \@headslist;
2926 sub git_get_tags_list {
2927 my $limit = shift;
2928 my @tagslist;
2930 open my $fd, '-|', git_cmd(), 'for-each-ref',
2931 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2932 '--format=%(objectname) %(objecttype) %(refname) '.
2933 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2934 'refs/tags'
2935 or return;
2936 while (my $line = <$fd>) {
2937 my %ref_item;
2939 chomp $line;
2940 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2941 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2942 my ($creator, $epoch, $tz) =
2943 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2944 $ref_item{'fullname'} = $name;
2945 $name =~ s!^refs/tags/!!;
2947 $ref_item{'type'} = $type;
2948 $ref_item{'id'} = $id;
2949 $ref_item{'name'} = $name;
2950 if ($type eq "tag") {
2951 $ref_item{'subject'} = $title;
2952 $ref_item{'reftype'} = $reftype;
2953 $ref_item{'refid'} = $refid;
2954 } else {
2955 $ref_item{'reftype'} = $type;
2956 $ref_item{'refid'} = $id;
2959 if ($type eq "tag" || $type eq "commit") {
2960 $ref_item{'epoch'} = $epoch;
2961 if ($epoch) {
2962 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2963 } else {
2964 $ref_item{'age'} = "unknown";
2968 push @tagslist, \%ref_item;
2970 close $fd;
2972 return wantarray ? @tagslist : \@tagslist;
2975 ## ----------------------------------------------------------------------
2976 ## filesystem-related functions
2978 sub get_file_owner {
2979 my $path = shift;
2981 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2982 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2983 if (!defined $gcos) {
2984 return undef;
2986 my $owner = $gcos;
2987 $owner =~ s/[,;].*$//;
2988 return to_utf8($owner);
2991 # assume that file exists
2992 sub insert_file {
2993 my $filename = shift;
2995 open my $fd, '<', $filename;
2996 print map { to_utf8($_) } <$fd>;
2997 close $fd;
3000 ## ......................................................................
3001 ## mimetype related functions
3003 sub mimetype_guess_file {
3004 my $filename = shift;
3005 my $mimemap = shift;
3006 -r $mimemap or return undef;
3008 my %mimemap;
3009 open(my $mh, '<', $mimemap) or return undef;
3010 while (<$mh>) {
3011 next if m/^#/; # skip comments
3012 my ($mimetype, $exts) = split(/\t+/);
3013 if (defined $exts) {
3014 my @exts = split(/\s+/, $exts);
3015 foreach my $ext (@exts) {
3016 $mimemap{$ext} = $mimetype;
3020 close($mh);
3022 $filename =~ /\.([^.]*)$/;
3023 return $mimemap{$1};
3026 sub mimetype_guess {
3027 my $filename = shift;
3028 my $mime;
3029 $filename =~ /\./ or return undef;
3031 if ($mimetypes_file) {
3032 my $file = $mimetypes_file;
3033 if ($file !~ m!^/!) { # if it is relative path
3034 # it is relative to project
3035 $file = "$projectroot/$project/$file";
3037 $mime = mimetype_guess_file($filename, $file);
3039 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3040 return $mime;
3043 sub blob_mimetype {
3044 my $fd = shift;
3045 my $filename = shift;
3047 if ($filename) {
3048 my $mime = mimetype_guess($filename);
3049 $mime and return $mime;
3052 # just in case
3053 return $default_blob_plain_mimetype unless $fd;
3055 if (-T $fd) {
3056 return 'text/plain';
3057 } elsif (! $filename) {
3058 return 'application/octet-stream';
3059 } elsif ($filename =~ m/\.png$/i) {
3060 return 'image/png';
3061 } elsif ($filename =~ m/\.gif$/i) {
3062 return 'image/gif';
3063 } elsif ($filename =~ m/\.jpe?g$/i) {
3064 return 'image/jpeg';
3065 } else {
3066 return 'application/octet-stream';
3070 sub blob_contenttype {
3071 my ($fd, $file_name, $type) = @_;
3073 $type ||= blob_mimetype($fd, $file_name);
3074 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3075 $type .= "; charset=$default_text_plain_charset";
3078 return $type;
3081 ## ======================================================================
3082 ## functions printing HTML: header, footer, error page
3084 sub git_header_html {
3085 my $status = shift || "200 OK";
3086 my $expires = shift;
3088 my $title = "$site_name";
3089 if (defined $project) {
3090 $title .= " - " . to_utf8($project);
3091 if (defined $action) {
3092 $title .= "/$action";
3093 if (defined $file_name) {
3094 $title .= " - " . esc_path($file_name);
3095 if ($action eq "tree" && $file_name !~ m|/$|) {
3096 $title .= "/";
3101 my $content_type;
3102 # require explicit support from the UA if we are to send the page as
3103 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3104 # we have to do this because MSIE sometimes globs '*/*', pretending to
3105 # support xhtml+xml but choking when it gets what it asked for.
3106 if (defined $cgi->http('HTTP_ACCEPT') &&
3107 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3108 $cgi->Accept('application/xhtml+xml') != 0) {
3109 $content_type = 'application/xhtml+xml';
3110 } else {
3111 $content_type = 'text/html';
3113 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3114 -status=> $status, -expires => $expires);
3115 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3116 print <<EOF;
3117 <?xml version="1.0" encoding="utf-8"?>
3118 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3119 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3120 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3121 <!-- git core binaries version $git_version -->
3122 <head>
3123 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3124 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3125 <meta name="robots" content="index, nofollow"/>
3126 <title>$title</title>
3128 # the stylesheet, favicon etc urls won't work correctly with path_info
3129 # unless we set the appropriate base URL
3130 if ($ENV{'PATH_INFO'}) {
3131 print "<base href=\"".esc_url($base_url)."\" />\n";
3133 # print out each stylesheet that exist, providing backwards capability
3134 # for those people who defined $stylesheet in a config file
3135 if (defined $stylesheet) {
3136 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3137 } else {
3138 foreach my $stylesheet (@stylesheets) {
3139 next unless $stylesheet;
3140 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3143 if (defined $project) {
3144 my %href_params = get_feed_info();
3145 if (!exists $href_params{'-title'}) {
3146 $href_params{'-title'} = 'log';
3149 foreach my $format qw(RSS Atom) {
3150 my $type = lc($format);
3151 my %link_attr = (
3152 '-rel' => 'alternate',
3153 '-title' => "$project - $href_params{'-title'} - $format feed",
3154 '-type' => "application/$type+xml"
3157 $href_params{'action'} = $type;
3158 $link_attr{'-href'} = href(%href_params);
3159 print "<link ".
3160 "rel=\"$link_attr{'-rel'}\" ".
3161 "title=\"$link_attr{'-title'}\" ".
3162 "href=\"$link_attr{'-href'}\" ".
3163 "type=\"$link_attr{'-type'}\" ".
3164 "/>\n";
3166 $href_params{'extra_options'} = '--no-merges';
3167 $link_attr{'-href'} = href(%href_params);
3168 $link_attr{'-title'} .= ' (no merges)';
3169 print "<link ".
3170 "rel=\"$link_attr{'-rel'}\" ".
3171 "title=\"$link_attr{'-title'}\" ".
3172 "href=\"$link_attr{'-href'}\" ".
3173 "type=\"$link_attr{'-type'}\" ".
3174 "/>\n";
3177 } else {
3178 printf('<link rel="alternate" title="%s projects list" '.
3179 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3180 $site_name, href(project=>undef, action=>"project_index"));
3181 printf('<link rel="alternate" title="%s projects feeds" '.
3182 'href="%s" type="text/x-opml" />'."\n",
3183 $site_name, href(project=>undef, action=>"opml"));
3185 if (defined $favicon) {
3186 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3189 print "</head>\n" .
3190 "<body>\n";
3192 if (-f $site_header) {
3193 insert_file($site_header);
3196 print "<div class=\"page_header\">\n" .
3197 $cgi->a({-href => esc_url($logo_url),
3198 -title => $logo_label},
3199 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3200 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3201 if (defined $project) {
3202 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3203 if (defined $action) {
3204 print " / $action";
3206 print "\n";
3208 print "</div>\n";
3210 my $have_search = gitweb_check_feature('search');
3211 if (defined $project && $have_search) {
3212 if (!defined $searchtext) {
3213 $searchtext = "";
3215 my $search_hash;
3216 if (defined $hash_base) {
3217 $search_hash = $hash_base;
3218 } elsif (defined $hash) {
3219 $search_hash = $hash;
3220 } else {
3221 $search_hash = "HEAD";
3223 my $action = $my_uri;
3224 my $use_pathinfo = gitweb_check_feature('pathinfo');
3225 if ($use_pathinfo) {
3226 $action .= "/".esc_url($project);
3228 print $cgi->startform(-method => "get", -action => $action) .
3229 "<div class=\"search\">\n" .
3230 (!$use_pathinfo &&
3231 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3232 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3233 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3234 $cgi->popup_menu(-name => 'st', -default => 'commit',
3235 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3236 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3237 " search:\n",
3238 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3239 "<span title=\"Extended regular expression\">" .
3240 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3241 -checked => $search_use_regexp) .
3242 "</span>" .
3243 "</div>" .
3244 $cgi->end_form() . "\n";
3248 sub git_footer_html {
3249 my $feed_class = 'rss_logo';
3251 print "<div class=\"page_footer\">\n";
3252 if (defined $project) {
3253 my $descr = git_get_project_description($project);
3254 if (defined $descr) {
3255 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3258 my %href_params = get_feed_info();
3259 if (!%href_params) {
3260 $feed_class .= ' generic';
3262 $href_params{'-title'} ||= 'log';
3264 foreach my $format qw(RSS Atom) {
3265 $href_params{'action'} = lc($format);
3266 print $cgi->a({-href => href(%href_params),
3267 -title => "$href_params{'-title'} $format feed",
3268 -class => $feed_class}, $format)."\n";
3271 } else {
3272 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3273 -class => $feed_class}, "OPML") . " ";
3274 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3275 -class => $feed_class}, "TXT") . "\n";
3277 print "</div>\n"; # class="page_footer"
3279 if (-f $site_footer) {
3280 insert_file($site_footer);
3283 print "</body>\n" .
3284 "</html>";
3287 # die_error(<http_status_code>, <error_message>)
3288 # Example: die_error(404, 'Hash not found')
3289 # By convention, use the following status codes (as defined in RFC 2616):
3290 # 400: Invalid or missing CGI parameters, or
3291 # requested object exists but has wrong type.
3292 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3293 # this server or project.
3294 # 404: Requested object/revision/project doesn't exist.
3295 # 500: The server isn't configured properly, or
3296 # an internal error occurred (e.g. failed assertions caused by bugs), or
3297 # an unknown error occurred (e.g. the git binary died unexpectedly).
3298 sub die_error {
3299 my $status = shift || 500;
3300 my $error = shift || "Internal server error";
3302 my %http_responses = (400 => '400 Bad Request',
3303 403 => '403 Forbidden',
3304 404 => '404 Not Found',
3305 500 => '500 Internal Server Error');
3306 git_header_html($http_responses{$status});
3307 print <<EOF;
3308 <div class="page_body">
3309 <br /><br />
3310 $status - $error
3311 <br />
3312 </div>
3314 git_footer_html();
3315 exit;
3318 ## ----------------------------------------------------------------------
3319 ## functions printing or outputting HTML: navigation
3321 sub git_print_page_nav {
3322 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3323 $extra = '' if !defined $extra; # pager or formats
3325 my @navs = qw(summary shortlog log commit commitdiff tree);
3326 if ($suppress) {
3327 @navs = grep { $_ ne $suppress } @navs;
3330 my %arg = map { $_ => {action=>$_} } @navs;
3331 if (defined $head) {
3332 for (qw(commit commitdiff)) {
3333 $arg{$_}{'hash'} = $head;
3335 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3336 for (qw(shortlog log)) {
3337 $arg{$_}{'hash'} = $head;
3342 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3343 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3345 my @actions = gitweb_get_feature('actions');
3346 my %repl = (
3347 '%' => '%',
3348 'n' => $project, # project name
3349 'f' => $git_dir, # project path within filesystem
3350 'h' => $treehead || '', # current hash ('h' parameter)
3351 'b' => $treebase || '', # hash base ('hb' parameter)
3353 while (@actions) {
3354 my ($label, $link, $pos) = splice(@actions,0,3);
3355 # insert
3356 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3357 # munch munch
3358 $link =~ s/%([%nfhb])/$repl{$1}/g;
3359 $arg{$label}{'_href'} = $link;
3362 print "<div class=\"page_nav\">\n" .
3363 (join " | ",
3364 map { $_ eq $current ?
3365 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3366 } @navs);
3367 print "<br/>\n$extra<br/>\n" .
3368 "</div>\n";
3371 sub format_paging_nav {
3372 my ($action, $hash, $head, $page, $has_next_link) = @_;
3373 my $paging_nav;
3376 if ($hash ne $head || $page) {
3377 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3378 } else {
3379 $paging_nav .= "HEAD";
3382 if ($page > 0) {
3383 $paging_nav .= " &sdot; " .
3384 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3385 -accesskey => "p", -title => "Alt-p"}, "prev");
3386 } else {
3387 $paging_nav .= " &sdot; prev";
3390 if ($has_next_link) {
3391 $paging_nav .= " &sdot; " .
3392 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3393 -accesskey => "n", -title => "Alt-n"}, "next");
3394 } else {
3395 $paging_nav .= " &sdot; next";
3398 return $paging_nav;
3401 ## ......................................................................
3402 ## functions printing or outputting HTML: div
3404 sub git_print_header_div {
3405 my ($action, $title, $hash, $hash_base) = @_;
3406 my %args = ();
3408 $args{'action'} = $action;
3409 $args{'hash'} = $hash if $hash;
3410 $args{'hash_base'} = $hash_base if $hash_base;
3412 print "<div class=\"header\">\n" .
3413 $cgi->a({-href => href(%args), -class => "title"},
3414 $title ? $title : $action) .
3415 "\n</div>\n";
3418 sub print_local_time {
3419 my %date = @_;
3420 if ($date{'hour_local'} < 6) {
3421 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3422 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3423 } else {
3424 printf(" (%02d:%02d %s)",
3425 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3429 # Outputs the author name and date in long form
3430 sub git_print_authorship {
3431 my $co = shift;
3432 my %opts = @_;
3433 my $tag = $opts{-tag} || 'div';
3434 my $author = $co->{'author_name'};
3436 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3437 print "<$tag class=\"author_date\">" .
3438 format_search_author($author, "author", esc_html($author)) .
3439 " [$ad{'rfc2822'}";
3440 print_local_time(%ad) if ($opts{-localtime});
3441 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3442 . "</$tag>\n";
3445 # Outputs table rows containing the full author or committer information,
3446 # in the format expected for 'commit' view (& similia).
3447 # Parameters are a commit hash reference, followed by the list of people
3448 # to output information for. If the list is empty it defalts to both
3449 # author and committer.
3450 sub git_print_authorship_rows {
3451 my $co = shift;
3452 # too bad we can't use @people = @_ || ('author', 'committer')
3453 my @people = @_;
3454 @people = ('author', 'committer') unless @people;
3455 foreach my $who (@people) {
3456 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3457 print "<tr><td>$who</td><td>" .
3458 format_search_author($co->{"${who}_name"}, $who,
3459 esc_html($co->{"${who}_name"})) . " " .
3460 format_search_author($co->{"${who}_email"}, $who,
3461 esc_html("<" . $co->{"${who}_email"} . ">")) .
3462 "</td><td rowspan=\"2\">" .
3463 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3464 "</td></tr>\n" .
3465 "<tr>" .
3466 "<td></td><td> $wd{'rfc2822'}";
3467 print_local_time(%wd);
3468 print "</td>" .
3469 "</tr>\n";
3473 sub git_print_page_path {
3474 my $name = shift;
3475 my $type = shift;
3476 my $hb = shift;
3479 print "<div class=\"page_path\">";
3480 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3481 -title => 'tree root'}, to_utf8("[$project]"));
3482 print " / ";
3483 if (defined $name) {
3484 my @dirname = split '/', $name;
3485 my $basename = pop @dirname;
3486 my $fullname = '';
3488 foreach my $dir (@dirname) {
3489 $fullname .= ($fullname ? '/' : '') . $dir;
3490 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3491 hash_base=>$hb),
3492 -title => $fullname}, esc_path($dir));
3493 print " / ";
3495 if (defined $type && $type eq 'blob') {
3496 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3497 hash_base=>$hb),
3498 -title => $name}, esc_path($basename));
3499 } elsif (defined $type && $type eq 'tree') {
3500 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3501 hash_base=>$hb),
3502 -title => $name}, esc_path($basename));
3503 print " / ";
3504 } else {
3505 print esc_path($basename);
3508 print "<br/></div>\n";
3511 sub git_print_log {
3512 my $log = shift;
3513 my %opts = @_;
3515 if ($opts{'-remove_title'}) {
3516 # remove title, i.e. first line of log
3517 shift @$log;
3519 # remove leading empty lines
3520 while (defined $log->[0] && $log->[0] eq "") {
3521 shift @$log;
3524 # print log
3525 my $signoff = 0;
3526 my $empty = 0;
3527 foreach my $line (@$log) {
3528 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3529 $signoff = 1;
3530 $empty = 0;
3531 if (! $opts{'-remove_signoff'}) {
3532 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3533 next;
3534 } else {
3535 # remove signoff lines
3536 next;
3538 } else {
3539 $signoff = 0;
3542 # print only one empty line
3543 # do not print empty line after signoff
3544 if ($line eq "") {
3545 next if ($empty || $signoff);
3546 $empty = 1;
3547 } else {
3548 $empty = 0;
3551 print format_log_line_html($line) . "<br/>\n";
3554 if ($opts{'-final_empty_line'}) {
3555 # end with single empty line
3556 print "<br/>\n" unless $empty;
3560 # return link target (what link points to)
3561 sub git_get_link_target {
3562 my $hash = shift;
3563 my $link_target;
3565 # read link
3566 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3567 or return;
3569 local $/ = undef;
3570 $link_target = <$fd>;
3572 close $fd
3573 or return;
3575 return $link_target;
3578 # given link target, and the directory (basedir) the link is in,
3579 # return target of link relative to top directory (top tree);
3580 # return undef if it is not possible (including absolute links).
3581 sub normalize_link_target {
3582 my ($link_target, $basedir) = @_;
3584 # absolute symlinks (beginning with '/') cannot be normalized
3585 return if (substr($link_target, 0, 1) eq '/');
3587 # normalize link target to path from top (root) tree (dir)
3588 my $path;
3589 if ($basedir) {
3590 $path = $basedir . '/' . $link_target;
3591 } else {
3592 # we are in top (root) tree (dir)
3593 $path = $link_target;
3596 # remove //, /./, and /../
3597 my @path_parts;
3598 foreach my $part (split('/', $path)) {
3599 # discard '.' and ''
3600 next if (!$part || $part eq '.');
3601 # handle '..'
3602 if ($part eq '..') {
3603 if (@path_parts) {
3604 pop @path_parts;
3605 } else {
3606 # link leads outside repository (outside top dir)
3607 return;
3609 } else {
3610 push @path_parts, $part;
3613 $path = join('/', @path_parts);
3615 return $path;
3618 # print tree entry (row of git_tree), but without encompassing <tr> element
3619 sub git_print_tree_entry {
3620 my ($t, $basedir, $hash_base, $have_blame) = @_;
3622 my %base_key = ();
3623 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3625 # The format of a table row is: mode list link. Where mode is
3626 # the mode of the entry, list is the name of the entry, an href,
3627 # and link is the action links of the entry.
3629 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3630 if (exists $t->{'size'}) {
3631 print "<td class=\"size\">$t->{'size'}</td>\n";
3633 if ($t->{'type'} eq "blob") {
3634 print "<td class=\"list\">" .
3635 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3636 file_name=>"$basedir$t->{'name'}", %base_key),
3637 -class => "list"}, esc_path($t->{'name'}));
3638 if (S_ISLNK(oct $t->{'mode'})) {
3639 my $link_target = git_get_link_target($t->{'hash'});
3640 if ($link_target) {
3641 my $norm_target = normalize_link_target($link_target, $basedir);
3642 if (defined $norm_target) {
3643 print " -> " .
3644 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3645 file_name=>$norm_target),
3646 -title => $norm_target}, esc_path($link_target));
3647 } else {
3648 print " -> " . esc_path($link_target);
3652 print "</td>\n";
3653 print "<td class=\"link\">";
3654 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3655 file_name=>"$basedir$t->{'name'}", %base_key)},
3656 "blob");
3657 if ($have_blame) {
3658 print " | " .
3659 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3660 file_name=>"$basedir$t->{'name'}", %base_key)},
3661 "blame");
3663 if (defined $hash_base) {
3664 print " | " .
3665 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3666 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3667 "history");
3669 print " | " .
3670 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3671 file_name=>"$basedir$t->{'name'}")},
3672 "raw");
3673 print "</td>\n";
3675 } elsif ($t->{'type'} eq "tree") {
3676 print "<td class=\"list\">";
3677 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3678 file_name=>"$basedir$t->{'name'}",
3679 %base_key)},
3680 esc_path($t->{'name'}));
3681 print "</td>\n";
3682 print "<td class=\"link\">";
3683 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3684 file_name=>"$basedir$t->{'name'}",
3685 %base_key)},
3686 "tree");
3687 if (defined $hash_base) {
3688 print " | " .
3689 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3690 file_name=>"$basedir$t->{'name'}")},
3691 "history");
3693 print "</td>\n";
3694 } else {
3695 # unknown object: we can only present history for it
3696 # (this includes 'commit' object, i.e. submodule support)
3697 print "<td class=\"list\">" .
3698 esc_path($t->{'name'}) .
3699 "</td>\n";
3700 print "<td class=\"link\">";
3701 if (defined $hash_base) {
3702 print $cgi->a({-href => href(action=>"history",
3703 hash_base=>$hash_base,
3704 file_name=>"$basedir$t->{'name'}")},
3705 "history");
3707 print "</td>\n";
3711 ## ......................................................................
3712 ## functions printing large fragments of HTML
3714 # get pre-image filenames for merge (combined) diff
3715 sub fill_from_file_info {
3716 my ($diff, @parents) = @_;
3718 $diff->{'from_file'} = [ ];
3719 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3720 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3721 if ($diff->{'status'}[$i] eq 'R' ||
3722 $diff->{'status'}[$i] eq 'C') {
3723 $diff->{'from_file'}[$i] =
3724 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3728 return $diff;
3731 # is current raw difftree line of file deletion
3732 sub is_deleted {
3733 my $diffinfo = shift;
3735 return $diffinfo->{'to_id'} eq ('0' x 40);
3738 # does patch correspond to [previous] difftree raw line
3739 # $diffinfo - hashref of parsed raw diff format
3740 # $patchinfo - hashref of parsed patch diff format
3741 # (the same keys as in $diffinfo)
3742 sub is_patch_split {
3743 my ($diffinfo, $patchinfo) = @_;
3745 return defined $diffinfo && defined $patchinfo
3746 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3750 sub git_difftree_body {
3751 my ($difftree, $hash, @parents) = @_;
3752 my ($parent) = $parents[0];
3753 my $have_blame = gitweb_check_feature('blame');
3754 print "<div class=\"list_head\">\n";
3755 if ($#{$difftree} > 10) {
3756 print(($#{$difftree} + 1) . " files changed:\n");
3758 print "</div>\n";
3760 print "<table class=\"" .
3761 (@parents > 1 ? "combined " : "") .
3762 "diff_tree\">\n";
3764 # header only for combined diff in 'commitdiff' view
3765 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3766 if ($has_header) {
3767 # table header
3768 print "<thead><tr>\n" .
3769 "<th></th><th></th>\n"; # filename, patchN link
3770 for (my $i = 0; $i < @parents; $i++) {
3771 my $par = $parents[$i];
3772 print "<th>" .
3773 $cgi->a({-href => href(action=>"commitdiff",
3774 hash=>$hash, hash_parent=>$par),
3775 -title => 'commitdiff to parent number ' .
3776 ($i+1) . ': ' . substr($par,0,7)},
3777 $i+1) .
3778 "&nbsp;</th>\n";
3780 print "</tr></thead>\n<tbody>\n";
3783 my $alternate = 1;
3784 my $patchno = 0;
3785 foreach my $line (@{$difftree}) {
3786 my $diff = parsed_difftree_line($line);
3788 if ($alternate) {
3789 print "<tr class=\"dark\">\n";
3790 } else {
3791 print "<tr class=\"light\">\n";
3793 $alternate ^= 1;
3795 if (exists $diff->{'nparents'}) { # combined diff
3797 fill_from_file_info($diff, @parents)
3798 unless exists $diff->{'from_file'};
3800 if (!is_deleted($diff)) {
3801 # file exists in the result (child) commit
3802 print "<td>" .
3803 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3804 file_name=>$diff->{'to_file'},
3805 hash_base=>$hash),
3806 -class => "list"}, esc_path($diff->{'to_file'})) .
3807 "</td>\n";
3808 } else {
3809 print "<td>" .
3810 esc_path($diff->{'to_file'}) .
3811 "</td>\n";
3814 if ($action eq 'commitdiff') {
3815 # link to patch
3816 $patchno++;
3817 print "<td class=\"link\">" .
3818 $cgi->a({-href => "#patch$patchno"}, "patch") .
3819 " | " .
3820 "</td>\n";
3823 my $has_history = 0;
3824 my $not_deleted = 0;
3825 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3826 my $hash_parent = $parents[$i];
3827 my $from_hash = $diff->{'from_id'}[$i];
3828 my $from_path = $diff->{'from_file'}[$i];
3829 my $status = $diff->{'status'}[$i];
3831 $has_history ||= ($status ne 'A');
3832 $not_deleted ||= ($status ne 'D');
3834 if ($status eq 'A') {
3835 print "<td class=\"link\" align=\"right\"> | </td>\n";
3836 } elsif ($status eq 'D') {
3837 print "<td class=\"link\">" .
3838 $cgi->a({-href => href(action=>"blob",
3839 hash_base=>$hash,
3840 hash=>$from_hash,
3841 file_name=>$from_path)},
3842 "blob" . ($i+1)) .
3843 " | </td>\n";
3844 } else {
3845 if ($diff->{'to_id'} eq $from_hash) {
3846 print "<td class=\"link nochange\">";
3847 } else {
3848 print "<td class=\"link\">";
3850 print $cgi->a({-href => href(action=>"blobdiff",
3851 hash=>$diff->{'to_id'},
3852 hash_parent=>$from_hash,
3853 hash_base=>$hash,
3854 hash_parent_base=>$hash_parent,
3855 file_name=>$diff->{'to_file'},
3856 file_parent=>$from_path)},
3857 "diff" . ($i+1)) .
3858 " | </td>\n";
3862 print "<td class=\"link\">";
3863 if ($not_deleted) {
3864 print $cgi->a({-href => href(action=>"blob",
3865 hash=>$diff->{'to_id'},
3866 file_name=>$diff->{'to_file'},
3867 hash_base=>$hash)},
3868 "blob");
3869 print " | " if ($has_history);
3871 if ($has_history) {
3872 print $cgi->a({-href => href(action=>"history",
3873 file_name=>$diff->{'to_file'},
3874 hash_base=>$hash)},
3875 "history");
3877 print "</td>\n";
3879 print "</tr>\n";
3880 next; # instead of 'else' clause, to avoid extra indent
3882 # else ordinary diff
3884 my ($to_mode_oct, $to_mode_str, $to_file_type);
3885 my ($from_mode_oct, $from_mode_str, $from_file_type);
3886 if ($diff->{'to_mode'} ne ('0' x 6)) {
3887 $to_mode_oct = oct $diff->{'to_mode'};
3888 if (S_ISREG($to_mode_oct)) { # only for regular file
3889 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3891 $to_file_type = file_type($diff->{'to_mode'});
3893 if ($diff->{'from_mode'} ne ('0' x 6)) {
3894 $from_mode_oct = oct $diff->{'from_mode'};
3895 if (S_ISREG($to_mode_oct)) { # only for regular file
3896 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3898 $from_file_type = file_type($diff->{'from_mode'});
3901 if ($diff->{'status'} eq "A") { # created
3902 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3903 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3904 $mode_chng .= "]</span>";
3905 print "<td>";
3906 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3907 hash_base=>$hash, file_name=>$diff->{'file'}),
3908 -class => "list"}, esc_path($diff->{'file'}));
3909 print "</td>\n";
3910 print "<td>$mode_chng</td>\n";
3911 print "<td class=\"link\">";
3912 if ($action eq 'commitdiff') {
3913 # link to patch
3914 $patchno++;
3915 print $cgi->a({-href => "#patch$patchno"}, "patch");
3916 print " | ";
3918 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3919 hash_base=>$hash, file_name=>$diff->{'file'})},
3920 "blob");
3921 print "</td>\n";
3923 } elsif ($diff->{'status'} eq "D") { # deleted
3924 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3925 print "<td>";
3926 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3927 hash_base=>$parent, file_name=>$diff->{'file'}),
3928 -class => "list"}, esc_path($diff->{'file'}));
3929 print "</td>\n";
3930 print "<td>$mode_chng</td>\n";
3931 print "<td class=\"link\">";
3932 if ($action eq 'commitdiff') {
3933 # link to patch
3934 $patchno++;
3935 print $cgi->a({-href => "#patch$patchno"}, "patch");
3936 print " | ";
3938 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3939 hash_base=>$parent, file_name=>$diff->{'file'})},
3940 "blob") . " | ";
3941 if ($have_blame) {
3942 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3943 file_name=>$diff->{'file'})},
3944 "blame") . " | ";
3946 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3947 file_name=>$diff->{'file'})},
3948 "history");
3949 print "</td>\n";
3951 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3952 my $mode_chnge = "";
3953 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3954 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3955 if ($from_file_type ne $to_file_type) {
3956 $mode_chnge .= " from $from_file_type to $to_file_type";
3958 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3959 if ($from_mode_str && $to_mode_str) {
3960 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3961 } elsif ($to_mode_str) {
3962 $mode_chnge .= " mode: $to_mode_str";
3965 $mode_chnge .= "]</span>\n";
3967 print "<td>";
3968 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3969 hash_base=>$hash, file_name=>$diff->{'file'}),
3970 -class => "list"}, esc_path($diff->{'file'}));
3971 print "</td>\n";
3972 print "<td>$mode_chnge</td>\n";
3973 print "<td class=\"link\">";
3974 if ($action eq 'commitdiff') {
3975 # link to patch
3976 $patchno++;
3977 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3978 " | ";
3979 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3980 # "commit" view and modified file (not onlu mode changed)
3981 print $cgi->a({-href => href(action=>"blobdiff",
3982 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3983 hash_base=>$hash, hash_parent_base=>$parent,
3984 file_name=>$diff->{'file'})},
3985 "diff") .
3986 " | ";
3988 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3989 hash_base=>$hash, file_name=>$diff->{'file'})},
3990 "blob") . " | ";
3991 if ($have_blame) {
3992 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3993 file_name=>$diff->{'file'})},
3994 "blame") . " | ";
3996 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3997 file_name=>$diff->{'file'})},
3998 "history");
3999 print "</td>\n";
4001 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4002 my %status_name = ('R' => 'moved', 'C' => 'copied');
4003 my $nstatus = $status_name{$diff->{'status'}};
4004 my $mode_chng = "";
4005 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4006 # mode also for directories, so we cannot use $to_mode_str
4007 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4009 print "<td>" .
4010 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4011 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4012 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4013 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4014 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4015 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4016 -class => "list"}, esc_path($diff->{'from_file'})) .
4017 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4018 "<td class=\"link\">";
4019 if ($action eq 'commitdiff') {
4020 # link to patch
4021 $patchno++;
4022 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4023 " | ";
4024 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4025 # "commit" view and modified file (not only pure rename or copy)
4026 print $cgi->a({-href => href(action=>"blobdiff",
4027 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4028 hash_base=>$hash, hash_parent_base=>$parent,
4029 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4030 "diff") .
4031 " | ";
4033 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4034 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4035 "blob") . " | ";
4036 if ($have_blame) {
4037 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4038 file_name=>$diff->{'to_file'})},
4039 "blame") . " | ";
4041 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4042 file_name=>$diff->{'to_file'})},
4043 "history");
4044 print "</td>\n";
4046 } # we should not encounter Unmerged (U) or Unknown (X) status
4047 print "</tr>\n";
4049 print "</tbody>" if $has_header;
4050 print "</table>\n";
4053 sub git_patchset_body {
4054 my ($fd, $difftree, $hash, @hash_parents) = @_;
4055 my ($hash_parent) = $hash_parents[0];
4057 my $is_combined = (@hash_parents > 1);
4058 my $patch_idx = 0;
4059 my $patch_number = 0;
4060 my $patch_line;
4061 my $diffinfo;
4062 my $to_name;
4063 my (%from, %to);
4065 print "<div class=\"patchset\">\n";
4067 # skip to first patch
4068 while ($patch_line = <$fd>) {
4069 chomp $patch_line;
4071 last if ($patch_line =~ m/^diff /);
4074 PATCH:
4075 while ($patch_line) {
4077 # parse "git diff" header line
4078 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4079 # $1 is from_name, which we do not use
4080 $to_name = unquote($2);
4081 $to_name =~ s!^b/!!;
4082 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4083 # $1 is 'cc' or 'combined', which we do not use
4084 $to_name = unquote($2);
4085 } else {
4086 $to_name = undef;
4089 # check if current patch belong to current raw line
4090 # and parse raw git-diff line if needed
4091 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4092 # this is continuation of a split patch
4093 print "<div class=\"patch cont\">\n";
4094 } else {
4095 # advance raw git-diff output if needed
4096 $patch_idx++ if defined $diffinfo;
4098 # read and prepare patch information
4099 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4101 # compact combined diff output can have some patches skipped
4102 # find which patch (using pathname of result) we are at now;
4103 if ($is_combined) {
4104 while ($to_name ne $diffinfo->{'to_file'}) {
4105 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4106 format_diff_cc_simplified($diffinfo, @hash_parents) .
4107 "</div>\n"; # class="patch"
4109 $patch_idx++;
4110 $patch_number++;
4112 last if $patch_idx > $#$difftree;
4113 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4117 # modifies %from, %to hashes
4118 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4120 # this is first patch for raw difftree line with $patch_idx index
4121 # we index @$difftree array from 0, but number patches from 1
4122 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4125 # git diff header
4126 #assert($patch_line =~ m/^diff /) if DEBUG;
4127 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4128 $patch_number++;
4129 # print "git diff" header
4130 print format_git_diff_header_line($patch_line, $diffinfo,
4131 \%from, \%to);
4133 # print extended diff header
4134 print "<div class=\"diff extended_header\">\n";
4135 EXTENDED_HEADER:
4136 while ($patch_line = <$fd>) {
4137 chomp $patch_line;
4139 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4141 print format_extended_diff_header_line($patch_line, $diffinfo,
4142 \%from, \%to);
4144 print "</div>\n"; # class="diff extended_header"
4146 # from-file/to-file diff header
4147 if (! $patch_line) {
4148 print "</div>\n"; # class="patch"
4149 last PATCH;
4151 next PATCH if ($patch_line =~ m/^diff /);
4152 #assert($patch_line =~ m/^---/) if DEBUG;
4154 my $last_patch_line = $patch_line;
4155 $patch_line = <$fd>;
4156 chomp $patch_line;
4157 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4159 print format_diff_from_to_header($last_patch_line, $patch_line,
4160 $diffinfo, \%from, \%to,
4161 @hash_parents);
4163 # the patch itself
4164 LINE:
4165 while ($patch_line = <$fd>) {
4166 chomp $patch_line;
4168 next PATCH if ($patch_line =~ m/^diff /);
4170 print format_diff_line($patch_line, \%from, \%to);
4173 } continue {
4174 print "</div>\n"; # class="patch"
4177 # for compact combined (--cc) format, with chunk and patch simpliciaction
4178 # patchset might be empty, but there might be unprocessed raw lines
4179 for (++$patch_idx if $patch_number > 0;
4180 $patch_idx < @$difftree;
4181 ++$patch_idx) {
4182 # read and prepare patch information
4183 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4185 # generate anchor for "patch" links in difftree / whatchanged part
4186 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4187 format_diff_cc_simplified($diffinfo, @hash_parents) .
4188 "</div>\n"; # class="patch"
4190 $patch_number++;
4193 if ($patch_number == 0) {
4194 if (@hash_parents > 1) {
4195 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4196 } else {
4197 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4201 print "</div>\n"; # class="patchset"
4204 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4206 # fills project list info (age, description, owner, forks) for each
4207 # project in the list, removing invalid projects from returned list
4208 # NOTE: modifies $projlist, but does not remove entries from it
4209 sub fill_project_list_info {
4210 my ($projlist, $check_forks) = @_;
4211 my @projects;
4213 my $show_ctags = gitweb_check_feature('ctags');
4214 PROJECT:
4215 foreach my $pr (@$projlist) {
4216 my (@activity) = git_get_last_activity($pr->{'path'});
4217 unless (@activity) {
4218 next PROJECT;
4220 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4221 if (!defined $pr->{'descr'}) {
4222 my $descr = git_get_project_description($pr->{'path'}) || "";
4223 $descr = to_utf8($descr);
4224 $pr->{'descr_long'} = $descr;
4225 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4227 if (!defined $pr->{'owner'}) {
4228 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4230 if ($check_forks) {
4231 my $pname = $pr->{'path'};
4232 if (($pname =~ s/\.git$//) &&
4233 ($pname !~ /\/$/) &&
4234 (-d "$projectroot/$pname")) {
4235 $pr->{'forks'} = "-d $projectroot/$pname";
4236 } else {
4237 $pr->{'forks'} = 0;
4240 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4241 push @projects, $pr;
4244 return @projects;
4247 # print 'sort by' <th> element, generating 'sort by $name' replay link
4248 # if that order is not selected
4249 sub print_sort_th {
4250 my ($name, $order, $header) = @_;
4251 $header ||= ucfirst($name);
4253 if ($order eq $name) {
4254 print "<th>$header</th>\n";
4255 } else {
4256 print "<th>" .
4257 $cgi->a({-href => href(-replay=>1, order=>$name),
4258 -class => "header"}, $header) .
4259 "</th>\n";
4263 sub git_project_list_ctags {
4264 my ($projects) = @_;
4266 my $show_ctags = gitweb_check_feature('ctags');
4267 if ($show_ctags) {
4268 my %ctags;
4269 foreach my $p (@$projects) {
4270 foreach my $ct (keys %{$p->{'ctags'}}) {
4271 $ctags{$ct} += $p->{'ctags'}->{$ct};
4274 my $cloud = git_populate_project_tagcloud(\%ctags);
4275 print git_show_project_tagcloud($cloud, 64);
4279 sub git_project_list_body {
4280 # actually uses global variable $project
4281 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4283 my $check_forks = gitweb_check_feature('forks');
4284 my @projects = fill_project_list_info($projlist, $check_forks);
4286 $order ||= $default_projects_order;
4287 $from = 0 unless defined $from;
4288 $to = $#projects if (!defined $to || $#projects < $to);
4290 my %order_info = (
4291 project => { key => 'path', type => 'str' },
4292 descr => { key => 'descr_long', type => 'str' },
4293 owner => { key => 'owner', type => 'str' },
4294 age => { key => 'age', type => 'num' }
4296 my $oi = $order_info{$order};
4297 if ($oi->{'type'} eq 'str') {
4298 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4299 } else {
4300 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4303 git_project_list_ctags(\@projects);
4305 print "<table class=\"project_list\">\n";
4306 unless ($no_header) {
4307 print "<tr>\n";
4308 if ($check_forks) {
4309 print "<th></th>\n";
4311 print_sort_th('project', $order, 'Project');
4312 print_sort_th('descr', $order, 'Description');
4313 print_sort_th('owner', $order, 'Owner');
4314 print_sort_th('age', $order, 'Last Change');
4315 print "<th></th>\n" . # for links
4316 "</tr>\n";
4318 my $alternate = 1;
4319 my $tagfilter = $cgi->param('by_tag');
4320 for (my $i = $from; $i <= $to; $i++) {
4321 my $pr = $projects[$i];
4323 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4324 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4325 and not $pr->{'descr_long'} =~ /$searchtext/;
4326 # Weed out forks or non-matching entries of search
4327 if ($check_forks) {
4328 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4329 $forkbase="^$forkbase" if $forkbase;
4330 next if not $searchtext and not $tagfilter and $show_ctags
4331 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4334 if ($alternate) {
4335 print "<tr class=\"dark\">\n";
4336 } else {
4337 print "<tr class=\"light\">\n";
4339 $alternate ^= 1;
4340 if ($check_forks) {
4341 print "<td>";
4342 if ($pr->{'forks'}) {
4343 print "<!-- $pr->{'forks'} -->\n";
4344 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4346 print "</td>\n";
4348 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4349 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4350 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4351 -class => "list", -title => $pr->{'descr_long'}},
4352 esc_html($pr->{'descr'})) . "</td>\n" .
4353 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4354 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4355 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4356 "<td class=\"link\">" .
4357 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4358 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4359 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4360 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4361 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4362 "</td>\n" .
4363 "</tr>\n";
4365 if (defined $extra) {
4366 print "<tr>\n";
4367 if ($check_forks) {
4368 print "<td></td>\n";
4370 print "<td colspan=\"5\">$extra</td>\n" .
4371 "</tr>\n";
4373 print "</table>\n";
4376 sub git_project_search_form {
4377 print $cgi->startform(-method => "get") .
4378 "<p class=\"projsearch\">Search:\n" .
4379 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4380 "</p>" .
4381 $cgi->end_form() . "\n";
4384 sub git_project_list_all {
4385 my $order = $input_params{'order'};
4386 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4387 die_error(400, "Unknown order parameter");
4390 my @list = git_get_projects_list();
4391 if (!@list) {
4392 die_error(404, "No projects found");
4395 git_project_list_body(\@list, $order, undef, undef, undef, undef, $projlist_cache_lifetime);
4398 sub git_shortlog_body {
4399 # uses global variable $project
4400 my ($commitlist, $from, $to, $refs, $extra) = @_;
4402 $from = 0 unless defined $from;
4403 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4405 print "<table class=\"shortlog\">\n";
4406 my $alternate = 1;
4407 for (my $i = $from; $i <= $to; $i++) {
4408 my %co = %{$commitlist->[$i]};
4409 my $commit = $co{'id'};
4410 my $ref = format_ref_marker($refs, $commit);
4411 if ($alternate) {
4412 print "<tr class=\"dark\">\n";
4413 } else {
4414 print "<tr class=\"light\">\n";
4416 $alternate ^= 1;
4417 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4418 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4419 format_author_html('td', \%co, 10) . "<td>";
4420 print format_subject_html($co{'title'}, $co{'title_short'},
4421 href(action=>"commit", hash=>$commit), $ref);
4422 print "</td>\n" .
4423 "<td class=\"link\">" .
4424 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4425 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4426 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4427 my $snapshot_links = format_snapshot_links($commit);
4428 if (defined $snapshot_links) {
4429 print " | " . $snapshot_links;
4431 print "</td>\n" .
4432 "</tr>\n";
4434 if (defined $extra) {
4435 print "<tr>\n" .
4436 "<td colspan=\"4\">$extra</td>\n" .
4437 "</tr>\n";
4439 print "</table>\n";
4442 sub git_history_body {
4443 # Warning: assumes constant type (blob or tree) during history
4444 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4446 $from = 0 unless defined $from;
4447 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4449 print "<table class=\"history\">\n";
4450 my $alternate = 1;
4451 for (my $i = $from; $i <= $to; $i++) {
4452 my %co = %{$commitlist->[$i]};
4453 if (!%co) {
4454 next;
4456 my $commit = $co{'id'};
4458 my $ref = format_ref_marker($refs, $commit);
4460 if ($alternate) {
4461 print "<tr class=\"dark\">\n";
4462 } else {
4463 print "<tr class=\"light\">\n";
4465 $alternate ^= 1;
4466 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4467 # shortlog: format_author_html('td', \%co, 10)
4468 format_author_html('td', \%co, 15, 3) . "<td>";
4469 # originally git_history used chop_str($co{'title'}, 50)
4470 print format_subject_html($co{'title'}, $co{'title_short'},
4471 href(action=>"commit", hash=>$commit), $ref);
4472 print "</td>\n" .
4473 "<td class=\"link\">" .
4474 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4475 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4477 if ($ftype eq 'blob') {
4478 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4479 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4480 if (defined $blob_current && defined $blob_parent &&
4481 $blob_current ne $blob_parent) {
4482 print " | " .
4483 $cgi->a({-href => href(action=>"blobdiff",
4484 hash=>$blob_current, hash_parent=>$blob_parent,
4485 hash_base=>$hash_base, hash_parent_base=>$commit,
4486 file_name=>$file_name)},
4487 "diff to current");
4490 print "</td>\n" .
4491 "</tr>\n";
4493 if (defined $extra) {
4494 print "<tr>\n" .
4495 "<td colspan=\"4\">$extra</td>\n" .
4496 "</tr>\n";
4498 print "</table>\n";
4501 sub git_tags_body {
4502 # uses global variable $project
4503 my ($taglist, $from, $to, $extra) = @_;
4504 $from = 0 unless defined $from;
4505 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4507 print "<table class=\"tags\">\n";
4508 my $alternate = 1;
4509 for (my $i = $from; $i <= $to; $i++) {
4510 my $entry = $taglist->[$i];
4511 my %tag = %$entry;
4512 my $comment = $tag{'subject'};
4513 my $comment_short;
4514 if (defined $comment) {
4515 $comment_short = chop_str($comment, 30, 5);
4517 if ($alternate) {
4518 print "<tr class=\"dark\">\n";
4519 } else {
4520 print "<tr class=\"light\">\n";
4522 $alternate ^= 1;
4523 if (defined $tag{'age'}) {
4524 print "<td><i>$tag{'age'}</i></td>\n";
4525 } else {
4526 print "<td></td>\n";
4528 print "<td>" .
4529 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4530 -class => "list name"}, esc_html($tag{'name'})) .
4531 "</td>\n" .
4532 "<td>";
4533 if (defined $comment) {
4534 print format_subject_html($comment, $comment_short,
4535 href(action=>"tag", hash=>$tag{'id'}));
4537 print "</td>\n" .
4538 "<td class=\"selflink\">";
4539 if ($tag{'type'} eq "tag") {
4540 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4541 } else {
4542 print "&nbsp;";
4544 print "</td>\n" .
4545 "<td class=\"link\">" . " | " .
4546 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4547 if ($tag{'reftype'} eq "commit") {
4548 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4549 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4550 } elsif ($tag{'reftype'} eq "blob") {
4551 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4553 print "</td>\n" .
4554 "</tr>";
4556 if (defined $extra) {
4557 print "<tr>\n" .
4558 "<td colspan=\"5\">$extra</td>\n" .
4559 "</tr>\n";
4561 print "</table>\n";
4564 sub git_heads_body {
4565 # uses global variable $project
4566 my ($headlist, $head, $from, $to, $extra) = @_;
4567 $from = 0 unless defined $from;
4568 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4570 print "<table class=\"heads\">\n";
4571 my $alternate = 1;
4572 for (my $i = $from; $i <= $to; $i++) {
4573 my $entry = $headlist->[$i];
4574 my %ref = %$entry;
4575 my $curr = $ref{'id'} eq $head;
4576 if ($alternate) {
4577 print "<tr class=\"dark\">\n";
4578 } else {
4579 print "<tr class=\"light\">\n";
4581 $alternate ^= 1;
4582 print "<td><i>$ref{'age'}</i></td>\n" .
4583 ($curr ? "<td class=\"current_head\">" : "<td>") .
4584 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4585 -class => "list name"},esc_html($ref{'name'})) .
4586 "</td>\n" .
4587 "<td class=\"link\">" .
4588 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4589 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4590 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4591 "</td>\n" .
4592 "</tr>";
4594 if (defined $extra) {
4595 print "<tr>\n" .
4596 "<td colspan=\"3\">$extra</td>\n" .
4597 "</tr>\n";
4599 print "</table>\n";
4602 sub git_search_grep_body {
4603 my ($commitlist, $from, $to, $extra) = @_;
4604 $from = 0 unless defined $from;
4605 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4607 print "<table class=\"commit_search\">\n";
4608 my $alternate = 1;
4609 for (my $i = $from; $i <= $to; $i++) {
4610 my %co = %{$commitlist->[$i]};
4611 if (!%co) {
4612 next;
4614 my $commit = $co{'id'};
4615 if ($alternate) {
4616 print "<tr class=\"dark\">\n";
4617 } else {
4618 print "<tr class=\"light\">\n";
4620 $alternate ^= 1;
4621 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4622 format_author_html('td', \%co, 15, 5) .
4623 "<td>" .
4624 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4625 -class => "list subject"},
4626 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4627 my $comment = $co{'comment'};
4628 foreach my $line (@$comment) {
4629 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4630 my ($lead, $match, $trail) = ($1, $2, $3);
4631 $match = chop_str($match, 70, 5, 'center');
4632 my $contextlen = int((80 - length($match))/2);
4633 $contextlen = 30 if ($contextlen > 30);
4634 $lead = chop_str($lead, $contextlen, 10, 'left');
4635 $trail = chop_str($trail, $contextlen, 10, 'right');
4637 $lead = esc_html($lead);
4638 $match = esc_html($match);
4639 $trail = esc_html($trail);
4641 print "$lead<span class=\"match\">$match</span>$trail<br />";
4644 print "</td>\n" .
4645 "<td class=\"link\">" .
4646 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4647 " | " .
4648 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4649 " | " .
4650 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4651 print "</td>\n" .
4652 "</tr>\n";
4654 if (defined $extra) {
4655 print "<tr>\n" .
4656 "<td colspan=\"3\">$extra</td>\n" .
4657 "</tr>\n";
4659 print "</table>\n";
4662 ## ======================================================================
4663 ## ======================================================================
4664 ## actions
4666 sub git_frontpage {
4667 git_header_html();
4668 if (-f $home_text) {
4669 print "<div class=\"index_include\">\n";
4670 insert_file($home_text);
4671 print "</div>\n";
4673 git_project_search_form();
4674 if (not $frontpage_no_project_list) {
4675 git_project_list_all();
4676 } else {
4677 if ($frontpage_no_project_list == 1 and gitweb_check_feature('ctags'))
4678 my @list = git_get_projects_list();
4679 my @projects = fill_project_list_info(\@list, gitweb_check_feature('forks'));
4680 git_project_list_ctags(\@projects);
4682 print "<p class=\"projectlist_link\">" .
4683 $cgi->a({-href => href(action=>'project_list')}, "Browse all projects") .
4684 "</p>\n";
4686 git_footer_html();
4689 sub git_project_list {
4690 git_header_html();
4691 git_project_search_form();
4692 git_project_list_all();
4693 git_footer_html();
4696 sub git_forks {
4697 my $order = $input_params{'order'};
4698 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4699 die_error(400, "Unknown order parameter");
4702 my @list = git_get_projects_list($project);
4703 if (!@list) {
4704 die_error(404, "No forks found");
4707 git_header_html();
4708 git_print_page_nav('','');
4709 git_print_header_div('summary', "$project forks");
4710 git_project_list_body(\@list, $order);
4711 git_footer_html();
4714 sub git_project_index {
4715 my @projects = git_get_projects_list($project);
4717 print $cgi->header(
4718 -type => 'text/plain',
4719 -charset => 'utf-8',
4720 -content_disposition => 'inline; filename="index.aux"');
4722 foreach my $pr (@projects) {
4723 if (!exists $pr->{'owner'}) {
4724 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4727 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4728 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4729 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4730 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4731 $path =~ s/ /\+/g;
4732 $owner =~ s/ /\+/g;
4734 print "$path $owner\n";
4738 sub git_summary {
4739 my $descr = git_get_project_description($project) || "none";
4740 my %co = parse_commit("HEAD");
4741 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4742 my $head = $co{'id'};
4744 my $owner = git_get_project_owner($project);
4746 my $refs = git_get_references();
4747 # These get_*_list functions return one more to allow us to see if
4748 # there are more ...
4749 my @taglist = git_get_tags_list(16);
4750 my @headlist = git_get_heads_list(16);
4751 my @forklist;
4752 my $check_forks = gitweb_check_feature('forks');
4754 if ($check_forks) {
4755 @forklist = git_get_projects_list($project);
4758 git_header_html();
4759 git_print_page_nav('summary','', $head);
4761 print "<div class=\"title\">&nbsp;</div>\n";
4762 print "<table class=\"projects_list\">\n" .
4763 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4764 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4765 if (defined $cd{'rfc2822'}) {
4766 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4769 # use per project git URL list in $projectroot/$project/cloneurl
4770 # or make project git URL from git base URL and project name
4771 my $url_tag = "URL";
4772 my @url_list = git_get_project_url_list($project);
4773 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4774 foreach my $git_url (@url_list) {
4775 next unless $git_url;
4776 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4777 $url_tag = "";
4780 # Tag cloud
4781 my $show_ctags = gitweb_check_feature('ctags');
4782 if ($show_ctags) {
4783 my $ctags = git_get_project_ctags($project);
4784 my $cloud = git_populate_project_tagcloud($ctags);
4785 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4786 print "</td>\n<td>" unless %$ctags;
4787 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4788 print "</td>\n<td>" if %$ctags;
4789 print git_show_project_tagcloud($cloud, 48);
4790 print "</td></tr>";
4793 print "</table>\n";
4795 # If XSS prevention is on, we don't include README.html.
4796 # TODO: Allow a readme in some safe format.
4797 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4798 print "<div class=\"title\">readme</div>\n" .
4799 "<div class=\"readme\">\n";
4800 insert_file("$projectroot/$project/README.html");
4801 print "\n</div>\n"; # class="readme"
4804 # we need to request one more than 16 (0..15) to check if
4805 # those 16 are all
4806 my @commitlist = $head ? parse_commits($head, 17) : ();
4807 if (@commitlist) {
4808 git_print_header_div('shortlog');
4809 git_shortlog_body(\@commitlist, 0, 15, $refs,
4810 $#commitlist <= 15 ? undef :
4811 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4814 if (@taglist) {
4815 git_print_header_div('tags');
4816 git_tags_body(\@taglist, 0, 15,
4817 $#taglist <= 15 ? undef :
4818 $cgi->a({-href => href(action=>"tags")}, "..."));
4821 if (@headlist) {
4822 git_print_header_div('heads');
4823 git_heads_body(\@headlist, $head, 0, 15,
4824 $#headlist <= 15 ? undef :
4825 $cgi->a({-href => href(action=>"heads")}, "..."));
4828 if (@forklist) {
4829 git_print_header_div('forks');
4830 git_project_list_body(\@forklist, 'age', 0, 15,
4831 $#forklist <= 15 ? undef :
4832 $cgi->a({-href => href(action=>"forks")}, "..."),
4833 'no_header');
4836 git_footer_html();
4839 sub git_tag {
4840 my $head = git_get_head_hash($project);
4841 git_header_html();
4842 git_print_page_nav('','', $head,undef,$head);
4843 my %tag = parse_tag($hash);
4845 if (! %tag) {
4846 die_error(404, "Unknown tag object");
4849 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4850 print "<div class=\"title_text\">\n" .
4851 "<table class=\"object_header\">\n" .
4852 "<tr>\n" .
4853 "<td>object</td>\n" .
4854 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4855 $tag{'object'}) . "</td>\n" .
4856 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4857 $tag{'type'}) . "</td>\n" .
4858 "</tr>\n";
4859 if (defined($tag{'author'})) {
4860 git_print_authorship_rows(\%tag, 'author');
4862 print "</table>\n\n" .
4863 "</div>\n";
4864 print "<div class=\"page_body\">";
4865 my $comment = $tag{'comment'};
4866 foreach my $line (@$comment) {
4867 chomp $line;
4868 print esc_html($line, -nbsp=>1) . "<br/>\n";
4870 print "</div>\n";
4871 git_footer_html();
4874 sub git_blame {
4875 # permissions
4876 gitweb_check_feature('blame')
4877 or die_error(403, "Blame view not allowed");
4879 # error checking
4880 die_error(400, "No file name given") unless $file_name;
4881 $hash_base ||= git_get_head_hash($project);
4882 die_error(404, "Couldn't find base commit") unless $hash_base;
4883 my %co = parse_commit($hash_base)
4884 or die_error(404, "Commit not found");
4885 my $ftype = "blob";
4886 if (!defined $hash) {
4887 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4888 or die_error(404, "Error looking up file");
4889 } else {
4890 $ftype = git_get_type($hash);
4891 if ($ftype !~ "blob") {
4892 die_error(400, "Object is not a blob");
4896 # run git-blame --porcelain
4897 open my $fd, "-|", git_cmd(), "blame", '-p',
4898 $hash_base, '--', $file_name
4899 or die_error(500, "Open git-blame failed");
4901 # page header
4902 git_header_html();
4903 my $formats_nav =
4904 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4905 "blob") .
4906 " | " .
4907 $cgi->a({-href => href(action=>"history", -replay=>1)},
4908 "history") .
4909 " | " .
4910 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4911 "HEAD");
4912 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4913 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4914 git_print_page_path($file_name, $ftype, $hash_base);
4916 # page body
4917 my @rev_color = qw(light dark);
4918 my $num_colors = scalar(@rev_color);
4919 my $current_color = 0;
4920 my %metainfo = ();
4922 print <<HTML;
4923 <div class="page_body">
4924 <table class="blame">
4925 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4926 HTML
4927 LINE:
4928 while (my $line = <$fd>) {
4929 chomp $line;
4930 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4931 # no <lines in group> for subsequent lines in group of lines
4932 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4933 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
4934 if (!exists $metainfo{$full_rev}) {
4935 $metainfo{$full_rev} = { 'nprevious' => 0 };
4937 my $meta = $metainfo{$full_rev};
4938 my $data;
4939 while ($data = <$fd>) {
4940 chomp $data;
4941 last if ($data =~ s/^\t//); # contents of line
4942 if ($data =~ /^(\S+)(?: (.*))?$/) {
4943 $meta->{$1} = $2 unless exists $meta->{$1};
4945 if ($data =~ /^previous /) {
4946 $meta->{'nprevious'}++;
4949 my $short_rev = substr($full_rev, 0, 8);
4950 my $author = $meta->{'author'};
4951 my %date =
4952 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
4953 my $date = $date{'iso-tz'};
4954 if ($group_size) {
4955 $current_color = ($current_color + 1) % $num_colors;
4957 my $tr_class = $rev_color[$current_color];
4958 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
4959 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
4960 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
4961 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
4962 if ($group_size) {
4963 print "<td class=\"sha1\"";
4964 print " title=\"". esc_html($author) . ", $date\"";
4965 print " rowspan=\"$group_size\"" if ($group_size > 1);
4966 print ">";
4967 print $cgi->a({-href => href(action=>"commit",
4968 hash=>$full_rev,
4969 file_name=>$file_name)},
4970 esc_html($short_rev));
4971 if ($group_size >= 2) {
4972 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
4973 if (@author_initials) {
4974 print "<br />" .
4975 esc_html(join('', @author_initials));
4976 # or join('.', ...)
4979 print "</td>\n";
4981 # 'previous' <sha1 of parent commit> <filename at commit>
4982 if (exists $meta->{'previous'} &&
4983 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
4984 $meta->{'parent'} = $1;
4985 $meta->{'file_parent'} = unquote($2);
4987 my $linenr_commit =
4988 exists($meta->{'parent'}) ?
4989 $meta->{'parent'} : $full_rev;
4990 my $linenr_filename =
4991 exists($meta->{'file_parent'}) ?
4992 $meta->{'file_parent'} : unquote($meta->{'filename'});
4993 my $blamed = href(action => 'blame',
4994 file_name => $linenr_filename,
4995 hash_base => $linenr_commit);
4996 print "<td class=\"linenr\">";
4997 print $cgi->a({ -href => "$blamed#l$orig_lineno",
4998 -class => "linenr" },
4999 esc_html($lineno));
5000 print "</td>";
5001 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5002 print "</tr>\n";
5004 print "</table>\n";
5005 print "</div>";
5006 close $fd
5007 or print "Reading blob failed\n";
5009 # page footer
5010 git_footer_html();
5013 sub git_tags {
5014 my $head = git_get_head_hash($project);
5015 git_header_html();
5016 git_print_page_nav('','', $head,undef,$head);
5017 git_print_header_div('summary', $project);
5019 my @tagslist = git_get_tags_list();
5020 if (@tagslist) {
5021 git_tags_body(\@tagslist);
5023 git_footer_html();
5026 sub git_heads {
5027 my $head = git_get_head_hash($project);
5028 git_header_html();
5029 git_print_page_nav('','', $head,undef,$head);
5030 git_print_header_div('summary', $project);
5032 my @headslist = git_get_heads_list();
5033 if (@headslist) {
5034 git_heads_body(\@headslist, $head);
5036 git_footer_html();
5039 sub git_blob_plain {
5040 my $type = shift;
5041 my $expires;
5043 if (!defined $hash) {
5044 if (defined $file_name) {
5045 my $base = $hash_base || git_get_head_hash($project);
5046 $hash = git_get_hash_by_path($base, $file_name, "blob")
5047 or die_error(404, "Cannot find file");
5048 } else {
5049 die_error(400, "No file name defined");
5051 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5052 # blobs defined by non-textual hash id's can be cached
5053 $expires = "+1d";
5056 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5057 or die_error(500, "Open git-cat-file blob '$hash' failed");
5059 # content-type (can include charset)
5060 $type = blob_contenttype($fd, $file_name, $type);
5062 # "save as" filename, even when no $file_name is given
5063 my $save_as = "$hash";
5064 if (defined $file_name) {
5065 $save_as = $file_name;
5066 } elsif ($type =~ m/^text\//) {
5067 $save_as .= '.txt';
5070 # With XSS prevention on, blobs of all types except a few known safe
5071 # ones are served with "Content-Disposition: attachment" to make sure
5072 # they don't run in our security domain. For certain image types,
5073 # blob view writes an <img> tag referring to blob_plain view, and we
5074 # want to be sure not to break that by serving the image as an
5075 # attachment (though Firefox 3 doesn't seem to care).
5076 my $sandbox = $prevent_xss &&
5077 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5079 print $cgi->header(
5080 -type => $type,
5081 -expires => $expires,
5082 -content_disposition =>
5083 ($sandbox ? 'attachment' : 'inline')
5084 . '; filename="' . $save_as . '"');
5085 local $/ = undef;
5086 binmode STDOUT, ':raw';
5087 print <$fd>;
5088 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5089 close $fd;
5092 sub git_blob {
5093 my $expires;
5095 if (!defined $hash) {
5096 if (defined $file_name) {
5097 my $base = $hash_base || git_get_head_hash($project);
5098 $hash = git_get_hash_by_path($base, $file_name, "blob")
5099 or die_error(404, "Cannot find file");
5100 } else {
5101 die_error(400, "No file name defined");
5103 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5104 # blobs defined by non-textual hash id's can be cached
5105 $expires = "+1d";
5108 my $have_blame = gitweb_check_feature('blame');
5109 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5110 or die_error(500, "Couldn't cat $file_name, $hash");
5111 my $mimetype = blob_mimetype($fd, $file_name);
5112 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5113 close $fd;
5114 return git_blob_plain($mimetype);
5116 # we can have blame only for text/* mimetype
5117 $have_blame &&= ($mimetype =~ m!^text/!);
5119 git_header_html(undef, $expires);
5120 my $formats_nav = '';
5121 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5122 if (defined $file_name) {
5123 if ($have_blame) {
5124 $formats_nav .=
5125 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5126 "blame") .
5127 " | ";
5129 $formats_nav .=
5130 $cgi->a({-href => href(action=>"history", -replay=>1)},
5131 "history") .
5132 " | " .
5133 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5134 "raw") .
5135 " | " .
5136 $cgi->a({-href => href(action=>"blob",
5137 hash_base=>"HEAD", file_name=>$file_name)},
5138 "HEAD");
5139 } else {
5140 $formats_nav .=
5141 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5142 "raw");
5144 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5145 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5146 } else {
5147 print "<div class=\"page_nav\">\n" .
5148 "<br/><br/></div>\n" .
5149 "<div class=\"title\">$hash</div>\n";
5151 git_print_page_path($file_name, "blob", $hash_base);
5152 print "<div class=\"page_body\">\n";
5153 if ($mimetype =~ m!^image/!) {
5154 print qq!<img type="$mimetype"!;
5155 if ($file_name) {
5156 print qq! alt="$file_name" title="$file_name"!;
5158 print qq! src="! .
5159 href(action=>"blob_plain", hash=>$hash,
5160 hash_base=>$hash_base, file_name=>$file_name) .
5161 qq!" />\n!;
5162 } else {
5163 my $nr;
5164 while (my $line = <$fd>) {
5165 chomp $line;
5166 $nr++;
5167 $line = untabify($line);
5168 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5169 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5172 close $fd
5173 or print "Reading blob failed.\n";
5174 print "</div>";
5175 git_footer_html();
5178 sub git_tree {
5179 if (!defined $hash_base) {
5180 $hash_base = "HEAD";
5182 if (!defined $hash) {
5183 if (defined $file_name) {
5184 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5185 } else {
5186 $hash = $hash_base;
5189 die_error(404, "No such tree") unless defined($hash);
5191 my $show_sizes = gitweb_check_feature('show-sizes');
5192 my $have_blame = gitweb_check_feature('blame');
5194 my @entries = ();
5196 local $/ = "\0";
5197 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5198 ($show_sizes ? '-l' : ()), @extra_options, $hash
5199 or die_error(500, "Open git-ls-tree failed");
5200 @entries = map { chomp; $_ } <$fd>;
5201 close $fd
5202 or die_error(404, "Reading tree failed");
5205 my $refs = git_get_references();
5206 my $ref = format_ref_marker($refs, $hash_base);
5207 git_header_html();
5208 my $basedir = '';
5209 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5210 my @views_nav = ();
5211 if (defined $file_name) {
5212 push @views_nav,
5213 $cgi->a({-href => href(action=>"history", -replay=>1)},
5214 "history"),
5215 $cgi->a({-href => href(action=>"tree",
5216 hash_base=>"HEAD", file_name=>$file_name)},
5217 "HEAD"),
5219 my $snapshot_links = format_snapshot_links($hash);
5220 if (defined $snapshot_links) {
5221 # FIXME: Should be available when we have no hash base as well.
5222 push @views_nav, $snapshot_links;
5224 git_print_page_nav('tree','', $hash_base, undef, undef,
5225 join(' | ', @views_nav));
5226 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5227 } else {
5228 undef $hash_base;
5229 print "<div class=\"page_nav\">\n";
5230 print "<br/><br/></div>\n";
5231 print "<div class=\"title\">$hash</div>\n";
5233 if (defined $file_name) {
5234 $basedir = $file_name;
5235 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5236 $basedir .= '/';
5238 git_print_page_path($file_name, 'tree', $hash_base);
5240 print "<div class=\"page_body\">\n";
5241 print "<table class=\"tree\">\n";
5242 my $alternate = 1;
5243 # '..' (top directory) link if possible
5244 if (defined $hash_base &&
5245 defined $file_name && $file_name =~ m![^/]+$!) {
5246 if ($alternate) {
5247 print "<tr class=\"dark\">\n";
5248 } else {
5249 print "<tr class=\"light\">\n";
5251 $alternate ^= 1;
5253 my $up = $file_name;
5254 $up =~ s!/?[^/]+$!!;
5255 undef $up unless $up;
5256 # based on git_print_tree_entry
5257 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5258 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5259 print '<td class="list">';
5260 print $cgi->a({-href => href(action=>"tree",
5261 hash_base=>$hash_base,
5262 file_name=>$up)},
5263 "..");
5264 print "</td>\n";
5265 print "<td class=\"link\"></td>\n";
5267 print "</tr>\n";
5269 foreach my $line (@entries) {
5270 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5272 if ($alternate) {
5273 print "<tr class=\"dark\">\n";
5274 } else {
5275 print "<tr class=\"light\">\n";
5277 $alternate ^= 1;
5279 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5281 print "</tr>\n";
5283 print "</table>\n" .
5284 "</div>";
5285 git_footer_html();
5288 sub git_snapshot {
5289 my $format = $input_params{'snapshot_format'};
5290 if (!@snapshot_fmts) {
5291 die_error(403, "Snapshots not allowed");
5293 # default to first supported snapshot format
5294 $format ||= $snapshot_fmts[0];
5295 if ($format !~ m/^[a-z0-9]+$/) {
5296 die_error(400, "Invalid snapshot format parameter");
5297 } elsif (!exists($known_snapshot_formats{$format})) {
5298 die_error(400, "Unknown snapshot format");
5299 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5300 die_error(403, "Snapshot format not allowed");
5301 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5302 die_error(403, "Unsupported snapshot format");
5305 if (!defined $hash) {
5306 $hash = git_get_head_hash($project);
5309 my $name = $project;
5310 $name =~ s,([^/])/*\.git$,$1,;
5311 $name = basename($name);
5312 my $filename = to_utf8($name);
5313 $name =~ s/\047/\047\\\047\047/g;
5314 my $cmd;
5315 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5316 $cmd = quote_command(
5317 git_cmd(), 'archive',
5318 "--format=$known_snapshot_formats{$format}{'format'}",
5319 "--prefix=$name/", $hash);
5320 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5321 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5324 print $cgi->header(
5325 -type => $known_snapshot_formats{$format}{'type'},
5326 -content_disposition => 'inline; filename="' . "$filename" . '"',
5327 -status => '200 OK');
5329 open my $fd, "-|", $cmd
5330 or die_error(500, "Execute git-archive failed");
5331 binmode STDOUT, ':raw';
5332 print <$fd>;
5333 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5334 close $fd;
5337 sub git_log {
5338 my $head = git_get_head_hash($project);
5339 if (!defined $hash) {
5340 $hash = $head;
5342 if (!defined $page) {
5343 $page = 0;
5345 my $refs = git_get_references();
5347 my @commitlist = parse_commits($hash, 101, (100 * $page));
5349 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
5351 my ($patch_max) = gitweb_get_feature('patches');
5352 if ($patch_max) {
5353 if ($patch_max < 0 || @commitlist <= $patch_max) {
5354 $paging_nav .= " &sdot; " .
5355 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5356 "patches");
5360 git_header_html();
5361 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5363 if (!@commitlist) {
5364 my %co = parse_commit($hash);
5366 git_print_header_div('summary', $project);
5367 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5369 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5370 for (my $i = 0; $i <= $to; $i++) {
5371 my %co = %{$commitlist[$i]};
5372 next if !%co;
5373 my $commit = $co{'id'};
5374 my $ref = format_ref_marker($refs, $commit);
5375 my %ad = parse_date($co{'author_epoch'});
5376 git_print_header_div('commit',
5377 "<span class=\"age\">$co{'age_string'}</span>" .
5378 esc_html($co{'title'}) . $ref,
5379 $commit);
5380 print "<div class=\"title_text\">\n" .
5381 "<div class=\"log_link\">\n" .
5382 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5383 " | " .
5384 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5385 " | " .
5386 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5387 "<br/>\n" .
5388 "</div>\n";
5389 git_print_authorship(\%co, -tag => 'span');
5390 print "<br/>\n</div>\n";
5392 print "<div class=\"log_body\">\n";
5393 git_print_log($co{'comment'}, -final_empty_line=> 1);
5394 print "</div>\n";
5396 if ($#commitlist >= 100) {
5397 print "<div class=\"page_nav\">\n";
5398 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5399 -accesskey => "n", -title => "Alt-n"}, "next");
5400 print "</div>\n";
5402 git_footer_html();
5405 sub git_commit {
5406 $hash ||= $hash_base || "HEAD";
5407 my %co = parse_commit($hash)
5408 or die_error(404, "Unknown commit object");
5410 my $parent = $co{'parent'};
5411 my $parents = $co{'parents'}; # listref
5413 # we need to prepare $formats_nav before any parameter munging
5414 my $formats_nav;
5415 if (!defined $parent) {
5416 # --root commitdiff
5417 $formats_nav .= '(initial)';
5418 } elsif (@$parents == 1) {
5419 # single parent commit
5420 $formats_nav .=
5421 '(parent: ' .
5422 $cgi->a({-href => href(action=>"commit",
5423 hash=>$parent)},
5424 esc_html(substr($parent, 0, 7))) .
5425 ')';
5426 } else {
5427 # merge commit
5428 $formats_nav .=
5429 '(merge: ' .
5430 join(' ', map {
5431 $cgi->a({-href => href(action=>"commit",
5432 hash=>$_)},
5433 esc_html(substr($_, 0, 7)));
5434 } @$parents ) .
5435 ')';
5437 if (gitweb_check_feature('patches') && @$parents <= 1) {
5438 $formats_nav .= " | " .
5439 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5440 "patch");
5443 if (!defined $parent) {
5444 $parent = "--root";
5446 my @difftree;
5447 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5448 @diff_opts,
5449 (@$parents <= 1 ? $parent : '-c'),
5450 $hash, "--"
5451 or die_error(500, "Open git-diff-tree failed");
5452 @difftree = map { chomp; $_ } <$fd>;
5453 close $fd or die_error(404, "Reading git-diff-tree failed");
5455 # non-textual hash id's can be cached
5456 my $expires;
5457 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5458 $expires = "+1d";
5460 my $refs = git_get_references();
5461 my $ref = format_ref_marker($refs, $co{'id'});
5463 git_header_html(undef, $expires);
5464 git_print_page_nav('commit', '',
5465 $hash, $co{'tree'}, $hash,
5466 $formats_nav);
5468 if (defined $co{'parent'}) {
5469 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5470 } else {
5471 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5473 print "<div class=\"title_text\">\n" .
5474 "<table class=\"object_header\">\n";
5475 git_print_authorship_rows(\%co);
5476 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5477 print "<tr>" .
5478 "<td>tree</td>" .
5479 "<td class=\"sha1\">" .
5480 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5481 class => "list"}, $co{'tree'}) .
5482 "</td>" .
5483 "<td class=\"link\">" .
5484 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5485 "tree");
5486 my $snapshot_links = format_snapshot_links($hash);
5487 if (defined $snapshot_links) {
5488 print " | " . $snapshot_links;
5490 print "</td>" .
5491 "</tr>\n";
5493 foreach my $par (@$parents) {
5494 print "<tr>" .
5495 "<td>parent</td>" .
5496 "<td class=\"sha1\">" .
5497 $cgi->a({-href => href(action=>"commit", hash=>$par),
5498 class => "list"}, $par) .
5499 "</td>" .
5500 "<td class=\"link\">" .
5501 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5502 " | " .
5503 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5504 "</td>" .
5505 "</tr>\n";
5507 print "</table>".
5508 "</div>\n";
5510 print "<div class=\"page_body\">\n";
5511 git_print_log($co{'comment'});
5512 print "</div>\n";
5514 git_difftree_body(\@difftree, $hash, @$parents);
5516 git_footer_html();
5519 sub git_object {
5520 # object is defined by:
5521 # - hash or hash_base alone
5522 # - hash_base and file_name
5523 my $type;
5525 # - hash or hash_base alone
5526 if ($hash || ($hash_base && !defined $file_name)) {
5527 my $object_id = $hash || $hash_base;
5529 open my $fd, "-|", quote_command(
5530 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5531 or die_error(404, "Object does not exist");
5532 $type = <$fd>;
5533 chomp $type;
5534 close $fd
5535 or die_error(404, "Object does not exist");
5537 # - hash_base and file_name
5538 } elsif ($hash_base && defined $file_name) {
5539 $file_name =~ s,/+$,,;
5541 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5542 or die_error(404, "Base object does not exist");
5544 # here errors should not hapen
5545 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5546 or die_error(500, "Open git-ls-tree failed");
5547 my $line = <$fd>;
5548 close $fd;
5550 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5551 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5552 die_error(404, "File or directory for given base does not exist");
5554 $type = $2;
5555 $hash = $3;
5556 } else {
5557 die_error(400, "Not enough information to find object");
5560 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5561 hash=>$hash, hash_base=>$hash_base,
5562 file_name=>$file_name),
5563 -status => '302 Found');
5566 sub git_blobdiff {
5567 my $format = shift || 'html';
5569 my $fd;
5570 my @difftree;
5571 my %diffinfo;
5572 my $expires;
5574 # preparing $fd and %diffinfo for git_patchset_body
5575 # new style URI
5576 if (defined $hash_base && defined $hash_parent_base) {
5577 if (defined $file_name) {
5578 # read raw output
5579 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5580 $hash_parent_base, $hash_base,
5581 "--", (defined $file_parent ? $file_parent : ()), $file_name
5582 or die_error(500, "Open git-diff-tree failed");
5583 @difftree = map { chomp; $_ } <$fd>;
5584 close $fd
5585 or die_error(404, "Reading git-diff-tree failed");
5586 @difftree
5587 or die_error(404, "Blob diff not found");
5589 } elsif (defined $hash &&
5590 $hash =~ /[0-9a-fA-F]{40}/) {
5591 # try to find filename from $hash
5593 # read filtered raw output
5594 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5595 $hash_parent_base, $hash_base, "--"
5596 or die_error(500, "Open git-diff-tree failed");
5597 @difftree =
5598 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5599 # $hash == to_id
5600 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5601 map { chomp; $_ } <$fd>;
5602 close $fd
5603 or die_error(404, "Reading git-diff-tree failed");
5604 @difftree
5605 or die_error(404, "Blob diff not found");
5607 } else {
5608 die_error(400, "Missing one of the blob diff parameters");
5611 if (@difftree > 1) {
5612 die_error(400, "Ambiguous blob diff specification");
5615 %diffinfo = parse_difftree_raw_line($difftree[0]);
5616 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5617 $file_name ||= $diffinfo{'to_file'};
5619 $hash_parent ||= $diffinfo{'from_id'};
5620 $hash ||= $diffinfo{'to_id'};
5622 # non-textual hash id's can be cached
5623 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5624 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5625 $expires = '+1d';
5628 # open patch output
5629 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5630 '-p', ($format eq 'html' ? "--full-index" : ()),
5631 $hash_parent_base, $hash_base,
5632 "--", (defined $file_parent ? $file_parent : ()), $file_name
5633 or die_error(500, "Open git-diff-tree failed");
5636 # old/legacy style URI -- not generated anymore since 1.4.3.
5637 if (!%diffinfo) {
5638 die_error('404 Not Found', "Missing one of the blob diff parameters")
5641 # header
5642 if ($format eq 'html') {
5643 my $formats_nav =
5644 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5645 "raw");
5646 git_header_html(undef, $expires);
5647 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5648 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5649 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5650 } else {
5651 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5652 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5654 if (defined $file_name) {
5655 git_print_page_path($file_name, "blob", $hash_base);
5656 } else {
5657 print "<div class=\"page_path\"></div>\n";
5660 } elsif ($format eq 'plain') {
5661 print $cgi->header(
5662 -type => 'text/plain',
5663 -charset => 'utf-8',
5664 -expires => $expires,
5665 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5667 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5669 } else {
5670 die_error(400, "Unknown blobdiff format");
5673 # patch
5674 if ($format eq 'html') {
5675 print "<div class=\"page_body\">\n";
5677 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5678 close $fd;
5680 print "</div>\n"; # class="page_body"
5681 git_footer_html();
5683 } else {
5684 while (my $line = <$fd>) {
5685 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5686 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5688 print $line;
5690 last if $line =~ m!^\+\+\+!;
5692 local $/ = undef;
5693 print <$fd>;
5694 close $fd;
5698 sub git_blobdiff_plain {
5699 git_blobdiff('plain');
5702 sub git_commitdiff {
5703 my %params = @_;
5704 my $format = $params{-format} || 'html';
5706 my ($patch_max) = gitweb_get_feature('patches');
5707 if ($format eq 'patch') {
5708 die_error(403, "Patch view not allowed") unless $patch_max;
5711 $hash ||= $hash_base || "HEAD";
5712 my %co = parse_commit($hash)
5713 or die_error(404, "Unknown commit object");
5715 # choose format for commitdiff for merge
5716 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5717 $hash_parent = '--cc';
5719 # we need to prepare $formats_nav before almost any parameter munging
5720 my $formats_nav;
5721 if ($format eq 'html') {
5722 $formats_nav =
5723 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5724 "raw");
5725 if ($patch_max && @{$co{'parents'}} <= 1) {
5726 $formats_nav .= " | " .
5727 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5728 "patch");
5731 if (defined $hash_parent &&
5732 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5733 # commitdiff with two commits given
5734 my $hash_parent_short = $hash_parent;
5735 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5736 $hash_parent_short = substr($hash_parent, 0, 7);
5738 $formats_nav .=
5739 ' (from';
5740 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5741 if ($co{'parents'}[$i] eq $hash_parent) {
5742 $formats_nav .= ' parent ' . ($i+1);
5743 last;
5746 $formats_nav .= ': ' .
5747 $cgi->a({-href => href(action=>"commitdiff",
5748 hash=>$hash_parent)},
5749 esc_html($hash_parent_short)) .
5750 ')';
5751 } elsif (!$co{'parent'}) {
5752 # --root commitdiff
5753 $formats_nav .= ' (initial)';
5754 } elsif (scalar @{$co{'parents'}} == 1) {
5755 # single parent commit
5756 $formats_nav .=
5757 ' (parent: ' .
5758 $cgi->a({-href => href(action=>"commitdiff",
5759 hash=>$co{'parent'})},
5760 esc_html(substr($co{'parent'}, 0, 7))) .
5761 ')';
5762 } else {
5763 # merge commit
5764 if ($hash_parent eq '--cc') {
5765 $formats_nav .= ' | ' .
5766 $cgi->a({-href => href(action=>"commitdiff",
5767 hash=>$hash, hash_parent=>'-c')},
5768 'combined');
5769 } else { # $hash_parent eq '-c'
5770 $formats_nav .= ' | ' .
5771 $cgi->a({-href => href(action=>"commitdiff",
5772 hash=>$hash, hash_parent=>'--cc')},
5773 'compact');
5775 $formats_nav .=
5776 ' (merge: ' .
5777 join(' ', map {
5778 $cgi->a({-href => href(action=>"commitdiff",
5779 hash=>$_)},
5780 esc_html(substr($_, 0, 7)));
5781 } @{$co{'parents'}} ) .
5782 ')';
5786 my $hash_parent_param = $hash_parent;
5787 if (!defined $hash_parent_param) {
5788 # --cc for multiple parents, --root for parentless
5789 $hash_parent_param =
5790 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5793 # read commitdiff
5794 my $fd;
5795 my @difftree;
5796 if ($format eq 'html') {
5797 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5798 "--no-commit-id", "--patch-with-raw", "--full-index",
5799 $hash_parent_param, $hash, "--"
5800 or die_error(500, "Open git-diff-tree failed");
5802 while (my $line = <$fd>) {
5803 chomp $line;
5804 # empty line ends raw part of diff-tree output
5805 last unless $line;
5806 push @difftree, scalar parse_difftree_raw_line($line);
5809 } elsif ($format eq 'plain') {
5810 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5811 '-p', $hash_parent_param, $hash, "--"
5812 or die_error(500, "Open git-diff-tree failed");
5813 } elsif ($format eq 'patch') {
5814 # For commit ranges, we limit the output to the number of
5815 # patches specified in the 'patches' feature.
5816 # For single commits, we limit the output to a single patch,
5817 # diverging from the git-format-patch default.
5818 my @commit_spec = ();
5819 if ($hash_parent) {
5820 if ($patch_max > 0) {
5821 push @commit_spec, "-$patch_max";
5823 push @commit_spec, '-n', "$hash_parent..$hash";
5824 } else {
5825 if ($params{-single}) {
5826 push @commit_spec, '-1';
5827 } else {
5828 if ($patch_max > 0) {
5829 push @commit_spec, "-$patch_max";
5831 push @commit_spec, "-n";
5833 push @commit_spec, '--root', $hash;
5835 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5836 '--stdout', @commit_spec
5837 or die_error(500, "Open git-format-patch failed");
5838 } else {
5839 die_error(400, "Unknown commitdiff format");
5842 # non-textual hash id's can be cached
5843 my $expires;
5844 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5845 $expires = "+1d";
5848 # write commit message
5849 if ($format eq 'html') {
5850 my $refs = git_get_references();
5851 my $ref = format_ref_marker($refs, $co{'id'});
5853 git_header_html(undef, $expires);
5854 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5855 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5856 print "<div class=\"title_text\">\n" .
5857 "<table class=\"object_header\">\n";
5858 git_print_authorship_rows(\%co);
5859 print "</table>".
5860 "</div>\n";
5861 print "<div class=\"page_body\">\n";
5862 if (@{$co{'comment'}} > 1) {
5863 print "<div class=\"log\">\n";
5864 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5865 print "</div>\n"; # class="log"
5868 } elsif ($format eq 'plain') {
5869 my $refs = git_get_references("tags");
5870 my $tagname = git_get_rev_name_tags($hash);
5871 my $filename = basename($project) . "-$hash.patch";
5873 print $cgi->header(
5874 -type => 'text/plain',
5875 -charset => 'utf-8',
5876 -expires => $expires,
5877 -content_disposition => 'inline; filename="' . "$filename" . '"');
5878 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5879 print "From: " . to_utf8($co{'author'}) . "\n";
5880 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5881 print "Subject: " . to_utf8($co{'title'}) . "\n";
5883 print "X-Git-Tag: $tagname\n" if $tagname;
5884 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5886 foreach my $line (@{$co{'comment'}}) {
5887 print to_utf8($line) . "\n";
5889 print "---\n\n";
5890 } elsif ($format eq 'patch') {
5891 my $filename = basename($project) . "-$hash.patch";
5893 print $cgi->header(
5894 -type => 'text/plain',
5895 -charset => 'utf-8',
5896 -expires => $expires,
5897 -content_disposition => 'inline; filename="' . "$filename" . '"');
5900 # write patch
5901 if ($format eq 'html') {
5902 my $use_parents = !defined $hash_parent ||
5903 $hash_parent eq '-c' || $hash_parent eq '--cc';
5904 git_difftree_body(\@difftree, $hash,
5905 $use_parents ? @{$co{'parents'}} : $hash_parent);
5906 print "<br/>\n";
5908 git_patchset_body($fd, \@difftree, $hash,
5909 $use_parents ? @{$co{'parents'}} : $hash_parent);
5910 close $fd;
5911 print "</div>\n"; # class="page_body"
5912 git_footer_html();
5914 } elsif ($format eq 'plain') {
5915 local $/ = undef;
5916 print <$fd>;
5917 close $fd
5918 or print "Reading git-diff-tree failed\n";
5919 } elsif ($format eq 'patch') {
5920 local $/ = undef;
5921 print <$fd>;
5922 close $fd
5923 or print "Reading git-format-patch failed\n";
5927 sub git_commitdiff_plain {
5928 git_commitdiff(-format => 'plain');
5931 # format-patch-style patches
5932 sub git_patch {
5933 git_commitdiff(-format => 'patch', -single => 1);
5936 sub git_patches {
5937 git_commitdiff(-format => 'patch');
5940 sub git_history {
5941 if (!defined $hash_base) {
5942 $hash_base = git_get_head_hash($project);
5944 if (!defined $page) {
5945 $page = 0;
5947 my $ftype;
5948 my %co = parse_commit($hash_base)
5949 or die_error(404, "Unknown commit object");
5951 my $refs = git_get_references();
5952 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5954 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5955 $file_name, "--full-history")
5956 or die_error(404, "No such file or directory on given branch");
5958 if (!defined $hash && defined $file_name) {
5959 # some commits could have deleted file in question,
5960 # and not have it in tree, but one of them has to have it
5961 for (my $i = 0; $i <= @commitlist; $i++) {
5962 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5963 last if defined $hash;
5966 if (defined $hash) {
5967 $ftype = git_get_type($hash);
5969 if (!defined $ftype) {
5970 die_error(500, "Unknown type of object");
5973 my $paging_nav = '';
5974 if ($page > 0) {
5975 $paging_nav .=
5976 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5977 file_name=>$file_name)},
5978 "first");
5979 $paging_nav .= " &sdot; " .
5980 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5981 -accesskey => "p", -title => "Alt-p"}, "prev");
5982 } else {
5983 $paging_nav .= "first";
5984 $paging_nav .= " &sdot; prev";
5986 my $next_link = '';
5987 if ($#commitlist >= 100) {
5988 $next_link =
5989 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5990 -accesskey => "n", -title => "Alt-n"}, "next");
5991 $paging_nav .= " &sdot; $next_link";
5992 } else {
5993 $paging_nav .= " &sdot; next";
5996 git_header_html();
5997 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5998 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5999 git_print_page_path($file_name, $ftype, $hash_base);
6001 git_history_body(\@commitlist, 0, 99,
6002 $refs, $hash_base, $ftype, $next_link);
6004 git_footer_html();
6007 sub git_search {
6008 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6009 if (!defined $searchtext) {
6010 die_error(400, "Text field is empty");
6012 if (!defined $hash) {
6013 $hash = git_get_head_hash($project);
6015 my %co = parse_commit($hash);
6016 if (!%co) {
6017 die_error(404, "Unknown commit object");
6019 if (!defined $page) {
6020 $page = 0;
6023 $searchtype ||= 'commit';
6024 if ($searchtype eq 'pickaxe') {
6025 # pickaxe may take all resources of your box and run for several minutes
6026 # with every query - so decide by yourself how public you make this feature
6027 gitweb_check_feature('pickaxe')
6028 or die_error(403, "Pickaxe is disabled");
6030 if ($searchtype eq 'grep') {
6031 gitweb_check_feature('grep')
6032 or die_error(403, "Grep is disabled");
6035 git_header_html();
6037 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6038 my $greptype;
6039 if ($searchtype eq 'commit') {
6040 $greptype = "--grep=";
6041 } elsif ($searchtype eq 'author') {
6042 $greptype = "--author=";
6043 } elsif ($searchtype eq 'committer') {
6044 $greptype = "--committer=";
6046 $greptype .= $searchtext;
6047 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6048 $greptype, '--regexp-ignore-case',
6049 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6051 my $paging_nav = '';
6052 if ($page > 0) {
6053 $paging_nav .=
6054 $cgi->a({-href => href(action=>"search", hash=>$hash,
6055 searchtext=>$searchtext,
6056 searchtype=>$searchtype)},
6057 "first");
6058 $paging_nav .= " &sdot; " .
6059 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6060 -accesskey => "p", -title => "Alt-p"}, "prev");
6061 } else {
6062 $paging_nav .= "first";
6063 $paging_nav .= " &sdot; prev";
6065 my $next_link = '';
6066 if ($#commitlist >= 100) {
6067 $next_link =
6068 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6069 -accesskey => "n", -title => "Alt-n"}, "next");
6070 $paging_nav .= " &sdot; $next_link";
6071 } else {
6072 $paging_nav .= " &sdot; next";
6075 if ($#commitlist >= 100) {
6078 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6079 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6080 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6083 if ($searchtype eq 'pickaxe') {
6084 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6085 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6087 print "<table class=\"pickaxe search\">\n";
6088 my $alternate = 1;
6089 local $/ = "\n";
6090 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6091 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6092 ($search_use_regexp ? '--pickaxe-regex' : ());
6093 undef %co;
6094 my @files;
6095 while (my $line = <$fd>) {
6096 chomp $line;
6097 next unless $line;
6099 my %set = parse_difftree_raw_line($line);
6100 if (defined $set{'commit'}) {
6101 # finish previous commit
6102 if (%co) {
6103 print "</td>\n" .
6104 "<td class=\"link\">" .
6105 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6106 " | " .
6107 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6108 print "</td>\n" .
6109 "</tr>\n";
6112 if ($alternate) {
6113 print "<tr class=\"dark\">\n";
6114 } else {
6115 print "<tr class=\"light\">\n";
6117 $alternate ^= 1;
6118 %co = parse_commit($set{'commit'});
6119 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6120 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6121 "<td><i>$author</i></td>\n" .
6122 "<td>" .
6123 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6124 -class => "list subject"},
6125 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6126 } elsif (defined $set{'to_id'}) {
6127 next if ($set{'to_id'} =~ m/^0{40}$/);
6129 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6130 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6131 -class => "list"},
6132 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6133 "<br/>\n";
6136 close $fd;
6138 # finish last commit (warning: repetition!)
6139 if (%co) {
6140 print "</td>\n" .
6141 "<td class=\"link\">" .
6142 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6143 " | " .
6144 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6145 print "</td>\n" .
6146 "</tr>\n";
6149 print "</table>\n";
6152 if ($searchtype eq 'grep') {
6153 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6154 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6156 print "<table class=\"grep_search\">\n";
6157 my $alternate = 1;
6158 my $matches = 0;
6159 local $/ = "\n";
6160 open my $fd, "-|", git_cmd(), 'grep', '-n',
6161 $search_use_regexp ? ('-E', '-i') : '-F',
6162 $searchtext, $co{'tree'};
6163 my $lastfile = '';
6164 while (my $line = <$fd>) {
6165 chomp $line;
6166 my ($file, $lno, $ltext, $binary);
6167 last if ($matches++ > 1000);
6168 if ($line =~ /^Binary file (.+) matches$/) {
6169 $file = $1;
6170 $binary = 1;
6171 } else {
6172 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6174 if ($file ne $lastfile) {
6175 $lastfile and print "</td></tr>\n";
6176 if ($alternate++) {
6177 print "<tr class=\"dark\">\n";
6178 } else {
6179 print "<tr class=\"light\">\n";
6181 print "<td class=\"list\">".
6182 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6183 file_name=>"$file"),
6184 -class => "list"}, esc_path($file));
6185 print "</td><td>\n";
6186 $lastfile = $file;
6188 if ($binary) {
6189 print "<div class=\"binary\">Binary file</div>\n";
6190 } else {
6191 $ltext = untabify($ltext);
6192 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6193 $ltext = esc_html($1, -nbsp=>1);
6194 $ltext .= '<span class="match">';
6195 $ltext .= esc_html($2, -nbsp=>1);
6196 $ltext .= '</span>';
6197 $ltext .= esc_html($3, -nbsp=>1);
6198 } else {
6199 $ltext = esc_html($ltext, -nbsp=>1);
6201 print "<div class=\"pre\">" .
6202 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6203 file_name=>"$file").'#l'.$lno,
6204 -class => "linenr"}, sprintf('%4i', $lno))
6205 . ' ' . $ltext . "</div>\n";
6208 if ($lastfile) {
6209 print "</td></tr>\n";
6210 if ($matches > 1000) {
6211 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6213 } else {
6214 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6216 close $fd;
6218 print "</table>\n";
6220 git_footer_html();
6223 sub git_search_help {
6224 git_header_html();
6225 git_print_page_nav('','', $hash,$hash,$hash);
6226 print <<EOT;
6227 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6228 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6229 the pattern entered is recognized as the POSIX extended
6230 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6231 insensitive).</p>
6232 <dl>
6233 <dt><b>commit</b></dt>
6234 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6236 my $have_grep = gitweb_check_feature('grep');
6237 if ($have_grep) {
6238 print <<EOT;
6239 <dt><b>grep</b></dt>
6240 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6241 a different one) are searched for the given pattern. On large trees, this search can take
6242 a while and put some strain on the server, so please use it with some consideration. Note that
6243 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6244 case-sensitive.</dd>
6247 print <<EOT;
6248 <dt><b>author</b></dt>
6249 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6250 <dt><b>committer</b></dt>
6251 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6253 my $have_pickaxe = gitweb_check_feature('pickaxe');
6254 if ($have_pickaxe) {
6255 print <<EOT;
6256 <dt><b>pickaxe</b></dt>
6257 <dd>All commits that caused the string to appear or disappear from any file (changes that
6258 added, removed or "modified" the string) will be listed. This search can take a while and
6259 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6260 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6263 print "</dl>\n";
6264 git_footer_html();
6267 sub git_shortlog {
6268 my $head = git_get_head_hash($project);
6269 if (!defined $hash) {
6270 $hash = $head;
6272 if (!defined $page) {
6273 $page = 0;
6275 my $refs = git_get_references();
6277 my $commit_hash = $hash;
6278 if (defined $hash_parent) {
6279 $commit_hash = "$hash_parent..$hash";
6281 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6283 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6284 my $next_link = '';
6285 if ($#commitlist >= 100) {
6286 $next_link =
6287 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6288 -accesskey => "n", -title => "Alt-n"}, "next");
6290 my $patch_max = gitweb_check_feature('patches');
6291 if ($patch_max) {
6292 if ($patch_max < 0 || @commitlist <= $patch_max) {
6293 $paging_nav .= " &sdot; " .
6294 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6295 "patches");
6299 git_header_html();
6300 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6301 git_print_header_div('summary', $project);
6303 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6305 git_footer_html();
6308 ## ......................................................................
6309 ## feeds (RSS, Atom; OPML)
6311 sub git_feed {
6312 my $format = shift || 'atom';
6313 my $have_blame = gitweb_check_feature('blame');
6315 # Atom: http://www.atomenabled.org/developers/syndication/
6316 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6317 if ($format ne 'rss' && $format ne 'atom') {
6318 die_error(400, "Unknown web feed format");
6321 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6322 my $head = $hash || 'HEAD';
6323 my @commitlist = parse_commits($head, 150, 0, $file_name);
6325 my %latest_commit;
6326 my %latest_date;
6327 my $content_type = "application/$format+xml";
6328 if (defined $cgi->http('HTTP_ACCEPT') &&
6329 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6330 # browser (feed reader) prefers text/xml
6331 $content_type = 'text/xml';
6333 if (defined($commitlist[0])) {
6334 %latest_commit = %{$commitlist[0]};
6335 my $latest_epoch = $latest_commit{'committer_epoch'};
6336 %latest_date = parse_date($latest_epoch);
6337 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6338 if (defined $if_modified) {
6339 my $since;
6340 if (eval { require HTTP::Date; 1; }) {
6341 $since = HTTP::Date::str2time($if_modified);
6342 } elsif (eval { require Time::ParseDate; 1; }) {
6343 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6345 if (defined $since && $latest_epoch <= $since) {
6346 print $cgi->header(
6347 -type => $content_type,
6348 -charset => 'utf-8',
6349 -last_modified => $latest_date{'rfc2822'},
6350 -status => '304 Not Modified');
6351 return;
6354 print $cgi->header(
6355 -type => $content_type,
6356 -charset => 'utf-8',
6357 -last_modified => $latest_date{'rfc2822'});
6358 } else {
6359 print $cgi->header(
6360 -type => $content_type,
6361 -charset => 'utf-8');
6364 # Optimization: skip generating the body if client asks only
6365 # for Last-Modified date.
6366 return if ($cgi->request_method() eq 'HEAD');
6368 # header variables
6369 my $title = "$site_name - $project/$action";
6370 my $feed_type = 'log';
6371 if (defined $hash) {
6372 $title .= " - '$hash'";
6373 $feed_type = 'branch log';
6374 if (defined $file_name) {
6375 $title .= " :: $file_name";
6376 $feed_type = 'history';
6378 } elsif (defined $file_name) {
6379 $title .= " - $file_name";
6380 $feed_type = 'history';
6382 $title .= " $feed_type";
6383 my $descr = git_get_project_description($project);
6384 if (defined $descr) {
6385 $descr = esc_html($descr);
6386 } else {
6387 $descr = "$project " .
6388 ($format eq 'rss' ? 'RSS' : 'Atom') .
6389 " feed";
6391 my $owner = git_get_project_owner($project);
6392 $owner = esc_html($owner);
6394 #header
6395 my $alt_url;
6396 if (defined $file_name) {
6397 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6398 } elsif (defined $hash) {
6399 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6400 } else {
6401 $alt_url = href(-full=>1, action=>"summary");
6403 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6404 if ($format eq 'rss') {
6405 print <<XML;
6406 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6407 <channel>
6409 print "<title>$title</title>\n" .
6410 "<link>$alt_url</link>\n" .
6411 "<description>$descr</description>\n" .
6412 "<language>en</language>\n" .
6413 # project owner is responsible for 'editorial' content
6414 "<managingEditor>$owner</managingEditor>\n";
6415 if (defined $logo || defined $favicon) {
6416 # prefer the logo to the favicon, since RSS
6417 # doesn't allow both
6418 my $img = esc_url($logo || $favicon);
6419 print "<image>\n" .
6420 "<url>$img</url>\n" .
6421 "<title>$title</title>\n" .
6422 "<link>$alt_url</link>\n" .
6423 "</image>\n";
6425 if (%latest_date) {
6426 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6427 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6429 print "<generator>gitweb v.$version/$git_version</generator>\n";
6430 } elsif ($format eq 'atom') {
6431 print <<XML;
6432 <feed xmlns="http://www.w3.org/2005/Atom">
6434 print "<title>$title</title>\n" .
6435 "<subtitle>$descr</subtitle>\n" .
6436 '<link rel="alternate" type="text/html" href="' .
6437 $alt_url . '" />' . "\n" .
6438 '<link rel="self" type="' . $content_type . '" href="' .
6439 $cgi->self_url() . '" />' . "\n" .
6440 "<id>" . href(-full=>1) . "</id>\n" .
6441 # use project owner for feed author
6442 "<author><name>$owner</name></author>\n";
6443 if (defined $favicon) {
6444 print "<icon>" . esc_url($favicon) . "</icon>\n";
6446 if (defined $logo_url) {
6447 # not twice as wide as tall: 72 x 27 pixels
6448 print "<logo>" . esc_url($logo) . "</logo>\n";
6450 if (! %latest_date) {
6451 # dummy date to keep the feed valid until commits trickle in:
6452 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6453 } else {
6454 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6456 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6459 # contents
6460 for (my $i = 0; $i <= $#commitlist; $i++) {
6461 my %co = %{$commitlist[$i]};
6462 my $commit = $co{'id'};
6463 # we read 150, we always show 30 and the ones more recent than 48 hours
6464 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6465 last;
6467 my %cd = parse_date($co{'author_epoch'});
6469 # get list of changed files
6470 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6471 $co{'parent'} || "--root",
6472 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6473 or next;
6474 my @difftree = map { chomp; $_ } <$fd>;
6475 close $fd
6476 or next;
6478 # print element (entry, item)
6479 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6480 if ($format eq 'rss') {
6481 print "<item>\n" .
6482 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6483 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6484 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6485 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6486 "<link>$co_url</link>\n" .
6487 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6488 "<content:encoded>" .
6489 "<![CDATA[\n";
6490 } elsif ($format eq 'atom') {
6491 print "<entry>\n" .
6492 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6493 "<updated>$cd{'iso-8601'}</updated>\n" .
6494 "<author>\n" .
6495 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6496 if ($co{'author_email'}) {
6497 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6499 print "</author>\n" .
6500 # use committer for contributor
6501 "<contributor>\n" .
6502 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6503 if ($co{'committer_email'}) {
6504 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6506 print "</contributor>\n" .
6507 "<published>$cd{'iso-8601'}</published>\n" .
6508 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6509 "<id>$co_url</id>\n" .
6510 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6511 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6513 my $comment = $co{'comment'};
6514 print "<pre>\n";
6515 foreach my $line (@$comment) {
6516 $line = esc_html($line);
6517 print "$line\n";
6519 print "</pre><ul>\n";
6520 foreach my $difftree_line (@difftree) {
6521 my %difftree = parse_difftree_raw_line($difftree_line);
6522 next if !$difftree{'from_id'};
6524 my $file = $difftree{'file'} || $difftree{'to_file'};
6526 print "<li>" .
6527 "[" .
6528 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6529 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6530 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6531 file_name=>$file, file_parent=>$difftree{'from_file'}),
6532 -title => "diff"}, 'D');
6533 if ($have_blame) {
6534 print $cgi->a({-href => href(-full=>1, action=>"blame",
6535 file_name=>$file, hash_base=>$commit),
6536 -title => "blame"}, 'B');
6538 # if this is not a feed of a file history
6539 if (!defined $file_name || $file_name ne $file) {
6540 print $cgi->a({-href => href(-full=>1, action=>"history",
6541 file_name=>$file, hash=>$commit),
6542 -title => "history"}, 'H');
6544 $file = esc_path($file);
6545 print "] ".
6546 "$file</li>\n";
6548 if ($format eq 'rss') {
6549 print "</ul>]]>\n" .
6550 "</content:encoded>\n" .
6551 "</item>\n";
6552 } elsif ($format eq 'atom') {
6553 print "</ul>\n</div>\n" .
6554 "</content>\n" .
6555 "</entry>\n";
6559 # end of feed
6560 if ($format eq 'rss') {
6561 print "</channel>\n</rss>\n";
6562 } elsif ($format eq 'atom') {
6563 print "</feed>\n";
6567 sub git_rss {
6568 git_feed('rss');
6571 sub git_atom {
6572 git_feed('atom');
6575 sub git_opml {
6576 my @list = git_get_projects_list();
6578 print $cgi->header(
6579 -type => 'text/xml',
6580 -charset => 'utf-8',
6581 -content_disposition => 'inline; filename="opml.xml"');
6583 print <<XML;
6584 <?xml version="1.0" encoding="utf-8"?>
6585 <opml version="1.0">
6586 <head>
6587 <title>$site_name OPML Export</title>
6588 </head>
6589 <body>
6590 <outline text="git RSS feeds">
6593 foreach my $pr (@list) {
6594 my %proj = %$pr;
6595 my $head = git_get_head_hash($proj{'path'});
6596 if (!defined $head) {
6597 next;
6599 $git_dir = "$projectroot/$proj{'path'}";
6600 my %co = parse_commit($head);
6601 if (!%co) {
6602 next;
6605 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6606 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6607 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6608 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6610 print <<XML;
6611 </outline>
6612 </body>
6613 </opml>