Merge commit 'refs/top-bases/t/blame/incremental' into t/blame/incremental
[git/gitweb.git] / gitweb / gitweb.perl
blobe6a5584e20428e665fb09913ce0544f5ac880425
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++";
93 # URI of gitweb.js
94 our $gitwebjs = "++GITWEB_GITWEBJS++";
96 # URI and label (title) of GIT logo link
97 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
98 #our $logo_label = "git documentation";
99 our $logo_url = "http://git-scm.com/";
100 our $logo_label = "git homepage";
102 # source of projects list
103 our $projects_list = "++GITWEB_LIST++";
105 # the width (in characters) of the projects list "Description" column
106 our $projects_list_description_width = 25;
108 # default order of projects list
109 # valid values are none, project, descr, owner, and age
110 our $default_projects_order = "project";
112 # show repository only if this file exists
113 # (only effective if this variable evaluates to true)
114 our $export_ok = "++GITWEB_EXPORT_OK++";
116 # show repository only if this subroutine returns true
117 # when given the path to the project, for example:
118 # sub { return -e "$_[0]/git-daemon-export-ok"; }
119 our $export_auth_hook = undef;
121 # only allow viewing of repositories also shown on the overview page
122 our $strict_export = "++GITWEB_STRICT_EXPORT++";
124 # list of git base URLs used for URL to where fetch project from,
125 # i.e. full URL is "$git_base_url/$project"
126 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
128 # default blob_plain mimetype and default charset for text/plain blob
129 our $default_blob_plain_mimetype = 'text/plain';
130 our $default_text_plain_charset = undef;
132 # file to use for guessing MIME types before trying /etc/mime.types
133 # (relative to the current git repository)
134 our $mimetypes_file = undef;
136 # assume this charset if line contains non-UTF-8 characters;
137 # it should be valid encoding (see Encoding::Supported(3pm) for list),
138 # for which encoding all byte sequences are valid, for example
139 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
140 # could be even 'utf-8' for the old behavior)
141 our $fallback_encoding = 'latin1';
143 # rename detection options for git-diff and git-diff-tree
144 # - default is '-M', with the cost proportional to
145 # (number of removed files) * (number of new files).
146 # - more costly is '-C' (which implies '-M'), with the cost proportional to
147 # (number of changed files + number of removed files) * (number of new files)
148 # - even more costly is '-C', '--find-copies-harder' with cost
149 # (number of files in the original tree) * (number of new files)
150 # - one might want to include '-B' option, e.g. '-B', '-M'
151 our @diff_opts = ('-M'); # taken from git_commit
153 # Disables features that would allow repository owners to inject script into
154 # the gitweb domain.
155 our $prevent_xss = 0;
157 # information about snapshot formats that gitweb is capable of serving
158 our %known_snapshot_formats = (
159 # name => {
160 # 'display' => display name,
161 # 'type' => mime type,
162 # 'suffix' => filename suffix,
163 # 'format' => --format for git-archive,
164 # 'compressor' => [compressor command and arguments]
165 # (array reference, optional)
166 # 'disabled' => boolean (optional)}
168 'tgz' => {
169 'display' => 'tar.gz',
170 'type' => 'application/x-gzip',
171 'suffix' => '.tar.gz',
172 'format' => 'tar',
173 'compressor' => ['gzip']},
175 'tbz2' => {
176 'display' => 'tar.bz2',
177 'type' => 'application/x-bzip2',
178 'suffix' => '.tar.bz2',
179 'format' => 'tar',
180 'compressor' => ['bzip2']},
182 'txz' => {
183 'display' => 'tar.xz',
184 'type' => 'application/x-xz',
185 'suffix' => '.tar.xz',
186 'format' => 'tar',
187 'compressor' => ['xz'],
188 'disabled' => 1},
190 'zip' => {
191 'display' => 'zip',
192 'type' => 'application/x-zip',
193 'suffix' => '.zip',
194 'format' => 'zip'},
197 # Aliases so we understand old gitweb.snapshot values in repository
198 # configuration.
199 our %known_snapshot_format_aliases = (
200 'gzip' => 'tgz',
201 'bzip2' => 'tbz2',
202 'xz' => 'txz',
204 # backward compatibility: legacy gitweb config support
205 'x-gzip' => undef, 'gz' => undef,
206 'x-bzip2' => undef, 'bz2' => undef,
207 'x-zip' => undef, '' => undef,
210 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
211 # are changed, it may be appropriate to change these values too via
212 # $GITWEB_CONFIG.
213 our %avatar_size = (
214 'default' => 16,
215 'double' => 32
218 # You define site-wide feature defaults here; override them with
219 # $GITWEB_CONFIG as necessary.
220 our %feature = (
221 # feature => {
222 # 'sub' => feature-sub (subroutine),
223 # 'override' => allow-override (boolean),
224 # 'default' => [ default options...] (array reference)}
226 # if feature is overridable (it means that allow-override has true value),
227 # then feature-sub will be called with default options as parameters;
228 # return value of feature-sub indicates if to enable specified feature
230 # if there is no 'sub' key (no feature-sub), then feature cannot be
231 # overriden
233 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
234 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
235 # is enabled
237 # Enable the 'blame' blob view, showing the last commit that modified
238 # each line in the file. This can be very CPU-intensive.
240 # To enable system wide have in $GITWEB_CONFIG
241 # $feature{'blame'}{'default'} = [1];
242 # To have project specific config enable override in $GITWEB_CONFIG
243 # $feature{'blame'}{'override'} = 1;
244 # and in project config gitweb.blame = 0|1;
245 'blame' => {
246 'sub' => sub { feature_bool('blame', @_) },
247 'override' => 0,
248 'default' => [0]},
250 # Enable the 'snapshot' link, providing a compressed archive of any
251 # tree. This can potentially generate high traffic if you have large
252 # project.
254 # Value is a list of formats defined in %known_snapshot_formats that
255 # you wish to offer.
256 # To disable system wide have in $GITWEB_CONFIG
257 # $feature{'snapshot'}{'default'} = [];
258 # To have project specific config enable override in $GITWEB_CONFIG
259 # $feature{'snapshot'}{'override'} = 1;
260 # and in project config, a comma-separated list of formats or "none"
261 # to disable. Example: gitweb.snapshot = tbz2,zip;
262 'snapshot' => {
263 'sub' => \&feature_snapshot,
264 'override' => 0,
265 'default' => ['tgz']},
267 # Enable text search, which will list the commits which match author,
268 # committer or commit text to a given string. Enabled by default.
269 # Project specific override is not supported.
270 'search' => {
271 'override' => 0,
272 'default' => [1]},
274 # Enable grep search, which will list the files in currently selected
275 # tree containing the given string. Enabled by default. This can be
276 # potentially CPU-intensive, of course.
278 # To enable system wide have in $GITWEB_CONFIG
279 # $feature{'grep'}{'default'} = [1];
280 # To have project specific config enable override in $GITWEB_CONFIG
281 # $feature{'grep'}{'override'} = 1;
282 # and in project config gitweb.grep = 0|1;
283 'grep' => {
284 'sub' => sub { feature_bool('grep', @_) },
285 'override' => 0,
286 'default' => [1]},
288 # Enable the pickaxe search, which will list the commits that modified
289 # a given string in a file. This can be practical and quite faster
290 # alternative to 'blame', but still potentially CPU-intensive.
292 # To enable system wide have in $GITWEB_CONFIG
293 # $feature{'pickaxe'}{'default'} = [1];
294 # To have project specific config enable override in $GITWEB_CONFIG
295 # $feature{'pickaxe'}{'override'} = 1;
296 # and in project config gitweb.pickaxe = 0|1;
297 'pickaxe' => {
298 'sub' => sub { feature_bool('pickaxe', @_) },
299 'override' => 0,
300 'default' => [1]},
302 # Enable showing size of blobs in a 'tree' view, in a separate
303 # column, similar to what 'ls -l' does. This cost a bit of IO.
305 # To disable system wide have in $GITWEB_CONFIG
306 # $feature{'show-sizes'}{'default'} = [0];
307 # To have project specific config enable override in $GITWEB_CONFIG
308 # $feature{'show-sizes'}{'override'} = 1;
309 # and in project config gitweb.showsizes = 0|1;
310 'show-sizes' => {
311 'sub' => sub { feature_bool('showsizes', @_) },
312 'override' => 0,
313 'default' => [1]},
315 # Make gitweb use an alternative format of the URLs which can be
316 # more readable and natural-looking: project name is embedded
317 # directly in the path and the query string contains other
318 # auxiliary information. All gitweb installations recognize
319 # URL in either format; this configures in which formats gitweb
320 # generates links.
322 # To enable system wide have in $GITWEB_CONFIG
323 # $feature{'pathinfo'}{'default'} = [1];
324 # Project specific override is not supported.
326 # Note that you will need to change the default location of CSS,
327 # favicon, logo and possibly other files to an absolute URL. Also,
328 # if gitweb.cgi serves as your indexfile, you will need to force
329 # $my_uri to contain the script name in your $GITWEB_CONFIG.
330 'pathinfo' => {
331 'override' => 0,
332 'default' => [0]},
334 # Make gitweb consider projects in project root subdirectories
335 # to be forks of existing projects. Given project $projname.git,
336 # projects matching $projname/*.git will not be shown in the main
337 # projects list, instead a '+' mark will be added to $projname
338 # there and a 'forks' view will be enabled for the project, listing
339 # all the forks. If project list is taken from a file, forks have
340 # to be listed after the main project.
342 # To enable system wide have in $GITWEB_CONFIG
343 # $feature{'forks'}{'default'} = [1];
344 # Project specific override is not supported.
345 'forks' => {
346 'override' => 0,
347 'default' => [0]},
349 # Insert custom links to the action bar of all project pages.
350 # This enables you mainly to link to third-party scripts integrating
351 # into gitweb; e.g. git-browser for graphical history representation
352 # or custom web-based repository administration interface.
354 # The 'default' value consists of a list of triplets in the form
355 # (label, link, position) where position is the label after which
356 # to insert the link and link is a format string where %n expands
357 # to the project name, %f to the project path within the filesystem,
358 # %h to the current hash (h gitweb parameter) and %b to the current
359 # hash base (hb gitweb parameter); %% expands to %.
361 # To enable system wide have in $GITWEB_CONFIG e.g.
362 # $feature{'actions'}{'default'} = [('graphiclog',
363 # '/git-browser/by-commit.html?r=%n', 'summary')];
364 # Project specific override is not supported.
365 'actions' => {
366 'override' => 0,
367 'default' => []},
369 # Allow gitweb scan project content tags described in ctags/
370 # of project repository, and display the popular Web 2.0-ish
371 # "tag cloud" near the project list. Note that this is something
372 # COMPLETELY different from the normal Git tags.
374 # gitweb by itself can show existing tags, but it does not handle
375 # tagging itself; you need an external application for that.
376 # For an example script, check Girocco's cgi/tagproj.cgi.
377 # You may want to install the HTML::TagCloud Perl module to get
378 # a pretty tag cloud instead of just a list of tags.
380 # To enable system wide have in $GITWEB_CONFIG
381 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
382 # Project specific override is not supported.
383 'ctags' => {
384 'override' => 0,
385 'default' => [0]},
387 # The maximum number of patches in a patchset generated in patch
388 # view. Set this to 0 or undef to disable patch view, or to a
389 # negative number to remove any limit.
391 # To disable system wide have in $GITWEB_CONFIG
392 # $feature{'patches'}{'default'} = [0];
393 # To have project specific config enable override in $GITWEB_CONFIG
394 # $feature{'patches'}{'override'} = 1;
395 # and in project config gitweb.patches = 0|n;
396 # where n is the maximum number of patches allowed in a patchset.
397 'patches' => {
398 'sub' => \&feature_patches,
399 'override' => 0,
400 'default' => [16]},
402 # Avatar support. When this feature is enabled, views such as
403 # shortlog or commit will display an avatar associated with
404 # the email of the committer(s) and/or author(s).
406 # Currently available providers are gravatar and picon.
407 # If an unknown provider is specified, the feature is disabled.
409 # Gravatar depends on Digest::MD5.
410 # Picon currently relies on the indiana.edu database.
412 # To enable system wide have in $GITWEB_CONFIG
413 # $feature{'avatar'}{'default'} = ['<provider>'];
414 # where <provider> is either gravatar or picon.
415 # To have project specific config enable override in $GITWEB_CONFIG
416 # $feature{'avatar'}{'override'} = 1;
417 # and in project config gitweb.avatar = <provider>;
418 'avatar' => {
419 'sub' => \&feature_avatar,
420 'override' => 0,
421 'default' => ['']},
424 sub gitweb_get_feature {
425 my ($name) = @_;
426 return unless exists $feature{$name};
427 my ($sub, $override, @defaults) = (
428 $feature{$name}{'sub'},
429 $feature{$name}{'override'},
430 @{$feature{$name}{'default'}});
431 if (!$override) { return @defaults; }
432 if (!defined $sub) {
433 warn "feature $name is not overridable";
434 return @defaults;
436 return $sub->(@defaults);
439 # A wrapper to check if a given feature is enabled.
440 # With this, you can say
442 # my $bool_feat = gitweb_check_feature('bool_feat');
443 # gitweb_check_feature('bool_feat') or somecode;
445 # instead of
447 # my ($bool_feat) = gitweb_get_feature('bool_feat');
448 # (gitweb_get_feature('bool_feat'))[0] or somecode;
450 sub gitweb_check_feature {
451 return (gitweb_get_feature(@_))[0];
455 sub feature_bool {
456 my $key = shift;
457 my ($val) = git_get_project_config($key, '--bool');
459 if (!defined $val) {
460 return ($_[0]);
461 } elsif ($val eq 'true') {
462 return (1);
463 } elsif ($val eq 'false') {
464 return (0);
468 sub feature_snapshot {
469 my (@fmts) = @_;
471 my ($val) = git_get_project_config('snapshot');
473 if ($val) {
474 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
477 return @fmts;
480 sub feature_patches {
481 my @val = (git_get_project_config('patches', '--int'));
483 if (@val) {
484 return @val;
487 return ($_[0]);
490 sub feature_avatar {
491 my @val = (git_get_project_config('avatar'));
493 return @val ? @val : @_;
496 # checking HEAD file with -e is fragile if the repository was
497 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
498 # and then pruned.
499 sub check_head_link {
500 my ($dir) = @_;
501 my $headfile = "$dir/HEAD";
502 return ((-e $headfile) ||
503 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
506 sub check_export_ok {
507 my ($dir) = @_;
508 return (check_head_link($dir) &&
509 (!$export_ok || -e "$dir/$export_ok") &&
510 (!$export_auth_hook || $export_auth_hook->($dir)));
513 # process alternate names for backward compatibility
514 # filter out unsupported (unknown) snapshot formats
515 sub filter_snapshot_fmts {
516 my @fmts = @_;
518 @fmts = map {
519 exists $known_snapshot_format_aliases{$_} ?
520 $known_snapshot_format_aliases{$_} : $_} @fmts;
521 @fmts = grep {
522 exists $known_snapshot_formats{$_} &&
523 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
526 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
527 if (-e $GITWEB_CONFIG) {
528 do $GITWEB_CONFIG;
529 } else {
530 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
531 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
534 # version of the core git binary
535 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
537 $projects_list ||= $projectroot;
539 # ======================================================================
540 # input validation and dispatch
542 # input parameters can be collected from a variety of sources (presently, CGI
543 # and PATH_INFO), so we define an %input_params hash that collects them all
544 # together during validation: this allows subsequent uses (e.g. href()) to be
545 # agnostic of the parameter origin
547 our %input_params = ();
549 # input parameters are stored with the long parameter name as key. This will
550 # also be used in the href subroutine to convert parameters to their CGI
551 # equivalent, and since the href() usage is the most frequent one, we store
552 # the name -> CGI key mapping here, instead of the reverse.
554 # XXX: Warning: If you touch this, check the search form for updating,
555 # too.
557 our @cgi_param_mapping = (
558 project => "p",
559 action => "a",
560 file_name => "f",
561 file_parent => "fp",
562 hash => "h",
563 hash_parent => "hp",
564 hash_base => "hb",
565 hash_parent_base => "hpb",
566 page => "pg",
567 order => "o",
568 searchtext => "s",
569 searchtype => "st",
570 snapshot_format => "sf",
571 extra_options => "opt",
572 search_use_regexp => "sr",
574 our %cgi_param_mapping = @cgi_param_mapping;
576 # we will also need to know the possible actions, for validation
577 our %actions = (
578 "blame" => \&git_blame,
579 "blame_incremental" => \&git_blame_incremental,
580 "blame_data" => \&git_blame_data,
581 "blobdiff" => \&git_blobdiff,
582 "blobdiff_plain" => \&git_blobdiff_plain,
583 "blob" => \&git_blob,
584 "blob_plain" => \&git_blob_plain,
585 "commitdiff" => \&git_commitdiff,
586 "commitdiff_plain" => \&git_commitdiff_plain,
587 "commit" => \&git_commit,
588 "forks" => \&git_forks,
589 "heads" => \&git_heads,
590 "history" => \&git_history,
591 "log" => \&git_log,
592 "patch" => \&git_patch,
593 "patches" => \&git_patches,
594 "rss" => \&git_rss,
595 "atom" => \&git_atom,
596 "search" => \&git_search,
597 "search_help" => \&git_search_help,
598 "shortlog" => \&git_shortlog,
599 "summary" => \&git_summary,
600 "tag" => \&git_tag,
601 "tags" => \&git_tags,
602 "tree" => \&git_tree,
603 "snapshot" => \&git_snapshot,
604 "object" => \&git_object,
605 # those below don't need $project
606 "opml" => \&git_opml,
607 "project_list" => \&git_project_list,
608 "project_index" => \&git_project_index,
611 # finally, we have the hash of allowed extra_options for the commands that
612 # allow them
613 our %allowed_options = (
614 "--no-merges" => [ qw(rss atom log shortlog history) ],
617 # fill %input_params with the CGI parameters. All values except for 'opt'
618 # should be single values, but opt can be an array. We should probably
619 # build an array of parameters that can be multi-valued, but since for the time
620 # being it's only this one, we just single it out
621 while (my ($name, $symbol) = each %cgi_param_mapping) {
622 if ($symbol eq 'opt') {
623 $input_params{$name} = [ $cgi->param($symbol) ];
624 } else {
625 $input_params{$name} = $cgi->param($symbol);
629 # now read PATH_INFO and update the parameter list for missing parameters
630 sub evaluate_path_info {
631 return if defined $input_params{'project'};
632 return if !$path_info;
633 $path_info =~ s,^/+,,;
634 return if !$path_info;
636 # find which part of PATH_INFO is project
637 my $project = $path_info;
638 $project =~ s,/+$,,;
639 while ($project && !check_head_link("$projectroot/$project")) {
640 $project =~ s,/*[^/]*$,,;
642 return unless $project;
643 $input_params{'project'} = $project;
645 # do not change any parameters if an action is given using the query string
646 return if $input_params{'action'};
647 $path_info =~ s,^\Q$project\E/*,,;
649 # next, check if we have an action
650 my $action = $path_info;
651 $action =~ s,/.*$,,;
652 if (exists $actions{$action}) {
653 $path_info =~ s,^$action/*,,;
654 $input_params{'action'} = $action;
657 # list of actions that want hash_base instead of hash, but can have no
658 # pathname (f) parameter
659 my @wants_base = (
660 'tree',
661 'history',
664 # we want to catch
665 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
666 my ($parentrefname, $parentpathname, $refname, $pathname) =
667 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
669 # first, analyze the 'current' part
670 if (defined $pathname) {
671 # we got "branch:filename" or "branch:dir/"
672 # we could use git_get_type(branch:pathname), but:
673 # - it needs $git_dir
674 # - it does a git() call
675 # - the convention of terminating directories with a slash
676 # makes it superfluous
677 # - embedding the action in the PATH_INFO would make it even
678 # more superfluous
679 $pathname =~ s,^/+,,;
680 if (!$pathname || substr($pathname, -1) eq "/") {
681 $input_params{'action'} ||= "tree";
682 $pathname =~ s,/$,,;
683 } else {
684 # the default action depends on whether we had parent info
685 # or not
686 if ($parentrefname) {
687 $input_params{'action'} ||= "blobdiff_plain";
688 } else {
689 $input_params{'action'} ||= "blob_plain";
692 $input_params{'hash_base'} ||= $refname;
693 $input_params{'file_name'} ||= $pathname;
694 } elsif (defined $refname) {
695 # we got "branch". In this case we have to choose if we have to
696 # set hash or hash_base.
698 # Most of the actions without a pathname only want hash to be
699 # set, except for the ones specified in @wants_base that want
700 # hash_base instead. It should also be noted that hand-crafted
701 # links having 'history' as an action and no pathname or hash
702 # set will fail, but that happens regardless of PATH_INFO.
703 $input_params{'action'} ||= "shortlog";
704 if (grep { $_ eq $input_params{'action'} } @wants_base) {
705 $input_params{'hash_base'} ||= $refname;
706 } else {
707 $input_params{'hash'} ||= $refname;
711 # next, handle the 'parent' part, if present
712 if (defined $parentrefname) {
713 # a missing pathspec defaults to the 'current' filename, allowing e.g.
714 # someproject/blobdiff/oldrev..newrev:/filename
715 if ($parentpathname) {
716 $parentpathname =~ s,^/+,,;
717 $parentpathname =~ s,/$,,;
718 $input_params{'file_parent'} ||= $parentpathname;
719 } else {
720 $input_params{'file_parent'} ||= $input_params{'file_name'};
722 # we assume that hash_parent_base is wanted if a path was specified,
723 # or if the action wants hash_base instead of hash
724 if (defined $input_params{'file_parent'} ||
725 grep { $_ eq $input_params{'action'} } @wants_base) {
726 $input_params{'hash_parent_base'} ||= $parentrefname;
727 } else {
728 $input_params{'hash_parent'} ||= $parentrefname;
732 # for the snapshot action, we allow URLs in the form
733 # $project/snapshot/$hash.ext
734 # where .ext determines the snapshot and gets removed from the
735 # passed $refname to provide the $hash.
737 # To be able to tell that $refname includes the format extension, we
738 # require the following two conditions to be satisfied:
739 # - the hash input parameter MUST have been set from the $refname part
740 # of the URL (i.e. they must be equal)
741 # - the snapshot format MUST NOT have been defined already (e.g. from
742 # CGI parameter sf)
743 # It's also useless to try any matching unless $refname has a dot,
744 # so we check for that too
745 if (defined $input_params{'action'} &&
746 $input_params{'action'} eq 'snapshot' &&
747 defined $refname && index($refname, '.') != -1 &&
748 $refname eq $input_params{'hash'} &&
749 !defined $input_params{'snapshot_format'}) {
750 # We loop over the known snapshot formats, checking for
751 # extensions. Allowed extensions are both the defined suffix
752 # (which includes the initial dot already) and the snapshot
753 # format key itself, with a prepended dot
754 while (my ($fmt, $opt) = each %known_snapshot_formats) {
755 my $hash = $refname;
756 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
757 next;
759 my $sfx = $1;
760 # a valid suffix was found, so set the snapshot format
761 # and reset the hash parameter
762 $input_params{'snapshot_format'} = $fmt;
763 $input_params{'hash'} = $hash;
764 # we also set the format suffix to the one requested
765 # in the URL: this way a request for e.g. .tgz returns
766 # a .tgz instead of a .tar.gz
767 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
768 last;
772 evaluate_path_info();
774 our $action = $input_params{'action'};
775 if (defined $action) {
776 if (!validate_action($action)) {
777 die_error(400, "Invalid action parameter");
781 # parameters which are pathnames
782 our $project = $input_params{'project'};
783 if (defined $project) {
784 if (!validate_project($project)) {
785 undef $project;
786 die_error(404, "No such project");
790 our $file_name = $input_params{'file_name'};
791 if (defined $file_name) {
792 if (!validate_pathname($file_name)) {
793 die_error(400, "Invalid file parameter");
797 our $file_parent = $input_params{'file_parent'};
798 if (defined $file_parent) {
799 if (!validate_pathname($file_parent)) {
800 die_error(400, "Invalid file parent parameter");
804 # parameters which are refnames
805 our $hash = $input_params{'hash'};
806 if (defined $hash) {
807 if (!validate_refname($hash)) {
808 die_error(400, "Invalid hash parameter");
812 our $hash_parent = $input_params{'hash_parent'};
813 if (defined $hash_parent) {
814 if (!validate_refname($hash_parent)) {
815 die_error(400, "Invalid hash parent parameter");
819 our $hash_base = $input_params{'hash_base'};
820 if (defined $hash_base) {
821 if (!validate_refname($hash_base)) {
822 die_error(400, "Invalid hash base parameter");
826 our @extra_options = @{$input_params{'extra_options'}};
827 # @extra_options is always defined, since it can only be (currently) set from
828 # CGI, and $cgi->param() returns the empty array in array context if the param
829 # is not set
830 foreach my $opt (@extra_options) {
831 if (not exists $allowed_options{$opt}) {
832 die_error(400, "Invalid option parameter");
834 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
835 die_error(400, "Invalid option parameter for this action");
839 our $hash_parent_base = $input_params{'hash_parent_base'};
840 if (defined $hash_parent_base) {
841 if (!validate_refname($hash_parent_base)) {
842 die_error(400, "Invalid hash parent base parameter");
846 # other parameters
847 our $page = $input_params{'page'};
848 if (defined $page) {
849 if ($page =~ m/[^0-9]/) {
850 die_error(400, "Invalid page parameter");
854 our $searchtype = $input_params{'searchtype'};
855 if (defined $searchtype) {
856 if ($searchtype =~ m/[^a-z]/) {
857 die_error(400, "Invalid searchtype parameter");
861 our $search_use_regexp = $input_params{'search_use_regexp'};
863 our $searchtext = $input_params{'searchtext'};
864 our $search_regexp;
865 if (defined $searchtext) {
866 if (length($searchtext) < 2) {
867 die_error(403, "At least two characters are required for search parameter");
869 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
872 # path to the current git repository
873 our $git_dir;
874 $git_dir = "$projectroot/$project" if $project;
876 # list of supported snapshot formats
877 our @snapshot_fmts = gitweb_get_feature('snapshot');
878 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
880 # check that the avatar feature is set to a known provider name,
881 # and for each provider check if the dependencies are satisfied.
882 # if the provider name is invalid or the dependencies are not met,
883 # reset $git_avatar to the empty string.
884 our ($git_avatar) = gitweb_get_feature('avatar');
885 if ($git_avatar eq 'gravatar') {
886 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
887 } elsif ($git_avatar eq 'picon') {
888 # no dependencies
889 } else {
890 $git_avatar = '';
893 # dispatch
894 if (!defined $action) {
895 if (defined $hash) {
896 $action = git_get_type($hash);
897 } elsif (defined $hash_base && defined $file_name) {
898 $action = git_get_type("$hash_base:$file_name");
899 } elsif (defined $project) {
900 $action = 'summary';
901 } else {
902 $action = 'project_list';
905 if (!defined($actions{$action})) {
906 die_error(400, "Unknown action");
908 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
909 !$project) {
910 die_error(400, "Project needed");
912 $actions{$action}->();
913 exit;
915 ## ======================================================================
916 ## action links
918 sub href {
919 my %params = @_;
920 # default is to use -absolute url() i.e. $my_uri
921 my $href = $params{-full} ? $my_url : $my_uri;
923 $params{'project'} = $project unless exists $params{'project'};
925 if ($params{-replay}) {
926 while (my ($name, $symbol) = each %cgi_param_mapping) {
927 if (!exists $params{$name}) {
928 $params{$name} = $input_params{$name};
933 my $use_pathinfo = gitweb_check_feature('pathinfo');
934 if ($use_pathinfo and defined $params{'project'}) {
935 # try to put as many parameters as possible in PATH_INFO:
936 # - project name
937 # - action
938 # - hash_parent or hash_parent_base:/file_parent
939 # - hash or hash_base:/filename
940 # - the snapshot_format as an appropriate suffix
942 # When the script is the root DirectoryIndex for the domain,
943 # $href here would be something like http://gitweb.example.com/
944 # Thus, we strip any trailing / from $href, to spare us double
945 # slashes in the final URL
946 $href =~ s,/$,,;
948 # Then add the project name, if present
949 $href .= "/".esc_url($params{'project'});
950 delete $params{'project'};
952 # since we destructively absorb parameters, we keep this
953 # boolean that remembers if we're handling a snapshot
954 my $is_snapshot = $params{'action'} eq 'snapshot';
956 # Summary just uses the project path URL, any other action is
957 # added to the URL
958 if (defined $params{'action'}) {
959 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
960 delete $params{'action'};
963 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
964 # stripping nonexistent or useless pieces
965 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
966 || $params{'hash_parent'} || $params{'hash'});
967 if (defined $params{'hash_base'}) {
968 if (defined $params{'hash_parent_base'}) {
969 $href .= esc_url($params{'hash_parent_base'});
970 # skip the file_parent if it's the same as the file_name
971 if (defined $params{'file_parent'}) {
972 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
973 delete $params{'file_parent'};
974 } elsif ($params{'file_parent'} !~ /\.\./) {
975 $href .= ":/".esc_url($params{'file_parent'});
976 delete $params{'file_parent'};
979 $href .= "..";
980 delete $params{'hash_parent'};
981 delete $params{'hash_parent_base'};
982 } elsif (defined $params{'hash_parent'}) {
983 $href .= esc_url($params{'hash_parent'}). "..";
984 delete $params{'hash_parent'};
987 $href .= esc_url($params{'hash_base'});
988 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
989 $href .= ":/".esc_url($params{'file_name'});
990 delete $params{'file_name'};
992 delete $params{'hash'};
993 delete $params{'hash_base'};
994 } elsif (defined $params{'hash'}) {
995 $href .= esc_url($params{'hash'});
996 delete $params{'hash'};
999 # If the action was a snapshot, we can absorb the
1000 # snapshot_format parameter too
1001 if ($is_snapshot) {
1002 my $fmt = $params{'snapshot_format'};
1003 # snapshot_format should always be defined when href()
1004 # is called, but just in case some code forgets, we
1005 # fall back to the default
1006 $fmt ||= $snapshot_fmts[0];
1007 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1008 delete $params{'snapshot_format'};
1012 # now encode the parameters explicitly
1013 my @result = ();
1014 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1015 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1016 if (defined $params{$name}) {
1017 if (ref($params{$name}) eq "ARRAY") {
1018 foreach my $par (@{$params{$name}}) {
1019 push @result, $symbol . "=" . esc_param($par);
1021 } else {
1022 push @result, $symbol . "=" . esc_param($params{$name});
1026 $href .= "?" . join(';', @result) if $params{-partial_query} or scalar @result;
1028 return $href;
1032 ## ======================================================================
1033 ## validation, quoting/unquoting and escaping
1035 sub validate_action {
1036 my $input = shift || return undef;
1037 return undef unless exists $actions{$input};
1038 return $input;
1041 sub validate_project {
1042 my $input = shift || return undef;
1043 if (!validate_pathname($input) ||
1044 !(-d "$projectroot/$input") ||
1045 !check_export_ok("$projectroot/$input") ||
1046 ($strict_export && !project_in_list($input))) {
1047 return undef;
1048 } else {
1049 return $input;
1053 sub validate_pathname {
1054 my $input = shift || return undef;
1056 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1057 # at the beginning, at the end, and between slashes.
1058 # also this catches doubled slashes
1059 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1060 return undef;
1062 # no null characters
1063 if ($input =~ m!\0!) {
1064 return undef;
1066 return $input;
1069 sub validate_refname {
1070 my $input = shift || return undef;
1072 # textual hashes are O.K.
1073 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1074 return $input;
1076 # it must be correct pathname
1077 $input = validate_pathname($input)
1078 or return undef;
1079 # restrictions on ref name according to git-check-ref-format
1080 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1081 return undef;
1083 return $input;
1086 # decode sequences of octets in utf8 into Perl's internal form,
1087 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1088 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1089 sub to_utf8 {
1090 my $str = shift;
1091 if (utf8::valid($str)) {
1092 utf8::decode($str);
1093 return $str;
1094 } else {
1095 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1099 # quote unsafe chars, but keep the slash, even when it's not
1100 # correct, but quoted slashes look too horrible in bookmarks
1101 sub esc_param {
1102 my $str = shift;
1103 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1104 $str =~ s/ /\+/g;
1105 return $str;
1108 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1109 sub esc_url {
1110 my $str = shift;
1111 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1112 $str =~ s/\+/%2B/g;
1113 $str =~ s/ /\+/g;
1114 return $str;
1117 # replace invalid utf8 character with SUBSTITUTION sequence
1118 sub esc_html {
1119 my $str = shift;
1120 my %opts = @_;
1122 $str = to_utf8($str);
1123 $str = $cgi->escapeHTML($str);
1124 if ($opts{'-nbsp'}) {
1125 $str =~ s/ /&nbsp;/g;
1127 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1128 return $str;
1131 # quote control characters and escape filename to HTML
1132 sub esc_path {
1133 my $str = shift;
1134 my %opts = @_;
1136 $str = to_utf8($str);
1137 $str = $cgi->escapeHTML($str);
1138 if ($opts{'-nbsp'}) {
1139 $str =~ s/ /&nbsp;/g;
1141 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1142 return $str;
1145 # Make control characters "printable", using character escape codes (CEC)
1146 sub quot_cec {
1147 my $cntrl = shift;
1148 my %opts = @_;
1149 my %es = ( # character escape codes, aka escape sequences
1150 "\t" => '\t', # tab (HT)
1151 "\n" => '\n', # line feed (LF)
1152 "\r" => '\r', # carrige return (CR)
1153 "\f" => '\f', # form feed (FF)
1154 "\b" => '\b', # backspace (BS)
1155 "\a" => '\a', # alarm (bell) (BEL)
1156 "\e" => '\e', # escape (ESC)
1157 "\013" => '\v', # vertical tab (VT)
1158 "\000" => '\0', # nul character (NUL)
1160 my $chr = ( (exists $es{$cntrl})
1161 ? $es{$cntrl}
1162 : sprintf('\%2x', ord($cntrl)) );
1163 if ($opts{-nohtml}) {
1164 return $chr;
1165 } else {
1166 return "<span class=\"cntrl\">$chr</span>";
1170 # Alternatively use unicode control pictures codepoints,
1171 # Unicode "printable representation" (PR)
1172 sub quot_upr {
1173 my $cntrl = shift;
1174 my %opts = @_;
1176 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1177 if ($opts{-nohtml}) {
1178 return $chr;
1179 } else {
1180 return "<span class=\"cntrl\">$chr</span>";
1184 # git may return quoted and escaped filenames
1185 sub unquote {
1186 my $str = shift;
1188 sub unq {
1189 my $seq = shift;
1190 my %es = ( # character escape codes, aka escape sequences
1191 't' => "\t", # tab (HT, TAB)
1192 'n' => "\n", # newline (NL)
1193 'r' => "\r", # return (CR)
1194 'f' => "\f", # form feed (FF)
1195 'b' => "\b", # backspace (BS)
1196 'a' => "\a", # alarm (bell) (BEL)
1197 'e' => "\e", # escape (ESC)
1198 'v' => "\013", # vertical tab (VT)
1201 if ($seq =~ m/^[0-7]{1,3}$/) {
1202 # octal char sequence
1203 return chr(oct($seq));
1204 } elsif (exists $es{$seq}) {
1205 # C escape sequence, aka character escape code
1206 return $es{$seq};
1208 # quoted ordinary character
1209 return $seq;
1212 if ($str =~ m/^"(.*)"$/) {
1213 # needs unquoting
1214 $str = $1;
1215 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1217 return $str;
1220 # escape tabs (convert tabs to spaces)
1221 sub untabify {
1222 my $line = shift;
1224 while ((my $pos = index($line, "\t")) != -1) {
1225 if (my $count = (8 - ($pos % 8))) {
1226 my $spaces = ' ' x $count;
1227 $line =~ s/\t/$spaces/;
1231 return $line;
1234 sub project_in_list {
1235 my $project = shift;
1236 my @list = git_get_projects_list();
1237 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1240 ## ----------------------------------------------------------------------
1241 ## HTML aware string manipulation
1243 # Try to chop given string on a word boundary between position
1244 # $len and $len+$add_len. If there is no word boundary there,
1245 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1246 # (marking chopped part) would be longer than given string.
1247 sub chop_str {
1248 my $str = shift;
1249 my $len = shift;
1250 my $add_len = shift || 10;
1251 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1253 # Make sure perl knows it is utf8 encoded so we don't
1254 # cut in the middle of a utf8 multibyte char.
1255 $str = to_utf8($str);
1257 # allow only $len chars, but don't cut a word if it would fit in $add_len
1258 # if it doesn't fit, cut it if it's still longer than the dots we would add
1259 # remove chopped character entities entirely
1261 # when chopping in the middle, distribute $len into left and right part
1262 # return early if chopping wouldn't make string shorter
1263 if ($where eq 'center') {
1264 return $str if ($len + 5 >= length($str)); # filler is length 5
1265 $len = int($len/2);
1266 } else {
1267 return $str if ($len + 4 >= length($str)); # filler is length 4
1270 # regexps: ending and beginning with word part up to $add_len
1271 my $endre = qr/.{$len}\w{0,$add_len}/;
1272 my $begre = qr/\w{0,$add_len}.{$len}/;
1274 if ($where eq 'left') {
1275 $str =~ m/^(.*?)($begre)$/;
1276 my ($lead, $body) = ($1, $2);
1277 if (length($lead) > 4) {
1278 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1279 $lead = " ...";
1281 return "$lead$body";
1283 } elsif ($where eq 'center') {
1284 $str =~ m/^($endre)(.*)$/;
1285 my ($left, $str) = ($1, $2);
1286 $str =~ m/^(.*?)($begre)$/;
1287 my ($mid, $right) = ($1, $2);
1288 if (length($mid) > 5) {
1289 $left =~ s/&[^;]*$//;
1290 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1291 $mid = " ... ";
1293 return "$left$mid$right";
1295 } else {
1296 $str =~ m/^($endre)(.*)$/;
1297 my $body = $1;
1298 my $tail = $2;
1299 if (length($tail) > 4) {
1300 $body =~ s/&[^;]*$//;
1301 $tail = "... ";
1303 return "$body$tail";
1307 # takes the same arguments as chop_str, but also wraps a <span> around the
1308 # result with a title attribute if it does get chopped. Additionally, the
1309 # string is HTML-escaped.
1310 sub chop_and_escape_str {
1311 my ($str) = @_;
1313 my $chopped = chop_str(@_);
1314 if ($chopped eq $str) {
1315 return esc_html($chopped);
1316 } else {
1317 $str =~ s/[[:cntrl:]]/?/g;
1318 return $cgi->span({-title=>$str}, esc_html($chopped));
1322 ## ----------------------------------------------------------------------
1323 ## functions returning short strings
1325 # CSS class for given age value (in seconds)
1326 sub age_class {
1327 my $age = shift;
1329 if (!defined $age) {
1330 return "noage";
1331 } elsif ($age < 60*60*2) {
1332 return "age0";
1333 } elsif ($age < 60*60*24*2) {
1334 return "age1";
1335 } else {
1336 return "age2";
1340 # convert age in seconds to "nn units ago" string
1341 sub age_string {
1342 my $age = shift;
1343 my $age_str;
1345 if ($age > 60*60*24*365*2) {
1346 $age_str = (int $age/60/60/24/365);
1347 $age_str .= " years ago";
1348 } elsif ($age > 60*60*24*(365/12)*2) {
1349 $age_str = int $age/60/60/24/(365/12);
1350 $age_str .= " months ago";
1351 } elsif ($age > 60*60*24*7*2) {
1352 $age_str = int $age/60/60/24/7;
1353 $age_str .= " weeks ago";
1354 } elsif ($age > 60*60*24*2) {
1355 $age_str = int $age/60/60/24;
1356 $age_str .= " days ago";
1357 } elsif ($age > 60*60*2) {
1358 $age_str = int $age/60/60;
1359 $age_str .= " hours ago";
1360 } elsif ($age > 60*2) {
1361 $age_str = int $age/60;
1362 $age_str .= " min ago";
1363 } elsif ($age > 2) {
1364 $age_str = int $age;
1365 $age_str .= " sec ago";
1366 } else {
1367 $age_str .= " right now";
1369 return $age_str;
1372 use constant {
1373 S_IFINVALID => 0030000,
1374 S_IFGITLINK => 0160000,
1377 # submodule/subproject, a commit object reference
1378 sub S_ISGITLINK {
1379 my $mode = shift;
1381 return (($mode & S_IFMT) == S_IFGITLINK)
1384 # convert file mode in octal to symbolic file mode string
1385 sub mode_str {
1386 my $mode = oct shift;
1388 if (S_ISGITLINK($mode)) {
1389 return 'm---------';
1390 } elsif (S_ISDIR($mode & S_IFMT)) {
1391 return 'drwxr-xr-x';
1392 } elsif (S_ISLNK($mode)) {
1393 return 'lrwxrwxrwx';
1394 } elsif (S_ISREG($mode)) {
1395 # git cares only about the executable bit
1396 if ($mode & S_IXUSR) {
1397 return '-rwxr-xr-x';
1398 } else {
1399 return '-rw-r--r--';
1401 } else {
1402 return '----------';
1406 # convert file mode in octal to file type string
1407 sub file_type {
1408 my $mode = shift;
1410 if ($mode !~ m/^[0-7]+$/) {
1411 return $mode;
1412 } else {
1413 $mode = oct $mode;
1416 if (S_ISGITLINK($mode)) {
1417 return "submodule";
1418 } elsif (S_ISDIR($mode & S_IFMT)) {
1419 return "directory";
1420 } elsif (S_ISLNK($mode)) {
1421 return "symlink";
1422 } elsif (S_ISREG($mode)) {
1423 return "file";
1424 } else {
1425 return "unknown";
1429 # convert file mode in octal to file type description string
1430 sub file_type_long {
1431 my $mode = shift;
1433 if ($mode !~ m/^[0-7]+$/) {
1434 return $mode;
1435 } else {
1436 $mode = oct $mode;
1439 if (S_ISGITLINK($mode)) {
1440 return "submodule";
1441 } elsif (S_ISDIR($mode & S_IFMT)) {
1442 return "directory";
1443 } elsif (S_ISLNK($mode)) {
1444 return "symlink";
1445 } elsif (S_ISREG($mode)) {
1446 if ($mode & S_IXUSR) {
1447 return "executable";
1448 } else {
1449 return "file";
1451 } else {
1452 return "unknown";
1457 ## ----------------------------------------------------------------------
1458 ## functions returning short HTML fragments, or transforming HTML fragments
1459 ## which don't belong to other sections
1461 # format line of commit message.
1462 sub format_log_line_html {
1463 my $line = shift;
1465 $line = esc_html($line, -nbsp=>1);
1466 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1467 $cgi->a({-href => href(action=>"object", hash=>$1),
1468 -class => "text"}, $1);
1469 }eg;
1471 return $line;
1474 # format marker of refs pointing to given object
1476 # the destination action is chosen based on object type and current context:
1477 # - for annotated tags, we choose the tag view unless it's the current view
1478 # already, in which case we go to shortlog view
1479 # - for other refs, we keep the current view if we're in history, shortlog or
1480 # log view, and select shortlog otherwise
1481 sub format_ref_marker {
1482 my ($refs, $id) = @_;
1483 my $markers = '';
1485 if (defined $refs->{$id}) {
1486 foreach my $ref (@{$refs->{$id}}) {
1487 # this code exploits the fact that non-lightweight tags are the
1488 # only indirect objects, and that they are the only objects for which
1489 # we want to use tag instead of shortlog as action
1490 my ($type, $name) = qw();
1491 my $indirect = ($ref =~ s/\^\{\}$//);
1492 # e.g. tags/v2.6.11 or heads/next
1493 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1494 $type = $1;
1495 $name = $2;
1496 } else {
1497 $type = "ref";
1498 $name = $ref;
1501 my $class = $type;
1502 $class .= " indirect" if $indirect;
1504 my $dest_action = "shortlog";
1506 if ($indirect) {
1507 $dest_action = "tag" unless $action eq "tag";
1508 } elsif ($action =~ /^(history|(short)?log)$/) {
1509 $dest_action = $action;
1512 my $dest = "";
1513 $dest .= "refs/" unless $ref =~ m!^refs/!;
1514 $dest .= $ref;
1516 my $link = $cgi->a({
1517 -href => href(
1518 action=>$dest_action,
1519 hash=>$dest
1520 )}, $name);
1522 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1523 $link . "</span>";
1527 if ($markers) {
1528 return ' <span class="refs">'. $markers . '</span>';
1529 } else {
1530 return "";
1534 # format, perhaps shortened and with markers, title line
1535 sub format_subject_html {
1536 my ($long, $short, $href, $extra) = @_;
1537 $extra = '' unless defined($extra);
1539 if (length($short) < length($long)) {
1540 $long =~ s/[[:cntrl:]]/?/g;
1541 return $cgi->a({-href => $href, -class => "list subject",
1542 -title => to_utf8($long)},
1543 esc_html($short)) . $extra;
1544 } else {
1545 return $cgi->a({-href => $href, -class => "list subject"},
1546 esc_html($long)) . $extra;
1550 # Rather than recomputing the url for an email multiple times, we cache it
1551 # after the first hit. This gives a visible benefit in views where the avatar
1552 # for the same email is used repeatedly (e.g. shortlog).
1553 # The cache is shared by all avatar engines (currently gravatar only), which
1554 # are free to use it as preferred. Since only one avatar engine is used for any
1555 # given page, there's no risk for cache conflicts.
1556 our %avatar_cache = ();
1558 # Compute the picon url for a given email, by using the picon search service over at
1559 # http://www.cs.indiana.edu/picons/search.html
1560 sub picon_url {
1561 my $email = lc shift;
1562 if (!$avatar_cache{$email}) {
1563 my ($user, $domain) = split('@', $email);
1564 $avatar_cache{$email} =
1565 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1566 "$domain/$user/" .
1567 "users+domains+unknown/up/single";
1569 return $avatar_cache{$email};
1572 # Compute the gravatar url for a given email, if it's not in the cache already.
1573 # Gravatar stores only the part of the URL before the size, since that's the
1574 # one computationally more expensive. This also allows reuse of the cache for
1575 # different sizes (for this particular engine).
1576 sub gravatar_url {
1577 my $email = lc shift;
1578 my $size = shift;
1579 $avatar_cache{$email} ||=
1580 "http://www.gravatar.com/avatar/" .
1581 Digest::MD5::md5_hex($email) . "?s=";
1582 return $avatar_cache{$email} . $size;
1585 # Insert an avatar for the given $email at the given $size if the feature
1586 # is enabled.
1587 sub git_get_avatar {
1588 my ($email, %opts) = @_;
1589 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1590 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1591 $opts{-size} ||= 'default';
1592 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1593 my $url = "";
1594 if ($git_avatar eq 'gravatar') {
1595 $url = gravatar_url($email, $size);
1596 } elsif ($git_avatar eq 'picon') {
1597 $url = picon_url($email);
1599 # Other providers can be added by extending the if chain, defining $url
1600 # as needed. If no variant puts something in $url, we assume avatars
1601 # are completely disabled/unavailable.
1602 if ($url) {
1603 return $pre_white .
1604 "<img width=\"$size\" " .
1605 "class=\"avatar\" " .
1606 "src=\"$url\" " .
1607 "alt=\"\" " .
1608 "/>" . $post_white;
1609 } else {
1610 return "";
1614 sub format_search_author {
1615 my ($author, $searchtype, $displaytext) = @_;
1616 my $have_search = gitweb_check_feature('search');
1618 if ($have_search) {
1619 my $performed = "";
1620 if ($searchtype eq 'author') {
1621 $performed = "authored";
1622 } elsif ($searchtype eq 'committer') {
1623 $performed = "committed";
1626 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1627 searchtext=>$author,
1628 searchtype=>$searchtype), class=>"list",
1629 title=>"Search for commits $performed by $author"},
1630 $displaytext);
1632 } else {
1633 return $displaytext;
1637 # format the author name of the given commit with the given tag
1638 # the author name is chopped and escaped according to the other
1639 # optional parameters (see chop_str).
1640 sub format_author_html {
1641 my $tag = shift;
1642 my $co = shift;
1643 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1644 return "<$tag class=\"author\">" .
1645 format_search_author($co->{'author_name'}, "author",
1646 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1647 $author) .
1648 "</$tag>";
1651 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1652 sub format_git_diff_header_line {
1653 my $line = shift;
1654 my $diffinfo = shift;
1655 my ($from, $to) = @_;
1657 if ($diffinfo->{'nparents'}) {
1658 # combined diff
1659 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1660 if ($to->{'href'}) {
1661 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1662 esc_path($to->{'file'}));
1663 } else { # file was deleted (no href)
1664 $line .= esc_path($to->{'file'});
1666 } else {
1667 # "ordinary" diff
1668 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1669 if ($from->{'href'}) {
1670 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1671 'a/' . esc_path($from->{'file'}));
1672 } else { # file was added (no href)
1673 $line .= 'a/' . esc_path($from->{'file'});
1675 $line .= ' ';
1676 if ($to->{'href'}) {
1677 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1678 'b/' . esc_path($to->{'file'}));
1679 } else { # file was deleted
1680 $line .= 'b/' . esc_path($to->{'file'});
1684 return "<div class=\"diff header\">$line</div>\n";
1687 # format extended diff header line, before patch itself
1688 sub format_extended_diff_header_line {
1689 my $line = shift;
1690 my $diffinfo = shift;
1691 my ($from, $to) = @_;
1693 # match <path>
1694 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1695 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1696 esc_path($from->{'file'}));
1698 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1699 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1700 esc_path($to->{'file'}));
1702 # match single <mode>
1703 if ($line =~ m/\s(\d{6})$/) {
1704 $line .= '<span class="info"> (' .
1705 file_type_long($1) .
1706 ')</span>';
1708 # match <hash>
1709 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1710 # can match only for combined diff
1711 $line = 'index ';
1712 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1713 if ($from->{'href'}[$i]) {
1714 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1715 -class=>"hash"},
1716 substr($diffinfo->{'from_id'}[$i],0,7));
1717 } else {
1718 $line .= '0' x 7;
1720 # separator
1721 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1723 $line .= '..';
1724 if ($to->{'href'}) {
1725 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1726 substr($diffinfo->{'to_id'},0,7));
1727 } else {
1728 $line .= '0' x 7;
1731 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1732 # can match only for ordinary diff
1733 my ($from_link, $to_link);
1734 if ($from->{'href'}) {
1735 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1736 substr($diffinfo->{'from_id'},0,7));
1737 } else {
1738 $from_link = '0' x 7;
1740 if ($to->{'href'}) {
1741 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1742 substr($diffinfo->{'to_id'},0,7));
1743 } else {
1744 $to_link = '0' x 7;
1746 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1747 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1750 return $line . "<br/>\n";
1753 # format from-file/to-file diff header
1754 sub format_diff_from_to_header {
1755 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1756 my $line;
1757 my $result = '';
1759 $line = $from_line;
1760 #assert($line =~ m/^---/) if DEBUG;
1761 # no extra formatting for "^--- /dev/null"
1762 if (! $diffinfo->{'nparents'}) {
1763 # ordinary (single parent) diff
1764 if ($line =~ m!^--- "?a/!) {
1765 if ($from->{'href'}) {
1766 $line = '--- a/' .
1767 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1768 esc_path($from->{'file'}));
1769 } else {
1770 $line = '--- a/' .
1771 esc_path($from->{'file'});
1774 $result .= qq!<div class="diff from_file">$line</div>\n!;
1776 } else {
1777 # combined diff (merge commit)
1778 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1779 if ($from->{'href'}[$i]) {
1780 $line = '--- ' .
1781 $cgi->a({-href=>href(action=>"blobdiff",
1782 hash_parent=>$diffinfo->{'from_id'}[$i],
1783 hash_parent_base=>$parents[$i],
1784 file_parent=>$from->{'file'}[$i],
1785 hash=>$diffinfo->{'to_id'},
1786 hash_base=>$hash,
1787 file_name=>$to->{'file'}),
1788 -class=>"path",
1789 -title=>"diff" . ($i+1)},
1790 $i+1) .
1791 '/' .
1792 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1793 esc_path($from->{'file'}[$i]));
1794 } else {
1795 $line = '--- /dev/null';
1797 $result .= qq!<div class="diff from_file">$line</div>\n!;
1801 $line = $to_line;
1802 #assert($line =~ m/^\+\+\+/) if DEBUG;
1803 # no extra formatting for "^+++ /dev/null"
1804 if ($line =~ m!^\+\+\+ "?b/!) {
1805 if ($to->{'href'}) {
1806 $line = '+++ b/' .
1807 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1808 esc_path($to->{'file'}));
1809 } else {
1810 $line = '+++ b/' .
1811 esc_path($to->{'file'});
1814 $result .= qq!<div class="diff to_file">$line</div>\n!;
1816 return $result;
1819 # create note for patch simplified by combined diff
1820 sub format_diff_cc_simplified {
1821 my ($diffinfo, @parents) = @_;
1822 my $result = '';
1824 $result .= "<div class=\"diff header\">" .
1825 "diff --cc ";
1826 if (!is_deleted($diffinfo)) {
1827 $result .= $cgi->a({-href => href(action=>"blob",
1828 hash_base=>$hash,
1829 hash=>$diffinfo->{'to_id'},
1830 file_name=>$diffinfo->{'to_file'}),
1831 -class => "path"},
1832 esc_path($diffinfo->{'to_file'}));
1833 } else {
1834 $result .= esc_path($diffinfo->{'to_file'});
1836 $result .= "</div>\n" . # class="diff header"
1837 "<div class=\"diff nodifferences\">" .
1838 "Simple merge" .
1839 "</div>\n"; # class="diff nodifferences"
1841 return $result;
1844 # format patch (diff) line (not to be used for diff headers)
1845 sub format_diff_line {
1846 my $line = shift;
1847 my ($from, $to) = @_;
1848 my $diff_class = "";
1850 chomp $line;
1852 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1853 # combined diff
1854 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1855 if ($line =~ m/^\@{3}/) {
1856 $diff_class = " chunk_header";
1857 } elsif ($line =~ m/^\\/) {
1858 $diff_class = " incomplete";
1859 } elsif ($prefix =~ tr/+/+/) {
1860 $diff_class = " add";
1861 } elsif ($prefix =~ tr/-/-/) {
1862 $diff_class = " rem";
1864 } else {
1865 # assume ordinary diff
1866 my $char = substr($line, 0, 1);
1867 if ($char eq '+') {
1868 $diff_class = " add";
1869 } elsif ($char eq '-') {
1870 $diff_class = " rem";
1871 } elsif ($char eq '@') {
1872 $diff_class = " chunk_header";
1873 } elsif ($char eq "\\") {
1874 $diff_class = " incomplete";
1877 $line = untabify($line);
1878 if ($from && $to && $line =~ m/^\@{2} /) {
1879 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1880 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1882 $from_lines = 0 unless defined $from_lines;
1883 $to_lines = 0 unless defined $to_lines;
1885 if ($from->{'href'}) {
1886 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1887 -class=>"list"}, $from_text);
1889 if ($to->{'href'}) {
1890 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1891 -class=>"list"}, $to_text);
1893 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1894 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1895 return "<div class=\"diff$diff_class\">$line</div>\n";
1896 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1897 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1898 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1900 @from_text = split(' ', $ranges);
1901 for (my $i = 0; $i < @from_text; ++$i) {
1902 ($from_start[$i], $from_nlines[$i]) =
1903 (split(',', substr($from_text[$i], 1)), 0);
1906 $to_text = pop @from_text;
1907 $to_start = pop @from_start;
1908 $to_nlines = pop @from_nlines;
1910 $line = "<span class=\"chunk_info\">$prefix ";
1911 for (my $i = 0; $i < @from_text; ++$i) {
1912 if ($from->{'href'}[$i]) {
1913 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1914 -class=>"list"}, $from_text[$i]);
1915 } else {
1916 $line .= $from_text[$i];
1918 $line .= " ";
1920 if ($to->{'href'}) {
1921 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1922 -class=>"list"}, $to_text);
1923 } else {
1924 $line .= $to_text;
1926 $line .= " $prefix</span>" .
1927 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1928 return "<div class=\"diff$diff_class\">$line</div>\n";
1930 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1933 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1934 # linked. Pass the hash of the tree/commit to snapshot.
1935 sub format_snapshot_links {
1936 my ($hash) = @_;
1937 my $num_fmts = @snapshot_fmts;
1938 if ($num_fmts > 1) {
1939 # A parenthesized list of links bearing format names.
1940 # e.g. "snapshot (_tar.gz_ _zip_)"
1941 return "snapshot (" . join(' ', map
1942 $cgi->a({
1943 -href => href(
1944 action=>"snapshot",
1945 hash=>$hash,
1946 snapshot_format=>$_
1948 }, $known_snapshot_formats{$_}{'display'})
1949 , @snapshot_fmts) . ")";
1950 } elsif ($num_fmts == 1) {
1951 # A single "snapshot" link whose tooltip bears the format name.
1952 # i.e. "_snapshot_"
1953 my ($fmt) = @snapshot_fmts;
1954 return
1955 $cgi->a({
1956 -href => href(
1957 action=>"snapshot",
1958 hash=>$hash,
1959 snapshot_format=>$fmt
1961 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1962 }, "snapshot");
1963 } else { # $num_fmts == 0
1964 return undef;
1968 ## ......................................................................
1969 ## functions returning values to be passed, perhaps after some
1970 ## transformation, to other functions; e.g. returning arguments to href()
1972 # returns hash to be passed to href to generate gitweb URL
1973 # in -title key it returns description of link
1974 sub get_feed_info {
1975 my $format = shift || 'Atom';
1976 my %res = (action => lc($format));
1978 # feed links are possible only for project views
1979 return unless (defined $project);
1980 # some views should link to OPML, or to generic project feed,
1981 # or don't have specific feed yet (so they should use generic)
1982 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1984 my $branch;
1985 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1986 # from tag links; this also makes possible to detect branch links
1987 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1988 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1989 $branch = $1;
1991 # find log type for feed description (title)
1992 my $type = 'log';
1993 if (defined $file_name) {
1994 $type = "history of $file_name";
1995 $type .= "/" if ($action eq 'tree');
1996 $type .= " on '$branch'" if (defined $branch);
1997 } else {
1998 $type = "log of $branch" if (defined $branch);
2001 $res{-title} = $type;
2002 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2003 $res{'file_name'} = $file_name;
2005 return %res;
2008 ## ----------------------------------------------------------------------
2009 ## git utility subroutines, invoking git commands
2011 # returns path to the core git executable and the --git-dir parameter as list
2012 sub git_cmd {
2013 return $GIT, '--git-dir='.$git_dir;
2016 # quote the given arguments for passing them to the shell
2017 # quote_command("command", "arg 1", "arg with ' and ! characters")
2018 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2019 # Try to avoid using this function wherever possible.
2020 sub quote_command {
2021 return join(' ',
2022 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2025 # get HEAD ref of given project as hash
2026 sub git_get_head_hash {
2027 my $project = shift;
2028 my $o_git_dir = $git_dir;
2029 my $retval = undef;
2030 $git_dir = "$projectroot/$project";
2031 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
2032 my $head = <$fd>;
2033 close $fd;
2034 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
2035 $retval = $1;
2038 if (defined $o_git_dir) {
2039 $git_dir = $o_git_dir;
2041 return $retval;
2044 # get type of given object
2045 sub git_get_type {
2046 my $hash = shift;
2048 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2049 my $type = <$fd>;
2050 close $fd or return;
2051 chomp $type;
2052 return $type;
2055 # repository configuration
2056 our $config_file = '';
2057 our %config;
2059 # store multiple values for single key as anonymous array reference
2060 # single values stored directly in the hash, not as [ <value> ]
2061 sub hash_set_multi {
2062 my ($hash, $key, $value) = @_;
2064 if (!exists $hash->{$key}) {
2065 $hash->{$key} = $value;
2066 } elsif (!ref $hash->{$key}) {
2067 $hash->{$key} = [ $hash->{$key}, $value ];
2068 } else {
2069 push @{$hash->{$key}}, $value;
2073 # return hash of git project configuration
2074 # optionally limited to some section, e.g. 'gitweb'
2075 sub git_parse_project_config {
2076 my $section_regexp = shift;
2077 my %config;
2079 local $/ = "\0";
2081 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2082 or return;
2084 while (my $keyval = <$fh>) {
2085 chomp $keyval;
2086 my ($key, $value) = split(/\n/, $keyval, 2);
2088 hash_set_multi(\%config, $key, $value)
2089 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2091 close $fh;
2093 return %config;
2096 # convert config value to boolean: 'true' or 'false'
2097 # no value, number > 0, 'true' and 'yes' values are true
2098 # rest of values are treated as false (never as error)
2099 sub config_to_bool {
2100 my $val = shift;
2102 return 1 if !defined $val; # section.key
2104 # strip leading and trailing whitespace
2105 $val =~ s/^\s+//;
2106 $val =~ s/\s+$//;
2108 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2109 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2112 # convert config value to simple decimal number
2113 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2114 # to be multiplied by 1024, 1048576, or 1073741824
2115 sub config_to_int {
2116 my $val = shift;
2118 # strip leading and trailing whitespace
2119 $val =~ s/^\s+//;
2120 $val =~ s/\s+$//;
2122 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2123 $unit = lc($unit);
2124 # unknown unit is treated as 1
2125 return $num * ($unit eq 'g' ? 1073741824 :
2126 $unit eq 'm' ? 1048576 :
2127 $unit eq 'k' ? 1024 : 1);
2129 return $val;
2132 # convert config value to array reference, if needed
2133 sub config_to_multi {
2134 my $val = shift;
2136 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2139 sub git_get_project_config {
2140 my ($key, $type) = @_;
2142 # key sanity check
2143 return unless ($key);
2144 $key =~ s/^gitweb\.//;
2145 return if ($key =~ m/\W/);
2147 # type sanity check
2148 if (defined $type) {
2149 $type =~ s/^--//;
2150 $type = undef
2151 unless ($type eq 'bool' || $type eq 'int');
2154 # get config
2155 if (!defined $config_file ||
2156 $config_file ne "$git_dir/config") {
2157 %config = git_parse_project_config('gitweb');
2158 $config_file = "$git_dir/config";
2161 # check if config variable (key) exists
2162 return unless exists $config{"gitweb.$key"};
2164 # ensure given type
2165 if (!defined $type) {
2166 return $config{"gitweb.$key"};
2167 } elsif ($type eq 'bool') {
2168 # backward compatibility: 'git config --bool' returns true/false
2169 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2170 } elsif ($type eq 'int') {
2171 return config_to_int($config{"gitweb.$key"});
2173 return $config{"gitweb.$key"};
2176 # get hash of given path at given ref
2177 sub git_get_hash_by_path {
2178 my $base = shift;
2179 my $path = shift || return undef;
2180 my $type = shift;
2182 $path =~ s,/+$,,;
2184 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2185 or die_error(500, "Open git-ls-tree failed");
2186 my $line = <$fd>;
2187 close $fd or return undef;
2189 if (!defined $line) {
2190 # there is no tree or hash given by $path at $base
2191 return undef;
2194 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2195 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2196 if (defined $type && $type ne $2) {
2197 # type doesn't match
2198 return undef;
2200 return $3;
2203 # get path of entry with given hash at given tree-ish (ref)
2204 # used to get 'from' filename for combined diff (merge commit) for renames
2205 sub git_get_path_by_hash {
2206 my $base = shift || return;
2207 my $hash = shift || return;
2209 local $/ = "\0";
2211 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2212 or return undef;
2213 while (my $line = <$fd>) {
2214 chomp $line;
2216 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2217 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2218 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2219 close $fd;
2220 return $1;
2223 close $fd;
2224 return undef;
2227 ## ......................................................................
2228 ## git utility functions, directly accessing git repository
2230 sub git_get_project_description {
2231 my $path = shift;
2233 $git_dir = "$projectroot/$path";
2234 open my $fd, '<', "$git_dir/description"
2235 or return git_get_project_config('description');
2236 my $descr = <$fd>;
2237 close $fd;
2238 if (defined $descr) {
2239 chomp $descr;
2241 return $descr;
2244 sub git_get_project_ctags {
2245 my $path = shift;
2246 my $ctags = {};
2248 $git_dir = "$projectroot/$path";
2249 opendir my $dh, "$git_dir/ctags"
2250 or return $ctags;
2251 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2252 open my $ct, '<', $_ or next;
2253 my $val = <$ct>;
2254 chomp $val;
2255 close $ct;
2256 my $ctag = $_; $ctag =~ s#.*/##;
2257 $ctags->{$ctag} = $val;
2259 closedir $dh;
2260 $ctags;
2263 sub git_populate_project_tagcloud {
2264 my $ctags = shift;
2266 # First, merge different-cased tags; tags vote on casing
2267 my %ctags_lc;
2268 foreach (keys %$ctags) {
2269 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2270 if (not $ctags_lc{lc $_}->{topcount}
2271 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2272 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2273 $ctags_lc{lc $_}->{topname} = $_;
2277 my $cloud;
2278 if (eval { require HTML::TagCloud; 1; }) {
2279 $cloud = HTML::TagCloud->new;
2280 foreach (sort keys %ctags_lc) {
2281 # Pad the title with spaces so that the cloud looks
2282 # less crammed.
2283 my $title = $ctags_lc{$_}->{topname};
2284 $title =~ s/ /&nbsp;/g;
2285 $title =~ s/^/&nbsp;/g;
2286 $title =~ s/$/&nbsp;/g;
2287 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2289 } else {
2290 $cloud = \%ctags_lc;
2292 $cloud;
2295 sub git_show_project_tagcloud {
2296 my ($cloud, $count) = @_;
2297 print STDERR ref($cloud)."..\n";
2298 if (ref $cloud eq 'HTML::TagCloud') {
2299 return $cloud->html_and_css($count);
2300 } else {
2301 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2302 return '<p align="center">' . join (', ', map {
2303 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2304 } splice(@tags, 0, $count)) . '</p>';
2308 sub git_get_project_url_list {
2309 my $path = shift;
2311 $git_dir = "$projectroot/$path";
2312 open my $fd, '<', "$git_dir/cloneurl"
2313 or return wantarray ?
2314 @{ config_to_multi(git_get_project_config('url')) } :
2315 config_to_multi(git_get_project_config('url'));
2316 my @git_project_url_list = map { chomp; $_ } <$fd>;
2317 close $fd;
2319 return wantarray ? @git_project_url_list : \@git_project_url_list;
2322 sub git_get_projects_list {
2323 my ($filter) = @_;
2324 my @list;
2326 $filter ||= '';
2327 $filter =~ s/\.git$//;
2329 my $check_forks = gitweb_check_feature('forks');
2331 if (-d $projects_list) {
2332 # search in directory
2333 my $dir = $projects_list . ($filter ? "/$filter" : '');
2334 # remove the trailing "/"
2335 $dir =~ s!/+$!!;
2336 my $pfxlen = length("$dir");
2337 my $pfxdepth = ($dir =~ tr!/!!);
2339 File::Find::find({
2340 follow_fast => 1, # follow symbolic links
2341 follow_skip => 2, # ignore duplicates
2342 dangling_symlinks => 0, # ignore dangling symlinks, silently
2343 wanted => sub {
2344 # skip project-list toplevel, if we get it.
2345 return if (m!^[/.]$!);
2346 # only directories can be git repositories
2347 return unless (-d $_);
2348 # don't traverse too deep (Find is super slow on os x)
2349 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2350 $File::Find::prune = 1;
2351 return;
2354 my $subdir = substr($File::Find::name, $pfxlen + 1);
2355 # we check related file in $projectroot
2356 my $path = ($filter ? "$filter/" : '') . $subdir;
2357 if (check_export_ok("$projectroot/$path")) {
2358 push @list, { path => $path };
2359 $File::Find::prune = 1;
2362 }, "$dir");
2364 } elsif (-f $projects_list) {
2365 # read from file(url-encoded):
2366 # 'git%2Fgit.git Linus+Torvalds'
2367 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2368 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2369 my %paths;
2370 open my $fd, '<', $projects_list or return;
2371 PROJECT:
2372 while (my $line = <$fd>) {
2373 chomp $line;
2374 my ($path, $owner) = split ' ', $line;
2375 $path = unescape($path);
2376 $owner = unescape($owner);
2377 if (!defined $path) {
2378 next;
2380 if ($filter ne '') {
2381 # looking for forks;
2382 my $pfx = substr($path, 0, length($filter));
2383 if ($pfx ne $filter) {
2384 next PROJECT;
2386 my $sfx = substr($path, length($filter));
2387 if ($sfx !~ /^\/.*\.git$/) {
2388 next PROJECT;
2390 } elsif ($check_forks) {
2391 PATH:
2392 foreach my $filter (keys %paths) {
2393 # looking for forks;
2394 my $pfx = substr($path, 0, length($filter));
2395 if ($pfx ne $filter) {
2396 next PATH;
2398 my $sfx = substr($path, length($filter));
2399 if ($sfx !~ /^\/.*\.git$/) {
2400 next PATH;
2402 # is a fork, don't include it in
2403 # the list
2404 next PROJECT;
2407 if (check_export_ok("$projectroot/$path")) {
2408 my $pr = {
2409 path => $path,
2410 owner => to_utf8($owner),
2412 push @list, $pr;
2413 (my $forks_path = $path) =~ s/\.git$//;
2414 $paths{$forks_path}++;
2417 close $fd;
2419 return @list;
2422 our $gitweb_project_owner = undef;
2423 sub git_get_project_list_from_file {
2425 return if (defined $gitweb_project_owner);
2427 $gitweb_project_owner = {};
2428 # read from file (url-encoded):
2429 # 'git%2Fgit.git Linus+Torvalds'
2430 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2431 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2432 if (-f $projects_list) {
2433 open(my $fd, '<', $projects_list);
2434 while (my $line = <$fd>) {
2435 chomp $line;
2436 my ($pr, $ow) = split ' ', $line;
2437 $pr = unescape($pr);
2438 $ow = unescape($ow);
2439 $gitweb_project_owner->{$pr} = to_utf8($ow);
2441 close $fd;
2445 sub git_get_project_owner {
2446 my $project = shift;
2447 my $owner;
2449 return undef unless $project;
2450 $git_dir = "$projectroot/$project";
2452 if (!defined $gitweb_project_owner) {
2453 git_get_project_list_from_file();
2456 if (exists $gitweb_project_owner->{$project}) {
2457 $owner = $gitweb_project_owner->{$project};
2459 if (!defined $owner){
2460 $owner = git_get_project_config('owner');
2462 if (!defined $owner) {
2463 $owner = get_file_owner("$git_dir");
2466 return $owner;
2469 sub git_get_last_activity {
2470 my ($path) = @_;
2471 my $fd;
2473 $git_dir = "$projectroot/$path";
2474 open($fd, "-|", git_cmd(), 'for-each-ref',
2475 '--format=%(committer)',
2476 '--sort=-committerdate',
2477 '--count=1',
2478 'refs/heads') or return;
2479 my $most_recent = <$fd>;
2480 close $fd or return;
2481 if (defined $most_recent &&
2482 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2483 my $timestamp = $1;
2484 my $age = time - $timestamp;
2485 return ($age, age_string($age));
2487 return (undef, undef);
2490 sub git_get_references {
2491 my $type = shift || "";
2492 my %refs;
2493 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2494 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2495 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2496 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2497 or return;
2499 while (my $line = <$fd>) {
2500 chomp $line;
2501 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2502 if (defined $refs{$1}) {
2503 push @{$refs{$1}}, $2;
2504 } else {
2505 $refs{$1} = [ $2 ];
2509 close $fd or return;
2510 return \%refs;
2513 sub git_get_rev_name_tags {
2514 my $hash = shift || return undef;
2516 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2517 or return;
2518 my $name_rev = <$fd>;
2519 close $fd;
2521 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2522 return $1;
2523 } else {
2524 # catches also '$hash undefined' output
2525 return undef;
2529 ## ----------------------------------------------------------------------
2530 ## parse to hash functions
2532 sub parse_date {
2533 my $epoch = shift;
2534 my $tz = shift || "-0000";
2536 my %date;
2537 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2538 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2539 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2540 $date{'hour'} = $hour;
2541 $date{'minute'} = $min;
2542 $date{'mday'} = $mday;
2543 $date{'day'} = $days[$wday];
2544 $date{'month'} = $months[$mon];
2545 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2546 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2547 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2548 $mday, $months[$mon], $hour ,$min;
2549 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2550 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2552 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2553 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2554 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2555 $date{'hour_local'} = $hour;
2556 $date{'minute_local'} = $min;
2557 $date{'tz_local'} = $tz;
2558 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2559 1900+$year, $mon+1, $mday,
2560 $hour, $min, $sec, $tz);
2561 return %date;
2564 sub parse_tag {
2565 my $tag_id = shift;
2566 my %tag;
2567 my @comment;
2569 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2570 $tag{'id'} = $tag_id;
2571 while (my $line = <$fd>) {
2572 chomp $line;
2573 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2574 $tag{'object'} = $1;
2575 } elsif ($line =~ m/^type (.+)$/) {
2576 $tag{'type'} = $1;
2577 } elsif ($line =~ m/^tag (.+)$/) {
2578 $tag{'name'} = $1;
2579 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2580 $tag{'author'} = $1;
2581 $tag{'author_epoch'} = $2;
2582 $tag{'author_tz'} = $3;
2583 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2584 $tag{'author_name'} = $1;
2585 $tag{'author_email'} = $2;
2586 } else {
2587 $tag{'author_name'} = $tag{'author'};
2589 } elsif ($line =~ m/--BEGIN/) {
2590 push @comment, $line;
2591 last;
2592 } elsif ($line eq "") {
2593 last;
2596 push @comment, <$fd>;
2597 $tag{'comment'} = \@comment;
2598 close $fd or return;
2599 if (!defined $tag{'name'}) {
2600 return
2602 return %tag
2605 sub parse_commit_text {
2606 my ($commit_text, $withparents) = @_;
2607 my @commit_lines = split '\n', $commit_text;
2608 my %co;
2610 pop @commit_lines; # Remove '\0'
2612 if (! @commit_lines) {
2613 return;
2616 my $header = shift @commit_lines;
2617 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2618 return;
2620 ($co{'id'}, my @parents) = split ' ', $header;
2621 while (my $line = shift @commit_lines) {
2622 last if $line eq "\n";
2623 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2624 $co{'tree'} = $1;
2625 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2626 push @parents, $1;
2627 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2628 $co{'author'} = to_utf8($1);
2629 $co{'author_epoch'} = $2;
2630 $co{'author_tz'} = $3;
2631 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2632 $co{'author_name'} = $1;
2633 $co{'author_email'} = $2;
2634 } else {
2635 $co{'author_name'} = $co{'author'};
2637 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2638 $co{'committer'} = to_utf8($1);
2639 $co{'committer_epoch'} = $2;
2640 $co{'committer_tz'} = $3;
2641 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2642 $co{'committer_name'} = $1;
2643 $co{'committer_email'} = $2;
2644 } else {
2645 $co{'committer_name'} = $co{'committer'};
2649 if (!defined $co{'tree'}) {
2650 return;
2652 $co{'parents'} = \@parents;
2653 $co{'parent'} = $parents[0];
2655 foreach my $title (@commit_lines) {
2656 $title =~ s/^ //;
2657 if ($title ne "") {
2658 $co{'title'} = chop_str($title, 80, 5);
2659 # remove leading stuff of merges to make the interesting part visible
2660 if (length($title) > 50) {
2661 $title =~ s/^Automatic //;
2662 $title =~ s/^merge (of|with) /Merge ... /i;
2663 if (length($title) > 50) {
2664 $title =~ s/(http|rsync):\/\///;
2666 if (length($title) > 50) {
2667 $title =~ s/(master|www|rsync)\.//;
2669 if (length($title) > 50) {
2670 $title =~ s/kernel.org:?//;
2672 if (length($title) > 50) {
2673 $title =~ s/\/pub\/scm//;
2676 $co{'title_short'} = chop_str($title, 50, 5);
2677 last;
2680 if (! defined $co{'title'} || $co{'title'} eq "") {
2681 $co{'title'} = $co{'title_short'} = '(no commit message)';
2683 # remove added spaces
2684 foreach my $line (@commit_lines) {
2685 $line =~ s/^ //;
2687 $co{'comment'} = \@commit_lines;
2689 my $age = time - $co{'committer_epoch'};
2690 $co{'age'} = $age;
2691 $co{'age_string'} = age_string($age);
2692 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2693 if ($age > 60*60*24*7*2) {
2694 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2695 $co{'age_string_age'} = $co{'age_string'};
2696 } else {
2697 $co{'age_string_date'} = $co{'age_string'};
2698 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2700 return %co;
2703 sub parse_commit {
2704 my ($commit_id) = @_;
2705 my %co;
2707 local $/ = "\0";
2709 open my $fd, "-|", git_cmd(), "rev-list",
2710 "--parents",
2711 "--header",
2712 "--max-count=1",
2713 $commit_id,
2714 "--",
2715 or die_error(500, "Open git-rev-list failed");
2716 %co = parse_commit_text(<$fd>, 1);
2717 close $fd;
2719 return %co;
2722 sub parse_commits {
2723 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2724 my @cos;
2726 $maxcount ||= 1;
2727 $skip ||= 0;
2729 local $/ = "\0";
2731 open my $fd, "-|", git_cmd(), "rev-list",
2732 "--header",
2733 @args,
2734 ("--max-count=" . $maxcount),
2735 ("--skip=" . $skip),
2736 @extra_options,
2737 $commit_id,
2738 "--",
2739 ($filename ? ($filename) : ())
2740 or die_error(500, "Open git-rev-list failed");
2741 while (my $line = <$fd>) {
2742 my %co = parse_commit_text($line);
2743 push @cos, \%co;
2745 close $fd;
2747 return wantarray ? @cos : \@cos;
2750 # parse line of git-diff-tree "raw" output
2751 sub parse_difftree_raw_line {
2752 my $line = shift;
2753 my %res;
2755 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2756 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2757 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2758 $res{'from_mode'} = $1;
2759 $res{'to_mode'} = $2;
2760 $res{'from_id'} = $3;
2761 $res{'to_id'} = $4;
2762 $res{'status'} = $5;
2763 $res{'similarity'} = $6;
2764 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2765 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2766 } else {
2767 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2770 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2771 # combined diff (for merge commit)
2772 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2773 $res{'nparents'} = length($1);
2774 $res{'from_mode'} = [ split(' ', $2) ];
2775 $res{'to_mode'} = pop @{$res{'from_mode'}};
2776 $res{'from_id'} = [ split(' ', $3) ];
2777 $res{'to_id'} = pop @{$res{'from_id'}};
2778 $res{'status'} = [ split('', $4) ];
2779 $res{'to_file'} = unquote($5);
2781 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2782 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2783 $res{'commit'} = $1;
2786 return wantarray ? %res : \%res;
2789 # wrapper: return parsed line of git-diff-tree "raw" output
2790 # (the argument might be raw line, or parsed info)
2791 sub parsed_difftree_line {
2792 my $line_or_ref = shift;
2794 if (ref($line_or_ref) eq "HASH") {
2795 # pre-parsed (or generated by hand)
2796 return $line_or_ref;
2797 } else {
2798 return parse_difftree_raw_line($line_or_ref);
2802 # parse line of git-ls-tree output
2803 sub parse_ls_tree_line {
2804 my $line = shift;
2805 my %opts = @_;
2806 my %res;
2808 if ($opts{'-l'}) {
2809 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
2810 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
2812 $res{'mode'} = $1;
2813 $res{'type'} = $2;
2814 $res{'hash'} = $3;
2815 $res{'size'} = $4;
2816 if ($opts{'-z'}) {
2817 $res{'name'} = $5;
2818 } else {
2819 $res{'name'} = unquote($5);
2821 } else {
2822 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2823 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2825 $res{'mode'} = $1;
2826 $res{'type'} = $2;
2827 $res{'hash'} = $3;
2828 if ($opts{'-z'}) {
2829 $res{'name'} = $4;
2830 } else {
2831 $res{'name'} = unquote($4);
2835 return wantarray ? %res : \%res;
2838 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2839 sub parse_from_to_diffinfo {
2840 my ($diffinfo, $from, $to, @parents) = @_;
2842 if ($diffinfo->{'nparents'}) {
2843 # combined diff
2844 $from->{'file'} = [];
2845 $from->{'href'} = [];
2846 fill_from_file_info($diffinfo, @parents)
2847 unless exists $diffinfo->{'from_file'};
2848 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2849 $from->{'file'}[$i] =
2850 defined $diffinfo->{'from_file'}[$i] ?
2851 $diffinfo->{'from_file'}[$i] :
2852 $diffinfo->{'to_file'};
2853 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2854 $from->{'href'}[$i] = href(action=>"blob",
2855 hash_base=>$parents[$i],
2856 hash=>$diffinfo->{'from_id'}[$i],
2857 file_name=>$from->{'file'}[$i]);
2858 } else {
2859 $from->{'href'}[$i] = undef;
2862 } else {
2863 # ordinary (not combined) diff
2864 $from->{'file'} = $diffinfo->{'from_file'};
2865 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2866 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2867 hash=>$diffinfo->{'from_id'},
2868 file_name=>$from->{'file'});
2869 } else {
2870 delete $from->{'href'};
2874 $to->{'file'} = $diffinfo->{'to_file'};
2875 if (!is_deleted($diffinfo)) { # file exists in result
2876 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2877 hash=>$diffinfo->{'to_id'},
2878 file_name=>$to->{'file'});
2879 } else {
2880 delete $to->{'href'};
2884 ## ......................................................................
2885 ## parse to array of hashes functions
2887 sub git_get_heads_list {
2888 my $limit = shift;
2889 my @headslist;
2891 open my $fd, '-|', git_cmd(), 'for-each-ref',
2892 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2893 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2894 'refs/heads'
2895 or return;
2896 while (my $line = <$fd>) {
2897 my %ref_item;
2899 chomp $line;
2900 my ($refinfo, $committerinfo) = split(/\0/, $line);
2901 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2902 my ($committer, $epoch, $tz) =
2903 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2904 $ref_item{'fullname'} = $name;
2905 $name =~ s!^refs/heads/!!;
2907 $ref_item{'name'} = $name;
2908 $ref_item{'id'} = $hash;
2909 $ref_item{'title'} = $title || '(no commit message)';
2910 $ref_item{'epoch'} = $epoch;
2911 if ($epoch) {
2912 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2913 } else {
2914 $ref_item{'age'} = "unknown";
2917 push @headslist, \%ref_item;
2919 close $fd;
2921 return wantarray ? @headslist : \@headslist;
2924 sub git_get_tags_list {
2925 my $limit = shift;
2926 my @tagslist;
2928 open my $fd, '-|', git_cmd(), 'for-each-ref',
2929 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2930 '--format=%(objectname) %(objecttype) %(refname) '.
2931 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2932 'refs/tags'
2933 or return;
2934 while (my $line = <$fd>) {
2935 my %ref_item;
2937 chomp $line;
2938 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2939 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2940 my ($creator, $epoch, $tz) =
2941 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2942 $ref_item{'fullname'} = $name;
2943 $name =~ s!^refs/tags/!!;
2945 $ref_item{'type'} = $type;
2946 $ref_item{'id'} = $id;
2947 $ref_item{'name'} = $name;
2948 if ($type eq "tag") {
2949 $ref_item{'subject'} = $title;
2950 $ref_item{'reftype'} = $reftype;
2951 $ref_item{'refid'} = $refid;
2952 } else {
2953 $ref_item{'reftype'} = $type;
2954 $ref_item{'refid'} = $id;
2957 if ($type eq "tag" || $type eq "commit") {
2958 $ref_item{'epoch'} = $epoch;
2959 if ($epoch) {
2960 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2961 } else {
2962 $ref_item{'age'} = "unknown";
2966 push @tagslist, \%ref_item;
2968 close $fd;
2970 return wantarray ? @tagslist : \@tagslist;
2973 ## ----------------------------------------------------------------------
2974 ## filesystem-related functions
2976 sub get_file_owner {
2977 my $path = shift;
2979 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2980 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2981 if (!defined $gcos) {
2982 return undef;
2984 my $owner = $gcos;
2985 $owner =~ s/[,;].*$//;
2986 return to_utf8($owner);
2989 # assume that file exists
2990 sub insert_file {
2991 my $filename = shift;
2993 open my $fd, '<', $filename;
2994 print map { to_utf8($_) } <$fd>;
2995 close $fd;
2998 ## ......................................................................
2999 ## mimetype related functions
3001 sub mimetype_guess_file {
3002 my $filename = shift;
3003 my $mimemap = shift;
3004 -r $mimemap or return undef;
3006 my %mimemap;
3007 open(my $mh, '<', $mimemap) or return undef;
3008 while (<$mh>) {
3009 next if m/^#/; # skip comments
3010 my ($mimetype, $exts) = split(/\t+/);
3011 if (defined $exts) {
3012 my @exts = split(/\s+/, $exts);
3013 foreach my $ext (@exts) {
3014 $mimemap{$ext} = $mimetype;
3018 close($mh);
3020 $filename =~ /\.([^.]*)$/;
3021 return $mimemap{$1};
3024 sub mimetype_guess {
3025 my $filename = shift;
3026 my $mime;
3027 $filename =~ /\./ or return undef;
3029 if ($mimetypes_file) {
3030 my $file = $mimetypes_file;
3031 if ($file !~ m!^/!) { # if it is relative path
3032 # it is relative to project
3033 $file = "$projectroot/$project/$file";
3035 $mime = mimetype_guess_file($filename, $file);
3037 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3038 return $mime;
3041 sub blob_mimetype {
3042 my $fd = shift;
3043 my $filename = shift;
3045 if ($filename) {
3046 my $mime = mimetype_guess($filename);
3047 $mime and return $mime;
3050 # just in case
3051 return $default_blob_plain_mimetype unless $fd;
3053 if (-T $fd) {
3054 return 'text/plain';
3055 } elsif (! $filename) {
3056 return 'application/octet-stream';
3057 } elsif ($filename =~ m/\.png$/i) {
3058 return 'image/png';
3059 } elsif ($filename =~ m/\.gif$/i) {
3060 return 'image/gif';
3061 } elsif ($filename =~ m/\.jpe?g$/i) {
3062 return 'image/jpeg';
3063 } else {
3064 return 'application/octet-stream';
3068 sub blob_contenttype {
3069 my ($fd, $file_name, $type) = @_;
3071 $type ||= blob_mimetype($fd, $file_name);
3072 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3073 $type .= "; charset=$default_text_plain_charset";
3076 return $type;
3079 ## ======================================================================
3080 ## functions printing HTML: header, footer, error page
3082 sub git_header_html {
3083 my $status = shift || "200 OK";
3084 my $expires = shift;
3086 my $title = "$site_name";
3087 if (defined $project) {
3088 $title .= " - " . to_utf8($project);
3089 if (defined $action) {
3090 $title .= "/$action";
3091 if (defined $file_name) {
3092 $title .= " - " . esc_path($file_name);
3093 if ($action eq "tree" && $file_name !~ m|/$|) {
3094 $title .= "/";
3099 my $content_type;
3100 # require explicit support from the UA if we are to send the page as
3101 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3102 # we have to do this because MSIE sometimes globs '*/*', pretending to
3103 # support xhtml+xml but choking when it gets what it asked for.
3104 if (defined $cgi->http('HTTP_ACCEPT') &&
3105 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3106 $cgi->Accept('application/xhtml+xml') != 0) {
3107 $content_type = 'application/xhtml+xml';
3108 } else {
3109 $content_type = 'text/html';
3111 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3112 -status=> $status, -expires => $expires);
3113 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3114 print <<EOF;
3115 <?xml version="1.0" encoding="utf-8"?>
3116 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3117 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3118 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3119 <!-- git core binaries version $git_version -->
3120 <head>
3121 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3122 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3123 <meta name="robots" content="index, nofollow"/>
3124 <title>$title</title>
3125 <script type="text/javascript">/* <![CDATA[ */
3126 function fixBlameLinks() {
3127 var allLinks = document.getElementsByTagName("a");
3128 for (var i = 0; i < allLinks.length; i++) {
3129 var link = allLinks.item(i);
3130 if (link.className == 'blamelink')
3131 link.href = link.href.replace("a=blame", "a=blame_incremental");
3134 /* ]]> */</script>
3136 # the stylesheet, favicon etc urls won't work correctly with path_info
3137 # unless we set the appropriate base URL
3138 if ($ENV{'PATH_INFO'}) {
3139 print "<base href=\"".esc_url($base_url)."\" />\n";
3141 # print out each stylesheet that exist, providing backwards capability
3142 # for those people who defined $stylesheet in a config file
3143 if (defined $stylesheet) {
3144 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3145 } else {
3146 foreach my $stylesheet (@stylesheets) {
3147 next unless $stylesheet;
3148 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3151 if (defined $project) {
3152 my %href_params = get_feed_info();
3153 if (!exists $href_params{'-title'}) {
3154 $href_params{'-title'} = 'log';
3157 foreach my $format qw(RSS Atom) {
3158 my $type = lc($format);
3159 my %link_attr = (
3160 '-rel' => 'alternate',
3161 '-title' => "$project - $href_params{'-title'} - $format feed",
3162 '-type' => "application/$type+xml"
3165 $href_params{'action'} = $type;
3166 $link_attr{'-href'} = href(%href_params);
3167 print "<link ".
3168 "rel=\"$link_attr{'-rel'}\" ".
3169 "title=\"$link_attr{'-title'}\" ".
3170 "href=\"$link_attr{'-href'}\" ".
3171 "type=\"$link_attr{'-type'}\" ".
3172 "/>\n";
3174 $href_params{'extra_options'} = '--no-merges';
3175 $link_attr{'-href'} = href(%href_params);
3176 $link_attr{'-title'} .= ' (no merges)';
3177 print "<link ".
3178 "rel=\"$link_attr{'-rel'}\" ".
3179 "title=\"$link_attr{'-title'}\" ".
3180 "href=\"$link_attr{'-href'}\" ".
3181 "type=\"$link_attr{'-type'}\" ".
3182 "/>\n";
3185 } else {
3186 printf('<link rel="alternate" title="%s projects list" '.
3187 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3188 $site_name, href(project=>undef, action=>"project_index"));
3189 printf('<link rel="alternate" title="%s projects feeds" '.
3190 'href="%s" type="text/x-opml" />'."\n",
3191 $site_name, href(project=>undef, action=>"opml"));
3193 if (defined $favicon) {
3194 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3197 if (defined $gitwebjs) {
3198 print qq(<script src="$gitwebjs" type="text/javascript"></script>\n);
3201 print "</head>\n" .
3202 "<body onload=\"fixBlameLinks();\">\n";
3204 if (-f $site_header) {
3205 insert_file($site_header);
3208 print "<div class=\"page_header\">\n" .
3209 $cgi->a({-href => esc_url($logo_url),
3210 -title => $logo_label},
3211 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3212 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3213 if (defined $project) {
3214 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3215 if (defined $action) {
3216 print " / $action";
3218 print "\n";
3220 print "</div>\n";
3222 my $have_search = gitweb_check_feature('search');
3223 if (defined $project && $have_search) {
3224 if (!defined $searchtext) {
3225 $searchtext = "";
3227 my $search_hash;
3228 if (defined $hash_base) {
3229 $search_hash = $hash_base;
3230 } elsif (defined $hash) {
3231 $search_hash = $hash;
3232 } else {
3233 $search_hash = "HEAD";
3235 my $action = $my_uri;
3236 my $use_pathinfo = gitweb_check_feature('pathinfo');
3237 if ($use_pathinfo) {
3238 $action .= "/".esc_url($project);
3240 print $cgi->startform(-method => "get", -action => $action) .
3241 "<div class=\"search\">\n" .
3242 (!$use_pathinfo &&
3243 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3244 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3245 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3246 $cgi->popup_menu(-name => 'st', -default => 'commit',
3247 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3248 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3249 " search:\n",
3250 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3251 "<span title=\"Extended regular expression\">" .
3252 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3253 -checked => $search_use_regexp) .
3254 "</span>" .
3255 "</div>" .
3256 $cgi->end_form() . "\n";
3260 sub git_footer_html {
3261 my $feed_class = 'rss_logo';
3263 print "<div class=\"page_footer\">\n";
3264 if (defined $project) {
3265 my $descr = git_get_project_description($project);
3266 if (defined $descr) {
3267 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3270 my %href_params = get_feed_info();
3271 if (!%href_params) {
3272 $feed_class .= ' generic';
3274 $href_params{'-title'} ||= 'log';
3276 foreach my $format qw(RSS Atom) {
3277 $href_params{'action'} = lc($format);
3278 print $cgi->a({-href => href(%href_params),
3279 -title => "$href_params{'-title'} $format feed",
3280 -class => $feed_class}, $format)."\n";
3283 } else {
3284 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3285 -class => $feed_class}, "OPML") . " ";
3286 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3287 -class => $feed_class}, "TXT") . "\n";
3289 print "</div>\n"; # class="page_footer"
3291 if (-f $site_footer) {
3292 insert_file($site_footer);
3295 print "</body>\n" .
3296 "</html>";
3299 # die_error(<http_status_code>, <error_message>)
3300 # Example: die_error(404, 'Hash not found')
3301 # By convention, use the following status codes (as defined in RFC 2616):
3302 # 400: Invalid or missing CGI parameters, or
3303 # requested object exists but has wrong type.
3304 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3305 # this server or project.
3306 # 404: Requested object/revision/project doesn't exist.
3307 # 500: The server isn't configured properly, or
3308 # an internal error occurred (e.g. failed assertions caused by bugs), or
3309 # an unknown error occurred (e.g. the git binary died unexpectedly).
3310 sub die_error {
3311 my $status = shift || 500;
3312 my $error = shift || "Internal server error";
3314 my %http_responses = (400 => '400 Bad Request',
3315 403 => '403 Forbidden',
3316 404 => '404 Not Found',
3317 500 => '500 Internal Server Error');
3318 git_header_html($http_responses{$status});
3319 print <<EOF;
3320 <div class="page_body">
3321 <br /><br />
3322 $status - $error
3323 <br />
3324 </div>
3326 git_footer_html();
3327 exit;
3330 ## ----------------------------------------------------------------------
3331 ## functions printing or outputting HTML: navigation
3333 sub git_print_page_nav {
3334 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3335 $extra = '' if !defined $extra; # pager or formats
3337 my @navs = qw(summary shortlog log commit commitdiff tree);
3338 if ($suppress) {
3339 @navs = grep { $_ ne $suppress } @navs;
3342 my %arg = map { $_ => {action=>$_} } @navs;
3343 if (defined $head) {
3344 for (qw(commit commitdiff)) {
3345 $arg{$_}{'hash'} = $head;
3347 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3348 for (qw(shortlog log)) {
3349 $arg{$_}{'hash'} = $head;
3354 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3355 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3357 my @actions = gitweb_get_feature('actions');
3358 my %repl = (
3359 '%' => '%',
3360 'n' => $project, # project name
3361 'f' => $git_dir, # project path within filesystem
3362 'h' => $treehead || '', # current hash ('h' parameter)
3363 'b' => $treebase || '', # hash base ('hb' parameter)
3365 while (@actions) {
3366 my ($label, $link, $pos) = splice(@actions,0,3);
3367 # insert
3368 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3369 # munch munch
3370 $link =~ s/%([%nfhb])/$repl{$1}/g;
3371 $arg{$label}{'_href'} = $link;
3374 print "<div class=\"page_nav\">\n" .
3375 (join " | ",
3376 map { $_ eq $current ?
3377 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3378 } @navs);
3379 print "<br/>\n$extra<br/>\n" .
3380 "</div>\n";
3383 sub format_paging_nav {
3384 my ($action, $hash, $head, $page, $has_next_link) = @_;
3385 my $paging_nav;
3388 if ($hash ne $head || $page) {
3389 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3390 } else {
3391 $paging_nav .= "HEAD";
3394 if ($page > 0) {
3395 $paging_nav .= " &sdot; " .
3396 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3397 -accesskey => "p", -title => "Alt-p"}, "prev");
3398 } else {
3399 $paging_nav .= " &sdot; prev";
3402 if ($has_next_link) {
3403 $paging_nav .= " &sdot; " .
3404 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3405 -accesskey => "n", -title => "Alt-n"}, "next");
3406 } else {
3407 $paging_nav .= " &sdot; next";
3410 return $paging_nav;
3413 ## ......................................................................
3414 ## functions printing or outputting HTML: div
3416 sub git_print_header_div {
3417 my ($action, $title, $hash, $hash_base) = @_;
3418 my %args = ();
3420 $args{'action'} = $action;
3421 $args{'hash'} = $hash if $hash;
3422 $args{'hash_base'} = $hash_base if $hash_base;
3424 print "<div class=\"header\">\n" .
3425 $cgi->a({-href => href(%args), -class => "title"},
3426 $title ? $title : $action) .
3427 "\n</div>\n";
3430 sub print_local_time {
3431 my %date = @_;
3432 if ($date{'hour_local'} < 6) {
3433 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3434 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3435 } else {
3436 printf(" (%02d:%02d %s)",
3437 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3441 # Outputs the author name and date in long form
3442 sub git_print_authorship {
3443 my $co = shift;
3444 my %opts = @_;
3445 my $tag = $opts{-tag} || 'div';
3446 my $author = $co->{'author_name'};
3448 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3449 print "<$tag class=\"author_date\">" .
3450 format_search_author($author, "author", esc_html($author)) .
3451 " [$ad{'rfc2822'}";
3452 print_local_time(%ad) if ($opts{-localtime});
3453 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3454 . "</$tag>\n";
3457 # Outputs table rows containing the full author or committer information,
3458 # in the format expected for 'commit' view (& similia).
3459 # Parameters are a commit hash reference, followed by the list of people
3460 # to output information for. If the list is empty it defalts to both
3461 # author and committer.
3462 sub git_print_authorship_rows {
3463 my $co = shift;
3464 # too bad we can't use @people = @_ || ('author', 'committer')
3465 my @people = @_;
3466 @people = ('author', 'committer') unless @people;
3467 foreach my $who (@people) {
3468 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3469 print "<tr><td>$who</td><td>" .
3470 format_search_author($co->{"${who}_name"}, $who,
3471 esc_html($co->{"${who}_name"})) . " " .
3472 format_search_author($co->{"${who}_email"}, $who,
3473 esc_html("<" . $co->{"${who}_email"} . ">")) .
3474 "</td><td rowspan=\"2\">" .
3475 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3476 "</td></tr>\n" .
3477 "<tr>" .
3478 "<td></td><td> $wd{'rfc2822'}";
3479 print_local_time(%wd);
3480 print "</td>" .
3481 "</tr>\n";
3485 sub git_print_page_path {
3486 my $name = shift;
3487 my $type = shift;
3488 my $hb = shift;
3491 print "<div class=\"page_path\">";
3492 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3493 -title => 'tree root'}, to_utf8("[$project]"));
3494 print " / ";
3495 if (defined $name) {
3496 my @dirname = split '/', $name;
3497 my $basename = pop @dirname;
3498 my $fullname = '';
3500 foreach my $dir (@dirname) {
3501 $fullname .= ($fullname ? '/' : '') . $dir;
3502 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3503 hash_base=>$hb),
3504 -title => $fullname}, esc_path($dir));
3505 print " / ";
3507 if (defined $type && $type eq 'blob') {
3508 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3509 hash_base=>$hb),
3510 -title => $name}, esc_path($basename));
3511 } elsif (defined $type && $type eq 'tree') {
3512 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3513 hash_base=>$hb),
3514 -title => $name}, esc_path($basename));
3515 print " / ";
3516 } else {
3517 print esc_path($basename);
3520 print "<br/></div>\n";
3523 sub git_print_log {
3524 my $log = shift;
3525 my %opts = @_;
3527 if ($opts{'-remove_title'}) {
3528 # remove title, i.e. first line of log
3529 shift @$log;
3531 # remove leading empty lines
3532 while (defined $log->[0] && $log->[0] eq "") {
3533 shift @$log;
3536 # print log
3537 my $signoff = 0;
3538 my $empty = 0;
3539 foreach my $line (@$log) {
3540 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3541 $signoff = 1;
3542 $empty = 0;
3543 if (! $opts{'-remove_signoff'}) {
3544 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3545 next;
3546 } else {
3547 # remove signoff lines
3548 next;
3550 } else {
3551 $signoff = 0;
3554 # print only one empty line
3555 # do not print empty line after signoff
3556 if ($line eq "") {
3557 next if ($empty || $signoff);
3558 $empty = 1;
3559 } else {
3560 $empty = 0;
3563 print format_log_line_html($line) . "<br/>\n";
3566 if ($opts{'-final_empty_line'}) {
3567 # end with single empty line
3568 print "<br/>\n" unless $empty;
3572 # return link target (what link points to)
3573 sub git_get_link_target {
3574 my $hash = shift;
3575 my $link_target;
3577 # read link
3578 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3579 or return;
3581 local $/ = undef;
3582 $link_target = <$fd>;
3584 close $fd
3585 or return;
3587 return $link_target;
3590 # given link target, and the directory (basedir) the link is in,
3591 # return target of link relative to top directory (top tree);
3592 # return undef if it is not possible (including absolute links).
3593 sub normalize_link_target {
3594 my ($link_target, $basedir) = @_;
3596 # absolute symlinks (beginning with '/') cannot be normalized
3597 return if (substr($link_target, 0, 1) eq '/');
3599 # normalize link target to path from top (root) tree (dir)
3600 my $path;
3601 if ($basedir) {
3602 $path = $basedir . '/' . $link_target;
3603 } else {
3604 # we are in top (root) tree (dir)
3605 $path = $link_target;
3608 # remove //, /./, and /../
3609 my @path_parts;
3610 foreach my $part (split('/', $path)) {
3611 # discard '.' and ''
3612 next if (!$part || $part eq '.');
3613 # handle '..'
3614 if ($part eq '..') {
3615 if (@path_parts) {
3616 pop @path_parts;
3617 } else {
3618 # link leads outside repository (outside top dir)
3619 return;
3621 } else {
3622 push @path_parts, $part;
3625 $path = join('/', @path_parts);
3627 return $path;
3630 # print tree entry (row of git_tree), but without encompassing <tr> element
3631 sub git_print_tree_entry {
3632 my ($t, $basedir, $hash_base, $have_blame) = @_;
3634 my %base_key = ();
3635 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3637 # The format of a table row is: mode list link. Where mode is
3638 # the mode of the entry, list is the name of the entry, an href,
3639 # and link is the action links of the entry.
3641 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3642 if (exists $t->{'size'}) {
3643 print "<td class=\"size\">$t->{'size'}</td>\n";
3645 if ($t->{'type'} eq "blob") {
3646 print "<td class=\"list\">" .
3647 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3648 file_name=>"$basedir$t->{'name'}", %base_key),
3649 -class => "list"}, esc_path($t->{'name'}));
3650 if (S_ISLNK(oct $t->{'mode'})) {
3651 my $link_target = git_get_link_target($t->{'hash'});
3652 if ($link_target) {
3653 my $norm_target = normalize_link_target($link_target, $basedir);
3654 if (defined $norm_target) {
3655 print " -> " .
3656 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3657 file_name=>$norm_target),
3658 -title => $norm_target}, esc_path($link_target));
3659 } else {
3660 print " -> " . esc_path($link_target);
3664 print "</td>\n";
3665 print "<td class=\"link\">";
3666 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3667 file_name=>"$basedir$t->{'name'}", %base_key)},
3668 "blob");
3669 if ($have_blame) {
3670 print " | " .
3671 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3672 file_name=>"$basedir$t->{'name'}", %base_key), -class => "blamelink"},
3673 "blame");
3675 if (defined $hash_base) {
3676 print " | " .
3677 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3678 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3679 "history");
3681 print " | " .
3682 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3683 file_name=>"$basedir$t->{'name'}")},
3684 "raw");
3685 print "</td>\n";
3687 } elsif ($t->{'type'} eq "tree") {
3688 print "<td class=\"list\">";
3689 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3690 file_name=>"$basedir$t->{'name'}",
3691 %base_key)},
3692 esc_path($t->{'name'}));
3693 print "</td>\n";
3694 print "<td class=\"link\">";
3695 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3696 file_name=>"$basedir$t->{'name'}",
3697 %base_key)},
3698 "tree");
3699 if (defined $hash_base) {
3700 print " | " .
3701 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3702 file_name=>"$basedir$t->{'name'}")},
3703 "history");
3705 print "</td>\n";
3706 } else {
3707 # unknown object: we can only present history for it
3708 # (this includes 'commit' object, i.e. submodule support)
3709 print "<td class=\"list\">" .
3710 esc_path($t->{'name'}) .
3711 "</td>\n";
3712 print "<td class=\"link\">";
3713 if (defined $hash_base) {
3714 print $cgi->a({-href => href(action=>"history",
3715 hash_base=>$hash_base,
3716 file_name=>"$basedir$t->{'name'}")},
3717 "history");
3719 print "</td>\n";
3723 ## ......................................................................
3724 ## functions printing large fragments of HTML
3726 # get pre-image filenames for merge (combined) diff
3727 sub fill_from_file_info {
3728 my ($diff, @parents) = @_;
3730 $diff->{'from_file'} = [ ];
3731 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3732 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3733 if ($diff->{'status'}[$i] eq 'R' ||
3734 $diff->{'status'}[$i] eq 'C') {
3735 $diff->{'from_file'}[$i] =
3736 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3740 return $diff;
3743 # is current raw difftree line of file deletion
3744 sub is_deleted {
3745 my $diffinfo = shift;
3747 return $diffinfo->{'to_id'} eq ('0' x 40);
3750 # does patch correspond to [previous] difftree raw line
3751 # $diffinfo - hashref of parsed raw diff format
3752 # $patchinfo - hashref of parsed patch diff format
3753 # (the same keys as in $diffinfo)
3754 sub is_patch_split {
3755 my ($diffinfo, $patchinfo) = @_;
3757 return defined $diffinfo && defined $patchinfo
3758 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3762 sub git_difftree_body {
3763 my ($difftree, $hash, @parents) = @_;
3764 my ($parent) = $parents[0];
3765 my $have_blame = gitweb_check_feature('blame');
3766 print "<div class=\"list_head\">\n";
3767 if ($#{$difftree} > 10) {
3768 print(($#{$difftree} + 1) . " files changed:\n");
3770 print "</div>\n";
3772 print "<table class=\"" .
3773 (@parents > 1 ? "combined " : "") .
3774 "diff_tree\">\n";
3776 # header only for combined diff in 'commitdiff' view
3777 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3778 if ($has_header) {
3779 # table header
3780 print "<thead><tr>\n" .
3781 "<th></th><th></th>\n"; # filename, patchN link
3782 for (my $i = 0; $i < @parents; $i++) {
3783 my $par = $parents[$i];
3784 print "<th>" .
3785 $cgi->a({-href => href(action=>"commitdiff",
3786 hash=>$hash, hash_parent=>$par),
3787 -title => 'commitdiff to parent number ' .
3788 ($i+1) . ': ' . substr($par,0,7)},
3789 $i+1) .
3790 "&nbsp;</th>\n";
3792 print "</tr></thead>\n<tbody>\n";
3795 my $alternate = 1;
3796 my $patchno = 0;
3797 foreach my $line (@{$difftree}) {
3798 my $diff = parsed_difftree_line($line);
3800 if ($alternate) {
3801 print "<tr class=\"dark\">\n";
3802 } else {
3803 print "<tr class=\"light\">\n";
3805 $alternate ^= 1;
3807 if (exists $diff->{'nparents'}) { # combined diff
3809 fill_from_file_info($diff, @parents)
3810 unless exists $diff->{'from_file'};
3812 if (!is_deleted($diff)) {
3813 # file exists in the result (child) commit
3814 print "<td>" .
3815 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3816 file_name=>$diff->{'to_file'},
3817 hash_base=>$hash),
3818 -class => "list"}, esc_path($diff->{'to_file'})) .
3819 "</td>\n";
3820 } else {
3821 print "<td>" .
3822 esc_path($diff->{'to_file'}) .
3823 "</td>\n";
3826 if ($action eq 'commitdiff') {
3827 # link to patch
3828 $patchno++;
3829 print "<td class=\"link\">" .
3830 $cgi->a({-href => "#patch$patchno"}, "patch") .
3831 " | " .
3832 "</td>\n";
3835 my $has_history = 0;
3836 my $not_deleted = 0;
3837 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3838 my $hash_parent = $parents[$i];
3839 my $from_hash = $diff->{'from_id'}[$i];
3840 my $from_path = $diff->{'from_file'}[$i];
3841 my $status = $diff->{'status'}[$i];
3843 $has_history ||= ($status ne 'A');
3844 $not_deleted ||= ($status ne 'D');
3846 if ($status eq 'A') {
3847 print "<td class=\"link\" align=\"right\"> | </td>\n";
3848 } elsif ($status eq 'D') {
3849 print "<td class=\"link\">" .
3850 $cgi->a({-href => href(action=>"blob",
3851 hash_base=>$hash,
3852 hash=>$from_hash,
3853 file_name=>$from_path)},
3854 "blob" . ($i+1)) .
3855 " | </td>\n";
3856 } else {
3857 if ($diff->{'to_id'} eq $from_hash) {
3858 print "<td class=\"link nochange\">";
3859 } else {
3860 print "<td class=\"link\">";
3862 print $cgi->a({-href => href(action=>"blobdiff",
3863 hash=>$diff->{'to_id'},
3864 hash_parent=>$from_hash,
3865 hash_base=>$hash,
3866 hash_parent_base=>$hash_parent,
3867 file_name=>$diff->{'to_file'},
3868 file_parent=>$from_path)},
3869 "diff" . ($i+1)) .
3870 " | </td>\n";
3874 print "<td class=\"link\">";
3875 if ($not_deleted) {
3876 print $cgi->a({-href => href(action=>"blob",
3877 hash=>$diff->{'to_id'},
3878 file_name=>$diff->{'to_file'},
3879 hash_base=>$hash)},
3880 "blob");
3881 print " | " if ($has_history);
3883 if ($has_history) {
3884 print $cgi->a({-href => href(action=>"history",
3885 file_name=>$diff->{'to_file'},
3886 hash_base=>$hash)},
3887 "history");
3889 print "</td>\n";
3891 print "</tr>\n";
3892 next; # instead of 'else' clause, to avoid extra indent
3894 # else ordinary diff
3896 my ($to_mode_oct, $to_mode_str, $to_file_type);
3897 my ($from_mode_oct, $from_mode_str, $from_file_type);
3898 if ($diff->{'to_mode'} ne ('0' x 6)) {
3899 $to_mode_oct = oct $diff->{'to_mode'};
3900 if (S_ISREG($to_mode_oct)) { # only for regular file
3901 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3903 $to_file_type = file_type($diff->{'to_mode'});
3905 if ($diff->{'from_mode'} ne ('0' x 6)) {
3906 $from_mode_oct = oct $diff->{'from_mode'};
3907 if (S_ISREG($to_mode_oct)) { # only for regular file
3908 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3910 $from_file_type = file_type($diff->{'from_mode'});
3913 if ($diff->{'status'} eq "A") { # created
3914 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3915 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3916 $mode_chng .= "]</span>";
3917 print "<td>";
3918 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3919 hash_base=>$hash, file_name=>$diff->{'file'}),
3920 -class => "list"}, esc_path($diff->{'file'}));
3921 print "</td>\n";
3922 print "<td>$mode_chng</td>\n";
3923 print "<td class=\"link\">";
3924 if ($action eq 'commitdiff') {
3925 # link to patch
3926 $patchno++;
3927 print $cgi->a({-href => "#patch$patchno"}, "patch");
3928 print " | ";
3930 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3931 hash_base=>$hash, file_name=>$diff->{'file'})},
3932 "blob");
3933 print "</td>\n";
3935 } elsif ($diff->{'status'} eq "D") { # deleted
3936 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3937 print "<td>";
3938 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3939 hash_base=>$parent, file_name=>$diff->{'file'}),
3940 -class => "list"}, esc_path($diff->{'file'}));
3941 print "</td>\n";
3942 print "<td>$mode_chng</td>\n";
3943 print "<td class=\"link\">";
3944 if ($action eq 'commitdiff') {
3945 # link to patch
3946 $patchno++;
3947 print $cgi->a({-href => "#patch$patchno"}, "patch");
3948 print " | ";
3950 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3951 hash_base=>$parent, file_name=>$diff->{'file'})},
3952 "blob") . " | ";
3953 if ($have_blame) {
3954 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3955 file_name=>$diff->{'file'}), -class => "blamelink"},
3956 "blame") . " | ";
3958 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3959 file_name=>$diff->{'file'})},
3960 "history");
3961 print "</td>\n";
3963 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3964 my $mode_chnge = "";
3965 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3966 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3967 if ($from_file_type ne $to_file_type) {
3968 $mode_chnge .= " from $from_file_type to $to_file_type";
3970 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3971 if ($from_mode_str && $to_mode_str) {
3972 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3973 } elsif ($to_mode_str) {
3974 $mode_chnge .= " mode: $to_mode_str";
3977 $mode_chnge .= "]</span>\n";
3979 print "<td>";
3980 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3981 hash_base=>$hash, file_name=>$diff->{'file'}),
3982 -class => "list"}, esc_path($diff->{'file'}));
3983 print "</td>\n";
3984 print "<td>$mode_chnge</td>\n";
3985 print "<td class=\"link\">";
3986 if ($action eq 'commitdiff') {
3987 # link to patch
3988 $patchno++;
3989 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3990 " | ";
3991 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3992 # "commit" view and modified file (not onlu mode changed)
3993 print $cgi->a({-href => href(action=>"blobdiff",
3994 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3995 hash_base=>$hash, hash_parent_base=>$parent,
3996 file_name=>$diff->{'file'})},
3997 "diff") .
3998 " | ";
4000 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4001 hash_base=>$hash, file_name=>$diff->{'file'})},
4002 "blob") . " | ";
4003 if ($have_blame) {
4004 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4005 file_name=>$diff->{'file'}), -class => "blamelink"},
4006 "blame") . " | ";
4008 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4009 file_name=>$diff->{'file'})},
4010 "history");
4011 print "</td>\n";
4013 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4014 my %status_name = ('R' => 'moved', 'C' => 'copied');
4015 my $nstatus = $status_name{$diff->{'status'}};
4016 my $mode_chng = "";
4017 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4018 # mode also for directories, so we cannot use $to_mode_str
4019 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4021 print "<td>" .
4022 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4023 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4024 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4025 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4026 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4027 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4028 -class => "list"}, esc_path($diff->{'from_file'})) .
4029 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4030 "<td class=\"link\">";
4031 if ($action eq 'commitdiff') {
4032 # link to patch
4033 $patchno++;
4034 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4035 " | ";
4036 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4037 # "commit" view and modified file (not only pure rename or copy)
4038 print $cgi->a({-href => href(action=>"blobdiff",
4039 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4040 hash_base=>$hash, hash_parent_base=>$parent,
4041 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4042 "diff") .
4043 " | ";
4045 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4046 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4047 "blob") . " | ";
4048 if ($have_blame) {
4049 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4050 file_name=>$diff->{'to_file'}), -class => "blamelink"},
4051 "blame") . " | ";
4053 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4054 file_name=>$diff->{'to_file'})},
4055 "history");
4056 print "</td>\n";
4058 } # we should not encounter Unmerged (U) or Unknown (X) status
4059 print "</tr>\n";
4061 print "</tbody>" if $has_header;
4062 print "</table>\n";
4065 sub git_patchset_body {
4066 my ($fd, $difftree, $hash, @hash_parents) = @_;
4067 my ($hash_parent) = $hash_parents[0];
4069 my $is_combined = (@hash_parents > 1);
4070 my $patch_idx = 0;
4071 my $patch_number = 0;
4072 my $patch_line;
4073 my $diffinfo;
4074 my $to_name;
4075 my (%from, %to);
4077 print "<div class=\"patchset\">\n";
4079 # skip to first patch
4080 while ($patch_line = <$fd>) {
4081 chomp $patch_line;
4083 last if ($patch_line =~ m/^diff /);
4086 PATCH:
4087 while ($patch_line) {
4089 # parse "git diff" header line
4090 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4091 # $1 is from_name, which we do not use
4092 $to_name = unquote($2);
4093 $to_name =~ s!^b/!!;
4094 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4095 # $1 is 'cc' or 'combined', which we do not use
4096 $to_name = unquote($2);
4097 } else {
4098 $to_name = undef;
4101 # check if current patch belong to current raw line
4102 # and parse raw git-diff line if needed
4103 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4104 # this is continuation of a split patch
4105 print "<div class=\"patch cont\">\n";
4106 } else {
4107 # advance raw git-diff output if needed
4108 $patch_idx++ if defined $diffinfo;
4110 # read and prepare patch information
4111 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4113 # compact combined diff output can have some patches skipped
4114 # find which patch (using pathname of result) we are at now;
4115 if ($is_combined) {
4116 while ($to_name ne $diffinfo->{'to_file'}) {
4117 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4118 format_diff_cc_simplified($diffinfo, @hash_parents) .
4119 "</div>\n"; # class="patch"
4121 $patch_idx++;
4122 $patch_number++;
4124 last if $patch_idx > $#$difftree;
4125 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4129 # modifies %from, %to hashes
4130 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4132 # this is first patch for raw difftree line with $patch_idx index
4133 # we index @$difftree array from 0, but number patches from 1
4134 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4137 # git diff header
4138 #assert($patch_line =~ m/^diff /) if DEBUG;
4139 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4140 $patch_number++;
4141 # print "git diff" header
4142 print format_git_diff_header_line($patch_line, $diffinfo,
4143 \%from, \%to);
4145 # print extended diff header
4146 print "<div class=\"diff extended_header\">\n";
4147 EXTENDED_HEADER:
4148 while ($patch_line = <$fd>) {
4149 chomp $patch_line;
4151 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4153 print format_extended_diff_header_line($patch_line, $diffinfo,
4154 \%from, \%to);
4156 print "</div>\n"; # class="diff extended_header"
4158 # from-file/to-file diff header
4159 if (! $patch_line) {
4160 print "</div>\n"; # class="patch"
4161 last PATCH;
4163 next PATCH if ($patch_line =~ m/^diff /);
4164 #assert($patch_line =~ m/^---/) if DEBUG;
4166 my $last_patch_line = $patch_line;
4167 $patch_line = <$fd>;
4168 chomp $patch_line;
4169 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4171 print format_diff_from_to_header($last_patch_line, $patch_line,
4172 $diffinfo, \%from, \%to,
4173 @hash_parents);
4175 # the patch itself
4176 LINE:
4177 while ($patch_line = <$fd>) {
4178 chomp $patch_line;
4180 next PATCH if ($patch_line =~ m/^diff /);
4182 print format_diff_line($patch_line, \%from, \%to);
4185 } continue {
4186 print "</div>\n"; # class="patch"
4189 # for compact combined (--cc) format, with chunk and patch simpliciaction
4190 # patchset might be empty, but there might be unprocessed raw lines
4191 for (++$patch_idx if $patch_number > 0;
4192 $patch_idx < @$difftree;
4193 ++$patch_idx) {
4194 # read and prepare patch information
4195 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4197 # generate anchor for "patch" links in difftree / whatchanged part
4198 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4199 format_diff_cc_simplified($diffinfo, @hash_parents) .
4200 "</div>\n"; # class="patch"
4202 $patch_number++;
4205 if ($patch_number == 0) {
4206 if (@hash_parents > 1) {
4207 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4208 } else {
4209 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4213 print "</div>\n"; # class="patchset"
4216 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4218 # fills project list info (age, description, owner, forks) for each
4219 # project in the list, removing invalid projects from returned list
4220 # NOTE: modifies $projlist, but does not remove entries from it
4221 sub fill_project_list_info {
4222 my ($projlist, $check_forks) = @_;
4223 my @projects;
4225 my $show_ctags = gitweb_check_feature('ctags');
4226 PROJECT:
4227 foreach my $pr (@$projlist) {
4228 my (@activity) = git_get_last_activity($pr->{'path'});
4229 unless (@activity) {
4230 next PROJECT;
4232 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4233 if (!defined $pr->{'descr'}) {
4234 my $descr = git_get_project_description($pr->{'path'}) || "";
4235 $descr = to_utf8($descr);
4236 $pr->{'descr_long'} = $descr;
4237 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4239 if (!defined $pr->{'owner'}) {
4240 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4242 if ($check_forks) {
4243 my $pname = $pr->{'path'};
4244 if (($pname =~ s/\.git$//) &&
4245 ($pname !~ /\/$/) &&
4246 (-d "$projectroot/$pname")) {
4247 $pr->{'forks'} = "-d $projectroot/$pname";
4248 } else {
4249 $pr->{'forks'} = 0;
4252 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4253 push @projects, $pr;
4256 return @projects;
4259 # print 'sort by' <th> element, generating 'sort by $name' replay link
4260 # if that order is not selected
4261 sub print_sort_th {
4262 my ($name, $order, $header) = @_;
4263 $header ||= ucfirst($name);
4265 if ($order eq $name) {
4266 print "<th>$header</th>\n";
4267 } else {
4268 print "<th>" .
4269 $cgi->a({-href => href(-replay=>1, order=>$name),
4270 -class => "header"}, $header) .
4271 "</th>\n";
4275 sub git_project_list_body {
4276 # actually uses global variable $project
4277 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4279 my $check_forks = gitweb_check_feature('forks');
4280 my @projects = fill_project_list_info($projlist, $check_forks);
4282 $order ||= $default_projects_order;
4283 $from = 0 unless defined $from;
4284 $to = $#projects if (!defined $to || $#projects < $to);
4286 my %order_info = (
4287 project => { key => 'path', type => 'str' },
4288 descr => { key => 'descr_long', type => 'str' },
4289 owner => { key => 'owner', type => 'str' },
4290 age => { key => 'age', type => 'num' }
4292 my $oi = $order_info{$order};
4293 if ($oi->{'type'} eq 'str') {
4294 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4295 } else {
4296 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4299 my $show_ctags = gitweb_check_feature('ctags');
4300 if ($show_ctags) {
4301 my %ctags;
4302 foreach my $p (@projects) {
4303 foreach my $ct (keys %{$p->{'ctags'}}) {
4304 $ctags{$ct} += $p->{'ctags'}->{$ct};
4307 my $cloud = git_populate_project_tagcloud(\%ctags);
4308 print git_show_project_tagcloud($cloud, 64);
4311 print "<table class=\"project_list\">\n";
4312 unless ($no_header) {
4313 print "<tr>\n";
4314 if ($check_forks) {
4315 print "<th></th>\n";
4317 print_sort_th('project', $order, 'Project');
4318 print_sort_th('descr', $order, 'Description');
4319 print_sort_th('owner', $order, 'Owner');
4320 print_sort_th('age', $order, 'Last Change');
4321 print "<th></th>\n" . # for links
4322 "</tr>\n";
4324 my $alternate = 1;
4325 my $tagfilter = $cgi->param('by_tag');
4326 for (my $i = $from; $i <= $to; $i++) {
4327 my $pr = $projects[$i];
4329 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4330 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4331 and not $pr->{'descr_long'} =~ /$searchtext/;
4332 # Weed out forks or non-matching entries of search
4333 if ($check_forks) {
4334 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4335 $forkbase="^$forkbase" if $forkbase;
4336 next if not $searchtext and not $tagfilter and $show_ctags
4337 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4340 if ($alternate) {
4341 print "<tr class=\"dark\">\n";
4342 } else {
4343 print "<tr class=\"light\">\n";
4345 $alternate ^= 1;
4346 if ($check_forks) {
4347 print "<td>";
4348 if ($pr->{'forks'}) {
4349 print "<!-- $pr->{'forks'} -->\n";
4350 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4352 print "</td>\n";
4354 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4355 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4356 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4357 -class => "list", -title => $pr->{'descr_long'}},
4358 esc_html($pr->{'descr'})) . "</td>\n" .
4359 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4360 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4361 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4362 "<td class=\"link\">" .
4363 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4364 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4365 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4366 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4367 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4368 "</td>\n" .
4369 "</tr>\n";
4371 if (defined $extra) {
4372 print "<tr>\n";
4373 if ($check_forks) {
4374 print "<td></td>\n";
4376 print "<td colspan=\"5\">$extra</td>\n" .
4377 "</tr>\n";
4379 print "</table>\n";
4382 sub git_shortlog_body {
4383 # uses global variable $project
4384 my ($commitlist, $from, $to, $refs, $extra) = @_;
4386 $from = 0 unless defined $from;
4387 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4389 print "<table class=\"shortlog\">\n";
4390 my $alternate = 1;
4391 for (my $i = $from; $i <= $to; $i++) {
4392 my %co = %{$commitlist->[$i]};
4393 my $commit = $co{'id'};
4394 my $ref = format_ref_marker($refs, $commit);
4395 if ($alternate) {
4396 print "<tr class=\"dark\">\n";
4397 } else {
4398 print "<tr class=\"light\">\n";
4400 $alternate ^= 1;
4401 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4402 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4403 format_author_html('td', \%co, 10) . "<td>";
4404 print format_subject_html($co{'title'}, $co{'title_short'},
4405 href(action=>"commit", hash=>$commit), $ref);
4406 print "</td>\n" .
4407 "<td class=\"link\">" .
4408 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4409 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4410 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4411 my $snapshot_links = format_snapshot_links($commit);
4412 if (defined $snapshot_links) {
4413 print " | " . $snapshot_links;
4415 print "</td>\n" .
4416 "</tr>\n";
4418 if (defined $extra) {
4419 print "<tr>\n" .
4420 "<td colspan=\"4\">$extra</td>\n" .
4421 "</tr>\n";
4423 print "</table>\n";
4426 sub git_history_body {
4427 # Warning: assumes constant type (blob or tree) during history
4428 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4430 $from = 0 unless defined $from;
4431 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4433 print "<table class=\"history\">\n";
4434 my $alternate = 1;
4435 for (my $i = $from; $i <= $to; $i++) {
4436 my %co = %{$commitlist->[$i]};
4437 if (!%co) {
4438 next;
4440 my $commit = $co{'id'};
4442 my $ref = format_ref_marker($refs, $commit);
4444 if ($alternate) {
4445 print "<tr class=\"dark\">\n";
4446 } else {
4447 print "<tr class=\"light\">\n";
4449 $alternate ^= 1;
4450 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4451 # shortlog: format_author_html('td', \%co, 10)
4452 format_author_html('td', \%co, 15, 3) . "<td>";
4453 # originally git_history used chop_str($co{'title'}, 50)
4454 print format_subject_html($co{'title'}, $co{'title_short'},
4455 href(action=>"commit", hash=>$commit), $ref);
4456 print "</td>\n" .
4457 "<td class=\"link\">" .
4458 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4459 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4461 if ($ftype eq 'blob') {
4462 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4463 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4464 if (defined $blob_current && defined $blob_parent &&
4465 $blob_current ne $blob_parent) {
4466 print " | " .
4467 $cgi->a({-href => href(action=>"blobdiff",
4468 hash=>$blob_current, hash_parent=>$blob_parent,
4469 hash_base=>$hash_base, hash_parent_base=>$commit,
4470 file_name=>$file_name)},
4471 "diff to current");
4474 print "</td>\n" .
4475 "</tr>\n";
4477 if (defined $extra) {
4478 print "<tr>\n" .
4479 "<td colspan=\"4\">$extra</td>\n" .
4480 "</tr>\n";
4482 print "</table>\n";
4485 sub git_tags_body {
4486 # uses global variable $project
4487 my ($taglist, $from, $to, $extra) = @_;
4488 $from = 0 unless defined $from;
4489 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4491 print "<table class=\"tags\">\n";
4492 my $alternate = 1;
4493 for (my $i = $from; $i <= $to; $i++) {
4494 my $entry = $taglist->[$i];
4495 my %tag = %$entry;
4496 my $comment = $tag{'subject'};
4497 my $comment_short;
4498 if (defined $comment) {
4499 $comment_short = chop_str($comment, 30, 5);
4501 if ($alternate) {
4502 print "<tr class=\"dark\">\n";
4503 } else {
4504 print "<tr class=\"light\">\n";
4506 $alternate ^= 1;
4507 if (defined $tag{'age'}) {
4508 print "<td><i>$tag{'age'}</i></td>\n";
4509 } else {
4510 print "<td></td>\n";
4512 print "<td>" .
4513 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4514 -class => "list name"}, esc_html($tag{'name'})) .
4515 "</td>\n" .
4516 "<td>";
4517 if (defined $comment) {
4518 print format_subject_html($comment, $comment_short,
4519 href(action=>"tag", hash=>$tag{'id'}));
4521 print "</td>\n" .
4522 "<td class=\"selflink\">";
4523 if ($tag{'type'} eq "tag") {
4524 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4525 } else {
4526 print "&nbsp;";
4528 print "</td>\n" .
4529 "<td class=\"link\">" . " | " .
4530 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4531 if ($tag{'reftype'} eq "commit") {
4532 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4533 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4534 } elsif ($tag{'reftype'} eq "blob") {
4535 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4537 print "</td>\n" .
4538 "</tr>";
4540 if (defined $extra) {
4541 print "<tr>\n" .
4542 "<td colspan=\"5\">$extra</td>\n" .
4543 "</tr>\n";
4545 print "</table>\n";
4548 sub git_heads_body {
4549 # uses global variable $project
4550 my ($headlist, $head, $from, $to, $extra) = @_;
4551 $from = 0 unless defined $from;
4552 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4554 print "<table class=\"heads\">\n";
4555 my $alternate = 1;
4556 for (my $i = $from; $i <= $to; $i++) {
4557 my $entry = $headlist->[$i];
4558 my %ref = %$entry;
4559 my $curr = $ref{'id'} eq $head;
4560 if ($alternate) {
4561 print "<tr class=\"dark\">\n";
4562 } else {
4563 print "<tr class=\"light\">\n";
4565 $alternate ^= 1;
4566 print "<td><i>$ref{'age'}</i></td>\n" .
4567 ($curr ? "<td class=\"current_head\">" : "<td>") .
4568 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4569 -class => "list name"},esc_html($ref{'name'})) .
4570 "</td>\n" .
4571 "<td class=\"link\">" .
4572 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4573 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4574 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4575 "</td>\n" .
4576 "</tr>";
4578 if (defined $extra) {
4579 print "<tr>\n" .
4580 "<td colspan=\"3\">$extra</td>\n" .
4581 "</tr>\n";
4583 print "</table>\n";
4586 sub git_search_grep_body {
4587 my ($commitlist, $from, $to, $extra) = @_;
4588 $from = 0 unless defined $from;
4589 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4591 print "<table class=\"commit_search\">\n";
4592 my $alternate = 1;
4593 for (my $i = $from; $i <= $to; $i++) {
4594 my %co = %{$commitlist->[$i]};
4595 if (!%co) {
4596 next;
4598 my $commit = $co{'id'};
4599 if ($alternate) {
4600 print "<tr class=\"dark\">\n";
4601 } else {
4602 print "<tr class=\"light\">\n";
4604 $alternate ^= 1;
4605 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4606 format_author_html('td', \%co, 15, 5) .
4607 "<td>" .
4608 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4609 -class => "list subject"},
4610 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4611 my $comment = $co{'comment'};
4612 foreach my $line (@$comment) {
4613 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4614 my ($lead, $match, $trail) = ($1, $2, $3);
4615 $match = chop_str($match, 70, 5, 'center');
4616 my $contextlen = int((80 - length($match))/2);
4617 $contextlen = 30 if ($contextlen > 30);
4618 $lead = chop_str($lead, $contextlen, 10, 'left');
4619 $trail = chop_str($trail, $contextlen, 10, 'right');
4621 $lead = esc_html($lead);
4622 $match = esc_html($match);
4623 $trail = esc_html($trail);
4625 print "$lead<span class=\"match\">$match</span>$trail<br />";
4628 print "</td>\n" .
4629 "<td class=\"link\">" .
4630 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4631 " | " .
4632 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4633 " | " .
4634 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4635 print "</td>\n" .
4636 "</tr>\n";
4638 if (defined $extra) {
4639 print "<tr>\n" .
4640 "<td colspan=\"3\">$extra</td>\n" .
4641 "</tr>\n";
4643 print "</table>\n";
4646 ## ======================================================================
4647 ## ======================================================================
4648 ## actions
4650 sub git_project_list {
4651 my $order = $input_params{'order'};
4652 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4653 die_error(400, "Unknown order parameter");
4656 my @list = git_get_projects_list();
4657 if (!@list) {
4658 die_error(404, "No projects found");
4661 git_header_html();
4662 if (-f $home_text) {
4663 print "<div class=\"index_include\">\n";
4664 insert_file($home_text);
4665 print "</div>\n";
4667 print $cgi->startform(-method => "get") .
4668 "<p class=\"projsearch\">Search:\n" .
4669 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4670 "</p>" .
4671 $cgi->end_form() . "\n";
4672 git_project_list_body(\@list, $order);
4673 git_footer_html();
4676 sub git_forks {
4677 my $order = $input_params{'order'};
4678 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4679 die_error(400, "Unknown order parameter");
4682 my @list = git_get_projects_list($project);
4683 if (!@list) {
4684 die_error(404, "No forks found");
4687 git_header_html();
4688 git_print_page_nav('','');
4689 git_print_header_div('summary', "$project forks");
4690 git_project_list_body(\@list, $order);
4691 git_footer_html();
4694 sub git_project_index {
4695 my @projects = git_get_projects_list($project);
4697 print $cgi->header(
4698 -type => 'text/plain',
4699 -charset => 'utf-8',
4700 -content_disposition => 'inline; filename="index.aux"');
4702 foreach my $pr (@projects) {
4703 if (!exists $pr->{'owner'}) {
4704 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4707 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4708 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4709 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4710 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4711 $path =~ s/ /\+/g;
4712 $owner =~ s/ /\+/g;
4714 print "$path $owner\n";
4718 sub git_summary {
4719 my $descr = git_get_project_description($project) || "none";
4720 my %co = parse_commit("HEAD");
4721 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4722 my $head = $co{'id'};
4724 my $owner = git_get_project_owner($project);
4726 my $refs = git_get_references();
4727 # These get_*_list functions return one more to allow us to see if
4728 # there are more ...
4729 my @taglist = git_get_tags_list(16);
4730 my @headlist = git_get_heads_list(16);
4731 my @forklist;
4732 my $check_forks = gitweb_check_feature('forks');
4734 if ($check_forks) {
4735 @forklist = git_get_projects_list($project);
4738 git_header_html();
4739 git_print_page_nav('summary','', $head);
4741 print "<div class=\"title\">&nbsp;</div>\n";
4742 print "<table class=\"projects_list\">\n" .
4743 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4744 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4745 if (defined $cd{'rfc2822'}) {
4746 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4749 # use per project git URL list in $projectroot/$project/cloneurl
4750 # or make project git URL from git base URL and project name
4751 my $url_tag = "URL";
4752 my @url_list = git_get_project_url_list($project);
4753 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4754 foreach my $git_url (@url_list) {
4755 next unless $git_url;
4756 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4757 $url_tag = "";
4760 # Tag cloud
4761 my $show_ctags = gitweb_check_feature('ctags');
4762 if ($show_ctags) {
4763 my $ctags = git_get_project_ctags($project);
4764 my $cloud = git_populate_project_tagcloud($ctags);
4765 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4766 print "</td>\n<td>" unless %$ctags;
4767 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4768 print "</td>\n<td>" if %$ctags;
4769 print git_show_project_tagcloud($cloud, 48);
4770 print "</td></tr>";
4773 print "</table>\n";
4775 # If XSS prevention is on, we don't include README.html.
4776 # TODO: Allow a readme in some safe format.
4777 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4778 print "<div class=\"title\">readme</div>\n" .
4779 "<div class=\"readme\">\n";
4780 insert_file("$projectroot/$project/README.html");
4781 print "\n</div>\n"; # class="readme"
4784 # we need to request one more than 16 (0..15) to check if
4785 # those 16 are all
4786 my @commitlist = $head ? parse_commits($head, 17) : ();
4787 if (@commitlist) {
4788 git_print_header_div('shortlog');
4789 git_shortlog_body(\@commitlist, 0, 15, $refs,
4790 $#commitlist <= 15 ? undef :
4791 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4794 if (@taglist) {
4795 git_print_header_div('tags');
4796 git_tags_body(\@taglist, 0, 15,
4797 $#taglist <= 15 ? undef :
4798 $cgi->a({-href => href(action=>"tags")}, "..."));
4801 if (@headlist) {
4802 git_print_header_div('heads');
4803 git_heads_body(\@headlist, $head, 0, 15,
4804 $#headlist <= 15 ? undef :
4805 $cgi->a({-href => href(action=>"heads")}, "..."));
4808 if (@forklist) {
4809 git_print_header_div('forks');
4810 git_project_list_body(\@forklist, 'age', 0, 15,
4811 $#forklist <= 15 ? undef :
4812 $cgi->a({-href => href(action=>"forks")}, "..."),
4813 'no_header');
4816 git_footer_html();
4819 sub git_tag {
4820 my $head = git_get_head_hash($project);
4821 git_header_html();
4822 git_print_page_nav('','', $head,undef,$head);
4823 my %tag = parse_tag($hash);
4825 if (! %tag) {
4826 die_error(404, "Unknown tag object");
4829 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4830 print "<div class=\"title_text\">\n" .
4831 "<table class=\"object_header\">\n" .
4832 "<tr>\n" .
4833 "<td>object</td>\n" .
4834 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4835 $tag{'object'}) . "</td>\n" .
4836 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4837 $tag{'type'}) . "</td>\n" .
4838 "</tr>\n";
4839 if (defined($tag{'author'})) {
4840 git_print_authorship_rows(\%tag, 'author');
4842 print "</table>\n\n" .
4843 "</div>\n";
4844 print "<div class=\"page_body\">";
4845 my $comment = $tag{'comment'};
4846 foreach my $line (@$comment) {
4847 chomp $line;
4848 print esc_html($line, -nbsp=>1) . "<br/>\n";
4850 print "</div>\n";
4851 git_footer_html();
4854 sub git_blame_data {
4855 my $ftype;
4857 my ($have_blame) = gitweb_check_feature('blame');
4858 if (!$have_blame) {
4859 die_error('403 Permission denied', "Permission denied");
4861 die_error('404 Not Found', "File name not defined") if (!$file_name);
4862 $hash_base ||= git_get_head_hash($project);
4863 die_error(undef, "Couldn't find base commit") unless ($hash_base);
4864 my %co = parse_commit($hash_base)
4865 or die_error(undef, "Reading commit failed");
4866 if (!defined $hash) {
4867 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4868 or die_error(undef, "Error looking up file");
4870 $ftype = git_get_type($hash);
4871 if ($ftype !~ "blob") {
4872 die_error("400 Bad Request", "Object is not a blob");
4874 open my $fd, "-|", git_cmd(), "blame", '--incremental',
4875 $hash_base, '--', $file_name
4876 or die_error(undef, "Open git-blame --incremental failed");
4878 print $cgi->header(-type=>"text/plain", -charset => 'utf-8',
4879 -status=> "200 OK");
4881 while(<$fd>) {
4882 if (/^([0-9a-f]{40}) ([0-9]+) ([0-9]+) ([0-9]+)/ or
4883 /^author-time |^author |^filename /) {
4884 print;
4888 close $fd or print "Reading blame data failed\n";
4891 sub git_blame_common {
4892 my ($type) = @_;
4894 my $ftype;
4896 # permissions
4897 gitweb_check_feature('blame')
4898 or die_error(403, "Blame view not allowed");
4900 # error checking
4901 die_error(400, "No file name given") unless $file_name;
4902 $hash_base ||= git_get_head_hash($project);
4903 die_error(404, "Couldn't find base commit") unless $hash_base;
4904 my %co = parse_commit($hash_base)
4905 or die_error(404, "Commit not found");
4906 my $ftype = "blob";
4907 if (!defined $hash) {
4908 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4909 or die_error(404, "Error looking up file");
4910 } else {
4911 $ftype = git_get_type($hash);
4912 if ($ftype !~ "blob") {
4913 die_error(400, "Object is not a blob");
4916 $ftype = git_get_type($hash);
4917 if ($ftype !~ "blob") {
4918 die_error(400, "Object is not a blob");
4920 if ($type eq 'incremental') {
4921 open my $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
4922 or die_error(undef, "Open git-cat-file failed");
4923 } else {
4924 # run git-blame --porcelain
4925 open my $fd, "-|", git_cmd(), "blame", '-p',
4926 $hash_base, '--', $file_name
4927 or die_error(500, "Open git-blame failed");
4930 # page header
4931 git_header_html();
4932 my $formats_nav =
4933 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4934 "blob") .
4935 " | " .
4936 $cgi->a({-href => href(action=>"history", -replay=>1)},
4937 "history") .
4938 " | " .
4939 $cgi->a({-href => href(action=>"blame", file_name=>$file_name), -class => "blamelink"},
4940 "HEAD");
4941 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4942 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4943 git_print_page_path($file_name, $ftype, $hash_base);
4945 # page body
4946 my @rev_color = qw(light dark);
4947 my $num_colors = scalar(@rev_color);
4948 my $current_color = 0;
4949 my %metainfo = ();
4951 print <<HTML;
4952 <div class="page_body">
4953 <table class="blame">
4954 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4955 HTML
4956 LINE:
4957 my $linenr = 0;
4958 while (my $line = <$fd>) {
4959 chomp $line;
4960 if ($type eq 'incremental') {
4961 # Empty stage with just the file contents
4962 $linenr += 1;
4963 print "<tr id=\"l$linenr\" class=\"light2\">";
4964 print '<td class="sha1"><a href=""></a></td>';
4965 print "<td class=\"linenr\"><a class=\"linenr\" href=\"\">$linenr</a></td><td class=\"pre\">" . esc_html($line) . "</td>\n";
4966 print "</tr>\n";
4967 next;
4970 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4971 # no <lines in group> for subsequent lines in group of lines
4972 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4973 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
4974 if (!exists $metainfo{$full_rev}) {
4975 $metainfo{$full_rev} = { 'nprevious' => 0 };
4977 my $meta = $metainfo{$full_rev};
4978 my $data;
4979 while ($data = <$fd>) {
4980 chomp $data;
4981 last if ($data =~ s/^\t//); # contents of line
4982 if ($data =~ /^(\S+)(?: (.*))?$/) {
4983 $meta->{$1} = $2 unless exists $meta->{$1};
4985 if ($data =~ /^previous /) {
4986 $meta->{'nprevious'}++;
4989 my $short_rev = substr($full_rev, 0, 8);
4990 my $author = $meta->{'author'};
4991 my %date =
4992 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
4993 my $date = $date{'iso-tz'};
4994 if ($group_size) {
4995 $current_color = ($current_color + 1) % $num_colors;
4997 my $tr_class = $rev_color[$current_color];
4998 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
4999 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5000 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5001 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5002 if ($group_size) {
5003 print "<td class=\"sha1\"";
5004 print " title=\"". esc_html($author) . ", $date\"";
5005 print " rowspan=\"$group_size\"" if ($group_size > 1);
5006 print ">";
5007 print $cgi->a({-href => href(action=>"commit",
5008 hash=>$full_rev,
5009 file_name=>$file_name)},
5010 esc_html($short_rev));
5011 if ($group_size >= 2) {
5012 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5013 if (@author_initials) {
5014 print "<br />" .
5015 esc_html(join('', @author_initials));
5016 # or join('.', ...)
5019 print "</td>\n";
5021 # 'previous' <sha1 of parent commit> <filename at commit>
5022 if (exists $meta->{'previous'} &&
5023 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5024 $meta->{'parent'} = $1;
5025 $meta->{'file_parent'} = unquote($2);
5027 my $linenr_commit =
5028 exists($meta->{'parent'}) ?
5029 $meta->{'parent'} : $full_rev;
5030 my $linenr_filename =
5031 exists($meta->{'file_parent'}) ?
5032 $meta->{'file_parent'} : unquote($meta->{'filename'});
5033 my $blamed = href(action => 'blame',
5034 file_name => $linenr_filename,
5035 hash_base => $linenr_commit);
5036 print "<td class=\"linenr\">";
5037 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5038 -class => "linenr" },
5039 esc_html($lineno));
5040 print "</td>";
5041 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5042 print "</tr>\n";
5045 print "</table>\n";
5046 print "</div>";
5047 close $fd
5048 or print "Reading blob failed\n";
5050 if ($type eq 'incremental') {
5051 print "<script type=\"text/javascript\">\n";
5052 print "startBlame(\"" . href(action=>"blame_data", hash_base=>$hash_base, file_name=>$file_name) . "\", \"" .
5053 href(-partial_query=>1) . "\");\n";
5054 print "</script>\n";
5057 # page footer
5058 git_footer_html();
5061 sub git_blame_incremental {
5062 git_blame_common('incremental');
5065 sub git_blame {
5066 git_blame_common('oneshot');
5069 sub git_tags {
5070 my $head = git_get_head_hash($project);
5071 git_header_html();
5072 git_print_page_nav('','', $head,undef,$head);
5073 git_print_header_div('summary', $project);
5075 my @tagslist = git_get_tags_list();
5076 if (@tagslist) {
5077 git_tags_body(\@tagslist);
5079 git_footer_html();
5082 sub git_heads {
5083 my $head = git_get_head_hash($project);
5084 git_header_html();
5085 git_print_page_nav('','', $head,undef,$head);
5086 git_print_header_div('summary', $project);
5088 my @headslist = git_get_heads_list();
5089 if (@headslist) {
5090 git_heads_body(\@headslist, $head);
5092 git_footer_html();
5095 sub git_blob_plain {
5096 my $type = shift;
5097 my $expires;
5099 if (!defined $hash) {
5100 if (defined $file_name) {
5101 my $base = $hash_base || git_get_head_hash($project);
5102 $hash = git_get_hash_by_path($base, $file_name, "blob")
5103 or die_error(404, "Cannot find file");
5104 } else {
5105 die_error(400, "No file name defined");
5107 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5108 # blobs defined by non-textual hash id's can be cached
5109 $expires = "+1d";
5112 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5113 or die_error(500, "Open git-cat-file blob '$hash' failed");
5115 # content-type (can include charset)
5116 $type = blob_contenttype($fd, $file_name, $type);
5118 # "save as" filename, even when no $file_name is given
5119 my $save_as = "$hash";
5120 if (defined $file_name) {
5121 $save_as = $file_name;
5122 } elsif ($type =~ m/^text\//) {
5123 $save_as .= '.txt';
5126 # With XSS prevention on, blobs of all types except a few known safe
5127 # ones are served with "Content-Disposition: attachment" to make sure
5128 # they don't run in our security domain. For certain image types,
5129 # blob view writes an <img> tag referring to blob_plain view, and we
5130 # want to be sure not to break that by serving the image as an
5131 # attachment (though Firefox 3 doesn't seem to care).
5132 my $sandbox = $prevent_xss &&
5133 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5135 print $cgi->header(
5136 -type => $type,
5137 -expires => $expires,
5138 -content_disposition =>
5139 ($sandbox ? 'attachment' : 'inline')
5140 . '; filename="' . $save_as . '"');
5141 local $/ = undef;
5142 binmode STDOUT, ':raw';
5143 print <$fd>;
5144 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5145 close $fd;
5148 sub git_blob {
5149 my $expires;
5151 if (!defined $hash) {
5152 if (defined $file_name) {
5153 my $base = $hash_base || git_get_head_hash($project);
5154 $hash = git_get_hash_by_path($base, $file_name, "blob")
5155 or die_error(404, "Cannot find file");
5156 } else {
5157 die_error(400, "No file name defined");
5159 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5160 # blobs defined by non-textual hash id's can be cached
5161 $expires = "+1d";
5164 my $have_blame = gitweb_check_feature('blame');
5165 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5166 or die_error(500, "Couldn't cat $file_name, $hash");
5167 my $mimetype = blob_mimetype($fd, $file_name);
5168 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5169 close $fd;
5170 return git_blob_plain($mimetype);
5172 # we can have blame only for text/* mimetype
5173 $have_blame &&= ($mimetype =~ m!^text/!);
5175 git_header_html(undef, $expires);
5176 my $formats_nav = '';
5177 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5178 if (defined $file_name) {
5179 if ($have_blame) {
5180 $formats_nav .=
5181 $cgi->a({-href => href(action=>"blame", -replay=>1,
5182 -class => "blamelink")},
5183 "blame") .
5184 " | ";
5186 $formats_nav .=
5187 $cgi->a({-href => href(action=>"history", -replay=>1)},
5188 "history") .
5189 " | " .
5190 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5191 "raw") .
5192 " | " .
5193 $cgi->a({-href => href(action=>"blob",
5194 hash_base=>"HEAD", file_name=>$file_name)},
5195 "HEAD");
5196 } else {
5197 $formats_nav .=
5198 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5199 "raw");
5201 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5202 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5203 } else {
5204 print "<div class=\"page_nav\">\n" .
5205 "<br/><br/></div>\n" .
5206 "<div class=\"title\">$hash</div>\n";
5208 git_print_page_path($file_name, "blob", $hash_base);
5209 print "<div class=\"page_body\">\n";
5210 if ($mimetype =~ m!^image/!) {
5211 print qq!<img type="$mimetype"!;
5212 if ($file_name) {
5213 print qq! alt="$file_name" title="$file_name"!;
5215 print qq! src="! .
5216 href(action=>"blob_plain", hash=>$hash,
5217 hash_base=>$hash_base, file_name=>$file_name) .
5218 qq!" />\n!;
5219 } else {
5220 my $nr;
5221 while (my $line = <$fd>) {
5222 chomp $line;
5223 $nr++;
5224 $line = untabify($line);
5225 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5226 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5229 close $fd
5230 or print "Reading blob failed.\n";
5231 print "</div>";
5232 git_footer_html();
5235 sub git_tree {
5236 if (!defined $hash_base) {
5237 $hash_base = "HEAD";
5239 if (!defined $hash) {
5240 if (defined $file_name) {
5241 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5242 } else {
5243 $hash = $hash_base;
5246 die_error(404, "No such tree") unless defined($hash);
5248 my $show_sizes = gitweb_check_feature('show-sizes');
5249 my $have_blame = gitweb_check_feature('blame');
5251 my @entries = ();
5253 local $/ = "\0";
5254 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5255 ($show_sizes ? '-l' : ()), @extra_options, $hash
5256 or die_error(500, "Open git-ls-tree failed");
5257 @entries = map { chomp; $_ } <$fd>;
5258 close $fd
5259 or die_error(404, "Reading tree failed");
5262 my $refs = git_get_references();
5263 my $ref = format_ref_marker($refs, $hash_base);
5264 git_header_html();
5265 my $basedir = '';
5266 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5267 my @views_nav = ();
5268 if (defined $file_name) {
5269 push @views_nav,
5270 $cgi->a({-href => href(action=>"history", -replay=>1)},
5271 "history"),
5272 $cgi->a({-href => href(action=>"tree",
5273 hash_base=>"HEAD", file_name=>$file_name)},
5274 "HEAD"),
5276 my $snapshot_links = format_snapshot_links($hash);
5277 if (defined $snapshot_links) {
5278 # FIXME: Should be available when we have no hash base as well.
5279 push @views_nav, $snapshot_links;
5281 git_print_page_nav('tree','', $hash_base, undef, undef,
5282 join(' | ', @views_nav));
5283 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5284 } else {
5285 undef $hash_base;
5286 print "<div class=\"page_nav\">\n";
5287 print "<br/><br/></div>\n";
5288 print "<div class=\"title\">$hash</div>\n";
5290 if (defined $file_name) {
5291 $basedir = $file_name;
5292 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5293 $basedir .= '/';
5295 git_print_page_path($file_name, 'tree', $hash_base);
5297 print "<div class=\"page_body\">\n";
5298 print "<table class=\"tree\">\n";
5299 my $alternate = 1;
5300 # '..' (top directory) link if possible
5301 if (defined $hash_base &&
5302 defined $file_name && $file_name =~ m![^/]+$!) {
5303 if ($alternate) {
5304 print "<tr class=\"dark\">\n";
5305 } else {
5306 print "<tr class=\"light\">\n";
5308 $alternate ^= 1;
5310 my $up = $file_name;
5311 $up =~ s!/?[^/]+$!!;
5312 undef $up unless $up;
5313 # based on git_print_tree_entry
5314 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5315 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5316 print '<td class="list">';
5317 print $cgi->a({-href => href(action=>"tree",
5318 hash_base=>$hash_base,
5319 file_name=>$up)},
5320 "..");
5321 print "</td>\n";
5322 print "<td class=\"link\"></td>\n";
5324 print "</tr>\n";
5326 foreach my $line (@entries) {
5327 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5329 if ($alternate) {
5330 print "<tr class=\"dark\">\n";
5331 } else {
5332 print "<tr class=\"light\">\n";
5334 $alternate ^= 1;
5336 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5338 print "</tr>\n";
5340 print "</table>\n" .
5341 "</div>";
5342 git_footer_html();
5345 sub git_snapshot {
5346 my $format = $input_params{'snapshot_format'};
5347 if (!@snapshot_fmts) {
5348 die_error(403, "Snapshots not allowed");
5350 # default to first supported snapshot format
5351 $format ||= $snapshot_fmts[0];
5352 if ($format !~ m/^[a-z0-9]+$/) {
5353 die_error(400, "Invalid snapshot format parameter");
5354 } elsif (!exists($known_snapshot_formats{$format})) {
5355 die_error(400, "Unknown snapshot format");
5356 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5357 die_error(403, "Snapshot format not allowed");
5358 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5359 die_error(403, "Unsupported snapshot format");
5362 if (!defined $hash) {
5363 $hash = git_get_head_hash($project);
5366 my $name = $project;
5367 $name =~ s,([^/])/*\.git$,$1,;
5368 $name = basename($name);
5369 my $filename = to_utf8($name);
5370 $name =~ s/\047/\047\\\047\047/g;
5371 my $cmd;
5372 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5373 $cmd = quote_command(
5374 git_cmd(), 'archive',
5375 "--format=$known_snapshot_formats{$format}{'format'}",
5376 "--prefix=$name/", $hash);
5377 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5378 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5381 print $cgi->header(
5382 -type => $known_snapshot_formats{$format}{'type'},
5383 -content_disposition => 'inline; filename="' . "$filename" . '"',
5384 -status => '200 OK');
5386 open my $fd, "-|", $cmd
5387 or die_error(500, "Execute git-archive failed");
5388 binmode STDOUT, ':raw';
5389 print <$fd>;
5390 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5391 close $fd;
5394 sub git_log {
5395 my $head = git_get_head_hash($project);
5396 if (!defined $hash) {
5397 $hash = $head;
5399 if (!defined $page) {
5400 $page = 0;
5402 my $refs = git_get_references();
5404 my @commitlist = parse_commits($hash, 101, (100 * $page));
5406 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
5408 my ($patch_max) = gitweb_get_feature('patches');
5409 if ($patch_max) {
5410 if ($patch_max < 0 || @commitlist <= $patch_max) {
5411 $paging_nav .= " &sdot; " .
5412 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5413 "patches");
5417 git_header_html();
5418 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5420 if (!@commitlist) {
5421 my %co = parse_commit($hash);
5423 git_print_header_div('summary', $project);
5424 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5426 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5427 for (my $i = 0; $i <= $to; $i++) {
5428 my %co = %{$commitlist[$i]};
5429 next if !%co;
5430 my $commit = $co{'id'};
5431 my $ref = format_ref_marker($refs, $commit);
5432 my %ad = parse_date($co{'author_epoch'});
5433 git_print_header_div('commit',
5434 "<span class=\"age\">$co{'age_string'}</span>" .
5435 esc_html($co{'title'}) . $ref,
5436 $commit);
5437 print "<div class=\"title_text\">\n" .
5438 "<div class=\"log_link\">\n" .
5439 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5440 " | " .
5441 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5442 " | " .
5443 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5444 "<br/>\n" .
5445 "</div>\n";
5446 git_print_authorship(\%co, -tag => 'span');
5447 print "<br/>\n</div>\n";
5449 print "<div class=\"log_body\">\n";
5450 git_print_log($co{'comment'}, -final_empty_line=> 1);
5451 print "</div>\n";
5453 if ($#commitlist >= 100) {
5454 print "<div class=\"page_nav\">\n";
5455 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5456 -accesskey => "n", -title => "Alt-n"}, "next");
5457 print "</div>\n";
5459 git_footer_html();
5462 sub git_commit {
5463 $hash ||= $hash_base || "HEAD";
5464 my %co = parse_commit($hash)
5465 or die_error(404, "Unknown commit object");
5467 my $parent = $co{'parent'};
5468 my $parents = $co{'parents'}; # listref
5470 # we need to prepare $formats_nav before any parameter munging
5471 my $formats_nav;
5472 if (!defined $parent) {
5473 # --root commitdiff
5474 $formats_nav .= '(initial)';
5475 } elsif (@$parents == 1) {
5476 # single parent commit
5477 $formats_nav .=
5478 '(parent: ' .
5479 $cgi->a({-href => href(action=>"commit",
5480 hash=>$parent)},
5481 esc_html(substr($parent, 0, 7))) .
5482 ')';
5483 } else {
5484 # merge commit
5485 $formats_nav .=
5486 '(merge: ' .
5487 join(' ', map {
5488 $cgi->a({-href => href(action=>"commit",
5489 hash=>$_)},
5490 esc_html(substr($_, 0, 7)));
5491 } @$parents ) .
5492 ')';
5494 if (gitweb_check_feature('patches') && @$parents <= 1) {
5495 $formats_nav .= " | " .
5496 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5497 "patch");
5500 if (!defined $parent) {
5501 $parent = "--root";
5503 my @difftree;
5504 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5505 @diff_opts,
5506 (@$parents <= 1 ? $parent : '-c'),
5507 $hash, "--"
5508 or die_error(500, "Open git-diff-tree failed");
5509 @difftree = map { chomp; $_ } <$fd>;
5510 close $fd or die_error(404, "Reading git-diff-tree failed");
5512 # non-textual hash id's can be cached
5513 my $expires;
5514 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5515 $expires = "+1d";
5517 my $refs = git_get_references();
5518 my $ref = format_ref_marker($refs, $co{'id'});
5520 git_header_html(undef, $expires);
5521 git_print_page_nav('commit', '',
5522 $hash, $co{'tree'}, $hash,
5523 $formats_nav);
5525 if (defined $co{'parent'}) {
5526 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5527 } else {
5528 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5530 print "<div class=\"title_text\">\n" .
5531 "<table class=\"object_header\">\n";
5532 git_print_authorship_rows(\%co);
5533 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5534 print "<tr>" .
5535 "<td>tree</td>" .
5536 "<td class=\"sha1\">" .
5537 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5538 class => "list"}, $co{'tree'}) .
5539 "</td>" .
5540 "<td class=\"link\">" .
5541 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5542 "tree");
5543 my $snapshot_links = format_snapshot_links($hash);
5544 if (defined $snapshot_links) {
5545 print " | " . $snapshot_links;
5547 print "</td>" .
5548 "</tr>\n";
5550 foreach my $par (@$parents) {
5551 print "<tr>" .
5552 "<td>parent</td>" .
5553 "<td class=\"sha1\">" .
5554 $cgi->a({-href => href(action=>"commit", hash=>$par),
5555 class => "list"}, $par) .
5556 "</td>" .
5557 "<td class=\"link\">" .
5558 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5559 " | " .
5560 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5561 "</td>" .
5562 "</tr>\n";
5564 print "</table>".
5565 "</div>\n";
5567 print "<div class=\"page_body\">\n";
5568 git_print_log($co{'comment'});
5569 print "</div>\n";
5571 git_difftree_body(\@difftree, $hash, @$parents);
5573 git_footer_html();
5576 sub git_object {
5577 # object is defined by:
5578 # - hash or hash_base alone
5579 # - hash_base and file_name
5580 my $type;
5582 # - hash or hash_base alone
5583 if ($hash || ($hash_base && !defined $file_name)) {
5584 my $object_id = $hash || $hash_base;
5586 open my $fd, "-|", quote_command(
5587 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5588 or die_error(404, "Object does not exist");
5589 $type = <$fd>;
5590 chomp $type;
5591 close $fd
5592 or die_error(404, "Object does not exist");
5594 # - hash_base and file_name
5595 } elsif ($hash_base && defined $file_name) {
5596 $file_name =~ s,/+$,,;
5598 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5599 or die_error(404, "Base object does not exist");
5601 # here errors should not hapen
5602 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5603 or die_error(500, "Open git-ls-tree failed");
5604 my $line = <$fd>;
5605 close $fd;
5607 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5608 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5609 die_error(404, "File or directory for given base does not exist");
5611 $type = $2;
5612 $hash = $3;
5613 } else {
5614 die_error(400, "Not enough information to find object");
5617 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5618 hash=>$hash, hash_base=>$hash_base,
5619 file_name=>$file_name),
5620 -status => '302 Found');
5623 sub git_blobdiff {
5624 my $format = shift || 'html';
5626 my $fd;
5627 my @difftree;
5628 my %diffinfo;
5629 my $expires;
5631 # preparing $fd and %diffinfo for git_patchset_body
5632 # new style URI
5633 if (defined $hash_base && defined $hash_parent_base) {
5634 if (defined $file_name) {
5635 # read raw output
5636 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5637 $hash_parent_base, $hash_base,
5638 "--", (defined $file_parent ? $file_parent : ()), $file_name
5639 or die_error(500, "Open git-diff-tree failed");
5640 @difftree = map { chomp; $_ } <$fd>;
5641 close $fd
5642 or die_error(404, "Reading git-diff-tree failed");
5643 @difftree
5644 or die_error(404, "Blob diff not found");
5646 } elsif (defined $hash &&
5647 $hash =~ /[0-9a-fA-F]{40}/) {
5648 # try to find filename from $hash
5650 # read filtered raw output
5651 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5652 $hash_parent_base, $hash_base, "--"
5653 or die_error(500, "Open git-diff-tree failed");
5654 @difftree =
5655 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5656 # $hash == to_id
5657 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5658 map { chomp; $_ } <$fd>;
5659 close $fd
5660 or die_error(404, "Reading git-diff-tree failed");
5661 @difftree
5662 or die_error(404, "Blob diff not found");
5664 } else {
5665 die_error(400, "Missing one of the blob diff parameters");
5668 if (@difftree > 1) {
5669 die_error(400, "Ambiguous blob diff specification");
5672 %diffinfo = parse_difftree_raw_line($difftree[0]);
5673 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5674 $file_name ||= $diffinfo{'to_file'};
5676 $hash_parent ||= $diffinfo{'from_id'};
5677 $hash ||= $diffinfo{'to_id'};
5679 # non-textual hash id's can be cached
5680 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5681 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5682 $expires = '+1d';
5685 # open patch output
5686 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5687 '-p', ($format eq 'html' ? "--full-index" : ()),
5688 $hash_parent_base, $hash_base,
5689 "--", (defined $file_parent ? $file_parent : ()), $file_name
5690 or die_error(500, "Open git-diff-tree failed");
5693 # old/legacy style URI -- not generated anymore since 1.4.3.
5694 if (!%diffinfo) {
5695 die_error('404 Not Found', "Missing one of the blob diff parameters")
5698 # header
5699 if ($format eq 'html') {
5700 my $formats_nav =
5701 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5702 "raw");
5703 git_header_html(undef, $expires);
5704 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5705 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5706 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5707 } else {
5708 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5709 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5711 if (defined $file_name) {
5712 git_print_page_path($file_name, "blob", $hash_base);
5713 } else {
5714 print "<div class=\"page_path\"></div>\n";
5717 } elsif ($format eq 'plain') {
5718 print $cgi->header(
5719 -type => 'text/plain',
5720 -charset => 'utf-8',
5721 -expires => $expires,
5722 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5724 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5726 } else {
5727 die_error(400, "Unknown blobdiff format");
5730 # patch
5731 if ($format eq 'html') {
5732 print "<div class=\"page_body\">\n";
5734 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5735 close $fd;
5737 print "</div>\n"; # class="page_body"
5738 git_footer_html();
5740 } else {
5741 while (my $line = <$fd>) {
5742 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5743 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5745 print $line;
5747 last if $line =~ m!^\+\+\+!;
5749 local $/ = undef;
5750 print <$fd>;
5751 close $fd;
5755 sub git_blobdiff_plain {
5756 git_blobdiff('plain');
5759 sub git_commitdiff {
5760 my %params = @_;
5761 my $format = $params{-format} || 'html';
5763 my ($patch_max) = gitweb_get_feature('patches');
5764 if ($format eq 'patch') {
5765 die_error(403, "Patch view not allowed") unless $patch_max;
5768 $hash ||= $hash_base || "HEAD";
5769 my %co = parse_commit($hash)
5770 or die_error(404, "Unknown commit object");
5772 # choose format for commitdiff for merge
5773 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5774 $hash_parent = '--cc';
5776 # we need to prepare $formats_nav before almost any parameter munging
5777 my $formats_nav;
5778 if ($format eq 'html') {
5779 $formats_nav =
5780 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5781 "raw");
5782 if ($patch_max && @{$co{'parents'}} <= 1) {
5783 $formats_nav .= " | " .
5784 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5785 "patch");
5788 if (defined $hash_parent &&
5789 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5790 # commitdiff with two commits given
5791 my $hash_parent_short = $hash_parent;
5792 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5793 $hash_parent_short = substr($hash_parent, 0, 7);
5795 $formats_nav .=
5796 ' (from';
5797 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5798 if ($co{'parents'}[$i] eq $hash_parent) {
5799 $formats_nav .= ' parent ' . ($i+1);
5800 last;
5803 $formats_nav .= ': ' .
5804 $cgi->a({-href => href(action=>"commitdiff",
5805 hash=>$hash_parent)},
5806 esc_html($hash_parent_short)) .
5807 ')';
5808 } elsif (!$co{'parent'}) {
5809 # --root commitdiff
5810 $formats_nav .= ' (initial)';
5811 } elsif (scalar @{$co{'parents'}} == 1) {
5812 # single parent commit
5813 $formats_nav .=
5814 ' (parent: ' .
5815 $cgi->a({-href => href(action=>"commitdiff",
5816 hash=>$co{'parent'})},
5817 esc_html(substr($co{'parent'}, 0, 7))) .
5818 ')';
5819 } else {
5820 # merge commit
5821 if ($hash_parent eq '--cc') {
5822 $formats_nav .= ' | ' .
5823 $cgi->a({-href => href(action=>"commitdiff",
5824 hash=>$hash, hash_parent=>'-c')},
5825 'combined');
5826 } else { # $hash_parent eq '-c'
5827 $formats_nav .= ' | ' .
5828 $cgi->a({-href => href(action=>"commitdiff",
5829 hash=>$hash, hash_parent=>'--cc')},
5830 'compact');
5832 $formats_nav .=
5833 ' (merge: ' .
5834 join(' ', map {
5835 $cgi->a({-href => href(action=>"commitdiff",
5836 hash=>$_)},
5837 esc_html(substr($_, 0, 7)));
5838 } @{$co{'parents'}} ) .
5839 ')';
5843 my $hash_parent_param = $hash_parent;
5844 if (!defined $hash_parent_param) {
5845 # --cc for multiple parents, --root for parentless
5846 $hash_parent_param =
5847 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5850 # read commitdiff
5851 my $fd;
5852 my @difftree;
5853 if ($format eq 'html') {
5854 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5855 "--no-commit-id", "--patch-with-raw", "--full-index",
5856 $hash_parent_param, $hash, "--"
5857 or die_error(500, "Open git-diff-tree failed");
5859 while (my $line = <$fd>) {
5860 chomp $line;
5861 # empty line ends raw part of diff-tree output
5862 last unless $line;
5863 push @difftree, scalar parse_difftree_raw_line($line);
5866 } elsif ($format eq 'plain') {
5867 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5868 '-p', $hash_parent_param, $hash, "--"
5869 or die_error(500, "Open git-diff-tree failed");
5870 } elsif ($format eq 'patch') {
5871 # For commit ranges, we limit the output to the number of
5872 # patches specified in the 'patches' feature.
5873 # For single commits, we limit the output to a single patch,
5874 # diverging from the git-format-patch default.
5875 my @commit_spec = ();
5876 if ($hash_parent) {
5877 if ($patch_max > 0) {
5878 push @commit_spec, "-$patch_max";
5880 push @commit_spec, '-n', "$hash_parent..$hash";
5881 } else {
5882 if ($params{-single}) {
5883 push @commit_spec, '-1';
5884 } else {
5885 if ($patch_max > 0) {
5886 push @commit_spec, "-$patch_max";
5888 push @commit_spec, "-n";
5890 push @commit_spec, '--root', $hash;
5892 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5893 '--stdout', @commit_spec
5894 or die_error(500, "Open git-format-patch failed");
5895 } else {
5896 die_error(400, "Unknown commitdiff format");
5899 # non-textual hash id's can be cached
5900 my $expires;
5901 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5902 $expires = "+1d";
5905 # write commit message
5906 if ($format eq 'html') {
5907 my $refs = git_get_references();
5908 my $ref = format_ref_marker($refs, $co{'id'});
5910 git_header_html(undef, $expires);
5911 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5912 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5913 print "<div class=\"title_text\">\n" .
5914 "<table class=\"object_header\">\n";
5915 git_print_authorship_rows(\%co);
5916 print "</table>".
5917 "</div>\n";
5918 print "<div class=\"page_body\">\n";
5919 if (@{$co{'comment'}} > 1) {
5920 print "<div class=\"log\">\n";
5921 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5922 print "</div>\n"; # class="log"
5925 } elsif ($format eq 'plain') {
5926 my $refs = git_get_references("tags");
5927 my $tagname = git_get_rev_name_tags($hash);
5928 my $filename = basename($project) . "-$hash.patch";
5930 print $cgi->header(
5931 -type => 'text/plain',
5932 -charset => 'utf-8',
5933 -expires => $expires,
5934 -content_disposition => 'inline; filename="' . "$filename" . '"');
5935 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5936 print "From: " . to_utf8($co{'author'}) . "\n";
5937 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5938 print "Subject: " . to_utf8($co{'title'}) . "\n";
5940 print "X-Git-Tag: $tagname\n" if $tagname;
5941 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5943 foreach my $line (@{$co{'comment'}}) {
5944 print to_utf8($line) . "\n";
5946 print "---\n\n";
5947 } elsif ($format eq 'patch') {
5948 my $filename = basename($project) . "-$hash.patch";
5950 print $cgi->header(
5951 -type => 'text/plain',
5952 -charset => 'utf-8',
5953 -expires => $expires,
5954 -content_disposition => 'inline; filename="' . "$filename" . '"');
5957 # write patch
5958 if ($format eq 'html') {
5959 my $use_parents = !defined $hash_parent ||
5960 $hash_parent eq '-c' || $hash_parent eq '--cc';
5961 git_difftree_body(\@difftree, $hash,
5962 $use_parents ? @{$co{'parents'}} : $hash_parent);
5963 print "<br/>\n";
5965 git_patchset_body($fd, \@difftree, $hash,
5966 $use_parents ? @{$co{'parents'}} : $hash_parent);
5967 close $fd;
5968 print "</div>\n"; # class="page_body"
5969 git_footer_html();
5971 } elsif ($format eq 'plain') {
5972 local $/ = undef;
5973 print <$fd>;
5974 close $fd
5975 or print "Reading git-diff-tree failed\n";
5976 } elsif ($format eq 'patch') {
5977 local $/ = undef;
5978 print <$fd>;
5979 close $fd
5980 or print "Reading git-format-patch failed\n";
5984 sub git_commitdiff_plain {
5985 git_commitdiff(-format => 'plain');
5988 # format-patch-style patches
5989 sub git_patch {
5990 git_commitdiff(-format => 'patch', -single => 1);
5993 sub git_patches {
5994 git_commitdiff(-format => 'patch');
5997 sub git_history {
5998 if (!defined $hash_base) {
5999 $hash_base = git_get_head_hash($project);
6001 if (!defined $page) {
6002 $page = 0;
6004 my $ftype;
6005 my %co = parse_commit($hash_base)
6006 or die_error(404, "Unknown commit object");
6008 my $refs = git_get_references();
6009 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
6011 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
6012 $file_name, "--full-history")
6013 or die_error(404, "No such file or directory on given branch");
6015 if (!defined $hash && defined $file_name) {
6016 # some commits could have deleted file in question,
6017 # and not have it in tree, but one of them has to have it
6018 for (my $i = 0; $i <= @commitlist; $i++) {
6019 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6020 last if defined $hash;
6023 if (defined $hash) {
6024 $ftype = git_get_type($hash);
6026 if (!defined $ftype) {
6027 die_error(500, "Unknown type of object");
6030 my $paging_nav = '';
6031 if ($page > 0) {
6032 $paging_nav .=
6033 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
6034 file_name=>$file_name)},
6035 "first");
6036 $paging_nav .= " &sdot; " .
6037 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6038 -accesskey => "p", -title => "Alt-p"}, "prev");
6039 } else {
6040 $paging_nav .= "first";
6041 $paging_nav .= " &sdot; prev";
6043 my $next_link = '';
6044 if ($#commitlist >= 100) {
6045 $next_link =
6046 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6047 -accesskey => "n", -title => "Alt-n"}, "next");
6048 $paging_nav .= " &sdot; $next_link";
6049 } else {
6050 $paging_nav .= " &sdot; next";
6053 git_header_html();
6054 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
6055 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6056 git_print_page_path($file_name, $ftype, $hash_base);
6058 git_history_body(\@commitlist, 0, 99,
6059 $refs, $hash_base, $ftype, $next_link);
6061 git_footer_html();
6064 sub git_search {
6065 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6066 if (!defined $searchtext) {
6067 die_error(400, "Text field is empty");
6069 if (!defined $hash) {
6070 $hash = git_get_head_hash($project);
6072 my %co = parse_commit($hash);
6073 if (!%co) {
6074 die_error(404, "Unknown commit object");
6076 if (!defined $page) {
6077 $page = 0;
6080 $searchtype ||= 'commit';
6081 if ($searchtype eq 'pickaxe') {
6082 # pickaxe may take all resources of your box and run for several minutes
6083 # with every query - so decide by yourself how public you make this feature
6084 gitweb_check_feature('pickaxe')
6085 or die_error(403, "Pickaxe is disabled");
6087 if ($searchtype eq 'grep') {
6088 gitweb_check_feature('grep')
6089 or die_error(403, "Grep is disabled");
6092 git_header_html();
6094 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6095 my $greptype;
6096 if ($searchtype eq 'commit') {
6097 $greptype = "--grep=";
6098 } elsif ($searchtype eq 'author') {
6099 $greptype = "--author=";
6100 } elsif ($searchtype eq 'committer') {
6101 $greptype = "--committer=";
6103 $greptype .= $searchtext;
6104 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6105 $greptype, '--regexp-ignore-case',
6106 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6108 my $paging_nav = '';
6109 if ($page > 0) {
6110 $paging_nav .=
6111 $cgi->a({-href => href(action=>"search", hash=>$hash,
6112 searchtext=>$searchtext,
6113 searchtype=>$searchtype)},
6114 "first");
6115 $paging_nav .= " &sdot; " .
6116 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6117 -accesskey => "p", -title => "Alt-p"}, "prev");
6118 } else {
6119 $paging_nav .= "first";
6120 $paging_nav .= " &sdot; prev";
6122 my $next_link = '';
6123 if ($#commitlist >= 100) {
6124 $next_link =
6125 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6126 -accesskey => "n", -title => "Alt-n"}, "next");
6127 $paging_nav .= " &sdot; $next_link";
6128 } else {
6129 $paging_nav .= " &sdot; next";
6132 if ($#commitlist >= 100) {
6135 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6136 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6137 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6140 if ($searchtype eq 'pickaxe') {
6141 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6142 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6144 print "<table class=\"pickaxe search\">\n";
6145 my $alternate = 1;
6146 local $/ = "\n";
6147 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6148 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6149 ($search_use_regexp ? '--pickaxe-regex' : ());
6150 undef %co;
6151 my @files;
6152 while (my $line = <$fd>) {
6153 chomp $line;
6154 next unless $line;
6156 my %set = parse_difftree_raw_line($line);
6157 if (defined $set{'commit'}) {
6158 # finish previous commit
6159 if (%co) {
6160 print "</td>\n" .
6161 "<td class=\"link\">" .
6162 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6163 " | " .
6164 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6165 print "</td>\n" .
6166 "</tr>\n";
6169 if ($alternate) {
6170 print "<tr class=\"dark\">\n";
6171 } else {
6172 print "<tr class=\"light\">\n";
6174 $alternate ^= 1;
6175 %co = parse_commit($set{'commit'});
6176 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6177 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6178 "<td><i>$author</i></td>\n" .
6179 "<td>" .
6180 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6181 -class => "list subject"},
6182 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6183 } elsif (defined $set{'to_id'}) {
6184 next if ($set{'to_id'} =~ m/^0{40}$/);
6186 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6187 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6188 -class => "list"},
6189 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6190 "<br/>\n";
6193 close $fd;
6195 # finish last commit (warning: repetition!)
6196 if (%co) {
6197 print "</td>\n" .
6198 "<td class=\"link\">" .
6199 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6200 " | " .
6201 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6202 print "</td>\n" .
6203 "</tr>\n";
6206 print "</table>\n";
6209 if ($searchtype eq 'grep') {
6210 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6211 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6213 print "<table class=\"grep_search\">\n";
6214 my $alternate = 1;
6215 my $matches = 0;
6216 local $/ = "\n";
6217 open my $fd, "-|", git_cmd(), 'grep', '-n',
6218 $search_use_regexp ? ('-E', '-i') : '-F',
6219 $searchtext, $co{'tree'};
6220 my $lastfile = '';
6221 while (my $line = <$fd>) {
6222 chomp $line;
6223 my ($file, $lno, $ltext, $binary);
6224 last if ($matches++ > 1000);
6225 if ($line =~ /^Binary file (.+) matches$/) {
6226 $file = $1;
6227 $binary = 1;
6228 } else {
6229 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6231 if ($file ne $lastfile) {
6232 $lastfile and print "</td></tr>\n";
6233 if ($alternate++) {
6234 print "<tr class=\"dark\">\n";
6235 } else {
6236 print "<tr class=\"light\">\n";
6238 print "<td class=\"list\">".
6239 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6240 file_name=>"$file"),
6241 -class => "list"}, esc_path($file));
6242 print "</td><td>\n";
6243 $lastfile = $file;
6245 if ($binary) {
6246 print "<div class=\"binary\">Binary file</div>\n";
6247 } else {
6248 $ltext = untabify($ltext);
6249 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6250 $ltext = esc_html($1, -nbsp=>1);
6251 $ltext .= '<span class="match">';
6252 $ltext .= esc_html($2, -nbsp=>1);
6253 $ltext .= '</span>';
6254 $ltext .= esc_html($3, -nbsp=>1);
6255 } else {
6256 $ltext = esc_html($ltext, -nbsp=>1);
6258 print "<div class=\"pre\">" .
6259 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6260 file_name=>"$file").'#l'.$lno,
6261 -class => "linenr"}, sprintf('%4i', $lno))
6262 . ' ' . $ltext . "</div>\n";
6265 if ($lastfile) {
6266 print "</td></tr>\n";
6267 if ($matches > 1000) {
6268 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6270 } else {
6271 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6273 close $fd;
6275 print "</table>\n";
6277 git_footer_html();
6280 sub git_search_help {
6281 git_header_html();
6282 git_print_page_nav('','', $hash,$hash,$hash);
6283 print <<EOT;
6284 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6285 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6286 the pattern entered is recognized as the POSIX extended
6287 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6288 insensitive).</p>
6289 <dl>
6290 <dt><b>commit</b></dt>
6291 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6293 my $have_grep = gitweb_check_feature('grep');
6294 if ($have_grep) {
6295 print <<EOT;
6296 <dt><b>grep</b></dt>
6297 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6298 a different one) are searched for the given pattern. On large trees, this search can take
6299 a while and put some strain on the server, so please use it with some consideration. Note that
6300 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6301 case-sensitive.</dd>
6304 print <<EOT;
6305 <dt><b>author</b></dt>
6306 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6307 <dt><b>committer</b></dt>
6308 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6310 my $have_pickaxe = gitweb_check_feature('pickaxe');
6311 if ($have_pickaxe) {
6312 print <<EOT;
6313 <dt><b>pickaxe</b></dt>
6314 <dd>All commits that caused the string to appear or disappear from any file (changes that
6315 added, removed or "modified" the string) will be listed. This search can take a while and
6316 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6317 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6320 print "</dl>\n";
6321 git_footer_html();
6324 sub git_shortlog {
6325 my $head = git_get_head_hash($project);
6326 if (!defined $hash) {
6327 $hash = $head;
6329 if (!defined $page) {
6330 $page = 0;
6332 my $refs = git_get_references();
6334 my $commit_hash = $hash;
6335 if (defined $hash_parent) {
6336 $commit_hash = "$hash_parent..$hash";
6338 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6340 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6341 my $next_link = '';
6342 if ($#commitlist >= 100) {
6343 $next_link =
6344 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6345 -accesskey => "n", -title => "Alt-n"}, "next");
6347 my $patch_max = gitweb_check_feature('patches');
6348 if ($patch_max) {
6349 if ($patch_max < 0 || @commitlist <= $patch_max) {
6350 $paging_nav .= " &sdot; " .
6351 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6352 "patches");
6356 git_header_html();
6357 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6358 git_print_header_div('summary', $project);
6360 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6362 git_footer_html();
6365 ## ......................................................................
6366 ## feeds (RSS, Atom; OPML)
6368 sub git_feed {
6369 my $format = shift || 'atom';
6370 my $have_blame = gitweb_check_feature('blame');
6372 # Atom: http://www.atomenabled.org/developers/syndication/
6373 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6374 if ($format ne 'rss' && $format ne 'atom') {
6375 die_error(400, "Unknown web feed format");
6378 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6379 my $head = $hash || 'HEAD';
6380 my @commitlist = parse_commits($head, 150, 0, $file_name);
6382 my %latest_commit;
6383 my %latest_date;
6384 my $content_type = "application/$format+xml";
6385 if (defined $cgi->http('HTTP_ACCEPT') &&
6386 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6387 # browser (feed reader) prefers text/xml
6388 $content_type = 'text/xml';
6390 if (defined($commitlist[0])) {
6391 %latest_commit = %{$commitlist[0]};
6392 my $latest_epoch = $latest_commit{'committer_epoch'};
6393 %latest_date = parse_date($latest_epoch);
6394 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6395 if (defined $if_modified) {
6396 my $since;
6397 if (eval { require HTTP::Date; 1; }) {
6398 $since = HTTP::Date::str2time($if_modified);
6399 } elsif (eval { require Time::ParseDate; 1; }) {
6400 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6402 if (defined $since && $latest_epoch <= $since) {
6403 print $cgi->header(
6404 -type => $content_type,
6405 -charset => 'utf-8',
6406 -last_modified => $latest_date{'rfc2822'},
6407 -status => '304 Not Modified');
6408 return;
6411 print $cgi->header(
6412 -type => $content_type,
6413 -charset => 'utf-8',
6414 -last_modified => $latest_date{'rfc2822'});
6415 } else {
6416 print $cgi->header(
6417 -type => $content_type,
6418 -charset => 'utf-8');
6421 # Optimization: skip generating the body if client asks only
6422 # for Last-Modified date.
6423 return if ($cgi->request_method() eq 'HEAD');
6425 # header variables
6426 my $title = "$site_name - $project/$action";
6427 my $feed_type = 'log';
6428 if (defined $hash) {
6429 $title .= " - '$hash'";
6430 $feed_type = 'branch log';
6431 if (defined $file_name) {
6432 $title .= " :: $file_name";
6433 $feed_type = 'history';
6435 } elsif (defined $file_name) {
6436 $title .= " - $file_name";
6437 $feed_type = 'history';
6439 $title .= " $feed_type";
6440 my $descr = git_get_project_description($project);
6441 if (defined $descr) {
6442 $descr = esc_html($descr);
6443 } else {
6444 $descr = "$project " .
6445 ($format eq 'rss' ? 'RSS' : 'Atom') .
6446 " feed";
6448 my $owner = git_get_project_owner($project);
6449 $owner = esc_html($owner);
6451 #header
6452 my $alt_url;
6453 if (defined $file_name) {
6454 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6455 } elsif (defined $hash) {
6456 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6457 } else {
6458 $alt_url = href(-full=>1, action=>"summary");
6460 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6461 if ($format eq 'rss') {
6462 print <<XML;
6463 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6464 <channel>
6466 print "<title>$title</title>\n" .
6467 "<link>$alt_url</link>\n" .
6468 "<description>$descr</description>\n" .
6469 "<language>en</language>\n" .
6470 # project owner is responsible for 'editorial' content
6471 "<managingEditor>$owner</managingEditor>\n";
6472 if (defined $logo || defined $favicon) {
6473 # prefer the logo to the favicon, since RSS
6474 # doesn't allow both
6475 my $img = esc_url($logo || $favicon);
6476 print "<image>\n" .
6477 "<url>$img</url>\n" .
6478 "<title>$title</title>\n" .
6479 "<link>$alt_url</link>\n" .
6480 "</image>\n";
6482 if (%latest_date) {
6483 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6484 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6486 print "<generator>gitweb v.$version/$git_version</generator>\n";
6487 } elsif ($format eq 'atom') {
6488 print <<XML;
6489 <feed xmlns="http://www.w3.org/2005/Atom">
6491 print "<title>$title</title>\n" .
6492 "<subtitle>$descr</subtitle>\n" .
6493 '<link rel="alternate" type="text/html" href="' .
6494 $alt_url . '" />' . "\n" .
6495 '<link rel="self" type="' . $content_type . '" href="' .
6496 $cgi->self_url() . '" />' . "\n" .
6497 "<id>" . href(-full=>1) . "</id>\n" .
6498 # use project owner for feed author
6499 "<author><name>$owner</name></author>\n";
6500 if (defined $favicon) {
6501 print "<icon>" . esc_url($favicon) . "</icon>\n";
6503 if (defined $logo_url) {
6504 # not twice as wide as tall: 72 x 27 pixels
6505 print "<logo>" . esc_url($logo) . "</logo>\n";
6507 if (! %latest_date) {
6508 # dummy date to keep the feed valid until commits trickle in:
6509 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6510 } else {
6511 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6513 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6516 # contents
6517 for (my $i = 0; $i <= $#commitlist; $i++) {
6518 my %co = %{$commitlist[$i]};
6519 my $commit = $co{'id'};
6520 # we read 150, we always show 30 and the ones more recent than 48 hours
6521 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6522 last;
6524 my %cd = parse_date($co{'author_epoch'});
6526 # get list of changed files
6527 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6528 $co{'parent'} || "--root",
6529 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6530 or next;
6531 my @difftree = map { chomp; $_ } <$fd>;
6532 close $fd
6533 or next;
6535 # print element (entry, item)
6536 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6537 if ($format eq 'rss') {
6538 print "<item>\n" .
6539 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6540 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6541 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6542 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6543 "<link>$co_url</link>\n" .
6544 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6545 "<content:encoded>" .
6546 "<![CDATA[\n";
6547 } elsif ($format eq 'atom') {
6548 print "<entry>\n" .
6549 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6550 "<updated>$cd{'iso-8601'}</updated>\n" .
6551 "<author>\n" .
6552 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6553 if ($co{'author_email'}) {
6554 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6556 print "</author>\n" .
6557 # use committer for contributor
6558 "<contributor>\n" .
6559 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6560 if ($co{'committer_email'}) {
6561 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6563 print "</contributor>\n" .
6564 "<published>$cd{'iso-8601'}</published>\n" .
6565 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6566 "<id>$co_url</id>\n" .
6567 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6568 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6570 my $comment = $co{'comment'};
6571 print "<pre>\n";
6572 foreach my $line (@$comment) {
6573 $line = esc_html($line);
6574 print "$line\n";
6576 print "</pre><ul>\n";
6577 foreach my $difftree_line (@difftree) {
6578 my %difftree = parse_difftree_raw_line($difftree_line);
6579 next if !$difftree{'from_id'};
6581 my $file = $difftree{'file'} || $difftree{'to_file'};
6583 print "<li>" .
6584 "[" .
6585 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6586 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6587 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6588 file_name=>$file, file_parent=>$difftree{'from_file'}),
6589 -title => "diff"}, 'D');
6590 if ($have_blame) {
6591 print $cgi->a({-href => href(-full=>1, action=>"blame",
6592 file_name=>$file, hash_base=>$commit), -class => "blamelink",
6593 -title => "blame"}, 'B');
6595 # if this is not a feed of a file history
6596 if (!defined $file_name || $file_name ne $file) {
6597 print $cgi->a({-href => href(-full=>1, action=>"history",
6598 file_name=>$file, hash=>$commit),
6599 -title => "history"}, 'H');
6601 $file = esc_path($file);
6602 print "] ".
6603 "$file</li>\n";
6605 if ($format eq 'rss') {
6606 print "</ul>]]>\n" .
6607 "</content:encoded>\n" .
6608 "</item>\n";
6609 } elsif ($format eq 'atom') {
6610 print "</ul>\n</div>\n" .
6611 "</content>\n" .
6612 "</entry>\n";
6616 # end of feed
6617 if ($format eq 'rss') {
6618 print "</channel>\n</rss>\n";
6619 } elsif ($format eq 'atom') {
6620 print "</feed>\n";
6624 sub git_rss {
6625 git_feed('rss');
6628 sub git_atom {
6629 git_feed('atom');
6632 sub git_opml {
6633 my @list = git_get_projects_list();
6635 print $cgi->header(
6636 -type => 'text/xml',
6637 -charset => 'utf-8',
6638 -content_disposition => 'inline; filename="opml.xml"');
6640 print <<XML;
6641 <?xml version="1.0" encoding="utf-8"?>
6642 <opml version="1.0">
6643 <head>
6644 <title>$site_name OPML Export</title>
6645 </head>
6646 <body>
6647 <outline text="git RSS feeds">
6650 foreach my $pr (@list) {
6651 my %proj = %$pr;
6652 my $head = git_get_head_hash($proj{'path'});
6653 if (!defined $head) {
6654 next;
6656 $git_dir = "$projectroot/$proj{'path'}";
6657 my %co = parse_commit($head);
6658 if (!%co) {
6659 next;
6662 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6663 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6664 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6665 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6667 print <<XML;
6668 </outline>
6669 </body>
6670 </opml>