Tagcloud: Point by_tag links at project_list, use href()
[git/gitweb.git] / gitweb / gitweb.perl
blob93379f5103888b044ef314b5e37d645a0f3a8e80
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, href(action=>'project_list', by_tag=>$_),
2290 $ctags_lc{$_}->{count});
2292 } else {
2293 $cloud = \%ctags_lc;
2295 $cloud;
2298 sub git_show_project_tagcloud {
2299 my ($cloud, $count) = @_;
2300 print STDERR ref($cloud)."..\n";
2301 if (ref $cloud eq 'HTML::TagCloud') {
2302 return $cloud->html_and_css($count);
2303 } else {
2304 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2305 return '<p align="center">' . join (', ', map {
2306 $cgi->a({-href => href(action=>'project_list', by_tag=>$_)},
2307 $cloud->{$_}->{topname});
2308 } splice(@tags, 0, $count)) . '</p>';
2312 sub git_get_project_url_list {
2313 my $path = shift;
2315 $git_dir = "$projectroot/$path";
2316 open my $fd, '<', "$git_dir/cloneurl"
2317 or return wantarray ?
2318 @{ config_to_multi(git_get_project_config('url')) } :
2319 config_to_multi(git_get_project_config('url'));
2320 my @git_project_url_list = map { chomp; $_ } <$fd>;
2321 close $fd;
2323 return wantarray ? @git_project_url_list : \@git_project_url_list;
2326 sub git_get_projects_list {
2327 my ($filter) = @_;
2328 my @list;
2330 $filter ||= '';
2331 $filter =~ s/\.git$//;
2333 my $check_forks = gitweb_check_feature('forks');
2335 if (-d $projects_list) {
2336 # search in directory
2337 my $dir = $projects_list . ($filter ? "/$filter" : '');
2338 # remove the trailing "/"
2339 $dir =~ s!/+$!!;
2340 my $pfxlen = length("$dir");
2341 my $pfxdepth = ($dir =~ tr!/!!);
2343 File::Find::find({
2344 follow_fast => 1, # follow symbolic links
2345 follow_skip => 2, # ignore duplicates
2346 dangling_symlinks => 0, # ignore dangling symlinks, silently
2347 wanted => sub {
2348 # skip project-list toplevel, if we get it.
2349 return if (m!^[/.]$!);
2350 # only directories can be git repositories
2351 return unless (-d $_);
2352 # don't traverse too deep (Find is super slow on os x)
2353 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2354 $File::Find::prune = 1;
2355 return;
2358 my $subdir = substr($File::Find::name, $pfxlen + 1);
2359 # we check related file in $projectroot
2360 my $path = ($filter ? "$filter/" : '') . $subdir;
2361 if (check_export_ok("$projectroot/$path")) {
2362 push @list, { path => $path };
2363 $File::Find::prune = 1;
2366 }, "$dir");
2368 } elsif (-f $projects_list) {
2369 # read from file(url-encoded):
2370 # 'git%2Fgit.git Linus+Torvalds'
2371 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2372 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2373 my %paths;
2374 open my $fd, '<', $projects_list or return;
2375 PROJECT:
2376 while (my $line = <$fd>) {
2377 chomp $line;
2378 my ($path, $owner) = split ' ', $line;
2379 $path = unescape($path);
2380 $owner = unescape($owner);
2381 if (!defined $path) {
2382 next;
2384 if ($filter ne '') {
2385 # looking for forks;
2386 my $pfx = substr($path, 0, length($filter));
2387 if ($pfx ne $filter) {
2388 next PROJECT;
2390 my $sfx = substr($path, length($filter));
2391 if ($sfx !~ /^\/.*\.git$/) {
2392 next PROJECT;
2394 } elsif ($check_forks) {
2395 PATH:
2396 foreach my $filter (keys %paths) {
2397 # looking for forks;
2398 my $pfx = substr($path, 0, length($filter));
2399 if ($pfx ne $filter) {
2400 next PATH;
2402 my $sfx = substr($path, length($filter));
2403 if ($sfx !~ /^\/.*\.git$/) {
2404 next PATH;
2406 # is a fork, don't include it in
2407 # the list
2408 next PROJECT;
2411 if (check_export_ok("$projectroot/$path")) {
2412 my $pr = {
2413 path => $path,
2414 owner => to_utf8($owner),
2416 push @list, $pr;
2417 (my $forks_path = $path) =~ s/\.git$//;
2418 $paths{$forks_path}++;
2421 close $fd;
2423 return @list;
2426 our $gitweb_project_owner = undef;
2427 sub git_get_project_list_from_file {
2429 return if (defined $gitweb_project_owner);
2431 $gitweb_project_owner = {};
2432 # read from file (url-encoded):
2433 # 'git%2Fgit.git Linus+Torvalds'
2434 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2435 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2436 if (-f $projects_list) {
2437 open(my $fd, '<', $projects_list);
2438 while (my $line = <$fd>) {
2439 chomp $line;
2440 my ($pr, $ow) = split ' ', $line;
2441 $pr = unescape($pr);
2442 $ow = unescape($ow);
2443 $gitweb_project_owner->{$pr} = to_utf8($ow);
2445 close $fd;
2449 sub git_get_project_owner {
2450 my $project = shift;
2451 my $owner;
2453 return undef unless $project;
2454 $git_dir = "$projectroot/$project";
2456 if (!defined $gitweb_project_owner) {
2457 git_get_project_list_from_file();
2460 if (exists $gitweb_project_owner->{$project}) {
2461 $owner = $gitweb_project_owner->{$project};
2463 if (!defined $owner){
2464 $owner = git_get_project_config('owner');
2466 if (!defined $owner) {
2467 $owner = get_file_owner("$git_dir");
2470 return $owner;
2473 sub git_get_last_activity {
2474 my ($path) = @_;
2475 my $fd;
2477 $git_dir = "$projectroot/$path";
2478 open($fd, "-|", git_cmd(), 'for-each-ref',
2479 '--format=%(committer)',
2480 '--sort=-committerdate',
2481 '--count=1',
2482 'refs/heads') or return;
2483 my $most_recent = <$fd>;
2484 close $fd or return;
2485 if (defined $most_recent &&
2486 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2487 my $timestamp = $1;
2488 my $age = time - $timestamp;
2489 return ($age, age_string($age));
2491 return (undef, undef);
2494 sub git_get_references {
2495 my $type = shift || "";
2496 my %refs;
2497 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2498 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2499 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2500 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2501 or return;
2503 while (my $line = <$fd>) {
2504 chomp $line;
2505 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2506 if (defined $refs{$1}) {
2507 push @{$refs{$1}}, $2;
2508 } else {
2509 $refs{$1} = [ $2 ];
2513 close $fd or return;
2514 return \%refs;
2517 sub git_get_rev_name_tags {
2518 my $hash = shift || return undef;
2520 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2521 or return;
2522 my $name_rev = <$fd>;
2523 close $fd;
2525 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2526 return $1;
2527 } else {
2528 # catches also '$hash undefined' output
2529 return undef;
2533 ## ----------------------------------------------------------------------
2534 ## parse to hash functions
2536 sub parse_date {
2537 my $epoch = shift;
2538 my $tz = shift || "-0000";
2540 my %date;
2541 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2542 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2543 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2544 $date{'hour'} = $hour;
2545 $date{'minute'} = $min;
2546 $date{'mday'} = $mday;
2547 $date{'day'} = $days[$wday];
2548 $date{'month'} = $months[$mon];
2549 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2550 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2551 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2552 $mday, $months[$mon], $hour ,$min;
2553 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2554 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2556 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2557 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2558 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2559 $date{'hour_local'} = $hour;
2560 $date{'minute_local'} = $min;
2561 $date{'tz_local'} = $tz;
2562 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2563 1900+$year, $mon+1, $mday,
2564 $hour, $min, $sec, $tz);
2565 return %date;
2568 sub parse_tag {
2569 my $tag_id = shift;
2570 my %tag;
2571 my @comment;
2573 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2574 $tag{'id'} = $tag_id;
2575 while (my $line = <$fd>) {
2576 chomp $line;
2577 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2578 $tag{'object'} = $1;
2579 } elsif ($line =~ m/^type (.+)$/) {
2580 $tag{'type'} = $1;
2581 } elsif ($line =~ m/^tag (.+)$/) {
2582 $tag{'name'} = $1;
2583 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2584 $tag{'author'} = $1;
2585 $tag{'author_epoch'} = $2;
2586 $tag{'author_tz'} = $3;
2587 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2588 $tag{'author_name'} = $1;
2589 $tag{'author_email'} = $2;
2590 } else {
2591 $tag{'author_name'} = $tag{'author'};
2593 } elsif ($line =~ m/--BEGIN/) {
2594 push @comment, $line;
2595 last;
2596 } elsif ($line eq "") {
2597 last;
2600 push @comment, <$fd>;
2601 $tag{'comment'} = \@comment;
2602 close $fd or return;
2603 if (!defined $tag{'name'}) {
2604 return
2606 return %tag
2609 sub parse_commit_text {
2610 my ($commit_text, $withparents) = @_;
2611 my @commit_lines = split '\n', $commit_text;
2612 my %co;
2614 pop @commit_lines; # Remove '\0'
2616 if (! @commit_lines) {
2617 return;
2620 my $header = shift @commit_lines;
2621 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2622 return;
2624 ($co{'id'}, my @parents) = split ' ', $header;
2625 while (my $line = shift @commit_lines) {
2626 last if $line eq "\n";
2627 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2628 $co{'tree'} = $1;
2629 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2630 push @parents, $1;
2631 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2632 $co{'author'} = to_utf8($1);
2633 $co{'author_epoch'} = $2;
2634 $co{'author_tz'} = $3;
2635 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2636 $co{'author_name'} = $1;
2637 $co{'author_email'} = $2;
2638 } else {
2639 $co{'author_name'} = $co{'author'};
2641 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2642 $co{'committer'} = to_utf8($1);
2643 $co{'committer_epoch'} = $2;
2644 $co{'committer_tz'} = $3;
2645 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2646 $co{'committer_name'} = $1;
2647 $co{'committer_email'} = $2;
2648 } else {
2649 $co{'committer_name'} = $co{'committer'};
2653 if (!defined $co{'tree'}) {
2654 return;
2656 $co{'parents'} = \@parents;
2657 $co{'parent'} = $parents[0];
2659 foreach my $title (@commit_lines) {
2660 $title =~ s/^ //;
2661 if ($title ne "") {
2662 $co{'title'} = chop_str($title, 80, 5);
2663 # remove leading stuff of merges to make the interesting part visible
2664 if (length($title) > 50) {
2665 $title =~ s/^Automatic //;
2666 $title =~ s/^merge (of|with) /Merge ... /i;
2667 if (length($title) > 50) {
2668 $title =~ s/(http|rsync):\/\///;
2670 if (length($title) > 50) {
2671 $title =~ s/(master|www|rsync)\.//;
2673 if (length($title) > 50) {
2674 $title =~ s/kernel.org:?//;
2676 if (length($title) > 50) {
2677 $title =~ s/\/pub\/scm//;
2680 $co{'title_short'} = chop_str($title, 50, 5);
2681 last;
2684 if (! defined $co{'title'} || $co{'title'} eq "") {
2685 $co{'title'} = $co{'title_short'} = '(no commit message)';
2687 # remove added spaces
2688 foreach my $line (@commit_lines) {
2689 $line =~ s/^ //;
2691 $co{'comment'} = \@commit_lines;
2693 my $age = time - $co{'committer_epoch'};
2694 $co{'age'} = $age;
2695 $co{'age_string'} = age_string($age);
2696 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2697 if ($age > 60*60*24*7*2) {
2698 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2699 $co{'age_string_age'} = $co{'age_string'};
2700 } else {
2701 $co{'age_string_date'} = $co{'age_string'};
2702 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2704 return %co;
2707 sub parse_commit {
2708 my ($commit_id) = @_;
2709 my %co;
2711 local $/ = "\0";
2713 open my $fd, "-|", git_cmd(), "rev-list",
2714 "--parents",
2715 "--header",
2716 "--max-count=1",
2717 $commit_id,
2718 "--",
2719 or die_error(500, "Open git-rev-list failed");
2720 %co = parse_commit_text(<$fd>, 1);
2721 close $fd;
2723 return %co;
2726 sub parse_commits {
2727 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2728 my @cos;
2730 $maxcount ||= 1;
2731 $skip ||= 0;
2733 local $/ = "\0";
2735 open my $fd, "-|", git_cmd(), "rev-list",
2736 "--header",
2737 @args,
2738 ("--max-count=" . $maxcount),
2739 ("--skip=" . $skip),
2740 @extra_options,
2741 $commit_id,
2742 "--",
2743 ($filename ? ($filename) : ())
2744 or die_error(500, "Open git-rev-list failed");
2745 while (my $line = <$fd>) {
2746 my %co = parse_commit_text($line);
2747 push @cos, \%co;
2749 close $fd;
2751 return wantarray ? @cos : \@cos;
2754 # parse line of git-diff-tree "raw" output
2755 sub parse_difftree_raw_line {
2756 my $line = shift;
2757 my %res;
2759 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2760 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2761 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2762 $res{'from_mode'} = $1;
2763 $res{'to_mode'} = $2;
2764 $res{'from_id'} = $3;
2765 $res{'to_id'} = $4;
2766 $res{'status'} = $5;
2767 $res{'similarity'} = $6;
2768 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2769 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2770 } else {
2771 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2774 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2775 # combined diff (for merge commit)
2776 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2777 $res{'nparents'} = length($1);
2778 $res{'from_mode'} = [ split(' ', $2) ];
2779 $res{'to_mode'} = pop @{$res{'from_mode'}};
2780 $res{'from_id'} = [ split(' ', $3) ];
2781 $res{'to_id'} = pop @{$res{'from_id'}};
2782 $res{'status'} = [ split('', $4) ];
2783 $res{'to_file'} = unquote($5);
2785 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2786 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2787 $res{'commit'} = $1;
2790 return wantarray ? %res : \%res;
2793 # wrapper: return parsed line of git-diff-tree "raw" output
2794 # (the argument might be raw line, or parsed info)
2795 sub parsed_difftree_line {
2796 my $line_or_ref = shift;
2798 if (ref($line_or_ref) eq "HASH") {
2799 # pre-parsed (or generated by hand)
2800 return $line_or_ref;
2801 } else {
2802 return parse_difftree_raw_line($line_or_ref);
2806 # parse line of git-ls-tree output
2807 sub parse_ls_tree_line {
2808 my $line = shift;
2809 my %opts = @_;
2810 my %res;
2812 if ($opts{'-l'}) {
2813 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
2814 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
2816 $res{'mode'} = $1;
2817 $res{'type'} = $2;
2818 $res{'hash'} = $3;
2819 $res{'size'} = $4;
2820 if ($opts{'-z'}) {
2821 $res{'name'} = $5;
2822 } else {
2823 $res{'name'} = unquote($5);
2825 } else {
2826 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2827 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2829 $res{'mode'} = $1;
2830 $res{'type'} = $2;
2831 $res{'hash'} = $3;
2832 if ($opts{'-z'}) {
2833 $res{'name'} = $4;
2834 } else {
2835 $res{'name'} = unquote($4);
2839 return wantarray ? %res : \%res;
2842 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2843 sub parse_from_to_diffinfo {
2844 my ($diffinfo, $from, $to, @parents) = @_;
2846 if ($diffinfo->{'nparents'}) {
2847 # combined diff
2848 $from->{'file'} = [];
2849 $from->{'href'} = [];
2850 fill_from_file_info($diffinfo, @parents)
2851 unless exists $diffinfo->{'from_file'};
2852 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2853 $from->{'file'}[$i] =
2854 defined $diffinfo->{'from_file'}[$i] ?
2855 $diffinfo->{'from_file'}[$i] :
2856 $diffinfo->{'to_file'};
2857 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2858 $from->{'href'}[$i] = href(action=>"blob",
2859 hash_base=>$parents[$i],
2860 hash=>$diffinfo->{'from_id'}[$i],
2861 file_name=>$from->{'file'}[$i]);
2862 } else {
2863 $from->{'href'}[$i] = undef;
2866 } else {
2867 # ordinary (not combined) diff
2868 $from->{'file'} = $diffinfo->{'from_file'};
2869 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2870 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2871 hash=>$diffinfo->{'from_id'},
2872 file_name=>$from->{'file'});
2873 } else {
2874 delete $from->{'href'};
2878 $to->{'file'} = $diffinfo->{'to_file'};
2879 if (!is_deleted($diffinfo)) { # file exists in result
2880 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2881 hash=>$diffinfo->{'to_id'},
2882 file_name=>$to->{'file'});
2883 } else {
2884 delete $to->{'href'};
2888 ## ......................................................................
2889 ## parse to array of hashes functions
2891 sub git_get_heads_list {
2892 my $limit = shift;
2893 my @headslist;
2895 open my $fd, '-|', git_cmd(), 'for-each-ref',
2896 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2897 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2898 'refs/heads'
2899 or return;
2900 while (my $line = <$fd>) {
2901 my %ref_item;
2903 chomp $line;
2904 my ($refinfo, $committerinfo) = split(/\0/, $line);
2905 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2906 my ($committer, $epoch, $tz) =
2907 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2908 $ref_item{'fullname'} = $name;
2909 $name =~ s!^refs/heads/!!;
2911 $ref_item{'name'} = $name;
2912 $ref_item{'id'} = $hash;
2913 $ref_item{'title'} = $title || '(no commit message)';
2914 $ref_item{'epoch'} = $epoch;
2915 if ($epoch) {
2916 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2917 } else {
2918 $ref_item{'age'} = "unknown";
2921 push @headslist, \%ref_item;
2923 close $fd;
2925 return wantarray ? @headslist : \@headslist;
2928 sub git_get_tags_list {
2929 my $limit = shift;
2930 my @tagslist;
2932 open my $fd, '-|', git_cmd(), 'for-each-ref',
2933 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2934 '--format=%(objectname) %(objecttype) %(refname) '.
2935 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2936 'refs/tags'
2937 or return;
2938 while (my $line = <$fd>) {
2939 my %ref_item;
2941 chomp $line;
2942 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2943 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2944 my ($creator, $epoch, $tz) =
2945 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2946 $ref_item{'fullname'} = $name;
2947 $name =~ s!^refs/tags/!!;
2949 $ref_item{'type'} = $type;
2950 $ref_item{'id'} = $id;
2951 $ref_item{'name'} = $name;
2952 if ($type eq "tag") {
2953 $ref_item{'subject'} = $title;
2954 $ref_item{'reftype'} = $reftype;
2955 $ref_item{'refid'} = $refid;
2956 } else {
2957 $ref_item{'reftype'} = $type;
2958 $ref_item{'refid'} = $id;
2961 if ($type eq "tag" || $type eq "commit") {
2962 $ref_item{'epoch'} = $epoch;
2963 if ($epoch) {
2964 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2965 } else {
2966 $ref_item{'age'} = "unknown";
2970 push @tagslist, \%ref_item;
2972 close $fd;
2974 return wantarray ? @tagslist : \@tagslist;
2977 ## ----------------------------------------------------------------------
2978 ## filesystem-related functions
2980 sub get_file_owner {
2981 my $path = shift;
2983 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2984 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2985 if (!defined $gcos) {
2986 return undef;
2988 my $owner = $gcos;
2989 $owner =~ s/[,;].*$//;
2990 return to_utf8($owner);
2993 # assume that file exists
2994 sub insert_file {
2995 my $filename = shift;
2997 open my $fd, '<', $filename;
2998 print map { to_utf8($_) } <$fd>;
2999 close $fd;
3002 ## ......................................................................
3003 ## mimetype related functions
3005 sub mimetype_guess_file {
3006 my $filename = shift;
3007 my $mimemap = shift;
3008 -r $mimemap or return undef;
3010 my %mimemap;
3011 open(my $mh, '<', $mimemap) or return undef;
3012 while (<$mh>) {
3013 next if m/^#/; # skip comments
3014 my ($mimetype, $exts) = split(/\t+/);
3015 if (defined $exts) {
3016 my @exts = split(/\s+/, $exts);
3017 foreach my $ext (@exts) {
3018 $mimemap{$ext} = $mimetype;
3022 close($mh);
3024 $filename =~ /\.([^.]*)$/;
3025 return $mimemap{$1};
3028 sub mimetype_guess {
3029 my $filename = shift;
3030 my $mime;
3031 $filename =~ /\./ or return undef;
3033 if ($mimetypes_file) {
3034 my $file = $mimetypes_file;
3035 if ($file !~ m!^/!) { # if it is relative path
3036 # it is relative to project
3037 $file = "$projectroot/$project/$file";
3039 $mime = mimetype_guess_file($filename, $file);
3041 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3042 return $mime;
3045 sub blob_mimetype {
3046 my $fd = shift;
3047 my $filename = shift;
3049 if ($filename) {
3050 my $mime = mimetype_guess($filename);
3051 $mime and return $mime;
3054 # just in case
3055 return $default_blob_plain_mimetype unless $fd;
3057 if (-T $fd) {
3058 return 'text/plain';
3059 } elsif (! $filename) {
3060 return 'application/octet-stream';
3061 } elsif ($filename =~ m/\.png$/i) {
3062 return 'image/png';
3063 } elsif ($filename =~ m/\.gif$/i) {
3064 return 'image/gif';
3065 } elsif ($filename =~ m/\.jpe?g$/i) {
3066 return 'image/jpeg';
3067 } else {
3068 return 'application/octet-stream';
3072 sub blob_contenttype {
3073 my ($fd, $file_name, $type) = @_;
3075 $type ||= blob_mimetype($fd, $file_name);
3076 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3077 $type .= "; charset=$default_text_plain_charset";
3080 return $type;
3083 ## ======================================================================
3084 ## functions printing HTML: header, footer, error page
3086 sub git_header_html {
3087 my $status = shift || "200 OK";
3088 my $expires = shift;
3090 my $title = "$site_name";
3091 if (defined $project) {
3092 $title .= " - " . to_utf8($project);
3093 if (defined $action) {
3094 $title .= "/$action";
3095 if (defined $file_name) {
3096 $title .= " - " . esc_path($file_name);
3097 if ($action eq "tree" && $file_name !~ m|/$|) {
3098 $title .= "/";
3103 my $content_type;
3104 # require explicit support from the UA if we are to send the page as
3105 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3106 # we have to do this because MSIE sometimes globs '*/*', pretending to
3107 # support xhtml+xml but choking when it gets what it asked for.
3108 if (defined $cgi->http('HTTP_ACCEPT') &&
3109 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3110 $cgi->Accept('application/xhtml+xml') != 0) {
3111 $content_type = 'application/xhtml+xml';
3112 } else {
3113 $content_type = 'text/html';
3115 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3116 -status=> $status, -expires => $expires);
3117 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3118 print <<EOF;
3119 <?xml version="1.0" encoding="utf-8"?>
3120 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3121 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3122 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3123 <!-- git core binaries version $git_version -->
3124 <head>
3125 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3126 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3127 <meta name="robots" content="index, nofollow"/>
3128 <title>$title</title>
3130 # the stylesheet, favicon etc urls won't work correctly with path_info
3131 # unless we set the appropriate base URL
3132 if ($ENV{'PATH_INFO'}) {
3133 print "<base href=\"".esc_url($base_url)."\" />\n";
3135 # print out each stylesheet that exist, providing backwards capability
3136 # for those people who defined $stylesheet in a config file
3137 if (defined $stylesheet) {
3138 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3139 } else {
3140 foreach my $stylesheet (@stylesheets) {
3141 next unless $stylesheet;
3142 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3145 if (defined $project) {
3146 my %href_params = get_feed_info();
3147 if (!exists $href_params{'-title'}) {
3148 $href_params{'-title'} = 'log';
3151 foreach my $format qw(RSS Atom) {
3152 my $type = lc($format);
3153 my %link_attr = (
3154 '-rel' => 'alternate',
3155 '-title' => "$project - $href_params{'-title'} - $format feed",
3156 '-type' => "application/$type+xml"
3159 $href_params{'action'} = $type;
3160 $link_attr{'-href'} = href(%href_params);
3161 print "<link ".
3162 "rel=\"$link_attr{'-rel'}\" ".
3163 "title=\"$link_attr{'-title'}\" ".
3164 "href=\"$link_attr{'-href'}\" ".
3165 "type=\"$link_attr{'-type'}\" ".
3166 "/>\n";
3168 $href_params{'extra_options'} = '--no-merges';
3169 $link_attr{'-href'} = href(%href_params);
3170 $link_attr{'-title'} .= ' (no merges)';
3171 print "<link ".
3172 "rel=\"$link_attr{'-rel'}\" ".
3173 "title=\"$link_attr{'-title'}\" ".
3174 "href=\"$link_attr{'-href'}\" ".
3175 "type=\"$link_attr{'-type'}\" ".
3176 "/>\n";
3179 } else {
3180 printf('<link rel="alternate" title="%s projects list" '.
3181 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3182 $site_name, href(project=>undef, action=>"project_index"));
3183 printf('<link rel="alternate" title="%s projects feeds" '.
3184 'href="%s" type="text/x-opml" />'."\n",
3185 $site_name, href(project=>undef, action=>"opml"));
3187 if (defined $favicon) {
3188 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3191 print "</head>\n" .
3192 "<body>\n";
3194 if (-f $site_header) {
3195 insert_file($site_header);
3198 print "<div class=\"page_header\">\n" .
3199 $cgi->a({-href => esc_url($logo_url),
3200 -title => $logo_label},
3201 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3202 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3203 if (defined $project) {
3204 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3205 if (defined $action) {
3206 print " / $action";
3208 print "\n";
3210 print "</div>\n";
3212 my $have_search = gitweb_check_feature('search');
3213 if (defined $project && $have_search) {
3214 if (!defined $searchtext) {
3215 $searchtext = "";
3217 my $search_hash;
3218 if (defined $hash_base) {
3219 $search_hash = $hash_base;
3220 } elsif (defined $hash) {
3221 $search_hash = $hash;
3222 } else {
3223 $search_hash = "HEAD";
3225 my $action = $my_uri;
3226 my $use_pathinfo = gitweb_check_feature('pathinfo');
3227 if ($use_pathinfo) {
3228 $action .= "/".esc_url($project);
3230 print $cgi->startform(-method => "get", -action => $action) .
3231 "<div class=\"search\">\n" .
3232 (!$use_pathinfo &&
3233 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3234 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3235 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3236 $cgi->popup_menu(-name => 'st', -default => 'commit',
3237 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3238 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3239 " search:\n",
3240 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3241 "<span title=\"Extended regular expression\">" .
3242 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3243 -checked => $search_use_regexp) .
3244 "</span>" .
3245 "</div>" .
3246 $cgi->end_form() . "\n";
3250 sub git_footer_html {
3251 my $feed_class = 'rss_logo';
3253 print "<div class=\"page_footer\">\n";
3254 if (defined $project) {
3255 my $descr = git_get_project_description($project);
3256 if (defined $descr) {
3257 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3260 my %href_params = get_feed_info();
3261 if (!%href_params) {
3262 $feed_class .= ' generic';
3264 $href_params{'-title'} ||= 'log';
3266 foreach my $format qw(RSS Atom) {
3267 $href_params{'action'} = lc($format);
3268 print $cgi->a({-href => href(%href_params),
3269 -title => "$href_params{'-title'} $format feed",
3270 -class => $feed_class}, $format)."\n";
3273 } else {
3274 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3275 -class => $feed_class}, "OPML") . " ";
3276 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3277 -class => $feed_class}, "TXT") . "\n";
3279 print "</div>\n"; # class="page_footer"
3281 if (-f $site_footer) {
3282 insert_file($site_footer);
3285 print "</body>\n" .
3286 "</html>";
3289 # die_error(<http_status_code>, <error_message>)
3290 # Example: die_error(404, 'Hash not found')
3291 # By convention, use the following status codes (as defined in RFC 2616):
3292 # 400: Invalid or missing CGI parameters, or
3293 # requested object exists but has wrong type.
3294 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3295 # this server or project.
3296 # 404: Requested object/revision/project doesn't exist.
3297 # 500: The server isn't configured properly, or
3298 # an internal error occurred (e.g. failed assertions caused by bugs), or
3299 # an unknown error occurred (e.g. the git binary died unexpectedly).
3300 sub die_error {
3301 my $status = shift || 500;
3302 my $error = shift || "Internal server error";
3304 my %http_responses = (400 => '400 Bad Request',
3305 403 => '403 Forbidden',
3306 404 => '404 Not Found',
3307 500 => '500 Internal Server Error');
3308 git_header_html($http_responses{$status});
3309 print <<EOF;
3310 <div class="page_body">
3311 <br /><br />
3312 $status - $error
3313 <br />
3314 </div>
3316 git_footer_html();
3317 exit;
3320 ## ----------------------------------------------------------------------
3321 ## functions printing or outputting HTML: navigation
3323 sub git_print_page_nav {
3324 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3325 $extra = '' if !defined $extra; # pager or formats
3327 my @navs = qw(summary shortlog log commit commitdiff tree);
3328 if ($suppress) {
3329 @navs = grep { $_ ne $suppress } @navs;
3332 my %arg = map { $_ => {action=>$_} } @navs;
3333 if (defined $head) {
3334 for (qw(commit commitdiff)) {
3335 $arg{$_}{'hash'} = $head;
3337 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3338 for (qw(shortlog log)) {
3339 $arg{$_}{'hash'} = $head;
3344 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3345 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3347 my @actions = gitweb_get_feature('actions');
3348 my %repl = (
3349 '%' => '%',
3350 'n' => $project, # project name
3351 'f' => $git_dir, # project path within filesystem
3352 'h' => $treehead || '', # current hash ('h' parameter)
3353 'b' => $treebase || '', # hash base ('hb' parameter)
3355 while (@actions) {
3356 my ($label, $link, $pos) = splice(@actions,0,3);
3357 # insert
3358 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3359 # munch munch
3360 $link =~ s/%([%nfhb])/$repl{$1}/g;
3361 $arg{$label}{'_href'} = $link;
3364 print "<div class=\"page_nav\">\n" .
3365 (join " | ",
3366 map { $_ eq $current ?
3367 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3368 } @navs);
3369 print "<br/>\n$extra<br/>\n" .
3370 "</div>\n";
3373 sub format_paging_nav {
3374 my ($action, $hash, $head, $page, $has_next_link) = @_;
3375 my $paging_nav;
3378 if ($hash ne $head || $page) {
3379 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3380 } else {
3381 $paging_nav .= "HEAD";
3384 if ($page > 0) {
3385 $paging_nav .= " &sdot; " .
3386 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3387 -accesskey => "p", -title => "Alt-p"}, "prev");
3388 } else {
3389 $paging_nav .= " &sdot; prev";
3392 if ($has_next_link) {
3393 $paging_nav .= " &sdot; " .
3394 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3395 -accesskey => "n", -title => "Alt-n"}, "next");
3396 } else {
3397 $paging_nav .= " &sdot; next";
3400 return $paging_nav;
3403 ## ......................................................................
3404 ## functions printing or outputting HTML: div
3406 sub git_print_header_div {
3407 my ($action, $title, $hash, $hash_base) = @_;
3408 my %args = ();
3410 $args{'action'} = $action;
3411 $args{'hash'} = $hash if $hash;
3412 $args{'hash_base'} = $hash_base if $hash_base;
3414 print "<div class=\"header\">\n" .
3415 $cgi->a({-href => href(%args), -class => "title"},
3416 $title ? $title : $action) .
3417 "\n</div>\n";
3420 sub print_local_time {
3421 my %date = @_;
3422 if ($date{'hour_local'} < 6) {
3423 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3424 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3425 } else {
3426 printf(" (%02d:%02d %s)",
3427 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3431 # Outputs the author name and date in long form
3432 sub git_print_authorship {
3433 my $co = shift;
3434 my %opts = @_;
3435 my $tag = $opts{-tag} || 'div';
3436 my $author = $co->{'author_name'};
3438 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3439 print "<$tag class=\"author_date\">" .
3440 format_search_author($author, "author", esc_html($author)) .
3441 " [$ad{'rfc2822'}";
3442 print_local_time(%ad) if ($opts{-localtime});
3443 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3444 . "</$tag>\n";
3447 # Outputs table rows containing the full author or committer information,
3448 # in the format expected for 'commit' view (& similia).
3449 # Parameters are a commit hash reference, followed by the list of people
3450 # to output information for. If the list is empty it defalts to both
3451 # author and committer.
3452 sub git_print_authorship_rows {
3453 my $co = shift;
3454 # too bad we can't use @people = @_ || ('author', 'committer')
3455 my @people = @_;
3456 @people = ('author', 'committer') unless @people;
3457 foreach my $who (@people) {
3458 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3459 print "<tr><td>$who</td><td>" .
3460 format_search_author($co->{"${who}_name"}, $who,
3461 esc_html($co->{"${who}_name"})) . " " .
3462 format_search_author($co->{"${who}_email"}, $who,
3463 esc_html("<" . $co->{"${who}_email"} . ">")) .
3464 "</td><td rowspan=\"2\">" .
3465 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3466 "</td></tr>\n" .
3467 "<tr>" .
3468 "<td></td><td> $wd{'rfc2822'}";
3469 print_local_time(%wd);
3470 print "</td>" .
3471 "</tr>\n";
3475 sub git_print_page_path {
3476 my $name = shift;
3477 my $type = shift;
3478 my $hb = shift;
3481 print "<div class=\"page_path\">";
3482 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3483 -title => 'tree root'}, to_utf8("[$project]"));
3484 print " / ";
3485 if (defined $name) {
3486 my @dirname = split '/', $name;
3487 my $basename = pop @dirname;
3488 my $fullname = '';
3490 foreach my $dir (@dirname) {
3491 $fullname .= ($fullname ? '/' : '') . $dir;
3492 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3493 hash_base=>$hb),
3494 -title => $fullname}, esc_path($dir));
3495 print " / ";
3497 if (defined $type && $type eq 'blob') {
3498 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3499 hash_base=>$hb),
3500 -title => $name}, esc_path($basename));
3501 } elsif (defined $type && $type eq 'tree') {
3502 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3503 hash_base=>$hb),
3504 -title => $name}, esc_path($basename));
3505 print " / ";
3506 } else {
3507 print esc_path($basename);
3510 print "<br/></div>\n";
3513 sub git_print_log {
3514 my $log = shift;
3515 my %opts = @_;
3517 if ($opts{'-remove_title'}) {
3518 # remove title, i.e. first line of log
3519 shift @$log;
3521 # remove leading empty lines
3522 while (defined $log->[0] && $log->[0] eq "") {
3523 shift @$log;
3526 # print log
3527 my $signoff = 0;
3528 my $empty = 0;
3529 foreach my $line (@$log) {
3530 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3531 $signoff = 1;
3532 $empty = 0;
3533 if (! $opts{'-remove_signoff'}) {
3534 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3535 next;
3536 } else {
3537 # remove signoff lines
3538 next;
3540 } else {
3541 $signoff = 0;
3544 # print only one empty line
3545 # do not print empty line after signoff
3546 if ($line eq "") {
3547 next if ($empty || $signoff);
3548 $empty = 1;
3549 } else {
3550 $empty = 0;
3553 print format_log_line_html($line) . "<br/>\n";
3556 if ($opts{'-final_empty_line'}) {
3557 # end with single empty line
3558 print "<br/>\n" unless $empty;
3562 # return link target (what link points to)
3563 sub git_get_link_target {
3564 my $hash = shift;
3565 my $link_target;
3567 # read link
3568 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3569 or return;
3571 local $/ = undef;
3572 $link_target = <$fd>;
3574 close $fd
3575 or return;
3577 return $link_target;
3580 # given link target, and the directory (basedir) the link is in,
3581 # return target of link relative to top directory (top tree);
3582 # return undef if it is not possible (including absolute links).
3583 sub normalize_link_target {
3584 my ($link_target, $basedir) = @_;
3586 # absolute symlinks (beginning with '/') cannot be normalized
3587 return if (substr($link_target, 0, 1) eq '/');
3589 # normalize link target to path from top (root) tree (dir)
3590 my $path;
3591 if ($basedir) {
3592 $path = $basedir . '/' . $link_target;
3593 } else {
3594 # we are in top (root) tree (dir)
3595 $path = $link_target;
3598 # remove //, /./, and /../
3599 my @path_parts;
3600 foreach my $part (split('/', $path)) {
3601 # discard '.' and ''
3602 next if (!$part || $part eq '.');
3603 # handle '..'
3604 if ($part eq '..') {
3605 if (@path_parts) {
3606 pop @path_parts;
3607 } else {
3608 # link leads outside repository (outside top dir)
3609 return;
3611 } else {
3612 push @path_parts, $part;
3615 $path = join('/', @path_parts);
3617 return $path;
3620 # print tree entry (row of git_tree), but without encompassing <tr> element
3621 sub git_print_tree_entry {
3622 my ($t, $basedir, $hash_base, $have_blame) = @_;
3624 my %base_key = ();
3625 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3627 # The format of a table row is: mode list link. Where mode is
3628 # the mode of the entry, list is the name of the entry, an href,
3629 # and link is the action links of the entry.
3631 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3632 if (exists $t->{'size'}) {
3633 print "<td class=\"size\">$t->{'size'}</td>\n";
3635 if ($t->{'type'} eq "blob") {
3636 print "<td class=\"list\">" .
3637 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3638 file_name=>"$basedir$t->{'name'}", %base_key),
3639 -class => "list"}, esc_path($t->{'name'}));
3640 if (S_ISLNK(oct $t->{'mode'})) {
3641 my $link_target = git_get_link_target($t->{'hash'});
3642 if ($link_target) {
3643 my $norm_target = normalize_link_target($link_target, $basedir);
3644 if (defined $norm_target) {
3645 print " -> " .
3646 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3647 file_name=>$norm_target),
3648 -title => $norm_target}, esc_path($link_target));
3649 } else {
3650 print " -> " . esc_path($link_target);
3654 print "</td>\n";
3655 print "<td class=\"link\">";
3656 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3657 file_name=>"$basedir$t->{'name'}", %base_key)},
3658 "blob");
3659 if ($have_blame) {
3660 print " | " .
3661 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3662 file_name=>"$basedir$t->{'name'}", %base_key)},
3663 "blame");
3665 if (defined $hash_base) {
3666 print " | " .
3667 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3668 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3669 "history");
3671 print " | " .
3672 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3673 file_name=>"$basedir$t->{'name'}")},
3674 "raw");
3675 print "</td>\n";
3677 } elsif ($t->{'type'} eq "tree") {
3678 print "<td class=\"list\">";
3679 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3680 file_name=>"$basedir$t->{'name'}",
3681 %base_key)},
3682 esc_path($t->{'name'}));
3683 print "</td>\n";
3684 print "<td class=\"link\">";
3685 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3686 file_name=>"$basedir$t->{'name'}",
3687 %base_key)},
3688 "tree");
3689 if (defined $hash_base) {
3690 print " | " .
3691 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3692 file_name=>"$basedir$t->{'name'}")},
3693 "history");
3695 print "</td>\n";
3696 } else {
3697 # unknown object: we can only present history for it
3698 # (this includes 'commit' object, i.e. submodule support)
3699 print "<td class=\"list\">" .
3700 esc_path($t->{'name'}) .
3701 "</td>\n";
3702 print "<td class=\"link\">";
3703 if (defined $hash_base) {
3704 print $cgi->a({-href => href(action=>"history",
3705 hash_base=>$hash_base,
3706 file_name=>"$basedir$t->{'name'}")},
3707 "history");
3709 print "</td>\n";
3713 ## ......................................................................
3714 ## functions printing large fragments of HTML
3716 # get pre-image filenames for merge (combined) diff
3717 sub fill_from_file_info {
3718 my ($diff, @parents) = @_;
3720 $diff->{'from_file'} = [ ];
3721 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3722 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3723 if ($diff->{'status'}[$i] eq 'R' ||
3724 $diff->{'status'}[$i] eq 'C') {
3725 $diff->{'from_file'}[$i] =
3726 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3730 return $diff;
3733 # is current raw difftree line of file deletion
3734 sub is_deleted {
3735 my $diffinfo = shift;
3737 return $diffinfo->{'to_id'} eq ('0' x 40);
3740 # does patch correspond to [previous] difftree raw line
3741 # $diffinfo - hashref of parsed raw diff format
3742 # $patchinfo - hashref of parsed patch diff format
3743 # (the same keys as in $diffinfo)
3744 sub is_patch_split {
3745 my ($diffinfo, $patchinfo) = @_;
3747 return defined $diffinfo && defined $patchinfo
3748 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3752 sub git_difftree_body {
3753 my ($difftree, $hash, @parents) = @_;
3754 my ($parent) = $parents[0];
3755 my $have_blame = gitweb_check_feature('blame');
3756 print "<div class=\"list_head\">\n";
3757 if ($#{$difftree} > 10) {
3758 print(($#{$difftree} + 1) . " files changed:\n");
3760 print "</div>\n";
3762 print "<table class=\"" .
3763 (@parents > 1 ? "combined " : "") .
3764 "diff_tree\">\n";
3766 # header only for combined diff in 'commitdiff' view
3767 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3768 if ($has_header) {
3769 # table header
3770 print "<thead><tr>\n" .
3771 "<th></th><th></th>\n"; # filename, patchN link
3772 for (my $i = 0; $i < @parents; $i++) {
3773 my $par = $parents[$i];
3774 print "<th>" .
3775 $cgi->a({-href => href(action=>"commitdiff",
3776 hash=>$hash, hash_parent=>$par),
3777 -title => 'commitdiff to parent number ' .
3778 ($i+1) . ': ' . substr($par,0,7)},
3779 $i+1) .
3780 "&nbsp;</th>\n";
3782 print "</tr></thead>\n<tbody>\n";
3785 my $alternate = 1;
3786 my $patchno = 0;
3787 foreach my $line (@{$difftree}) {
3788 my $diff = parsed_difftree_line($line);
3790 if ($alternate) {
3791 print "<tr class=\"dark\">\n";
3792 } else {
3793 print "<tr class=\"light\">\n";
3795 $alternate ^= 1;
3797 if (exists $diff->{'nparents'}) { # combined diff
3799 fill_from_file_info($diff, @parents)
3800 unless exists $diff->{'from_file'};
3802 if (!is_deleted($diff)) {
3803 # file exists in the result (child) commit
3804 print "<td>" .
3805 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3806 file_name=>$diff->{'to_file'},
3807 hash_base=>$hash),
3808 -class => "list"}, esc_path($diff->{'to_file'})) .
3809 "</td>\n";
3810 } else {
3811 print "<td>" .
3812 esc_path($diff->{'to_file'}) .
3813 "</td>\n";
3816 if ($action eq 'commitdiff') {
3817 # link to patch
3818 $patchno++;
3819 print "<td class=\"link\">" .
3820 $cgi->a({-href => "#patch$patchno"}, "patch") .
3821 " | " .
3822 "</td>\n";
3825 my $has_history = 0;
3826 my $not_deleted = 0;
3827 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3828 my $hash_parent = $parents[$i];
3829 my $from_hash = $diff->{'from_id'}[$i];
3830 my $from_path = $diff->{'from_file'}[$i];
3831 my $status = $diff->{'status'}[$i];
3833 $has_history ||= ($status ne 'A');
3834 $not_deleted ||= ($status ne 'D');
3836 if ($status eq 'A') {
3837 print "<td class=\"link\" align=\"right\"> | </td>\n";
3838 } elsif ($status eq 'D') {
3839 print "<td class=\"link\">" .
3840 $cgi->a({-href => href(action=>"blob",
3841 hash_base=>$hash,
3842 hash=>$from_hash,
3843 file_name=>$from_path)},
3844 "blob" . ($i+1)) .
3845 " | </td>\n";
3846 } else {
3847 if ($diff->{'to_id'} eq $from_hash) {
3848 print "<td class=\"link nochange\">";
3849 } else {
3850 print "<td class=\"link\">";
3852 print $cgi->a({-href => href(action=>"blobdiff",
3853 hash=>$diff->{'to_id'},
3854 hash_parent=>$from_hash,
3855 hash_base=>$hash,
3856 hash_parent_base=>$hash_parent,
3857 file_name=>$diff->{'to_file'},
3858 file_parent=>$from_path)},
3859 "diff" . ($i+1)) .
3860 " | </td>\n";
3864 print "<td class=\"link\">";
3865 if ($not_deleted) {
3866 print $cgi->a({-href => href(action=>"blob",
3867 hash=>$diff->{'to_id'},
3868 file_name=>$diff->{'to_file'},
3869 hash_base=>$hash)},
3870 "blob");
3871 print " | " if ($has_history);
3873 if ($has_history) {
3874 print $cgi->a({-href => href(action=>"history",
3875 file_name=>$diff->{'to_file'},
3876 hash_base=>$hash)},
3877 "history");
3879 print "</td>\n";
3881 print "</tr>\n";
3882 next; # instead of 'else' clause, to avoid extra indent
3884 # else ordinary diff
3886 my ($to_mode_oct, $to_mode_str, $to_file_type);
3887 my ($from_mode_oct, $from_mode_str, $from_file_type);
3888 if ($diff->{'to_mode'} ne ('0' x 6)) {
3889 $to_mode_oct = oct $diff->{'to_mode'};
3890 if (S_ISREG($to_mode_oct)) { # only for regular file
3891 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3893 $to_file_type = file_type($diff->{'to_mode'});
3895 if ($diff->{'from_mode'} ne ('0' x 6)) {
3896 $from_mode_oct = oct $diff->{'from_mode'};
3897 if (S_ISREG($to_mode_oct)) { # only for regular file
3898 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3900 $from_file_type = file_type($diff->{'from_mode'});
3903 if ($diff->{'status'} eq "A") { # created
3904 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3905 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3906 $mode_chng .= "]</span>";
3907 print "<td>";
3908 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3909 hash_base=>$hash, file_name=>$diff->{'file'}),
3910 -class => "list"}, esc_path($diff->{'file'}));
3911 print "</td>\n";
3912 print "<td>$mode_chng</td>\n";
3913 print "<td class=\"link\">";
3914 if ($action eq 'commitdiff') {
3915 # link to patch
3916 $patchno++;
3917 print $cgi->a({-href => "#patch$patchno"}, "patch");
3918 print " | ";
3920 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3921 hash_base=>$hash, file_name=>$diff->{'file'})},
3922 "blob");
3923 print "</td>\n";
3925 } elsif ($diff->{'status'} eq "D") { # deleted
3926 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3927 print "<td>";
3928 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3929 hash_base=>$parent, file_name=>$diff->{'file'}),
3930 -class => "list"}, esc_path($diff->{'file'}));
3931 print "</td>\n";
3932 print "<td>$mode_chng</td>\n";
3933 print "<td class=\"link\">";
3934 if ($action eq 'commitdiff') {
3935 # link to patch
3936 $patchno++;
3937 print $cgi->a({-href => "#patch$patchno"}, "patch");
3938 print " | ";
3940 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3941 hash_base=>$parent, file_name=>$diff->{'file'})},
3942 "blob") . " | ";
3943 if ($have_blame) {
3944 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3945 file_name=>$diff->{'file'})},
3946 "blame") . " | ";
3948 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3949 file_name=>$diff->{'file'})},
3950 "history");
3951 print "</td>\n";
3953 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3954 my $mode_chnge = "";
3955 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3956 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3957 if ($from_file_type ne $to_file_type) {
3958 $mode_chnge .= " from $from_file_type to $to_file_type";
3960 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3961 if ($from_mode_str && $to_mode_str) {
3962 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3963 } elsif ($to_mode_str) {
3964 $mode_chnge .= " mode: $to_mode_str";
3967 $mode_chnge .= "]</span>\n";
3969 print "<td>";
3970 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3971 hash_base=>$hash, file_name=>$diff->{'file'}),
3972 -class => "list"}, esc_path($diff->{'file'}));
3973 print "</td>\n";
3974 print "<td>$mode_chnge</td>\n";
3975 print "<td class=\"link\">";
3976 if ($action eq 'commitdiff') {
3977 # link to patch
3978 $patchno++;
3979 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3980 " | ";
3981 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3982 # "commit" view and modified file (not onlu mode changed)
3983 print $cgi->a({-href => href(action=>"blobdiff",
3984 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3985 hash_base=>$hash, hash_parent_base=>$parent,
3986 file_name=>$diff->{'file'})},
3987 "diff") .
3988 " | ";
3990 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3991 hash_base=>$hash, file_name=>$diff->{'file'})},
3992 "blob") . " | ";
3993 if ($have_blame) {
3994 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3995 file_name=>$diff->{'file'})},
3996 "blame") . " | ";
3998 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3999 file_name=>$diff->{'file'})},
4000 "history");
4001 print "</td>\n";
4003 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4004 my %status_name = ('R' => 'moved', 'C' => 'copied');
4005 my $nstatus = $status_name{$diff->{'status'}};
4006 my $mode_chng = "";
4007 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4008 # mode also for directories, so we cannot use $to_mode_str
4009 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4011 print "<td>" .
4012 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4013 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4014 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4015 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4016 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4017 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4018 -class => "list"}, esc_path($diff->{'from_file'})) .
4019 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4020 "<td class=\"link\">";
4021 if ($action eq 'commitdiff') {
4022 # link to patch
4023 $patchno++;
4024 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4025 " | ";
4026 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4027 # "commit" view and modified file (not only pure rename or copy)
4028 print $cgi->a({-href => href(action=>"blobdiff",
4029 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4030 hash_base=>$hash, hash_parent_base=>$parent,
4031 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4032 "diff") .
4033 " | ";
4035 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4036 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4037 "blob") . " | ";
4038 if ($have_blame) {
4039 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4040 file_name=>$diff->{'to_file'})},
4041 "blame") . " | ";
4043 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4044 file_name=>$diff->{'to_file'})},
4045 "history");
4046 print "</td>\n";
4048 } # we should not encounter Unmerged (U) or Unknown (X) status
4049 print "</tr>\n";
4051 print "</tbody>" if $has_header;
4052 print "</table>\n";
4055 sub git_patchset_body {
4056 my ($fd, $difftree, $hash, @hash_parents) = @_;
4057 my ($hash_parent) = $hash_parents[0];
4059 my $is_combined = (@hash_parents > 1);
4060 my $patch_idx = 0;
4061 my $patch_number = 0;
4062 my $patch_line;
4063 my $diffinfo;
4064 my $to_name;
4065 my (%from, %to);
4067 print "<div class=\"patchset\">\n";
4069 # skip to first patch
4070 while ($patch_line = <$fd>) {
4071 chomp $patch_line;
4073 last if ($patch_line =~ m/^diff /);
4076 PATCH:
4077 while ($patch_line) {
4079 # parse "git diff" header line
4080 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4081 # $1 is from_name, which we do not use
4082 $to_name = unquote($2);
4083 $to_name =~ s!^b/!!;
4084 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4085 # $1 is 'cc' or 'combined', which we do not use
4086 $to_name = unquote($2);
4087 } else {
4088 $to_name = undef;
4091 # check if current patch belong to current raw line
4092 # and parse raw git-diff line if needed
4093 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4094 # this is continuation of a split patch
4095 print "<div class=\"patch cont\">\n";
4096 } else {
4097 # advance raw git-diff output if needed
4098 $patch_idx++ if defined $diffinfo;
4100 # read and prepare patch information
4101 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4103 # compact combined diff output can have some patches skipped
4104 # find which patch (using pathname of result) we are at now;
4105 if ($is_combined) {
4106 while ($to_name ne $diffinfo->{'to_file'}) {
4107 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4108 format_diff_cc_simplified($diffinfo, @hash_parents) .
4109 "</div>\n"; # class="patch"
4111 $patch_idx++;
4112 $patch_number++;
4114 last if $patch_idx > $#$difftree;
4115 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4119 # modifies %from, %to hashes
4120 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4122 # this is first patch for raw difftree line with $patch_idx index
4123 # we index @$difftree array from 0, but number patches from 1
4124 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4127 # git diff header
4128 #assert($patch_line =~ m/^diff /) if DEBUG;
4129 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4130 $patch_number++;
4131 # print "git diff" header
4132 print format_git_diff_header_line($patch_line, $diffinfo,
4133 \%from, \%to);
4135 # print extended diff header
4136 print "<div class=\"diff extended_header\">\n";
4137 EXTENDED_HEADER:
4138 while ($patch_line = <$fd>) {
4139 chomp $patch_line;
4141 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4143 print format_extended_diff_header_line($patch_line, $diffinfo,
4144 \%from, \%to);
4146 print "</div>\n"; # class="diff extended_header"
4148 # from-file/to-file diff header
4149 if (! $patch_line) {
4150 print "</div>\n"; # class="patch"
4151 last PATCH;
4153 next PATCH if ($patch_line =~ m/^diff /);
4154 #assert($patch_line =~ m/^---/) if DEBUG;
4156 my $last_patch_line = $patch_line;
4157 $patch_line = <$fd>;
4158 chomp $patch_line;
4159 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4161 print format_diff_from_to_header($last_patch_line, $patch_line,
4162 $diffinfo, \%from, \%to,
4163 @hash_parents);
4165 # the patch itself
4166 LINE:
4167 while ($patch_line = <$fd>) {
4168 chomp $patch_line;
4170 next PATCH if ($patch_line =~ m/^diff /);
4172 print format_diff_line($patch_line, \%from, \%to);
4175 } continue {
4176 print "</div>\n"; # class="patch"
4179 # for compact combined (--cc) format, with chunk and patch simpliciaction
4180 # patchset might be empty, but there might be unprocessed raw lines
4181 for (++$patch_idx if $patch_number > 0;
4182 $patch_idx < @$difftree;
4183 ++$patch_idx) {
4184 # read and prepare patch information
4185 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4187 # generate anchor for "patch" links in difftree / whatchanged part
4188 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4189 format_diff_cc_simplified($diffinfo, @hash_parents) .
4190 "</div>\n"; # class="patch"
4192 $patch_number++;
4195 if ($patch_number == 0) {
4196 if (@hash_parents > 1) {
4197 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4198 } else {
4199 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4203 print "</div>\n"; # class="patchset"
4206 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4208 # fills project list info (age, description, owner, forks) for each
4209 # project in the list, removing invalid projects from returned list
4210 # NOTE: modifies $projlist, but does not remove entries from it
4211 sub fill_project_list_info {
4212 my ($projlist, $check_forks, $show_ctags) = @_;
4213 my @projects;
4215 PROJECT:
4216 foreach my $pr (@$projlist) {
4217 my (@activity) = git_get_last_activity($pr->{'path'});
4218 unless (@activity) {
4219 next PROJECT;
4221 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4222 if (!defined $pr->{'descr'}) {
4223 my $descr = git_get_project_description($pr->{'path'}) || "";
4224 $descr = to_utf8($descr);
4225 $pr->{'descr_long'} = $descr;
4226 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4228 if (!defined $pr->{'owner'}) {
4229 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4231 if ($check_forks) {
4232 my $pname = $pr->{'path'};
4233 if (($pname =~ s/\.git$//) &&
4234 ($pname !~ /\/$/) &&
4235 (-d "$projectroot/$pname")) {
4236 $pr->{'forks'} = "-d $projectroot/$pname";
4237 } else {
4238 $pr->{'forks'} = 0;
4241 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4242 push @projects, $pr;
4245 return @projects;
4248 # print 'sort by' <th> element, generating 'sort by $name' replay link
4249 # if that order is not selected
4250 sub print_sort_th {
4251 my ($name, $order, $header) = @_;
4252 $header ||= ucfirst($name);
4254 if ($order eq $name) {
4255 print "<th>$header</th>\n";
4256 } else {
4257 print "<th>" .
4258 $cgi->a({-href => href(-replay=>1, order=>$name),
4259 -class => "header"}, $header) .
4260 "</th>\n";
4264 sub git_project_list_ctags {
4265 my ($projects) = @_;
4267 my %ctags;
4268 foreach my $p (@$projects) {
4269 foreach my $ct (keys %{$p->{'ctags'}}) {
4270 $ctags{$ct} += $p->{'ctags'}->{$ct};
4273 my $cloud = git_populate_project_tagcloud(\%ctags);
4274 print git_show_project_tagcloud($cloud, 64);
4277 sub git_project_list_body {
4278 # actually uses global variable $project
4279 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4281 my $check_forks = gitweb_check_feature('forks');
4282 my $show_ctags = gitweb_check_feature('ctags');
4283 my @projects = fill_project_list_info($projlist, $check_forks);
4285 $order ||= $default_projects_order;
4286 $from = 0 unless defined $from;
4287 $to = $#projects if (!defined $to || $#projects < $to);
4289 my %order_info = (
4290 project => { key => 'path', type => 'str' },
4291 descr => { key => 'descr_long', type => 'str' },
4292 owner => { key => 'owner', type => 'str' },
4293 age => { key => 'age', type => 'num' }
4295 my $oi = $order_info{$order};
4296 if ($oi->{'type'} eq 'str') {
4297 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4298 } else {
4299 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4302 if ($show_ctags) {
4303 git_project_list_ctags(\@projects);
4306 print "<table class=\"project_list\">\n";
4307 unless ($no_header) {
4308 print "<tr>\n";
4309 if ($check_forks) {
4310 print "<th></th>\n";
4312 print_sort_th('project', $order, 'Project');
4313 print_sort_th('descr', $order, 'Description');
4314 print_sort_th('owner', $order, 'Owner');
4315 print_sort_th('age', $order, 'Last Change');
4316 print "<th></th>\n" . # for links
4317 "</tr>\n";
4319 my $alternate = 1;
4320 my $tagfilter = $cgi->param('by_tag');
4321 for (my $i = $from; $i <= $to; $i++) {
4322 my $pr = $projects[$i];
4324 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4325 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4326 and not $pr->{'descr_long'} =~ /$searchtext/;
4327 # Weed out forks or non-matching entries of search
4328 if ($check_forks) {
4329 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4330 $forkbase="^$forkbase" if $forkbase;
4331 next if not $searchtext and not $tagfilter and $show_ctags
4332 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4335 if ($alternate) {
4336 print "<tr class=\"dark\">\n";
4337 } else {
4338 print "<tr class=\"light\">\n";
4340 $alternate ^= 1;
4341 if ($check_forks) {
4342 print "<td>";
4343 if ($pr->{'forks'}) {
4344 print "<!-- $pr->{'forks'} -->\n";
4345 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4347 print "</td>\n";
4349 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4350 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4351 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4352 -class => "list", -title => $pr->{'descr_long'}},
4353 esc_html($pr->{'descr'})) . "</td>\n" .
4354 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4355 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4356 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4357 "<td class=\"link\">" .
4358 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4359 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4360 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4361 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4362 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4363 "</td>\n" .
4364 "</tr>\n";
4366 if (defined $extra) {
4367 print "<tr>\n";
4368 if ($check_forks) {
4369 print "<td></td>\n";
4371 print "<td colspan=\"5\">$extra</td>\n" .
4372 "</tr>\n";
4374 print "</table>\n";
4377 sub git_project_search_form {
4378 print $cgi->startform(-method => "get") .
4379 $cgi->hidden({-name=>"a", -value=>"project_list"}) . "\n" .
4380 "<p class=\"projsearch\">Search:\n" .
4381 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4382 "</p>" .
4383 $cgi->end_form() . "\n";
4386 sub git_project_list_all {
4387 my $order = $input_params{'order'};
4388 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4389 die_error(400, "Unknown order parameter");
4392 my @list = git_get_projects_list();
4393 if (!@list) {
4394 die_error(404, "No projects found");
4397 git_project_list_body(\@list, $order, undef, undef, undef, undef, $projlist_cache_lifetime);
4400 sub git_shortlog_body {
4401 # uses global variable $project
4402 my ($commitlist, $from, $to, $refs, $extra) = @_;
4404 $from = 0 unless defined $from;
4405 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4407 print "<table class=\"shortlog\">\n";
4408 my $alternate = 1;
4409 for (my $i = $from; $i <= $to; $i++) {
4410 my %co = %{$commitlist->[$i]};
4411 my $commit = $co{'id'};
4412 my $ref = format_ref_marker($refs, $commit);
4413 if ($alternate) {
4414 print "<tr class=\"dark\">\n";
4415 } else {
4416 print "<tr class=\"light\">\n";
4418 $alternate ^= 1;
4419 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4420 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4421 format_author_html('td', \%co, 10) . "<td>";
4422 print format_subject_html($co{'title'}, $co{'title_short'},
4423 href(action=>"commit", hash=>$commit), $ref);
4424 print "</td>\n" .
4425 "<td class=\"link\">" .
4426 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4427 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4428 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4429 my $snapshot_links = format_snapshot_links($commit);
4430 if (defined $snapshot_links) {
4431 print " | " . $snapshot_links;
4433 print "</td>\n" .
4434 "</tr>\n";
4436 if (defined $extra) {
4437 print "<tr>\n" .
4438 "<td colspan=\"4\">$extra</td>\n" .
4439 "</tr>\n";
4441 print "</table>\n";
4444 sub git_history_body {
4445 # Warning: assumes constant type (blob or tree) during history
4446 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4448 $from = 0 unless defined $from;
4449 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4451 print "<table class=\"history\">\n";
4452 my $alternate = 1;
4453 for (my $i = $from; $i <= $to; $i++) {
4454 my %co = %{$commitlist->[$i]};
4455 if (!%co) {
4456 next;
4458 my $commit = $co{'id'};
4460 my $ref = format_ref_marker($refs, $commit);
4462 if ($alternate) {
4463 print "<tr class=\"dark\">\n";
4464 } else {
4465 print "<tr class=\"light\">\n";
4467 $alternate ^= 1;
4468 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4469 # shortlog: format_author_html('td', \%co, 10)
4470 format_author_html('td', \%co, 15, 3) . "<td>";
4471 # originally git_history used chop_str($co{'title'}, 50)
4472 print format_subject_html($co{'title'}, $co{'title_short'},
4473 href(action=>"commit", hash=>$commit), $ref);
4474 print "</td>\n" .
4475 "<td class=\"link\">" .
4476 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4477 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4479 if ($ftype eq 'blob') {
4480 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4481 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4482 if (defined $blob_current && defined $blob_parent &&
4483 $blob_current ne $blob_parent) {
4484 print " | " .
4485 $cgi->a({-href => href(action=>"blobdiff",
4486 hash=>$blob_current, hash_parent=>$blob_parent,
4487 hash_base=>$hash_base, hash_parent_base=>$commit,
4488 file_name=>$file_name)},
4489 "diff to current");
4492 print "</td>\n" .
4493 "</tr>\n";
4495 if (defined $extra) {
4496 print "<tr>\n" .
4497 "<td colspan=\"4\">$extra</td>\n" .
4498 "</tr>\n";
4500 print "</table>\n";
4503 sub git_tags_body {
4504 # uses global variable $project
4505 my ($taglist, $from, $to, $extra) = @_;
4506 $from = 0 unless defined $from;
4507 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4509 print "<table class=\"tags\">\n";
4510 my $alternate = 1;
4511 for (my $i = $from; $i <= $to; $i++) {
4512 my $entry = $taglist->[$i];
4513 my %tag = %$entry;
4514 my $comment = $tag{'subject'};
4515 my $comment_short;
4516 if (defined $comment) {
4517 $comment_short = chop_str($comment, 30, 5);
4519 if ($alternate) {
4520 print "<tr class=\"dark\">\n";
4521 } else {
4522 print "<tr class=\"light\">\n";
4524 $alternate ^= 1;
4525 if (defined $tag{'age'}) {
4526 print "<td><i>$tag{'age'}</i></td>\n";
4527 } else {
4528 print "<td></td>\n";
4530 print "<td>" .
4531 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4532 -class => "list name"}, esc_html($tag{'name'})) .
4533 "</td>\n" .
4534 "<td>";
4535 if (defined $comment) {
4536 print format_subject_html($comment, $comment_short,
4537 href(action=>"tag", hash=>$tag{'id'}));
4539 print "</td>\n" .
4540 "<td class=\"selflink\">";
4541 if ($tag{'type'} eq "tag") {
4542 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4543 } else {
4544 print "&nbsp;";
4546 print "</td>\n" .
4547 "<td class=\"link\">" . " | " .
4548 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4549 if ($tag{'reftype'} eq "commit") {
4550 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4551 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4552 } elsif ($tag{'reftype'} eq "blob") {
4553 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4555 print "</td>\n" .
4556 "</tr>";
4558 if (defined $extra) {
4559 print "<tr>\n" .
4560 "<td colspan=\"5\">$extra</td>\n" .
4561 "</tr>\n";
4563 print "</table>\n";
4566 sub git_heads_body {
4567 # uses global variable $project
4568 my ($headlist, $head, $from, $to, $extra) = @_;
4569 $from = 0 unless defined $from;
4570 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4572 print "<table class=\"heads\">\n";
4573 my $alternate = 1;
4574 for (my $i = $from; $i <= $to; $i++) {
4575 my $entry = $headlist->[$i];
4576 my %ref = %$entry;
4577 my $curr = $ref{'id'} eq $head;
4578 if ($alternate) {
4579 print "<tr class=\"dark\">\n";
4580 } else {
4581 print "<tr class=\"light\">\n";
4583 $alternate ^= 1;
4584 print "<td><i>$ref{'age'}</i></td>\n" .
4585 ($curr ? "<td class=\"current_head\">" : "<td>") .
4586 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4587 -class => "list name"},esc_html($ref{'name'})) .
4588 "</td>\n" .
4589 "<td class=\"link\">" .
4590 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4591 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4592 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4593 "</td>\n" .
4594 "</tr>";
4596 if (defined $extra) {
4597 print "<tr>\n" .
4598 "<td colspan=\"3\">$extra</td>\n" .
4599 "</tr>\n";
4601 print "</table>\n";
4604 sub git_search_grep_body {
4605 my ($commitlist, $from, $to, $extra) = @_;
4606 $from = 0 unless defined $from;
4607 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4609 print "<table class=\"commit_search\">\n";
4610 my $alternate = 1;
4611 for (my $i = $from; $i <= $to; $i++) {
4612 my %co = %{$commitlist->[$i]};
4613 if (!%co) {
4614 next;
4616 my $commit = $co{'id'};
4617 if ($alternate) {
4618 print "<tr class=\"dark\">\n";
4619 } else {
4620 print "<tr class=\"light\">\n";
4622 $alternate ^= 1;
4623 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4624 format_author_html('td', \%co, 15, 5) .
4625 "<td>" .
4626 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4627 -class => "list subject"},
4628 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4629 my $comment = $co{'comment'};
4630 foreach my $line (@$comment) {
4631 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4632 my ($lead, $match, $trail) = ($1, $2, $3);
4633 $match = chop_str($match, 70, 5, 'center');
4634 my $contextlen = int((80 - length($match))/2);
4635 $contextlen = 30 if ($contextlen > 30);
4636 $lead = chop_str($lead, $contextlen, 10, 'left');
4637 $trail = chop_str($trail, $contextlen, 10, 'right');
4639 $lead = esc_html($lead);
4640 $match = esc_html($match);
4641 $trail = esc_html($trail);
4643 print "$lead<span class=\"match\">$match</span>$trail<br />";
4646 print "</td>\n" .
4647 "<td class=\"link\">" .
4648 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4649 " | " .
4650 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4651 " | " .
4652 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4653 print "</td>\n" .
4654 "</tr>\n";
4656 if (defined $extra) {
4657 print "<tr>\n" .
4658 "<td colspan=\"3\">$extra</td>\n" .
4659 "</tr>\n";
4661 print "</table>\n";
4664 ## ======================================================================
4665 ## ======================================================================
4666 ## actions
4668 sub git_frontpage {
4669 git_header_html();
4670 if (-f $home_text) {
4671 print "<div class=\"index_include\">\n";
4672 insert_file($home_text);
4673 print "</div>\n";
4675 git_project_search_form();
4676 if (not $frontpage_no_project_list) {
4677 git_project_list_all();
4678 } else {
4679 my $show_ctags = gitweb_check_feature('ctags');
4680 if ($frontpage_no_project_list == 1 and $show_ctags) {
4681 my @list = git_get_projects_list();
4682 my @projects = fill_project_list_info(\@list, gitweb_check_feature('forks'), $show_ctags);
4683 git_project_list_ctags(\@projects);
4685 print "<p class=\"projectlist_link\">" .
4686 $cgi->a({-href => href(action=>'project_list')}, "Browse all projects") .
4687 "</p>\n";
4689 git_footer_html();
4692 sub git_project_list {
4693 git_header_html();
4694 git_project_search_form();
4695 git_project_list_all();
4696 git_footer_html();
4699 sub git_forks {
4700 my $order = $input_params{'order'};
4701 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4702 die_error(400, "Unknown order parameter");
4705 my @list = git_get_projects_list($project);
4706 if (!@list) {
4707 die_error(404, "No forks found");
4710 git_header_html();
4711 git_print_page_nav('','');
4712 git_print_header_div('summary', "$project forks");
4713 git_project_list_body(\@list, $order);
4714 git_footer_html();
4717 sub git_project_index {
4718 my @projects = git_get_projects_list($project);
4720 print $cgi->header(
4721 -type => 'text/plain',
4722 -charset => 'utf-8',
4723 -content_disposition => 'inline; filename="index.aux"');
4725 foreach my $pr (@projects) {
4726 if (!exists $pr->{'owner'}) {
4727 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4730 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4731 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4732 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4733 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4734 $path =~ s/ /\+/g;
4735 $owner =~ s/ /\+/g;
4737 print "$path $owner\n";
4741 sub git_summary {
4742 my $descr = git_get_project_description($project) || "none";
4743 my %co = parse_commit("HEAD");
4744 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4745 my $head = $co{'id'};
4747 my $owner = git_get_project_owner($project);
4749 my $refs = git_get_references();
4750 # These get_*_list functions return one more to allow us to see if
4751 # there are more ...
4752 my @taglist = git_get_tags_list(16);
4753 my @headlist = git_get_heads_list(16);
4754 my @forklist;
4755 my $check_forks = gitweb_check_feature('forks');
4757 if ($check_forks) {
4758 @forklist = git_get_projects_list($project);
4761 git_header_html();
4762 git_print_page_nav('summary','', $head);
4764 print "<div class=\"title\">&nbsp;</div>\n";
4765 print "<table class=\"projects_list\">\n" .
4766 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4767 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4768 if (defined $cd{'rfc2822'}) {
4769 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4772 # use per project git URL list in $projectroot/$project/cloneurl
4773 # or make project git URL from git base URL and project name
4774 my $url_tag = "URL";
4775 my @url_list = git_get_project_url_list($project);
4776 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4777 foreach my $git_url (@url_list) {
4778 next unless $git_url;
4779 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4780 $url_tag = "";
4783 # Tag cloud
4784 my $show_ctags = gitweb_check_feature('ctags');
4785 if ($show_ctags) {
4786 my $ctags = git_get_project_ctags($project);
4787 my $cloud = git_populate_project_tagcloud($ctags);
4788 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4789 print "</td>\n<td>" unless %$ctags;
4790 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4791 print "</td>\n<td>" if %$ctags;
4792 print git_show_project_tagcloud($cloud, 48);
4793 print "</td></tr>";
4796 print "</table>\n";
4798 # If XSS prevention is on, we don't include README.html.
4799 # TODO: Allow a readme in some safe format.
4800 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4801 print "<div class=\"title\">readme</div>\n" .
4802 "<div class=\"readme\">\n";
4803 insert_file("$projectroot/$project/README.html");
4804 print "\n</div>\n"; # class="readme"
4807 # we need to request one more than 16 (0..15) to check if
4808 # those 16 are all
4809 my @commitlist = $head ? parse_commits($head, 17) : ();
4810 if (@commitlist) {
4811 git_print_header_div('shortlog');
4812 git_shortlog_body(\@commitlist, 0, 15, $refs,
4813 $#commitlist <= 15 ? undef :
4814 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4817 if (@taglist) {
4818 git_print_header_div('tags');
4819 git_tags_body(\@taglist, 0, 15,
4820 $#taglist <= 15 ? undef :
4821 $cgi->a({-href => href(action=>"tags")}, "..."));
4824 if (@headlist) {
4825 git_print_header_div('heads');
4826 git_heads_body(\@headlist, $head, 0, 15,
4827 $#headlist <= 15 ? undef :
4828 $cgi->a({-href => href(action=>"heads")}, "..."));
4831 if (@forklist) {
4832 git_print_header_div('forks');
4833 git_project_list_body(\@forklist, 'age', 0, 15,
4834 $#forklist <= 15 ? undef :
4835 $cgi->a({-href => href(action=>"forks")}, "..."),
4836 'no_header');
4839 git_footer_html();
4842 sub git_tag {
4843 my $head = git_get_head_hash($project);
4844 git_header_html();
4845 git_print_page_nav('','', $head,undef,$head);
4846 my %tag = parse_tag($hash);
4848 if (! %tag) {
4849 die_error(404, "Unknown tag object");
4852 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4853 print "<div class=\"title_text\">\n" .
4854 "<table class=\"object_header\">\n" .
4855 "<tr>\n" .
4856 "<td>object</td>\n" .
4857 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4858 $tag{'object'}) . "</td>\n" .
4859 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4860 $tag{'type'}) . "</td>\n" .
4861 "</tr>\n";
4862 if (defined($tag{'author'})) {
4863 git_print_authorship_rows(\%tag, 'author');
4865 print "</table>\n\n" .
4866 "</div>\n";
4867 print "<div class=\"page_body\">";
4868 my $comment = $tag{'comment'};
4869 foreach my $line (@$comment) {
4870 chomp $line;
4871 print esc_html($line, -nbsp=>1) . "<br/>\n";
4873 print "</div>\n";
4874 git_footer_html();
4877 sub git_blame {
4878 # permissions
4879 gitweb_check_feature('blame')
4880 or die_error(403, "Blame view not allowed");
4882 # error checking
4883 die_error(400, "No file name given") unless $file_name;
4884 $hash_base ||= git_get_head_hash($project);
4885 die_error(404, "Couldn't find base commit") unless $hash_base;
4886 my %co = parse_commit($hash_base)
4887 or die_error(404, "Commit not found");
4888 my $ftype = "blob";
4889 if (!defined $hash) {
4890 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4891 or die_error(404, "Error looking up file");
4892 } else {
4893 $ftype = git_get_type($hash);
4894 if ($ftype !~ "blob") {
4895 die_error(400, "Object is not a blob");
4899 # run git-blame --porcelain
4900 open my $fd, "-|", git_cmd(), "blame", '-p',
4901 $hash_base, '--', $file_name
4902 or die_error(500, "Open git-blame failed");
4904 # page header
4905 git_header_html();
4906 my $formats_nav =
4907 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4908 "blob") .
4909 " | " .
4910 $cgi->a({-href => href(action=>"history", -replay=>1)},
4911 "history") .
4912 " | " .
4913 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4914 "HEAD");
4915 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4916 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4917 git_print_page_path($file_name, $ftype, $hash_base);
4919 # page body
4920 my @rev_color = qw(light dark);
4921 my $num_colors = scalar(@rev_color);
4922 my $current_color = 0;
4923 my %metainfo = ();
4925 print <<HTML;
4926 <div class="page_body">
4927 <table class="blame">
4928 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4929 HTML
4930 LINE:
4931 while (my $line = <$fd>) {
4932 chomp $line;
4933 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4934 # no <lines in group> for subsequent lines in group of lines
4935 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4936 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
4937 if (!exists $metainfo{$full_rev}) {
4938 $metainfo{$full_rev} = { 'nprevious' => 0 };
4940 my $meta = $metainfo{$full_rev};
4941 my $data;
4942 while ($data = <$fd>) {
4943 chomp $data;
4944 last if ($data =~ s/^\t//); # contents of line
4945 if ($data =~ /^(\S+)(?: (.*))?$/) {
4946 $meta->{$1} = $2 unless exists $meta->{$1};
4948 if ($data =~ /^previous /) {
4949 $meta->{'nprevious'}++;
4952 my $short_rev = substr($full_rev, 0, 8);
4953 my $author = $meta->{'author'};
4954 my %date =
4955 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
4956 my $date = $date{'iso-tz'};
4957 if ($group_size) {
4958 $current_color = ($current_color + 1) % $num_colors;
4960 my $tr_class = $rev_color[$current_color];
4961 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
4962 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
4963 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
4964 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
4965 if ($group_size) {
4966 print "<td class=\"sha1\"";
4967 print " title=\"". esc_html($author) . ", $date\"";
4968 print " rowspan=\"$group_size\"" if ($group_size > 1);
4969 print ">";
4970 print $cgi->a({-href => href(action=>"commit",
4971 hash=>$full_rev,
4972 file_name=>$file_name)},
4973 esc_html($short_rev));
4974 if ($group_size >= 2) {
4975 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
4976 if (@author_initials) {
4977 print "<br />" .
4978 esc_html(join('', @author_initials));
4979 # or join('.', ...)
4982 print "</td>\n";
4984 # 'previous' <sha1 of parent commit> <filename at commit>
4985 if (exists $meta->{'previous'} &&
4986 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
4987 $meta->{'parent'} = $1;
4988 $meta->{'file_parent'} = unquote($2);
4990 my $linenr_commit =
4991 exists($meta->{'parent'}) ?
4992 $meta->{'parent'} : $full_rev;
4993 my $linenr_filename =
4994 exists($meta->{'file_parent'}) ?
4995 $meta->{'file_parent'} : unquote($meta->{'filename'});
4996 my $blamed = href(action => 'blame',
4997 file_name => $linenr_filename,
4998 hash_base => $linenr_commit);
4999 print "<td class=\"linenr\">";
5000 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5001 -class => "linenr" },
5002 esc_html($lineno));
5003 print "</td>";
5004 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5005 print "</tr>\n";
5007 print "</table>\n";
5008 print "</div>";
5009 close $fd
5010 or print "Reading blob failed\n";
5012 # page footer
5013 git_footer_html();
5016 sub git_tags {
5017 my $head = git_get_head_hash($project);
5018 git_header_html();
5019 git_print_page_nav('','', $head,undef,$head);
5020 git_print_header_div('summary', $project);
5022 my @tagslist = git_get_tags_list();
5023 if (@tagslist) {
5024 git_tags_body(\@tagslist);
5026 git_footer_html();
5029 sub git_heads {
5030 my $head = git_get_head_hash($project);
5031 git_header_html();
5032 git_print_page_nav('','', $head,undef,$head);
5033 git_print_header_div('summary', $project);
5035 my @headslist = git_get_heads_list();
5036 if (@headslist) {
5037 git_heads_body(\@headslist, $head);
5039 git_footer_html();
5042 sub git_blob_plain {
5043 my $type = shift;
5044 my $expires;
5046 if (!defined $hash) {
5047 if (defined $file_name) {
5048 my $base = $hash_base || git_get_head_hash($project);
5049 $hash = git_get_hash_by_path($base, $file_name, "blob")
5050 or die_error(404, "Cannot find file");
5051 } else {
5052 die_error(400, "No file name defined");
5054 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5055 # blobs defined by non-textual hash id's can be cached
5056 $expires = "+1d";
5059 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5060 or die_error(500, "Open git-cat-file blob '$hash' failed");
5062 # content-type (can include charset)
5063 $type = blob_contenttype($fd, $file_name, $type);
5065 # "save as" filename, even when no $file_name is given
5066 my $save_as = "$hash";
5067 if (defined $file_name) {
5068 $save_as = $file_name;
5069 } elsif ($type =~ m/^text\//) {
5070 $save_as .= '.txt';
5073 # With XSS prevention on, blobs of all types except a few known safe
5074 # ones are served with "Content-Disposition: attachment" to make sure
5075 # they don't run in our security domain. For certain image types,
5076 # blob view writes an <img> tag referring to blob_plain view, and we
5077 # want to be sure not to break that by serving the image as an
5078 # attachment (though Firefox 3 doesn't seem to care).
5079 my $sandbox = $prevent_xss &&
5080 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5082 print $cgi->header(
5083 -type => $type,
5084 -expires => $expires,
5085 -content_disposition =>
5086 ($sandbox ? 'attachment' : 'inline')
5087 . '; filename="' . $save_as . '"');
5088 local $/ = undef;
5089 binmode STDOUT, ':raw';
5090 print <$fd>;
5091 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5092 close $fd;
5095 sub git_blob {
5096 my $expires;
5098 if (!defined $hash) {
5099 if (defined $file_name) {
5100 my $base = $hash_base || git_get_head_hash($project);
5101 $hash = git_get_hash_by_path($base, $file_name, "blob")
5102 or die_error(404, "Cannot find file");
5103 } else {
5104 die_error(400, "No file name defined");
5106 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5107 # blobs defined by non-textual hash id's can be cached
5108 $expires = "+1d";
5111 my $have_blame = gitweb_check_feature('blame');
5112 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5113 or die_error(500, "Couldn't cat $file_name, $hash");
5114 my $mimetype = blob_mimetype($fd, $file_name);
5115 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5116 close $fd;
5117 return git_blob_plain($mimetype);
5119 # we can have blame only for text/* mimetype
5120 $have_blame &&= ($mimetype =~ m!^text/!);
5122 git_header_html(undef, $expires);
5123 my $formats_nav = '';
5124 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5125 if (defined $file_name) {
5126 if ($have_blame) {
5127 $formats_nav .=
5128 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5129 "blame") .
5130 " | ";
5132 $formats_nav .=
5133 $cgi->a({-href => href(action=>"history", -replay=>1)},
5134 "history") .
5135 " | " .
5136 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5137 "raw") .
5138 " | " .
5139 $cgi->a({-href => href(action=>"blob",
5140 hash_base=>"HEAD", file_name=>$file_name)},
5141 "HEAD");
5142 } else {
5143 $formats_nav .=
5144 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5145 "raw");
5147 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5148 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5149 } else {
5150 print "<div class=\"page_nav\">\n" .
5151 "<br/><br/></div>\n" .
5152 "<div class=\"title\">$hash</div>\n";
5154 git_print_page_path($file_name, "blob", $hash_base);
5155 print "<div class=\"page_body\">\n";
5156 if ($mimetype =~ m!^image/!) {
5157 print qq!<img type="$mimetype"!;
5158 if ($file_name) {
5159 print qq! alt="$file_name" title="$file_name"!;
5161 print qq! src="! .
5162 href(action=>"blob_plain", hash=>$hash,
5163 hash_base=>$hash_base, file_name=>$file_name) .
5164 qq!" />\n!;
5165 } else {
5166 my $nr;
5167 while (my $line = <$fd>) {
5168 chomp $line;
5169 $nr++;
5170 $line = untabify($line);
5171 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5172 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5175 close $fd
5176 or print "Reading blob failed.\n";
5177 print "</div>";
5178 git_footer_html();
5181 sub git_tree {
5182 if (!defined $hash_base) {
5183 $hash_base = "HEAD";
5185 if (!defined $hash) {
5186 if (defined $file_name) {
5187 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5188 } else {
5189 $hash = $hash_base;
5192 die_error(404, "No such tree") unless defined($hash);
5194 my $show_sizes = gitweb_check_feature('show-sizes');
5195 my $have_blame = gitweb_check_feature('blame');
5197 my @entries = ();
5199 local $/ = "\0";
5200 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5201 ($show_sizes ? '-l' : ()), @extra_options, $hash
5202 or die_error(500, "Open git-ls-tree failed");
5203 @entries = map { chomp; $_ } <$fd>;
5204 close $fd
5205 or die_error(404, "Reading tree failed");
5208 my $refs = git_get_references();
5209 my $ref = format_ref_marker($refs, $hash_base);
5210 git_header_html();
5211 my $basedir = '';
5212 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5213 my @views_nav = ();
5214 if (defined $file_name) {
5215 push @views_nav,
5216 $cgi->a({-href => href(action=>"history", -replay=>1)},
5217 "history"),
5218 $cgi->a({-href => href(action=>"tree",
5219 hash_base=>"HEAD", file_name=>$file_name)},
5220 "HEAD"),
5222 my $snapshot_links = format_snapshot_links($hash);
5223 if (defined $snapshot_links) {
5224 # FIXME: Should be available when we have no hash base as well.
5225 push @views_nav, $snapshot_links;
5227 git_print_page_nav('tree','', $hash_base, undef, undef,
5228 join(' | ', @views_nav));
5229 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5230 } else {
5231 undef $hash_base;
5232 print "<div class=\"page_nav\">\n";
5233 print "<br/><br/></div>\n";
5234 print "<div class=\"title\">$hash</div>\n";
5236 if (defined $file_name) {
5237 $basedir = $file_name;
5238 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5239 $basedir .= '/';
5241 git_print_page_path($file_name, 'tree', $hash_base);
5243 print "<div class=\"page_body\">\n";
5244 print "<table class=\"tree\">\n";
5245 my $alternate = 1;
5246 # '..' (top directory) link if possible
5247 if (defined $hash_base &&
5248 defined $file_name && $file_name =~ m![^/]+$!) {
5249 if ($alternate) {
5250 print "<tr class=\"dark\">\n";
5251 } else {
5252 print "<tr class=\"light\">\n";
5254 $alternate ^= 1;
5256 my $up = $file_name;
5257 $up =~ s!/?[^/]+$!!;
5258 undef $up unless $up;
5259 # based on git_print_tree_entry
5260 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5261 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5262 print '<td class="list">';
5263 print $cgi->a({-href => href(action=>"tree",
5264 hash_base=>$hash_base,
5265 file_name=>$up)},
5266 "..");
5267 print "</td>\n";
5268 print "<td class=\"link\"></td>\n";
5270 print "</tr>\n";
5272 foreach my $line (@entries) {
5273 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5275 if ($alternate) {
5276 print "<tr class=\"dark\">\n";
5277 } else {
5278 print "<tr class=\"light\">\n";
5280 $alternate ^= 1;
5282 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5284 print "</tr>\n";
5286 print "</table>\n" .
5287 "</div>";
5288 git_footer_html();
5291 sub git_snapshot {
5292 my $format = $input_params{'snapshot_format'};
5293 if (!@snapshot_fmts) {
5294 die_error(403, "Snapshots not allowed");
5296 # default to first supported snapshot format
5297 $format ||= $snapshot_fmts[0];
5298 if ($format !~ m/^[a-z0-9]+$/) {
5299 die_error(400, "Invalid snapshot format parameter");
5300 } elsif (!exists($known_snapshot_formats{$format})) {
5301 die_error(400, "Unknown snapshot format");
5302 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5303 die_error(403, "Snapshot format not allowed");
5304 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5305 die_error(403, "Unsupported snapshot format");
5308 if (!defined $hash) {
5309 $hash = git_get_head_hash($project);
5312 my $name = $project;
5313 $name =~ s,([^/])/*\.git$,$1,;
5314 $name = basename($name);
5315 my $filename = to_utf8($name);
5316 $name =~ s/\047/\047\\\047\047/g;
5317 my $cmd;
5318 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5319 $cmd = quote_command(
5320 git_cmd(), 'archive',
5321 "--format=$known_snapshot_formats{$format}{'format'}",
5322 "--prefix=$name/", $hash);
5323 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5324 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5327 print $cgi->header(
5328 -type => $known_snapshot_formats{$format}{'type'},
5329 -content_disposition => 'inline; filename="' . "$filename" . '"',
5330 -status => '200 OK');
5332 open my $fd, "-|", $cmd
5333 or die_error(500, "Execute git-archive failed");
5334 binmode STDOUT, ':raw';
5335 print <$fd>;
5336 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5337 close $fd;
5340 sub git_log {
5341 my $head = git_get_head_hash($project);
5342 if (!defined $hash) {
5343 $hash = $head;
5345 if (!defined $page) {
5346 $page = 0;
5348 my $refs = git_get_references();
5350 my @commitlist = parse_commits($hash, 101, (100 * $page));
5352 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
5354 my ($patch_max) = gitweb_get_feature('patches');
5355 if ($patch_max) {
5356 if ($patch_max < 0 || @commitlist <= $patch_max) {
5357 $paging_nav .= " &sdot; " .
5358 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5359 "patches");
5363 git_header_html();
5364 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5366 if (!@commitlist) {
5367 my %co = parse_commit($hash);
5369 git_print_header_div('summary', $project);
5370 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5372 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5373 for (my $i = 0; $i <= $to; $i++) {
5374 my %co = %{$commitlist[$i]};
5375 next if !%co;
5376 my $commit = $co{'id'};
5377 my $ref = format_ref_marker($refs, $commit);
5378 my %ad = parse_date($co{'author_epoch'});
5379 git_print_header_div('commit',
5380 "<span class=\"age\">$co{'age_string'}</span>" .
5381 esc_html($co{'title'}) . $ref,
5382 $commit);
5383 print "<div class=\"title_text\">\n" .
5384 "<div class=\"log_link\">\n" .
5385 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5386 " | " .
5387 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5388 " | " .
5389 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5390 "<br/>\n" .
5391 "</div>\n";
5392 git_print_authorship(\%co, -tag => 'span');
5393 print "<br/>\n</div>\n";
5395 print "<div class=\"log_body\">\n";
5396 git_print_log($co{'comment'}, -final_empty_line=> 1);
5397 print "</div>\n";
5399 if ($#commitlist >= 100) {
5400 print "<div class=\"page_nav\">\n";
5401 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5402 -accesskey => "n", -title => "Alt-n"}, "next");
5403 print "</div>\n";
5405 git_footer_html();
5408 sub git_commit {
5409 $hash ||= $hash_base || "HEAD";
5410 my %co = parse_commit($hash)
5411 or die_error(404, "Unknown commit object");
5413 my $parent = $co{'parent'};
5414 my $parents = $co{'parents'}; # listref
5416 # we need to prepare $formats_nav before any parameter munging
5417 my $formats_nav;
5418 if (!defined $parent) {
5419 # --root commitdiff
5420 $formats_nav .= '(initial)';
5421 } elsif (@$parents == 1) {
5422 # single parent commit
5423 $formats_nav .=
5424 '(parent: ' .
5425 $cgi->a({-href => href(action=>"commit",
5426 hash=>$parent)},
5427 esc_html(substr($parent, 0, 7))) .
5428 ')';
5429 } else {
5430 # merge commit
5431 $formats_nav .=
5432 '(merge: ' .
5433 join(' ', map {
5434 $cgi->a({-href => href(action=>"commit",
5435 hash=>$_)},
5436 esc_html(substr($_, 0, 7)));
5437 } @$parents ) .
5438 ')';
5440 if (gitweb_check_feature('patches') && @$parents <= 1) {
5441 $formats_nav .= " | " .
5442 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5443 "patch");
5446 if (!defined $parent) {
5447 $parent = "--root";
5449 my @difftree;
5450 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5451 @diff_opts,
5452 (@$parents <= 1 ? $parent : '-c'),
5453 $hash, "--"
5454 or die_error(500, "Open git-diff-tree failed");
5455 @difftree = map { chomp; $_ } <$fd>;
5456 close $fd or die_error(404, "Reading git-diff-tree failed");
5458 # non-textual hash id's can be cached
5459 my $expires;
5460 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5461 $expires = "+1d";
5463 my $refs = git_get_references();
5464 my $ref = format_ref_marker($refs, $co{'id'});
5466 git_header_html(undef, $expires);
5467 git_print_page_nav('commit', '',
5468 $hash, $co{'tree'}, $hash,
5469 $formats_nav);
5471 if (defined $co{'parent'}) {
5472 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5473 } else {
5474 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5476 print "<div class=\"title_text\">\n" .
5477 "<table class=\"object_header\">\n";
5478 git_print_authorship_rows(\%co);
5479 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5480 print "<tr>" .
5481 "<td>tree</td>" .
5482 "<td class=\"sha1\">" .
5483 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5484 class => "list"}, $co{'tree'}) .
5485 "</td>" .
5486 "<td class=\"link\">" .
5487 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5488 "tree");
5489 my $snapshot_links = format_snapshot_links($hash);
5490 if (defined $snapshot_links) {
5491 print " | " . $snapshot_links;
5493 print "</td>" .
5494 "</tr>\n";
5496 foreach my $par (@$parents) {
5497 print "<tr>" .
5498 "<td>parent</td>" .
5499 "<td class=\"sha1\">" .
5500 $cgi->a({-href => href(action=>"commit", hash=>$par),
5501 class => "list"}, $par) .
5502 "</td>" .
5503 "<td class=\"link\">" .
5504 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5505 " | " .
5506 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5507 "</td>" .
5508 "</tr>\n";
5510 print "</table>".
5511 "</div>\n";
5513 print "<div class=\"page_body\">\n";
5514 git_print_log($co{'comment'});
5515 print "</div>\n";
5517 git_difftree_body(\@difftree, $hash, @$parents);
5519 git_footer_html();
5522 sub git_object {
5523 # object is defined by:
5524 # - hash or hash_base alone
5525 # - hash_base and file_name
5526 my $type;
5528 # - hash or hash_base alone
5529 if ($hash || ($hash_base && !defined $file_name)) {
5530 my $object_id = $hash || $hash_base;
5532 open my $fd, "-|", quote_command(
5533 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5534 or die_error(404, "Object does not exist");
5535 $type = <$fd>;
5536 chomp $type;
5537 close $fd
5538 or die_error(404, "Object does not exist");
5540 # - hash_base and file_name
5541 } elsif ($hash_base && defined $file_name) {
5542 $file_name =~ s,/+$,,;
5544 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5545 or die_error(404, "Base object does not exist");
5547 # here errors should not hapen
5548 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5549 or die_error(500, "Open git-ls-tree failed");
5550 my $line = <$fd>;
5551 close $fd;
5553 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5554 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5555 die_error(404, "File or directory for given base does not exist");
5557 $type = $2;
5558 $hash = $3;
5559 } else {
5560 die_error(400, "Not enough information to find object");
5563 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5564 hash=>$hash, hash_base=>$hash_base,
5565 file_name=>$file_name),
5566 -status => '302 Found');
5569 sub git_blobdiff {
5570 my $format = shift || 'html';
5572 my $fd;
5573 my @difftree;
5574 my %diffinfo;
5575 my $expires;
5577 # preparing $fd and %diffinfo for git_patchset_body
5578 # new style URI
5579 if (defined $hash_base && defined $hash_parent_base) {
5580 if (defined $file_name) {
5581 # read raw output
5582 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5583 $hash_parent_base, $hash_base,
5584 "--", (defined $file_parent ? $file_parent : ()), $file_name
5585 or die_error(500, "Open git-diff-tree failed");
5586 @difftree = map { chomp; $_ } <$fd>;
5587 close $fd
5588 or die_error(404, "Reading git-diff-tree failed");
5589 @difftree
5590 or die_error(404, "Blob diff not found");
5592 } elsif (defined $hash &&
5593 $hash =~ /[0-9a-fA-F]{40}/) {
5594 # try to find filename from $hash
5596 # read filtered raw output
5597 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5598 $hash_parent_base, $hash_base, "--"
5599 or die_error(500, "Open git-diff-tree failed");
5600 @difftree =
5601 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5602 # $hash == to_id
5603 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5604 map { chomp; $_ } <$fd>;
5605 close $fd
5606 or die_error(404, "Reading git-diff-tree failed");
5607 @difftree
5608 or die_error(404, "Blob diff not found");
5610 } else {
5611 die_error(400, "Missing one of the blob diff parameters");
5614 if (@difftree > 1) {
5615 die_error(400, "Ambiguous blob diff specification");
5618 %diffinfo = parse_difftree_raw_line($difftree[0]);
5619 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5620 $file_name ||= $diffinfo{'to_file'};
5622 $hash_parent ||= $diffinfo{'from_id'};
5623 $hash ||= $diffinfo{'to_id'};
5625 # non-textual hash id's can be cached
5626 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5627 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5628 $expires = '+1d';
5631 # open patch output
5632 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5633 '-p', ($format eq 'html' ? "--full-index" : ()),
5634 $hash_parent_base, $hash_base,
5635 "--", (defined $file_parent ? $file_parent : ()), $file_name
5636 or die_error(500, "Open git-diff-tree failed");
5639 # old/legacy style URI -- not generated anymore since 1.4.3.
5640 if (!%diffinfo) {
5641 die_error('404 Not Found', "Missing one of the blob diff parameters")
5644 # header
5645 if ($format eq 'html') {
5646 my $formats_nav =
5647 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5648 "raw");
5649 git_header_html(undef, $expires);
5650 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5651 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5652 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5653 } else {
5654 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5655 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5657 if (defined $file_name) {
5658 git_print_page_path($file_name, "blob", $hash_base);
5659 } else {
5660 print "<div class=\"page_path\"></div>\n";
5663 } elsif ($format eq 'plain') {
5664 print $cgi->header(
5665 -type => 'text/plain',
5666 -charset => 'utf-8',
5667 -expires => $expires,
5668 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5670 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5672 } else {
5673 die_error(400, "Unknown blobdiff format");
5676 # patch
5677 if ($format eq 'html') {
5678 print "<div class=\"page_body\">\n";
5680 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5681 close $fd;
5683 print "</div>\n"; # class="page_body"
5684 git_footer_html();
5686 } else {
5687 while (my $line = <$fd>) {
5688 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5689 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5691 print $line;
5693 last if $line =~ m!^\+\+\+!;
5695 local $/ = undef;
5696 print <$fd>;
5697 close $fd;
5701 sub git_blobdiff_plain {
5702 git_blobdiff('plain');
5705 sub git_commitdiff {
5706 my %params = @_;
5707 my $format = $params{-format} || 'html';
5709 my ($patch_max) = gitweb_get_feature('patches');
5710 if ($format eq 'patch') {
5711 die_error(403, "Patch view not allowed") unless $patch_max;
5714 $hash ||= $hash_base || "HEAD";
5715 my %co = parse_commit($hash)
5716 or die_error(404, "Unknown commit object");
5718 # choose format for commitdiff for merge
5719 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5720 $hash_parent = '--cc';
5722 # we need to prepare $formats_nav before almost any parameter munging
5723 my $formats_nav;
5724 if ($format eq 'html') {
5725 $formats_nav =
5726 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5727 "raw");
5728 if ($patch_max && @{$co{'parents'}} <= 1) {
5729 $formats_nav .= " | " .
5730 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5731 "patch");
5734 if (defined $hash_parent &&
5735 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5736 # commitdiff with two commits given
5737 my $hash_parent_short = $hash_parent;
5738 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5739 $hash_parent_short = substr($hash_parent, 0, 7);
5741 $formats_nav .=
5742 ' (from';
5743 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5744 if ($co{'parents'}[$i] eq $hash_parent) {
5745 $formats_nav .= ' parent ' . ($i+1);
5746 last;
5749 $formats_nav .= ': ' .
5750 $cgi->a({-href => href(action=>"commitdiff",
5751 hash=>$hash_parent)},
5752 esc_html($hash_parent_short)) .
5753 ')';
5754 } elsif (!$co{'parent'}) {
5755 # --root commitdiff
5756 $formats_nav .= ' (initial)';
5757 } elsif (scalar @{$co{'parents'}} == 1) {
5758 # single parent commit
5759 $formats_nav .=
5760 ' (parent: ' .
5761 $cgi->a({-href => href(action=>"commitdiff",
5762 hash=>$co{'parent'})},
5763 esc_html(substr($co{'parent'}, 0, 7))) .
5764 ')';
5765 } else {
5766 # merge commit
5767 if ($hash_parent eq '--cc') {
5768 $formats_nav .= ' | ' .
5769 $cgi->a({-href => href(action=>"commitdiff",
5770 hash=>$hash, hash_parent=>'-c')},
5771 'combined');
5772 } else { # $hash_parent eq '-c'
5773 $formats_nav .= ' | ' .
5774 $cgi->a({-href => href(action=>"commitdiff",
5775 hash=>$hash, hash_parent=>'--cc')},
5776 'compact');
5778 $formats_nav .=
5779 ' (merge: ' .
5780 join(' ', map {
5781 $cgi->a({-href => href(action=>"commitdiff",
5782 hash=>$_)},
5783 esc_html(substr($_, 0, 7)));
5784 } @{$co{'parents'}} ) .
5785 ')';
5789 my $hash_parent_param = $hash_parent;
5790 if (!defined $hash_parent_param) {
5791 # --cc for multiple parents, --root for parentless
5792 $hash_parent_param =
5793 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5796 # read commitdiff
5797 my $fd;
5798 my @difftree;
5799 if ($format eq 'html') {
5800 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5801 "--no-commit-id", "--patch-with-raw", "--full-index",
5802 $hash_parent_param, $hash, "--"
5803 or die_error(500, "Open git-diff-tree failed");
5805 while (my $line = <$fd>) {
5806 chomp $line;
5807 # empty line ends raw part of diff-tree output
5808 last unless $line;
5809 push @difftree, scalar parse_difftree_raw_line($line);
5812 } elsif ($format eq 'plain') {
5813 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5814 '-p', $hash_parent_param, $hash, "--"
5815 or die_error(500, "Open git-diff-tree failed");
5816 } elsif ($format eq 'patch') {
5817 # For commit ranges, we limit the output to the number of
5818 # patches specified in the 'patches' feature.
5819 # For single commits, we limit the output to a single patch,
5820 # diverging from the git-format-patch default.
5821 my @commit_spec = ();
5822 if ($hash_parent) {
5823 if ($patch_max > 0) {
5824 push @commit_spec, "-$patch_max";
5826 push @commit_spec, '-n', "$hash_parent..$hash";
5827 } else {
5828 if ($params{-single}) {
5829 push @commit_spec, '-1';
5830 } else {
5831 if ($patch_max > 0) {
5832 push @commit_spec, "-$patch_max";
5834 push @commit_spec, "-n";
5836 push @commit_spec, '--root', $hash;
5838 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5839 '--stdout', @commit_spec
5840 or die_error(500, "Open git-format-patch failed");
5841 } else {
5842 die_error(400, "Unknown commitdiff format");
5845 # non-textual hash id's can be cached
5846 my $expires;
5847 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5848 $expires = "+1d";
5851 # write commit message
5852 if ($format eq 'html') {
5853 my $refs = git_get_references();
5854 my $ref = format_ref_marker($refs, $co{'id'});
5856 git_header_html(undef, $expires);
5857 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5858 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5859 print "<div class=\"title_text\">\n" .
5860 "<table class=\"object_header\">\n";
5861 git_print_authorship_rows(\%co);
5862 print "</table>".
5863 "</div>\n";
5864 print "<div class=\"page_body\">\n";
5865 if (@{$co{'comment'}} > 1) {
5866 print "<div class=\"log\">\n";
5867 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5868 print "</div>\n"; # class="log"
5871 } elsif ($format eq 'plain') {
5872 my $refs = git_get_references("tags");
5873 my $tagname = git_get_rev_name_tags($hash);
5874 my $filename = basename($project) . "-$hash.patch";
5876 print $cgi->header(
5877 -type => 'text/plain',
5878 -charset => 'utf-8',
5879 -expires => $expires,
5880 -content_disposition => 'inline; filename="' . "$filename" . '"');
5881 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5882 print "From: " . to_utf8($co{'author'}) . "\n";
5883 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5884 print "Subject: " . to_utf8($co{'title'}) . "\n";
5886 print "X-Git-Tag: $tagname\n" if $tagname;
5887 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5889 foreach my $line (@{$co{'comment'}}) {
5890 print to_utf8($line) . "\n";
5892 print "---\n\n";
5893 } elsif ($format eq 'patch') {
5894 my $filename = basename($project) . "-$hash.patch";
5896 print $cgi->header(
5897 -type => 'text/plain',
5898 -charset => 'utf-8',
5899 -expires => $expires,
5900 -content_disposition => 'inline; filename="' . "$filename" . '"');
5903 # write patch
5904 if ($format eq 'html') {
5905 my $use_parents = !defined $hash_parent ||
5906 $hash_parent eq '-c' || $hash_parent eq '--cc';
5907 git_difftree_body(\@difftree, $hash,
5908 $use_parents ? @{$co{'parents'}} : $hash_parent);
5909 print "<br/>\n";
5911 git_patchset_body($fd, \@difftree, $hash,
5912 $use_parents ? @{$co{'parents'}} : $hash_parent);
5913 close $fd;
5914 print "</div>\n"; # class="page_body"
5915 git_footer_html();
5917 } elsif ($format eq 'plain') {
5918 local $/ = undef;
5919 print <$fd>;
5920 close $fd
5921 or print "Reading git-diff-tree failed\n";
5922 } elsif ($format eq 'patch') {
5923 local $/ = undef;
5924 print <$fd>;
5925 close $fd
5926 or print "Reading git-format-patch failed\n";
5930 sub git_commitdiff_plain {
5931 git_commitdiff(-format => 'plain');
5934 # format-patch-style patches
5935 sub git_patch {
5936 git_commitdiff(-format => 'patch', -single => 1);
5939 sub git_patches {
5940 git_commitdiff(-format => 'patch');
5943 sub git_history {
5944 if (!defined $hash_base) {
5945 $hash_base = git_get_head_hash($project);
5947 if (!defined $page) {
5948 $page = 0;
5950 my $ftype;
5951 my %co = parse_commit($hash_base)
5952 or die_error(404, "Unknown commit object");
5954 my $refs = git_get_references();
5955 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5957 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5958 $file_name, "--full-history")
5959 or die_error(404, "No such file or directory on given branch");
5961 if (!defined $hash && defined $file_name) {
5962 # some commits could have deleted file in question,
5963 # and not have it in tree, but one of them has to have it
5964 for (my $i = 0; $i <= @commitlist; $i++) {
5965 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5966 last if defined $hash;
5969 if (defined $hash) {
5970 $ftype = git_get_type($hash);
5972 if (!defined $ftype) {
5973 die_error(500, "Unknown type of object");
5976 my $paging_nav = '';
5977 if ($page > 0) {
5978 $paging_nav .=
5979 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5980 file_name=>$file_name)},
5981 "first");
5982 $paging_nav .= " &sdot; " .
5983 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5984 -accesskey => "p", -title => "Alt-p"}, "prev");
5985 } else {
5986 $paging_nav .= "first";
5987 $paging_nav .= " &sdot; prev";
5989 my $next_link = '';
5990 if ($#commitlist >= 100) {
5991 $next_link =
5992 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5993 -accesskey => "n", -title => "Alt-n"}, "next");
5994 $paging_nav .= " &sdot; $next_link";
5995 } else {
5996 $paging_nav .= " &sdot; next";
5999 git_header_html();
6000 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
6001 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6002 git_print_page_path($file_name, $ftype, $hash_base);
6004 git_history_body(\@commitlist, 0, 99,
6005 $refs, $hash_base, $ftype, $next_link);
6007 git_footer_html();
6010 sub git_search {
6011 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6012 if (!defined $searchtext) {
6013 die_error(400, "Text field is empty");
6015 if (!defined $hash) {
6016 $hash = git_get_head_hash($project);
6018 my %co = parse_commit($hash);
6019 if (!%co) {
6020 die_error(404, "Unknown commit object");
6022 if (!defined $page) {
6023 $page = 0;
6026 $searchtype ||= 'commit';
6027 if ($searchtype eq 'pickaxe') {
6028 # pickaxe may take all resources of your box and run for several minutes
6029 # with every query - so decide by yourself how public you make this feature
6030 gitweb_check_feature('pickaxe')
6031 or die_error(403, "Pickaxe is disabled");
6033 if ($searchtype eq 'grep') {
6034 gitweb_check_feature('grep')
6035 or die_error(403, "Grep is disabled");
6038 git_header_html();
6040 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6041 my $greptype;
6042 if ($searchtype eq 'commit') {
6043 $greptype = "--grep=";
6044 } elsif ($searchtype eq 'author') {
6045 $greptype = "--author=";
6046 } elsif ($searchtype eq 'committer') {
6047 $greptype = "--committer=";
6049 $greptype .= $searchtext;
6050 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6051 $greptype, '--regexp-ignore-case',
6052 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6054 my $paging_nav = '';
6055 if ($page > 0) {
6056 $paging_nav .=
6057 $cgi->a({-href => href(action=>"search", hash=>$hash,
6058 searchtext=>$searchtext,
6059 searchtype=>$searchtype)},
6060 "first");
6061 $paging_nav .= " &sdot; " .
6062 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6063 -accesskey => "p", -title => "Alt-p"}, "prev");
6064 } else {
6065 $paging_nav .= "first";
6066 $paging_nav .= " &sdot; prev";
6068 my $next_link = '';
6069 if ($#commitlist >= 100) {
6070 $next_link =
6071 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6072 -accesskey => "n", -title => "Alt-n"}, "next");
6073 $paging_nav .= " &sdot; $next_link";
6074 } else {
6075 $paging_nav .= " &sdot; next";
6078 if ($#commitlist >= 100) {
6081 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6082 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6083 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6086 if ($searchtype eq 'pickaxe') {
6087 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6088 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6090 print "<table class=\"pickaxe search\">\n";
6091 my $alternate = 1;
6092 local $/ = "\n";
6093 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6094 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6095 ($search_use_regexp ? '--pickaxe-regex' : ());
6096 undef %co;
6097 my @files;
6098 while (my $line = <$fd>) {
6099 chomp $line;
6100 next unless $line;
6102 my %set = parse_difftree_raw_line($line);
6103 if (defined $set{'commit'}) {
6104 # finish previous commit
6105 if (%co) {
6106 print "</td>\n" .
6107 "<td class=\"link\">" .
6108 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6109 " | " .
6110 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6111 print "</td>\n" .
6112 "</tr>\n";
6115 if ($alternate) {
6116 print "<tr class=\"dark\">\n";
6117 } else {
6118 print "<tr class=\"light\">\n";
6120 $alternate ^= 1;
6121 %co = parse_commit($set{'commit'});
6122 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6123 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6124 "<td><i>$author</i></td>\n" .
6125 "<td>" .
6126 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6127 -class => "list subject"},
6128 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6129 } elsif (defined $set{'to_id'}) {
6130 next if ($set{'to_id'} =~ m/^0{40}$/);
6132 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6133 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6134 -class => "list"},
6135 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6136 "<br/>\n";
6139 close $fd;
6141 # finish last commit (warning: repetition!)
6142 if (%co) {
6143 print "</td>\n" .
6144 "<td class=\"link\">" .
6145 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6146 " | " .
6147 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6148 print "</td>\n" .
6149 "</tr>\n";
6152 print "</table>\n";
6155 if ($searchtype eq 'grep') {
6156 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6157 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6159 print "<table class=\"grep_search\">\n";
6160 my $alternate = 1;
6161 my $matches = 0;
6162 local $/ = "\n";
6163 open my $fd, "-|", git_cmd(), 'grep', '-n',
6164 $search_use_regexp ? ('-E', '-i') : '-F',
6165 $searchtext, $co{'tree'};
6166 my $lastfile = '';
6167 while (my $line = <$fd>) {
6168 chomp $line;
6169 my ($file, $lno, $ltext, $binary);
6170 last if ($matches++ > 1000);
6171 if ($line =~ /^Binary file (.+) matches$/) {
6172 $file = $1;
6173 $binary = 1;
6174 } else {
6175 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6177 if ($file ne $lastfile) {
6178 $lastfile and print "</td></tr>\n";
6179 if ($alternate++) {
6180 print "<tr class=\"dark\">\n";
6181 } else {
6182 print "<tr class=\"light\">\n";
6184 print "<td class=\"list\">".
6185 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6186 file_name=>"$file"),
6187 -class => "list"}, esc_path($file));
6188 print "</td><td>\n";
6189 $lastfile = $file;
6191 if ($binary) {
6192 print "<div class=\"binary\">Binary file</div>\n";
6193 } else {
6194 $ltext = untabify($ltext);
6195 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6196 $ltext = esc_html($1, -nbsp=>1);
6197 $ltext .= '<span class="match">';
6198 $ltext .= esc_html($2, -nbsp=>1);
6199 $ltext .= '</span>';
6200 $ltext .= esc_html($3, -nbsp=>1);
6201 } else {
6202 $ltext = esc_html($ltext, -nbsp=>1);
6204 print "<div class=\"pre\">" .
6205 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6206 file_name=>"$file").'#l'.$lno,
6207 -class => "linenr"}, sprintf('%4i', $lno))
6208 . ' ' . $ltext . "</div>\n";
6211 if ($lastfile) {
6212 print "</td></tr>\n";
6213 if ($matches > 1000) {
6214 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6216 } else {
6217 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6219 close $fd;
6221 print "</table>\n";
6223 git_footer_html();
6226 sub git_search_help {
6227 git_header_html();
6228 git_print_page_nav('','', $hash,$hash,$hash);
6229 print <<EOT;
6230 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6231 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6232 the pattern entered is recognized as the POSIX extended
6233 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6234 insensitive).</p>
6235 <dl>
6236 <dt><b>commit</b></dt>
6237 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6239 my $have_grep = gitweb_check_feature('grep');
6240 if ($have_grep) {
6241 print <<EOT;
6242 <dt><b>grep</b></dt>
6243 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6244 a different one) are searched for the given pattern. On large trees, this search can take
6245 a while and put some strain on the server, so please use it with some consideration. Note that
6246 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6247 case-sensitive.</dd>
6250 print <<EOT;
6251 <dt><b>author</b></dt>
6252 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6253 <dt><b>committer</b></dt>
6254 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6256 my $have_pickaxe = gitweb_check_feature('pickaxe');
6257 if ($have_pickaxe) {
6258 print <<EOT;
6259 <dt><b>pickaxe</b></dt>
6260 <dd>All commits that caused the string to appear or disappear from any file (changes that
6261 added, removed or "modified" the string) will be listed. This search can take a while and
6262 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6263 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6266 print "</dl>\n";
6267 git_footer_html();
6270 sub git_shortlog {
6271 my $head = git_get_head_hash($project);
6272 if (!defined $hash) {
6273 $hash = $head;
6275 if (!defined $page) {
6276 $page = 0;
6278 my $refs = git_get_references();
6280 my $commit_hash = $hash;
6281 if (defined $hash_parent) {
6282 $commit_hash = "$hash_parent..$hash";
6284 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6286 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6287 my $next_link = '';
6288 if ($#commitlist >= 100) {
6289 $next_link =
6290 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6291 -accesskey => "n", -title => "Alt-n"}, "next");
6293 my $patch_max = gitweb_check_feature('patches');
6294 if ($patch_max) {
6295 if ($patch_max < 0 || @commitlist <= $patch_max) {
6296 $paging_nav .= " &sdot; " .
6297 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6298 "patches");
6302 git_header_html();
6303 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6304 git_print_header_div('summary', $project);
6306 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6308 git_footer_html();
6311 ## ......................................................................
6312 ## feeds (RSS, Atom; OPML)
6314 sub git_feed {
6315 my $format = shift || 'atom';
6316 my $have_blame = gitweb_check_feature('blame');
6318 # Atom: http://www.atomenabled.org/developers/syndication/
6319 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6320 if ($format ne 'rss' && $format ne 'atom') {
6321 die_error(400, "Unknown web feed format");
6324 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6325 my $head = $hash || 'HEAD';
6326 my @commitlist = parse_commits($head, 150, 0, $file_name);
6328 my %latest_commit;
6329 my %latest_date;
6330 my $content_type = "application/$format+xml";
6331 if (defined $cgi->http('HTTP_ACCEPT') &&
6332 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6333 # browser (feed reader) prefers text/xml
6334 $content_type = 'text/xml';
6336 if (defined($commitlist[0])) {
6337 %latest_commit = %{$commitlist[0]};
6338 my $latest_epoch = $latest_commit{'committer_epoch'};
6339 %latest_date = parse_date($latest_epoch);
6340 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6341 if (defined $if_modified) {
6342 my $since;
6343 if (eval { require HTTP::Date; 1; }) {
6344 $since = HTTP::Date::str2time($if_modified);
6345 } elsif (eval { require Time::ParseDate; 1; }) {
6346 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6348 if (defined $since && $latest_epoch <= $since) {
6349 print $cgi->header(
6350 -type => $content_type,
6351 -charset => 'utf-8',
6352 -last_modified => $latest_date{'rfc2822'},
6353 -status => '304 Not Modified');
6354 return;
6357 print $cgi->header(
6358 -type => $content_type,
6359 -charset => 'utf-8',
6360 -last_modified => $latest_date{'rfc2822'});
6361 } else {
6362 print $cgi->header(
6363 -type => $content_type,
6364 -charset => 'utf-8');
6367 # Optimization: skip generating the body if client asks only
6368 # for Last-Modified date.
6369 return if ($cgi->request_method() eq 'HEAD');
6371 # header variables
6372 my $title = "$site_name - $project/$action";
6373 my $feed_type = 'log';
6374 if (defined $hash) {
6375 $title .= " - '$hash'";
6376 $feed_type = 'branch log';
6377 if (defined $file_name) {
6378 $title .= " :: $file_name";
6379 $feed_type = 'history';
6381 } elsif (defined $file_name) {
6382 $title .= " - $file_name";
6383 $feed_type = 'history';
6385 $title .= " $feed_type";
6386 my $descr = git_get_project_description($project);
6387 if (defined $descr) {
6388 $descr = esc_html($descr);
6389 } else {
6390 $descr = "$project " .
6391 ($format eq 'rss' ? 'RSS' : 'Atom') .
6392 " feed";
6394 my $owner = git_get_project_owner($project);
6395 $owner = esc_html($owner);
6397 #header
6398 my $alt_url;
6399 if (defined $file_name) {
6400 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6401 } elsif (defined $hash) {
6402 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6403 } else {
6404 $alt_url = href(-full=>1, action=>"summary");
6406 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6407 if ($format eq 'rss') {
6408 print <<XML;
6409 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6410 <channel>
6412 print "<title>$title</title>\n" .
6413 "<link>$alt_url</link>\n" .
6414 "<description>$descr</description>\n" .
6415 "<language>en</language>\n" .
6416 # project owner is responsible for 'editorial' content
6417 "<managingEditor>$owner</managingEditor>\n";
6418 if (defined $logo || defined $favicon) {
6419 # prefer the logo to the favicon, since RSS
6420 # doesn't allow both
6421 my $img = esc_url($logo || $favicon);
6422 print "<image>\n" .
6423 "<url>$img</url>\n" .
6424 "<title>$title</title>\n" .
6425 "<link>$alt_url</link>\n" .
6426 "</image>\n";
6428 if (%latest_date) {
6429 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6430 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6432 print "<generator>gitweb v.$version/$git_version</generator>\n";
6433 } elsif ($format eq 'atom') {
6434 print <<XML;
6435 <feed xmlns="http://www.w3.org/2005/Atom">
6437 print "<title>$title</title>\n" .
6438 "<subtitle>$descr</subtitle>\n" .
6439 '<link rel="alternate" type="text/html" href="' .
6440 $alt_url . '" />' . "\n" .
6441 '<link rel="self" type="' . $content_type . '" href="' .
6442 $cgi->self_url() . '" />' . "\n" .
6443 "<id>" . href(-full=>1) . "</id>\n" .
6444 # use project owner for feed author
6445 "<author><name>$owner</name></author>\n";
6446 if (defined $favicon) {
6447 print "<icon>" . esc_url($favicon) . "</icon>\n";
6449 if (defined $logo_url) {
6450 # not twice as wide as tall: 72 x 27 pixels
6451 print "<logo>" . esc_url($logo) . "</logo>\n";
6453 if (! %latest_date) {
6454 # dummy date to keep the feed valid until commits trickle in:
6455 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6456 } else {
6457 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6459 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6462 # contents
6463 for (my $i = 0; $i <= $#commitlist; $i++) {
6464 my %co = %{$commitlist[$i]};
6465 my $commit = $co{'id'};
6466 # we read 150, we always show 30 and the ones more recent than 48 hours
6467 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6468 last;
6470 my %cd = parse_date($co{'author_epoch'});
6472 # get list of changed files
6473 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6474 $co{'parent'} || "--root",
6475 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6476 or next;
6477 my @difftree = map { chomp; $_ } <$fd>;
6478 close $fd
6479 or next;
6481 # print element (entry, item)
6482 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6483 if ($format eq 'rss') {
6484 print "<item>\n" .
6485 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6486 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6487 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6488 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6489 "<link>$co_url</link>\n" .
6490 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6491 "<content:encoded>" .
6492 "<![CDATA[\n";
6493 } elsif ($format eq 'atom') {
6494 print "<entry>\n" .
6495 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6496 "<updated>$cd{'iso-8601'}</updated>\n" .
6497 "<author>\n" .
6498 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6499 if ($co{'author_email'}) {
6500 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6502 print "</author>\n" .
6503 # use committer for contributor
6504 "<contributor>\n" .
6505 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6506 if ($co{'committer_email'}) {
6507 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6509 print "</contributor>\n" .
6510 "<published>$cd{'iso-8601'}</published>\n" .
6511 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6512 "<id>$co_url</id>\n" .
6513 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6514 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6516 my $comment = $co{'comment'};
6517 print "<pre>\n";
6518 foreach my $line (@$comment) {
6519 $line = esc_html($line);
6520 print "$line\n";
6522 print "</pre><ul>\n";
6523 foreach my $difftree_line (@difftree) {
6524 my %difftree = parse_difftree_raw_line($difftree_line);
6525 next if !$difftree{'from_id'};
6527 my $file = $difftree{'file'} || $difftree{'to_file'};
6529 print "<li>" .
6530 "[" .
6531 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6532 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6533 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6534 file_name=>$file, file_parent=>$difftree{'from_file'}),
6535 -title => "diff"}, 'D');
6536 if ($have_blame) {
6537 print $cgi->a({-href => href(-full=>1, action=>"blame",
6538 file_name=>$file, hash_base=>$commit),
6539 -title => "blame"}, 'B');
6541 # if this is not a feed of a file history
6542 if (!defined $file_name || $file_name ne $file) {
6543 print $cgi->a({-href => href(-full=>1, action=>"history",
6544 file_name=>$file, hash=>$commit),
6545 -title => "history"}, 'H');
6547 $file = esc_path($file);
6548 print "] ".
6549 "$file</li>\n";
6551 if ($format eq 'rss') {
6552 print "</ul>]]>\n" .
6553 "</content:encoded>\n" .
6554 "</item>\n";
6555 } elsif ($format eq 'atom') {
6556 print "</ul>\n</div>\n" .
6557 "</content>\n" .
6558 "</entry>\n";
6562 # end of feed
6563 if ($format eq 'rss') {
6564 print "</channel>\n</rss>\n";
6565 } elsif ($format eq 'atom') {
6566 print "</feed>\n";
6570 sub git_rss {
6571 git_feed('rss');
6574 sub git_atom {
6575 git_feed('atom');
6578 sub git_opml {
6579 my @list = git_get_projects_list();
6581 print $cgi->header(
6582 -type => 'text/xml',
6583 -charset => 'utf-8',
6584 -content_disposition => 'inline; filename="opml.xml"');
6586 print <<XML;
6587 <?xml version="1.0" encoding="utf-8"?>
6588 <opml version="1.0">
6589 <head>
6590 <title>$site_name OPML Export</title>
6591 </head>
6592 <body>
6593 <outline text="git RSS feeds">
6596 foreach my $pr (@list) {
6597 my %proj = %$pr;
6598 my $head = git_get_head_hash($proj{'path'});
6599 if (!defined $head) {
6600 next;
6602 $git_dir = "$projectroot/$proj{'path'}";
6603 my %co = parse_commit($head);
6604 if (!%co) {
6605 next;
6608 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6609 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6610 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6611 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6613 print <<XML;
6614 </outline>
6615 </body>
6616 </opml>