gitweb: append short hash ids to snapshot files
[git/spearce.git] / gitweb / gitweb.perl
blobbc132a537e21b0a2ab9f485fe03f404b0c84b3a1
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use strict;
11 use warnings;
12 use CGI qw(:standard :escapeHTML -nosticky);
13 use CGI::Util qw(unescape);
14 use CGI::Carp qw(fatalsToBrowser);
15 use Encode;
16 use Fcntl ':mode';
17 use File::Find qw();
18 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
21 BEGIN {
22 CGI->compile() if $ENV{'MOD_PERL'};
25 our $cgi = new CGI;
26 our $version = "++GIT_VERSION++";
27 our $my_url = $cgi->url();
28 our $my_uri = $cgi->url(-absolute => 1);
30 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
31 # needed and used only for URLs with nonempty PATH_INFO
32 our $base_url = $my_url;
34 # When the script is used as DirectoryIndex, the URL does not contain the name
35 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
36 # have to do it ourselves. We make $path_info global because it's also used
37 # later on.
39 # Another issue with the script being the DirectoryIndex is that the resulting
40 # $my_url data is not the full script URL: this is good, because we want
41 # generated links to keep implying the script name if it wasn't explicitly
42 # indicated in the URL we're handling, but it means that $my_url cannot be used
43 # as base URL.
44 # Therefore, if we needed to strip PATH_INFO, then we know that we have
45 # to build the base URL ourselves:
46 our $path_info = $ENV{"PATH_INFO"};
47 if ($path_info) {
48 if ($my_url =~ s,\Q$path_info\E$,, &&
49 $my_uri =~ s,\Q$path_info\E$,, &&
50 defined $ENV{'SCRIPT_NAME'}) {
51 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
55 # core git executable to use
56 # this can just be "git" if your webserver has a sensible PATH
57 our $GIT = "++GIT_BINDIR++/git";
59 # absolute fs-path which will be prepended to the project path
60 #our $projectroot = "/pub/scm";
61 our $projectroot = "++GITWEB_PROJECTROOT++";
63 # fs traversing limit for getting project list
64 # the number is relative to the projectroot
65 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
67 # target of the home link on top of all pages
68 our $home_link = $my_uri || "/";
70 # string of the home link on top of all pages
71 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
73 # name of your site or organization to appear in page titles
74 # replace this with something more descriptive for clearer bookmarks
75 our $site_name = "++GITWEB_SITENAME++"
76 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
78 # filename of html text to include at top of each page
79 our $site_header = "++GITWEB_SITE_HEADER++";
80 # html text to include at home page
81 our $home_text = "++GITWEB_HOMETEXT++";
82 # filename of html text to include at bottom of each page
83 our $site_footer = "++GITWEB_SITE_FOOTER++";
85 # URI of stylesheets
86 our @stylesheets = ("++GITWEB_CSS++");
87 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
88 our $stylesheet = undef;
89 # URI of GIT logo (72x27 size)
90 our $logo = "++GITWEB_LOGO++";
91 # URI of GIT favicon, assumed to be image/png type
92 our $favicon = "++GITWEB_FAVICON++";
94 # URI and label (title) of GIT logo link
95 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
96 #our $logo_label = "git documentation";
97 our $logo_url = "http://git-scm.com/";
98 our $logo_label = "git homepage";
100 # source of projects list
101 our $projects_list = "++GITWEB_LIST++";
103 # the width (in characters) of the projects list "Description" column
104 our $projects_list_description_width = 25;
106 # default order of projects list
107 # valid values are none, project, descr, owner, and age
108 our $default_projects_order = "project";
110 # show repository only if this file exists
111 # (only effective if this variable evaluates to true)
112 our $export_ok = "++GITWEB_EXPORT_OK++";
114 # show repository only if this subroutine returns true
115 # when given the path to the project, for example:
116 # sub { return -e "$_[0]/git-daemon-export-ok"; }
117 our $export_auth_hook = undef;
119 # only allow viewing of repositories also shown on the overview page
120 our $strict_export = "++GITWEB_STRICT_EXPORT++";
122 # list of git base URLs used for URL to where fetch project from,
123 # i.e. full URL is "$git_base_url/$project"
124 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
126 # default blob_plain mimetype and default charset for text/plain blob
127 our $default_blob_plain_mimetype = 'text/plain';
128 our $default_text_plain_charset = undef;
130 # file to use for guessing MIME types before trying /etc/mime.types
131 # (relative to the current git repository)
132 our $mimetypes_file = undef;
134 # assume this charset if line contains non-UTF-8 characters;
135 # it should be valid encoding (see Encoding::Supported(3pm) for list),
136 # for which encoding all byte sequences are valid, for example
137 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
138 # could be even 'utf-8' for the old behavior)
139 our $fallback_encoding = 'latin1';
141 # rename detection options for git-diff and git-diff-tree
142 # - default is '-M', with the cost proportional to
143 # (number of removed files) * (number of new files).
144 # - more costly is '-C' (which implies '-M'), with the cost proportional to
145 # (number of changed files + number of removed files) * (number of new files)
146 # - even more costly is '-C', '--find-copies-harder' with cost
147 # (number of files in the original tree) * (number of new files)
148 # - one might want to include '-B' option, e.g. '-B', '-M'
149 our @diff_opts = ('-M'); # taken from git_commit
151 # Disables features that would allow repository owners to inject script into
152 # the gitweb domain.
153 our $prevent_xss = 0;
155 # information about snapshot formats that gitweb is capable of serving
156 our %known_snapshot_formats = (
157 # name => {
158 # 'display' => display name,
159 # 'type' => mime type,
160 # 'suffix' => filename suffix,
161 # 'format' => --format for git-archive,
162 # 'compressor' => [compressor command and arguments]
163 # (array reference, optional)
164 # 'disabled' => boolean (optional)}
166 'tgz' => {
167 'display' => 'tar.gz',
168 'type' => 'application/x-gzip',
169 'suffix' => '.tar.gz',
170 'format' => 'tar',
171 'compressor' => ['gzip']},
173 'tbz2' => {
174 'display' => 'tar.bz2',
175 'type' => 'application/x-bzip2',
176 'suffix' => '.tar.bz2',
177 'format' => 'tar',
178 'compressor' => ['bzip2']},
180 'txz' => {
181 'display' => 'tar.xz',
182 'type' => 'application/x-xz',
183 'suffix' => '.tar.xz',
184 'format' => 'tar',
185 'compressor' => ['xz'],
186 'disabled' => 1},
188 'zip' => {
189 'display' => 'zip',
190 'type' => 'application/x-zip',
191 'suffix' => '.zip',
192 'format' => 'zip'},
195 # Aliases so we understand old gitweb.snapshot values in repository
196 # configuration.
197 our %known_snapshot_format_aliases = (
198 'gzip' => 'tgz',
199 'bzip2' => 'tbz2',
200 'xz' => 'txz',
202 # backward compatibility: legacy gitweb config support
203 'x-gzip' => undef, 'gz' => undef,
204 'x-bzip2' => undef, 'bz2' => undef,
205 'x-zip' => undef, '' => undef,
208 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
209 # are changed, it may be appropriate to change these values too via
210 # $GITWEB_CONFIG.
211 our %avatar_size = (
212 'default' => 16,
213 'double' => 32
216 # You define site-wide feature defaults here; override them with
217 # $GITWEB_CONFIG as necessary.
218 our %feature = (
219 # feature => {
220 # 'sub' => feature-sub (subroutine),
221 # 'override' => allow-override (boolean),
222 # 'default' => [ default options...] (array reference)}
224 # if feature is overridable (it means that allow-override has true value),
225 # then feature-sub will be called with default options as parameters;
226 # return value of feature-sub indicates if to enable specified feature
228 # if there is no 'sub' key (no feature-sub), then feature cannot be
229 # overriden
231 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
232 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
233 # is enabled
235 # Enable the 'blame' blob view, showing the last commit that modified
236 # each line in the file. This can be very CPU-intensive.
238 # To enable system wide have in $GITWEB_CONFIG
239 # $feature{'blame'}{'default'} = [1];
240 # To have project specific config enable override in $GITWEB_CONFIG
241 # $feature{'blame'}{'override'} = 1;
242 # and in project config gitweb.blame = 0|1;
243 'blame' => {
244 'sub' => sub { feature_bool('blame', @_) },
245 'override' => 0,
246 'default' => [0]},
248 # Enable the 'snapshot' link, providing a compressed archive of any
249 # tree. This can potentially generate high traffic if you have large
250 # project.
252 # Value is a list of formats defined in %known_snapshot_formats that
253 # you wish to offer.
254 # To disable system wide have in $GITWEB_CONFIG
255 # $feature{'snapshot'}{'default'} = [];
256 # To have project specific config enable override in $GITWEB_CONFIG
257 # $feature{'snapshot'}{'override'} = 1;
258 # and in project config, a comma-separated list of formats or "none"
259 # to disable. Example: gitweb.snapshot = tbz2,zip;
260 'snapshot' => {
261 'sub' => \&feature_snapshot,
262 'override' => 0,
263 'default' => ['tgz']},
265 # Enable text search, which will list the commits which match author,
266 # committer or commit text to a given string. Enabled by default.
267 # Project specific override is not supported.
268 'search' => {
269 'override' => 0,
270 'default' => [1]},
272 # Enable grep search, which will list the files in currently selected
273 # tree containing the given string. Enabled by default. This can be
274 # potentially CPU-intensive, of course.
276 # To enable system wide have in $GITWEB_CONFIG
277 # $feature{'grep'}{'default'} = [1];
278 # To have project specific config enable override in $GITWEB_CONFIG
279 # $feature{'grep'}{'override'} = 1;
280 # and in project config gitweb.grep = 0|1;
281 'grep' => {
282 'sub' => sub { feature_bool('grep', @_) },
283 'override' => 0,
284 'default' => [1]},
286 # Enable the pickaxe search, which will list the commits that modified
287 # a given string in a file. This can be practical and quite faster
288 # alternative to 'blame', but still potentially CPU-intensive.
290 # To enable system wide have in $GITWEB_CONFIG
291 # $feature{'pickaxe'}{'default'} = [1];
292 # To have project specific config enable override in $GITWEB_CONFIG
293 # $feature{'pickaxe'}{'override'} = 1;
294 # and in project config gitweb.pickaxe = 0|1;
295 'pickaxe' => {
296 'sub' => sub { feature_bool('pickaxe', @_) },
297 'override' => 0,
298 'default' => [1]},
300 # Make gitweb use an alternative format of the URLs which can be
301 # more readable and natural-looking: project name is embedded
302 # directly in the path and the query string contains other
303 # auxiliary information. All gitweb installations recognize
304 # URL in either format; this configures in which formats gitweb
305 # generates links.
307 # To enable system wide have in $GITWEB_CONFIG
308 # $feature{'pathinfo'}{'default'} = [1];
309 # Project specific override is not supported.
311 # Note that you will need to change the default location of CSS,
312 # favicon, logo and possibly other files to an absolute URL. Also,
313 # if gitweb.cgi serves as your indexfile, you will need to force
314 # $my_uri to contain the script name in your $GITWEB_CONFIG.
315 'pathinfo' => {
316 'override' => 0,
317 'default' => [0]},
319 # Make gitweb consider projects in project root subdirectories
320 # to be forks of existing projects. Given project $projname.git,
321 # projects matching $projname/*.git will not be shown in the main
322 # projects list, instead a '+' mark will be added to $projname
323 # there and a 'forks' view will be enabled for the project, listing
324 # all the forks. If project list is taken from a file, forks have
325 # to be listed after the main project.
327 # To enable system wide have in $GITWEB_CONFIG
328 # $feature{'forks'}{'default'} = [1];
329 # Project specific override is not supported.
330 'forks' => {
331 'override' => 0,
332 'default' => [0]},
334 # Insert custom links to the action bar of all project pages.
335 # This enables you mainly to link to third-party scripts integrating
336 # into gitweb; e.g. git-browser for graphical history representation
337 # or custom web-based repository administration interface.
339 # The 'default' value consists of a list of triplets in the form
340 # (label, link, position) where position is the label after which
341 # to insert the link and link is a format string where %n expands
342 # to the project name, %f to the project path within the filesystem,
343 # %h to the current hash (h gitweb parameter) and %b to the current
344 # hash base (hb gitweb parameter); %% expands to %.
346 # To enable system wide have in $GITWEB_CONFIG e.g.
347 # $feature{'actions'}{'default'} = [('graphiclog',
348 # '/git-browser/by-commit.html?r=%n', 'summary')];
349 # Project specific override is not supported.
350 'actions' => {
351 'override' => 0,
352 'default' => []},
354 # Allow gitweb scan project content tags described in ctags/
355 # of project repository, and display the popular Web 2.0-ish
356 # "tag cloud" near the project list. Note that this is something
357 # COMPLETELY different from the normal Git tags.
359 # gitweb by itself can show existing tags, but it does not handle
360 # tagging itself; you need an external application for that.
361 # For an example script, check Girocco's cgi/tagproj.cgi.
362 # You may want to install the HTML::TagCloud Perl module to get
363 # a pretty tag cloud instead of just a list of tags.
365 # To enable system wide have in $GITWEB_CONFIG
366 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
367 # Project specific override is not supported.
368 'ctags' => {
369 'override' => 0,
370 'default' => [0]},
372 # The maximum number of patches in a patchset generated in patch
373 # view. Set this to 0 or undef to disable patch view, or to a
374 # negative number to remove any limit.
376 # To disable system wide have in $GITWEB_CONFIG
377 # $feature{'patches'}{'default'} = [0];
378 # To have project specific config enable override in $GITWEB_CONFIG
379 # $feature{'patches'}{'override'} = 1;
380 # and in project config gitweb.patches = 0|n;
381 # where n is the maximum number of patches allowed in a patchset.
382 'patches' => {
383 'sub' => \&feature_patches,
384 'override' => 0,
385 'default' => [16]},
387 # Avatar support. When this feature is enabled, views such as
388 # shortlog or commit will display an avatar associated with
389 # the email of the committer(s) and/or author(s).
391 # Currently available providers are gravatar and picon.
392 # If an unknown provider is specified, the feature is disabled.
394 # Gravatar depends on Digest::MD5.
395 # Picon currently relies on the indiana.edu database.
397 # To enable system wide have in $GITWEB_CONFIG
398 # $feature{'avatar'}{'default'} = ['<provider>'];
399 # where <provider> is either gravatar or picon.
400 # To have project specific config enable override in $GITWEB_CONFIG
401 # $feature{'avatar'}{'override'} = 1;
402 # and in project config gitweb.avatar = <provider>;
403 'avatar' => {
404 'sub' => \&feature_avatar,
405 'override' => 0,
406 'default' => ['']},
409 sub gitweb_get_feature {
410 my ($name) = @_;
411 return unless exists $feature{$name};
412 my ($sub, $override, @defaults) = (
413 $feature{$name}{'sub'},
414 $feature{$name}{'override'},
415 @{$feature{$name}{'default'}});
416 if (!$override) { return @defaults; }
417 if (!defined $sub) {
418 warn "feature $name is not overridable";
419 return @defaults;
421 return $sub->(@defaults);
424 # A wrapper to check if a given feature is enabled.
425 # With this, you can say
427 # my $bool_feat = gitweb_check_feature('bool_feat');
428 # gitweb_check_feature('bool_feat') or somecode;
430 # instead of
432 # my ($bool_feat) = gitweb_get_feature('bool_feat');
433 # (gitweb_get_feature('bool_feat'))[0] or somecode;
435 sub gitweb_check_feature {
436 return (gitweb_get_feature(@_))[0];
440 sub feature_bool {
441 my $key = shift;
442 my ($val) = git_get_project_config($key, '--bool');
444 if (!defined $val) {
445 return ($_[0]);
446 } elsif ($val eq 'true') {
447 return (1);
448 } elsif ($val eq 'false') {
449 return (0);
453 sub feature_snapshot {
454 my (@fmts) = @_;
456 my ($val) = git_get_project_config('snapshot');
458 if ($val) {
459 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
462 return @fmts;
465 sub feature_patches {
466 my @val = (git_get_project_config('patches', '--int'));
468 if (@val) {
469 return @val;
472 return ($_[0]);
475 sub feature_avatar {
476 my @val = (git_get_project_config('avatar'));
478 return @val ? @val : @_;
481 # checking HEAD file with -e is fragile if the repository was
482 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
483 # and then pruned.
484 sub check_head_link {
485 my ($dir) = @_;
486 my $headfile = "$dir/HEAD";
487 return ((-e $headfile) ||
488 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
491 sub check_export_ok {
492 my ($dir) = @_;
493 return (check_head_link($dir) &&
494 (!$export_ok || -e "$dir/$export_ok") &&
495 (!$export_auth_hook || $export_auth_hook->($dir)));
498 # process alternate names for backward compatibility
499 # filter out unsupported (unknown) snapshot formats
500 sub filter_snapshot_fmts {
501 my @fmts = @_;
503 @fmts = map {
504 exists $known_snapshot_format_aliases{$_} ?
505 $known_snapshot_format_aliases{$_} : $_} @fmts;
506 @fmts = grep {
507 exists $known_snapshot_formats{$_} &&
508 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
511 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
512 if (-e $GITWEB_CONFIG) {
513 do $GITWEB_CONFIG;
514 } else {
515 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
516 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
519 # version of the core git binary
520 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
522 $projects_list ||= $projectroot;
524 # ======================================================================
525 # input validation and dispatch
527 # input parameters can be collected from a variety of sources (presently, CGI
528 # and PATH_INFO), so we define an %input_params hash that collects them all
529 # together during validation: this allows subsequent uses (e.g. href()) to be
530 # agnostic of the parameter origin
532 our %input_params = ();
534 # input parameters are stored with the long parameter name as key. This will
535 # also be used in the href subroutine to convert parameters to their CGI
536 # equivalent, and since the href() usage is the most frequent one, we store
537 # the name -> CGI key mapping here, instead of the reverse.
539 # XXX: Warning: If you touch this, check the search form for updating,
540 # too.
542 our @cgi_param_mapping = (
543 project => "p",
544 action => "a",
545 file_name => "f",
546 file_parent => "fp",
547 hash => "h",
548 hash_parent => "hp",
549 hash_base => "hb",
550 hash_parent_base => "hpb",
551 page => "pg",
552 order => "o",
553 searchtext => "s",
554 searchtype => "st",
555 snapshot_format => "sf",
556 extra_options => "opt",
557 search_use_regexp => "sr",
559 our %cgi_param_mapping = @cgi_param_mapping;
561 # we will also need to know the possible actions, for validation
562 our %actions = (
563 "blame" => \&git_blame,
564 "blobdiff" => \&git_blobdiff,
565 "blobdiff_plain" => \&git_blobdiff_plain,
566 "blob" => \&git_blob,
567 "blob_plain" => \&git_blob_plain,
568 "commitdiff" => \&git_commitdiff,
569 "commitdiff_plain" => \&git_commitdiff_plain,
570 "commit" => \&git_commit,
571 "forks" => \&git_forks,
572 "heads" => \&git_heads,
573 "history" => \&git_history,
574 "log" => \&git_log,
575 "patch" => \&git_patch,
576 "patches" => \&git_patches,
577 "rss" => \&git_rss,
578 "atom" => \&git_atom,
579 "search" => \&git_search,
580 "search_help" => \&git_search_help,
581 "shortlog" => \&git_shortlog,
582 "summary" => \&git_summary,
583 "tag" => \&git_tag,
584 "tags" => \&git_tags,
585 "tree" => \&git_tree,
586 "snapshot" => \&git_snapshot,
587 "object" => \&git_object,
588 # those below don't need $project
589 "opml" => \&git_opml,
590 "project_list" => \&git_project_list,
591 "project_index" => \&git_project_index,
594 # finally, we have the hash of allowed extra_options for the commands that
595 # allow them
596 our %allowed_options = (
597 "--no-merges" => [ qw(rss atom log shortlog history) ],
600 # fill %input_params with the CGI parameters. All values except for 'opt'
601 # should be single values, but opt can be an array. We should probably
602 # build an array of parameters that can be multi-valued, but since for the time
603 # being it's only this one, we just single it out
604 while (my ($name, $symbol) = each %cgi_param_mapping) {
605 if ($symbol eq 'opt') {
606 $input_params{$name} = [ $cgi->param($symbol) ];
607 } else {
608 $input_params{$name} = $cgi->param($symbol);
612 # now read PATH_INFO and update the parameter list for missing parameters
613 sub evaluate_path_info {
614 return if defined $input_params{'project'};
615 return if !$path_info;
616 $path_info =~ s,^/+,,;
617 return if !$path_info;
619 # find which part of PATH_INFO is project
620 my $project = $path_info;
621 $project =~ s,/+$,,;
622 while ($project && !check_head_link("$projectroot/$project")) {
623 $project =~ s,/*[^/]*$,,;
625 return unless $project;
626 $input_params{'project'} = $project;
628 # do not change any parameters if an action is given using the query string
629 return if $input_params{'action'};
630 $path_info =~ s,^\Q$project\E/*,,;
632 # next, check if we have an action
633 my $action = $path_info;
634 $action =~ s,/.*$,,;
635 if (exists $actions{$action}) {
636 $path_info =~ s,^$action/*,,;
637 $input_params{'action'} = $action;
640 # list of actions that want hash_base instead of hash, but can have no
641 # pathname (f) parameter
642 my @wants_base = (
643 'tree',
644 'history',
647 # we want to catch
648 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
649 my ($parentrefname, $parentpathname, $refname, $pathname) =
650 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
652 # first, analyze the 'current' part
653 if (defined $pathname) {
654 # we got "branch:filename" or "branch:dir/"
655 # we could use git_get_type(branch:pathname), but:
656 # - it needs $git_dir
657 # - it does a git() call
658 # - the convention of terminating directories with a slash
659 # makes it superfluous
660 # - embedding the action in the PATH_INFO would make it even
661 # more superfluous
662 $pathname =~ s,^/+,,;
663 if (!$pathname || substr($pathname, -1) eq "/") {
664 $input_params{'action'} ||= "tree";
665 $pathname =~ s,/$,,;
666 } else {
667 # the default action depends on whether we had parent info
668 # or not
669 if ($parentrefname) {
670 $input_params{'action'} ||= "blobdiff_plain";
671 } else {
672 $input_params{'action'} ||= "blob_plain";
675 $input_params{'hash_base'} ||= $refname;
676 $input_params{'file_name'} ||= $pathname;
677 } elsif (defined $refname) {
678 # we got "branch". In this case we have to choose if we have to
679 # set hash or hash_base.
681 # Most of the actions without a pathname only want hash to be
682 # set, except for the ones specified in @wants_base that want
683 # hash_base instead. It should also be noted that hand-crafted
684 # links having 'history' as an action and no pathname or hash
685 # set will fail, but that happens regardless of PATH_INFO.
686 $input_params{'action'} ||= "shortlog";
687 if (grep { $_ eq $input_params{'action'} } @wants_base) {
688 $input_params{'hash_base'} ||= $refname;
689 } else {
690 $input_params{'hash'} ||= $refname;
694 # next, handle the 'parent' part, if present
695 if (defined $parentrefname) {
696 # a missing pathspec defaults to the 'current' filename, allowing e.g.
697 # someproject/blobdiff/oldrev..newrev:/filename
698 if ($parentpathname) {
699 $parentpathname =~ s,^/+,,;
700 $parentpathname =~ s,/$,,;
701 $input_params{'file_parent'} ||= $parentpathname;
702 } else {
703 $input_params{'file_parent'} ||= $input_params{'file_name'};
705 # we assume that hash_parent_base is wanted if a path was specified,
706 # or if the action wants hash_base instead of hash
707 if (defined $input_params{'file_parent'} ||
708 grep { $_ eq $input_params{'action'} } @wants_base) {
709 $input_params{'hash_parent_base'} ||= $parentrefname;
710 } else {
711 $input_params{'hash_parent'} ||= $parentrefname;
715 # for the snapshot action, we allow URLs in the form
716 # $project/snapshot/$hash.ext
717 # where .ext determines the snapshot and gets removed from the
718 # passed $refname to provide the $hash.
720 # To be able to tell that $refname includes the format extension, we
721 # require the following two conditions to be satisfied:
722 # - the hash input parameter MUST have been set from the $refname part
723 # of the URL (i.e. they must be equal)
724 # - the snapshot format MUST NOT have been defined already (e.g. from
725 # CGI parameter sf)
726 # It's also useless to try any matching unless $refname has a dot,
727 # so we check for that too
728 if (defined $input_params{'action'} &&
729 $input_params{'action'} eq 'snapshot' &&
730 defined $refname && index($refname, '.') != -1 &&
731 $refname eq $input_params{'hash'} &&
732 !defined $input_params{'snapshot_format'}) {
733 # We loop over the known snapshot formats, checking for
734 # extensions. Allowed extensions are both the defined suffix
735 # (which includes the initial dot already) and the snapshot
736 # format key itself, with a prepended dot
737 while (my ($fmt, $opt) = each %known_snapshot_formats) {
738 my $hash = $refname;
739 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
740 next;
742 my $sfx = $1;
743 # a valid suffix was found, so set the snapshot format
744 # and reset the hash parameter
745 $input_params{'snapshot_format'} = $fmt;
746 $input_params{'hash'} = $hash;
747 # we also set the format suffix to the one requested
748 # in the URL: this way a request for e.g. .tgz returns
749 # a .tgz instead of a .tar.gz
750 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
751 last;
755 evaluate_path_info();
757 our $action = $input_params{'action'};
758 if (defined $action) {
759 if (!validate_action($action)) {
760 die_error(400, "Invalid action parameter");
764 # parameters which are pathnames
765 our $project = $input_params{'project'};
766 if (defined $project) {
767 if (!validate_project($project)) {
768 undef $project;
769 die_error(404, "No such project");
773 our $file_name = $input_params{'file_name'};
774 if (defined $file_name) {
775 if (!validate_pathname($file_name)) {
776 die_error(400, "Invalid file parameter");
780 our $file_parent = $input_params{'file_parent'};
781 if (defined $file_parent) {
782 if (!validate_pathname($file_parent)) {
783 die_error(400, "Invalid file parent parameter");
787 # parameters which are refnames
788 our $hash = $input_params{'hash'};
789 if (defined $hash) {
790 if (!validate_refname($hash)) {
791 die_error(400, "Invalid hash parameter");
795 our $hash_parent = $input_params{'hash_parent'};
796 if (defined $hash_parent) {
797 if (!validate_refname($hash_parent)) {
798 die_error(400, "Invalid hash parent parameter");
802 our $hash_base = $input_params{'hash_base'};
803 if (defined $hash_base) {
804 if (!validate_refname($hash_base)) {
805 die_error(400, "Invalid hash base parameter");
809 our @extra_options = @{$input_params{'extra_options'}};
810 # @extra_options is always defined, since it can only be (currently) set from
811 # CGI, and $cgi->param() returns the empty array in array context if the param
812 # is not set
813 foreach my $opt (@extra_options) {
814 if (not exists $allowed_options{$opt}) {
815 die_error(400, "Invalid option parameter");
817 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
818 die_error(400, "Invalid option parameter for this action");
822 our $hash_parent_base = $input_params{'hash_parent_base'};
823 if (defined $hash_parent_base) {
824 if (!validate_refname($hash_parent_base)) {
825 die_error(400, "Invalid hash parent base parameter");
829 # other parameters
830 our $page = $input_params{'page'};
831 if (defined $page) {
832 if ($page =~ m/[^0-9]/) {
833 die_error(400, "Invalid page parameter");
837 our $searchtype = $input_params{'searchtype'};
838 if (defined $searchtype) {
839 if ($searchtype =~ m/[^a-z]/) {
840 die_error(400, "Invalid searchtype parameter");
844 our $search_use_regexp = $input_params{'search_use_regexp'};
846 our $searchtext = $input_params{'searchtext'};
847 our $search_regexp;
848 if (defined $searchtext) {
849 if (length($searchtext) < 2) {
850 die_error(403, "At least two characters are required for search parameter");
852 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
855 # path to the current git repository
856 our $git_dir;
857 $git_dir = "$projectroot/$project" if $project;
859 # list of supported snapshot formats
860 our @snapshot_fmts = gitweb_get_feature('snapshot');
861 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
863 # check that the avatar feature is set to a known provider name,
864 # and for each provider check if the dependencies are satisfied.
865 # if the provider name is invalid or the dependencies are not met,
866 # reset $git_avatar to the empty string.
867 our ($git_avatar) = gitweb_get_feature('avatar');
868 if ($git_avatar eq 'gravatar') {
869 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
870 } elsif ($git_avatar eq 'picon') {
871 # no dependencies
872 } else {
873 $git_avatar = '';
876 # dispatch
877 if (!defined $action) {
878 if (defined $hash) {
879 $action = git_get_type($hash);
880 } elsif (defined $hash_base && defined $file_name) {
881 $action = git_get_type("$hash_base:$file_name");
882 } elsif (defined $project) {
883 $action = 'summary';
884 } else {
885 $action = 'project_list';
888 if (!defined($actions{$action})) {
889 die_error(400, "Unknown action");
891 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
892 !$project) {
893 die_error(400, "Project needed");
895 $actions{$action}->();
896 exit;
898 ## ======================================================================
899 ## action links
901 sub href {
902 my %params = @_;
903 # default is to use -absolute url() i.e. $my_uri
904 my $href = $params{-full} ? $my_url : $my_uri;
906 $params{'project'} = $project unless exists $params{'project'};
908 if ($params{-replay}) {
909 while (my ($name, $symbol) = each %cgi_param_mapping) {
910 if (!exists $params{$name}) {
911 $params{$name} = $input_params{$name};
916 my $use_pathinfo = gitweb_check_feature('pathinfo');
917 if ($use_pathinfo and defined $params{'project'}) {
918 # try to put as many parameters as possible in PATH_INFO:
919 # - project name
920 # - action
921 # - hash_parent or hash_parent_base:/file_parent
922 # - hash or hash_base:/filename
923 # - the snapshot_format as an appropriate suffix
925 # When the script is the root DirectoryIndex for the domain,
926 # $href here would be something like http://gitweb.example.com/
927 # Thus, we strip any trailing / from $href, to spare us double
928 # slashes in the final URL
929 $href =~ s,/$,,;
931 # Then add the project name, if present
932 $href .= "/".esc_url($params{'project'});
933 delete $params{'project'};
935 # since we destructively absorb parameters, we keep this
936 # boolean that remembers if we're handling a snapshot
937 my $is_snapshot = $params{'action'} eq 'snapshot';
939 # Summary just uses the project path URL, any other action is
940 # added to the URL
941 if (defined $params{'action'}) {
942 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
943 delete $params{'action'};
946 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
947 # stripping nonexistent or useless pieces
948 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
949 || $params{'hash_parent'} || $params{'hash'});
950 if (defined $params{'hash_base'}) {
951 if (defined $params{'hash_parent_base'}) {
952 $href .= esc_url($params{'hash_parent_base'});
953 # skip the file_parent if it's the same as the file_name
954 if (defined $params{'file_parent'}) {
955 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
956 delete $params{'file_parent'};
957 } elsif ($params{'file_parent'} !~ /\.\./) {
958 $href .= ":/".esc_url($params{'file_parent'});
959 delete $params{'file_parent'};
962 $href .= "..";
963 delete $params{'hash_parent'};
964 delete $params{'hash_parent_base'};
965 } elsif (defined $params{'hash_parent'}) {
966 $href .= esc_url($params{'hash_parent'}). "..";
967 delete $params{'hash_parent'};
970 $href .= esc_url($params{'hash_base'});
971 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
972 $href .= ":/".esc_url($params{'file_name'});
973 delete $params{'file_name'};
975 delete $params{'hash'};
976 delete $params{'hash_base'};
977 } elsif (defined $params{'hash'}) {
978 $href .= esc_url($params{'hash'});
979 delete $params{'hash'};
982 # If the action was a snapshot, we can absorb the
983 # snapshot_format parameter too
984 if ($is_snapshot) {
985 my $fmt = $params{'snapshot_format'};
986 # snapshot_format should always be defined when href()
987 # is called, but just in case some code forgets, we
988 # fall back to the default
989 $fmt ||= $snapshot_fmts[0];
990 $href .= $known_snapshot_formats{$fmt}{'suffix'};
991 delete $params{'snapshot_format'};
995 # now encode the parameters explicitly
996 my @result = ();
997 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
998 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
999 if (defined $params{$name}) {
1000 if (ref($params{$name}) eq "ARRAY") {
1001 foreach my $par (@{$params{$name}}) {
1002 push @result, $symbol . "=" . esc_param($par);
1004 } else {
1005 push @result, $symbol . "=" . esc_param($params{$name});
1009 $href .= "?" . join(';', @result) if scalar @result;
1011 return $href;
1015 ## ======================================================================
1016 ## validation, quoting/unquoting and escaping
1018 sub validate_action {
1019 my $input = shift || return undef;
1020 return undef unless exists $actions{$input};
1021 return $input;
1024 sub validate_project {
1025 my $input = shift || return undef;
1026 if (!validate_pathname($input) ||
1027 !(-d "$projectroot/$input") ||
1028 !check_export_ok("$projectroot/$input") ||
1029 ($strict_export && !project_in_list($input))) {
1030 return undef;
1031 } else {
1032 return $input;
1036 sub validate_pathname {
1037 my $input = shift || return undef;
1039 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1040 # at the beginning, at the end, and between slashes.
1041 # also this catches doubled slashes
1042 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1043 return undef;
1045 # no null characters
1046 if ($input =~ m!\0!) {
1047 return undef;
1049 return $input;
1052 sub validate_refname {
1053 my $input = shift || return undef;
1055 # textual hashes are O.K.
1056 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1057 return $input;
1059 # it must be correct pathname
1060 $input = validate_pathname($input)
1061 or return undef;
1062 # restrictions on ref name according to git-check-ref-format
1063 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1064 return undef;
1066 return $input;
1069 # decode sequences of octets in utf8 into Perl's internal form,
1070 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1071 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1072 sub to_utf8 {
1073 my $str = shift;
1074 if (utf8::valid($str)) {
1075 utf8::decode($str);
1076 return $str;
1077 } else {
1078 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1082 # quote unsafe chars, but keep the slash, even when it's not
1083 # correct, but quoted slashes look too horrible in bookmarks
1084 sub esc_param {
1085 my $str = shift;
1086 $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
1087 $str =~ s/\+/%2B/g;
1088 $str =~ s/ /\+/g;
1089 return $str;
1092 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1093 sub esc_url {
1094 my $str = shift;
1095 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1096 $str =~ s/\+/%2B/g;
1097 $str =~ s/ /\+/g;
1098 return $str;
1101 # replace invalid utf8 character with SUBSTITUTION sequence
1102 sub esc_html {
1103 my $str = shift;
1104 my %opts = @_;
1106 $str = to_utf8($str);
1107 $str = $cgi->escapeHTML($str);
1108 if ($opts{'-nbsp'}) {
1109 $str =~ s/ /&nbsp;/g;
1111 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1112 return $str;
1115 # quote control characters and escape filename to HTML
1116 sub esc_path {
1117 my $str = shift;
1118 my %opts = @_;
1120 $str = to_utf8($str);
1121 $str = $cgi->escapeHTML($str);
1122 if ($opts{'-nbsp'}) {
1123 $str =~ s/ /&nbsp;/g;
1125 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1126 return $str;
1129 # Make control characters "printable", using character escape codes (CEC)
1130 sub quot_cec {
1131 my $cntrl = shift;
1132 my %opts = @_;
1133 my %es = ( # character escape codes, aka escape sequences
1134 "\t" => '\t', # tab (HT)
1135 "\n" => '\n', # line feed (LF)
1136 "\r" => '\r', # carrige return (CR)
1137 "\f" => '\f', # form feed (FF)
1138 "\b" => '\b', # backspace (BS)
1139 "\a" => '\a', # alarm (bell) (BEL)
1140 "\e" => '\e', # escape (ESC)
1141 "\013" => '\v', # vertical tab (VT)
1142 "\000" => '\0', # nul character (NUL)
1144 my $chr = ( (exists $es{$cntrl})
1145 ? $es{$cntrl}
1146 : sprintf('\%2x', ord($cntrl)) );
1147 if ($opts{-nohtml}) {
1148 return $chr;
1149 } else {
1150 return "<span class=\"cntrl\">$chr</span>";
1154 # Alternatively use unicode control pictures codepoints,
1155 # Unicode "printable representation" (PR)
1156 sub quot_upr {
1157 my $cntrl = shift;
1158 my %opts = @_;
1160 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1161 if ($opts{-nohtml}) {
1162 return $chr;
1163 } else {
1164 return "<span class=\"cntrl\">$chr</span>";
1168 # git may return quoted and escaped filenames
1169 sub unquote {
1170 my $str = shift;
1172 sub unq {
1173 my $seq = shift;
1174 my %es = ( # character escape codes, aka escape sequences
1175 't' => "\t", # tab (HT, TAB)
1176 'n' => "\n", # newline (NL)
1177 'r' => "\r", # return (CR)
1178 'f' => "\f", # form feed (FF)
1179 'b' => "\b", # backspace (BS)
1180 'a' => "\a", # alarm (bell) (BEL)
1181 'e' => "\e", # escape (ESC)
1182 'v' => "\013", # vertical tab (VT)
1185 if ($seq =~ m/^[0-7]{1,3}$/) {
1186 # octal char sequence
1187 return chr(oct($seq));
1188 } elsif (exists $es{$seq}) {
1189 # C escape sequence, aka character escape code
1190 return $es{$seq};
1192 # quoted ordinary character
1193 return $seq;
1196 if ($str =~ m/^"(.*)"$/) {
1197 # needs unquoting
1198 $str = $1;
1199 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1201 return $str;
1204 # escape tabs (convert tabs to spaces)
1205 sub untabify {
1206 my $line = shift;
1208 while ((my $pos = index($line, "\t")) != -1) {
1209 if (my $count = (8 - ($pos % 8))) {
1210 my $spaces = ' ' x $count;
1211 $line =~ s/\t/$spaces/;
1215 return $line;
1218 sub project_in_list {
1219 my $project = shift;
1220 my @list = git_get_projects_list();
1221 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1224 ## ----------------------------------------------------------------------
1225 ## HTML aware string manipulation
1227 # Try to chop given string on a word boundary between position
1228 # $len and $len+$add_len. If there is no word boundary there,
1229 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1230 # (marking chopped part) would be longer than given string.
1231 sub chop_str {
1232 my $str = shift;
1233 my $len = shift;
1234 my $add_len = shift || 10;
1235 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1237 # Make sure perl knows it is utf8 encoded so we don't
1238 # cut in the middle of a utf8 multibyte char.
1239 $str = to_utf8($str);
1241 # allow only $len chars, but don't cut a word if it would fit in $add_len
1242 # if it doesn't fit, cut it if it's still longer than the dots we would add
1243 # remove chopped character entities entirely
1245 # when chopping in the middle, distribute $len into left and right part
1246 # return early if chopping wouldn't make string shorter
1247 if ($where eq 'center') {
1248 return $str if ($len + 5 >= length($str)); # filler is length 5
1249 $len = int($len/2);
1250 } else {
1251 return $str if ($len + 4 >= length($str)); # filler is length 4
1254 # regexps: ending and beginning with word part up to $add_len
1255 my $endre = qr/.{$len}\w{0,$add_len}/;
1256 my $begre = qr/\w{0,$add_len}.{$len}/;
1258 if ($where eq 'left') {
1259 $str =~ m/^(.*?)($begre)$/;
1260 my ($lead, $body) = ($1, $2);
1261 if (length($lead) > 4) {
1262 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1263 $lead = " ...";
1265 return "$lead$body";
1267 } elsif ($where eq 'center') {
1268 $str =~ m/^($endre)(.*)$/;
1269 my ($left, $str) = ($1, $2);
1270 $str =~ m/^(.*?)($begre)$/;
1271 my ($mid, $right) = ($1, $2);
1272 if (length($mid) > 5) {
1273 $left =~ s/&[^;]*$//;
1274 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1275 $mid = " ... ";
1277 return "$left$mid$right";
1279 } else {
1280 $str =~ m/^($endre)(.*)$/;
1281 my $body = $1;
1282 my $tail = $2;
1283 if (length($tail) > 4) {
1284 $body =~ s/&[^;]*$//;
1285 $tail = "... ";
1287 return "$body$tail";
1291 # takes the same arguments as chop_str, but also wraps a <span> around the
1292 # result with a title attribute if it does get chopped. Additionally, the
1293 # string is HTML-escaped.
1294 sub chop_and_escape_str {
1295 my ($str) = @_;
1297 my $chopped = chop_str(@_);
1298 if ($chopped eq $str) {
1299 return esc_html($chopped);
1300 } else {
1301 $str =~ s/[[:cntrl:]]/?/g;
1302 return $cgi->span({-title=>$str}, esc_html($chopped));
1306 ## ----------------------------------------------------------------------
1307 ## functions returning short strings
1309 # CSS class for given age value (in seconds)
1310 sub age_class {
1311 my $age = shift;
1313 if (!defined $age) {
1314 return "noage";
1315 } elsif ($age < 60*60*2) {
1316 return "age0";
1317 } elsif ($age < 60*60*24*2) {
1318 return "age1";
1319 } else {
1320 return "age2";
1324 # convert age in seconds to "nn units ago" string
1325 sub age_string {
1326 my $age = shift;
1327 my $age_str;
1329 if ($age > 60*60*24*365*2) {
1330 $age_str = (int $age/60/60/24/365);
1331 $age_str .= " years ago";
1332 } elsif ($age > 60*60*24*(365/12)*2) {
1333 $age_str = int $age/60/60/24/(365/12);
1334 $age_str .= " months ago";
1335 } elsif ($age > 60*60*24*7*2) {
1336 $age_str = int $age/60/60/24/7;
1337 $age_str .= " weeks ago";
1338 } elsif ($age > 60*60*24*2) {
1339 $age_str = int $age/60/60/24;
1340 $age_str .= " days ago";
1341 } elsif ($age > 60*60*2) {
1342 $age_str = int $age/60/60;
1343 $age_str .= " hours ago";
1344 } elsif ($age > 60*2) {
1345 $age_str = int $age/60;
1346 $age_str .= " min ago";
1347 } elsif ($age > 2) {
1348 $age_str = int $age;
1349 $age_str .= " sec ago";
1350 } else {
1351 $age_str .= " right now";
1353 return $age_str;
1356 use constant {
1357 S_IFINVALID => 0030000,
1358 S_IFGITLINK => 0160000,
1361 # submodule/subproject, a commit object reference
1362 sub S_ISGITLINK {
1363 my $mode = shift;
1365 return (($mode & S_IFMT) == S_IFGITLINK)
1368 # convert file mode in octal to symbolic file mode string
1369 sub mode_str {
1370 my $mode = oct shift;
1372 if (S_ISGITLINK($mode)) {
1373 return 'm---------';
1374 } elsif (S_ISDIR($mode & S_IFMT)) {
1375 return 'drwxr-xr-x';
1376 } elsif (S_ISLNK($mode)) {
1377 return 'lrwxrwxrwx';
1378 } elsif (S_ISREG($mode)) {
1379 # git cares only about the executable bit
1380 if ($mode & S_IXUSR) {
1381 return '-rwxr-xr-x';
1382 } else {
1383 return '-rw-r--r--';
1385 } else {
1386 return '----------';
1390 # convert file mode in octal to file type string
1391 sub file_type {
1392 my $mode = shift;
1394 if ($mode !~ m/^[0-7]+$/) {
1395 return $mode;
1396 } else {
1397 $mode = oct $mode;
1400 if (S_ISGITLINK($mode)) {
1401 return "submodule";
1402 } elsif (S_ISDIR($mode & S_IFMT)) {
1403 return "directory";
1404 } elsif (S_ISLNK($mode)) {
1405 return "symlink";
1406 } elsif (S_ISREG($mode)) {
1407 return "file";
1408 } else {
1409 return "unknown";
1413 # convert file mode in octal to file type description string
1414 sub file_type_long {
1415 my $mode = shift;
1417 if ($mode !~ m/^[0-7]+$/) {
1418 return $mode;
1419 } else {
1420 $mode = oct $mode;
1423 if (S_ISGITLINK($mode)) {
1424 return "submodule";
1425 } elsif (S_ISDIR($mode & S_IFMT)) {
1426 return "directory";
1427 } elsif (S_ISLNK($mode)) {
1428 return "symlink";
1429 } elsif (S_ISREG($mode)) {
1430 if ($mode & S_IXUSR) {
1431 return "executable";
1432 } else {
1433 return "file";
1435 } else {
1436 return "unknown";
1441 ## ----------------------------------------------------------------------
1442 ## functions returning short HTML fragments, or transforming HTML fragments
1443 ## which don't belong to other sections
1445 # format line of commit message.
1446 sub format_log_line_html {
1447 my $line = shift;
1449 $line = esc_html($line, -nbsp=>1);
1450 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1451 $cgi->a({-href => href(action=>"object", hash=>$1),
1452 -class => "text"}, $1);
1453 }eg;
1455 return $line;
1458 # format marker of refs pointing to given object
1460 # the destination action is chosen based on object type and current context:
1461 # - for annotated tags, we choose the tag view unless it's the current view
1462 # already, in which case we go to shortlog view
1463 # - for other refs, we keep the current view if we're in history, shortlog or
1464 # log view, and select shortlog otherwise
1465 sub format_ref_marker {
1466 my ($refs, $id) = @_;
1467 my $markers = '';
1469 if (defined $refs->{$id}) {
1470 foreach my $ref (@{$refs->{$id}}) {
1471 # this code exploits the fact that non-lightweight tags are the
1472 # only indirect objects, and that they are the only objects for which
1473 # we want to use tag instead of shortlog as action
1474 my ($type, $name) = qw();
1475 my $indirect = ($ref =~ s/\^\{\}$//);
1476 # e.g. tags/v2.6.11 or heads/next
1477 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1478 $type = $1;
1479 $name = $2;
1480 } else {
1481 $type = "ref";
1482 $name = $ref;
1485 my $class = $type;
1486 $class .= " indirect" if $indirect;
1488 my $dest_action = "shortlog";
1490 if ($indirect) {
1491 $dest_action = "tag" unless $action eq "tag";
1492 } elsif ($action =~ /^(history|(short)?log)$/) {
1493 $dest_action = $action;
1496 my $dest = "";
1497 $dest .= "refs/" unless $ref =~ m!^refs/!;
1498 $dest .= $ref;
1500 my $link = $cgi->a({
1501 -href => href(
1502 action=>$dest_action,
1503 hash=>$dest
1504 )}, $name);
1506 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1507 $link . "</span>";
1511 if ($markers) {
1512 return ' <span class="refs">'. $markers . '</span>';
1513 } else {
1514 return "";
1518 # format, perhaps shortened and with markers, title line
1519 sub format_subject_html {
1520 my ($long, $short, $href, $extra) = @_;
1521 $extra = '' unless defined($extra);
1523 if (length($short) < length($long)) {
1524 $long =~ s/[[:cntrl:]]/?/g;
1525 return $cgi->a({-href => $href, -class => "list subject",
1526 -title => to_utf8($long)},
1527 esc_html($short)) . $extra;
1528 } else {
1529 return $cgi->a({-href => $href, -class => "list subject"},
1530 esc_html($long)) . $extra;
1534 # Rather than recomputing the url for an email multiple times, we cache it
1535 # after the first hit. This gives a visible benefit in views where the avatar
1536 # for the same email is used repeatedly (e.g. shortlog).
1537 # The cache is shared by all avatar engines (currently gravatar only), which
1538 # are free to use it as preferred. Since only one avatar engine is used for any
1539 # given page, there's no risk for cache conflicts.
1540 our %avatar_cache = ();
1542 # Compute the picon url for a given email, by using the picon search service over at
1543 # http://www.cs.indiana.edu/picons/search.html
1544 sub picon_url {
1545 my $email = lc shift;
1546 if (!$avatar_cache{$email}) {
1547 my ($user, $domain) = split('@', $email);
1548 $avatar_cache{$email} =
1549 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1550 "$domain/$user/" .
1551 "users+domains+unknown/up/single";
1553 return $avatar_cache{$email};
1556 # Compute the gravatar url for a given email, if it's not in the cache already.
1557 # Gravatar stores only the part of the URL before the size, since that's the
1558 # one computationally more expensive. This also allows reuse of the cache for
1559 # different sizes (for this particular engine).
1560 sub gravatar_url {
1561 my $email = lc shift;
1562 my $size = shift;
1563 $avatar_cache{$email} ||=
1564 "http://www.gravatar.com/avatar/" .
1565 Digest::MD5::md5_hex($email) . "?s=";
1566 return $avatar_cache{$email} . $size;
1569 # Insert an avatar for the given $email at the given $size if the feature
1570 # is enabled.
1571 sub git_get_avatar {
1572 my ($email, %opts) = @_;
1573 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1574 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1575 $opts{-size} ||= 'default';
1576 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1577 my $url = "";
1578 if ($git_avatar eq 'gravatar') {
1579 $url = gravatar_url($email, $size);
1580 } elsif ($git_avatar eq 'picon') {
1581 $url = picon_url($email);
1583 # Other providers can be added by extending the if chain, defining $url
1584 # as needed. If no variant puts something in $url, we assume avatars
1585 # are completely disabled/unavailable.
1586 if ($url) {
1587 return $pre_white .
1588 "<img width=\"$size\" " .
1589 "class=\"avatar\" " .
1590 "src=\"$url\" " .
1591 "alt=\"\" " .
1592 "/>" . $post_white;
1593 } else {
1594 return "";
1598 # format the author name of the given commit with the given tag
1599 # the author name is chopped and escaped according to the other
1600 # optional parameters (see chop_str).
1601 sub format_author_html {
1602 my $tag = shift;
1603 my $co = shift;
1604 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1605 return "<$tag class=\"author\">" .
1606 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1607 $author . "</$tag>";
1610 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1611 sub format_git_diff_header_line {
1612 my $line = shift;
1613 my $diffinfo = shift;
1614 my ($from, $to) = @_;
1616 if ($diffinfo->{'nparents'}) {
1617 # combined diff
1618 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1619 if ($to->{'href'}) {
1620 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1621 esc_path($to->{'file'}));
1622 } else { # file was deleted (no href)
1623 $line .= esc_path($to->{'file'});
1625 } else {
1626 # "ordinary" diff
1627 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1628 if ($from->{'href'}) {
1629 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1630 'a/' . esc_path($from->{'file'}));
1631 } else { # file was added (no href)
1632 $line .= 'a/' . esc_path($from->{'file'});
1634 $line .= ' ';
1635 if ($to->{'href'}) {
1636 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1637 'b/' . esc_path($to->{'file'}));
1638 } else { # file was deleted
1639 $line .= 'b/' . esc_path($to->{'file'});
1643 return "<div class=\"diff header\">$line</div>\n";
1646 # format extended diff header line, before patch itself
1647 sub format_extended_diff_header_line {
1648 my $line = shift;
1649 my $diffinfo = shift;
1650 my ($from, $to) = @_;
1652 # match <path>
1653 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1654 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1655 esc_path($from->{'file'}));
1657 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1658 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1659 esc_path($to->{'file'}));
1661 # match single <mode>
1662 if ($line =~ m/\s(\d{6})$/) {
1663 $line .= '<span class="info"> (' .
1664 file_type_long($1) .
1665 ')</span>';
1667 # match <hash>
1668 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1669 # can match only for combined diff
1670 $line = 'index ';
1671 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1672 if ($from->{'href'}[$i]) {
1673 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1674 -class=>"hash"},
1675 substr($diffinfo->{'from_id'}[$i],0,7));
1676 } else {
1677 $line .= '0' x 7;
1679 # separator
1680 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1682 $line .= '..';
1683 if ($to->{'href'}) {
1684 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1685 substr($diffinfo->{'to_id'},0,7));
1686 } else {
1687 $line .= '0' x 7;
1690 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1691 # can match only for ordinary diff
1692 my ($from_link, $to_link);
1693 if ($from->{'href'}) {
1694 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1695 substr($diffinfo->{'from_id'},0,7));
1696 } else {
1697 $from_link = '0' x 7;
1699 if ($to->{'href'}) {
1700 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1701 substr($diffinfo->{'to_id'},0,7));
1702 } else {
1703 $to_link = '0' x 7;
1705 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1706 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1709 return $line . "<br/>\n";
1712 # format from-file/to-file diff header
1713 sub format_diff_from_to_header {
1714 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1715 my $line;
1716 my $result = '';
1718 $line = $from_line;
1719 #assert($line =~ m/^---/) if DEBUG;
1720 # no extra formatting for "^--- /dev/null"
1721 if (! $diffinfo->{'nparents'}) {
1722 # ordinary (single parent) diff
1723 if ($line =~ m!^--- "?a/!) {
1724 if ($from->{'href'}) {
1725 $line = '--- a/' .
1726 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1727 esc_path($from->{'file'}));
1728 } else {
1729 $line = '--- a/' .
1730 esc_path($from->{'file'});
1733 $result .= qq!<div class="diff from_file">$line</div>\n!;
1735 } else {
1736 # combined diff (merge commit)
1737 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1738 if ($from->{'href'}[$i]) {
1739 $line = '--- ' .
1740 $cgi->a({-href=>href(action=>"blobdiff",
1741 hash_parent=>$diffinfo->{'from_id'}[$i],
1742 hash_parent_base=>$parents[$i],
1743 file_parent=>$from->{'file'}[$i],
1744 hash=>$diffinfo->{'to_id'},
1745 hash_base=>$hash,
1746 file_name=>$to->{'file'}),
1747 -class=>"path",
1748 -title=>"diff" . ($i+1)},
1749 $i+1) .
1750 '/' .
1751 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1752 esc_path($from->{'file'}[$i]));
1753 } else {
1754 $line = '--- /dev/null';
1756 $result .= qq!<div class="diff from_file">$line</div>\n!;
1760 $line = $to_line;
1761 #assert($line =~ m/^\+\+\+/) if DEBUG;
1762 # no extra formatting for "^+++ /dev/null"
1763 if ($line =~ m!^\+\+\+ "?b/!) {
1764 if ($to->{'href'}) {
1765 $line = '+++ b/' .
1766 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1767 esc_path($to->{'file'}));
1768 } else {
1769 $line = '+++ b/' .
1770 esc_path($to->{'file'});
1773 $result .= qq!<div class="diff to_file">$line</div>\n!;
1775 return $result;
1778 # create note for patch simplified by combined diff
1779 sub format_diff_cc_simplified {
1780 my ($diffinfo, @parents) = @_;
1781 my $result = '';
1783 $result .= "<div class=\"diff header\">" .
1784 "diff --cc ";
1785 if (!is_deleted($diffinfo)) {
1786 $result .= $cgi->a({-href => href(action=>"blob",
1787 hash_base=>$hash,
1788 hash=>$diffinfo->{'to_id'},
1789 file_name=>$diffinfo->{'to_file'}),
1790 -class => "path"},
1791 esc_path($diffinfo->{'to_file'}));
1792 } else {
1793 $result .= esc_path($diffinfo->{'to_file'});
1795 $result .= "</div>\n" . # class="diff header"
1796 "<div class=\"diff nodifferences\">" .
1797 "Simple merge" .
1798 "</div>\n"; # class="diff nodifferences"
1800 return $result;
1803 # format patch (diff) line (not to be used for diff headers)
1804 sub format_diff_line {
1805 my $line = shift;
1806 my ($from, $to) = @_;
1807 my $diff_class = "";
1809 chomp $line;
1811 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1812 # combined diff
1813 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1814 if ($line =~ m/^\@{3}/) {
1815 $diff_class = " chunk_header";
1816 } elsif ($line =~ m/^\\/) {
1817 $diff_class = " incomplete";
1818 } elsif ($prefix =~ tr/+/+/) {
1819 $diff_class = " add";
1820 } elsif ($prefix =~ tr/-/-/) {
1821 $diff_class = " rem";
1823 } else {
1824 # assume ordinary diff
1825 my $char = substr($line, 0, 1);
1826 if ($char eq '+') {
1827 $diff_class = " add";
1828 } elsif ($char eq '-') {
1829 $diff_class = " rem";
1830 } elsif ($char eq '@') {
1831 $diff_class = " chunk_header";
1832 } elsif ($char eq "\\") {
1833 $diff_class = " incomplete";
1836 $line = untabify($line);
1837 if ($from && $to && $line =~ m/^\@{2} /) {
1838 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1839 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1841 $from_lines = 0 unless defined $from_lines;
1842 $to_lines = 0 unless defined $to_lines;
1844 if ($from->{'href'}) {
1845 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1846 -class=>"list"}, $from_text);
1848 if ($to->{'href'}) {
1849 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1850 -class=>"list"}, $to_text);
1852 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1853 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1854 return "<div class=\"diff$diff_class\">$line</div>\n";
1855 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1856 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1857 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1859 @from_text = split(' ', $ranges);
1860 for (my $i = 0; $i < @from_text; ++$i) {
1861 ($from_start[$i], $from_nlines[$i]) =
1862 (split(',', substr($from_text[$i], 1)), 0);
1865 $to_text = pop @from_text;
1866 $to_start = pop @from_start;
1867 $to_nlines = pop @from_nlines;
1869 $line = "<span class=\"chunk_info\">$prefix ";
1870 for (my $i = 0; $i < @from_text; ++$i) {
1871 if ($from->{'href'}[$i]) {
1872 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1873 -class=>"list"}, $from_text[$i]);
1874 } else {
1875 $line .= $from_text[$i];
1877 $line .= " ";
1879 if ($to->{'href'}) {
1880 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1881 -class=>"list"}, $to_text);
1882 } else {
1883 $line .= $to_text;
1885 $line .= " $prefix</span>" .
1886 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1887 return "<div class=\"diff$diff_class\">$line</div>\n";
1889 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1892 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1893 # linked. Pass the hash of the tree/commit to snapshot.
1894 sub format_snapshot_links {
1895 my ($hash) = @_;
1896 my $num_fmts = @snapshot_fmts;
1897 if ($num_fmts > 1) {
1898 # A parenthesized list of links bearing format names.
1899 # e.g. "snapshot (_tar.gz_ _zip_)"
1900 return "snapshot (" . join(' ', map
1901 $cgi->a({
1902 -href => href(
1903 action=>"snapshot",
1904 hash=>$hash,
1905 snapshot_format=>$_
1907 }, $known_snapshot_formats{$_}{'display'})
1908 , @snapshot_fmts) . ")";
1909 } elsif ($num_fmts == 1) {
1910 # A single "snapshot" link whose tooltip bears the format name.
1911 # i.e. "_snapshot_"
1912 my ($fmt) = @snapshot_fmts;
1913 return
1914 $cgi->a({
1915 -href => href(
1916 action=>"snapshot",
1917 hash=>$hash,
1918 snapshot_format=>$fmt
1920 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1921 }, "snapshot");
1922 } else { # $num_fmts == 0
1923 return undef;
1927 ## ......................................................................
1928 ## functions returning values to be passed, perhaps after some
1929 ## transformation, to other functions; e.g. returning arguments to href()
1931 # returns hash to be passed to href to generate gitweb URL
1932 # in -title key it returns description of link
1933 sub get_feed_info {
1934 my $format = shift || 'Atom';
1935 my %res = (action => lc($format));
1937 # feed links are possible only for project views
1938 return unless (defined $project);
1939 # some views should link to OPML, or to generic project feed,
1940 # or don't have specific feed yet (so they should use generic)
1941 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1943 my $branch;
1944 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1945 # from tag links; this also makes possible to detect branch links
1946 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1947 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1948 $branch = $1;
1950 # find log type for feed description (title)
1951 my $type = 'log';
1952 if (defined $file_name) {
1953 $type = "history of $file_name";
1954 $type .= "/" if ($action eq 'tree');
1955 $type .= " on '$branch'" if (defined $branch);
1956 } else {
1957 $type = "log of $branch" if (defined $branch);
1960 $res{-title} = $type;
1961 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
1962 $res{'file_name'} = $file_name;
1964 return %res;
1967 ## ----------------------------------------------------------------------
1968 ## git utility subroutines, invoking git commands
1970 # returns path to the core git executable and the --git-dir parameter as list
1971 sub git_cmd {
1972 return $GIT, '--git-dir='.$git_dir;
1975 # quote the given arguments for passing them to the shell
1976 # quote_command("command", "arg 1", "arg with ' and ! characters")
1977 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
1978 # Try to avoid using this function wherever possible.
1979 sub quote_command {
1980 return join(' ',
1981 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
1984 # get HEAD ref of given project as hash
1985 sub git_get_head_hash {
1986 return git_get_full_hash(shift, 'HEAD');
1989 sub git_get_full_hash {
1990 my $project = shift;
1991 my $hash = shift;
1992 my $o_git_dir = $git_dir;
1993 my $retval = undef;
1994 $git_dir = "$projectroot/$project";
1995 if (open my $fd, '-|', git_cmd(), 'rev-parse', '--verify', $hash) {
1996 $hash = <$fd>;
1997 close $fd;
1998 if (defined $hash && $hash =~ /^([0-9a-fA-F]{40})$/) {
1999 $retval = $1;
2002 if (defined $o_git_dir) {
2003 $git_dir = $o_git_dir;
2005 return $retval;
2008 # try and get a shorter hash id
2009 sub git_get_short_hash {
2010 my $project = shift;
2011 my $hash = shift;
2012 my $o_git_dir = $git_dir;
2013 my $retval = undef;
2014 $git_dir = "$projectroot/$project";
2015 if (open my $fd, '-|', git_cmd(), 'rev-parse', '--short=7', $hash) {
2016 $hash = <$fd>;
2017 close $fd;
2018 if (defined $hash && $hash =~ /^([0-9a-fA-F]{7,})$/) {
2019 $retval = $1;
2022 if (defined $o_git_dir) {
2023 $git_dir = $o_git_dir;
2025 return $retval;
2028 # get type of given object
2029 sub git_get_type {
2030 my $hash = shift;
2032 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2033 my $type = <$fd>;
2034 close $fd or return;
2035 chomp $type;
2036 return $type;
2039 # repository configuration
2040 our $config_file = '';
2041 our %config;
2043 # store multiple values for single key as anonymous array reference
2044 # single values stored directly in the hash, not as [ <value> ]
2045 sub hash_set_multi {
2046 my ($hash, $key, $value) = @_;
2048 if (!exists $hash->{$key}) {
2049 $hash->{$key} = $value;
2050 } elsif (!ref $hash->{$key}) {
2051 $hash->{$key} = [ $hash->{$key}, $value ];
2052 } else {
2053 push @{$hash->{$key}}, $value;
2057 # return hash of git project configuration
2058 # optionally limited to some section, e.g. 'gitweb'
2059 sub git_parse_project_config {
2060 my $section_regexp = shift;
2061 my %config;
2063 local $/ = "\0";
2065 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2066 or return;
2068 while (my $keyval = <$fh>) {
2069 chomp $keyval;
2070 my ($key, $value) = split(/\n/, $keyval, 2);
2072 hash_set_multi(\%config, $key, $value)
2073 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2075 close $fh;
2077 return %config;
2080 # convert config value to boolean: 'true' or 'false'
2081 # no value, number > 0, 'true' and 'yes' values are true
2082 # rest of values are treated as false (never as error)
2083 sub config_to_bool {
2084 my $val = shift;
2086 return 1 if !defined $val; # section.key
2088 # strip leading and trailing whitespace
2089 $val =~ s/^\s+//;
2090 $val =~ s/\s+$//;
2092 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2093 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2096 # convert config value to simple decimal number
2097 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2098 # to be multiplied by 1024, 1048576, or 1073741824
2099 sub config_to_int {
2100 my $val = shift;
2102 # strip leading and trailing whitespace
2103 $val =~ s/^\s+//;
2104 $val =~ s/\s+$//;
2106 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2107 $unit = lc($unit);
2108 # unknown unit is treated as 1
2109 return $num * ($unit eq 'g' ? 1073741824 :
2110 $unit eq 'm' ? 1048576 :
2111 $unit eq 'k' ? 1024 : 1);
2113 return $val;
2116 # convert config value to array reference, if needed
2117 sub config_to_multi {
2118 my $val = shift;
2120 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2123 sub git_get_project_config {
2124 my ($key, $type) = @_;
2126 # key sanity check
2127 return unless ($key);
2128 $key =~ s/^gitweb\.//;
2129 return if ($key =~ m/\W/);
2131 # type sanity check
2132 if (defined $type) {
2133 $type =~ s/^--//;
2134 $type = undef
2135 unless ($type eq 'bool' || $type eq 'int');
2138 # get config
2139 if (!defined $config_file ||
2140 $config_file ne "$git_dir/config") {
2141 %config = git_parse_project_config('gitweb');
2142 $config_file = "$git_dir/config";
2145 # check if config variable (key) exists
2146 return unless exists $config{"gitweb.$key"};
2148 # ensure given type
2149 if (!defined $type) {
2150 return $config{"gitweb.$key"};
2151 } elsif ($type eq 'bool') {
2152 # backward compatibility: 'git config --bool' returns true/false
2153 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2154 } elsif ($type eq 'int') {
2155 return config_to_int($config{"gitweb.$key"});
2157 return $config{"gitweb.$key"};
2160 # get hash of given path at given ref
2161 sub git_get_hash_by_path {
2162 my $base = shift;
2163 my $path = shift || return undef;
2164 my $type = shift;
2166 $path =~ s,/+$,,;
2168 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2169 or die_error(500, "Open git-ls-tree failed");
2170 my $line = <$fd>;
2171 close $fd or return undef;
2173 if (!defined $line) {
2174 # there is no tree or hash given by $path at $base
2175 return undef;
2178 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2179 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2180 if (defined $type && $type ne $2) {
2181 # type doesn't match
2182 return undef;
2184 return $3;
2187 # get path of entry with given hash at given tree-ish (ref)
2188 # used to get 'from' filename for combined diff (merge commit) for renames
2189 sub git_get_path_by_hash {
2190 my $base = shift || return;
2191 my $hash = shift || return;
2193 local $/ = "\0";
2195 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2196 or return undef;
2197 while (my $line = <$fd>) {
2198 chomp $line;
2200 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2201 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2202 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2203 close $fd;
2204 return $1;
2207 close $fd;
2208 return undef;
2211 ## ......................................................................
2212 ## git utility functions, directly accessing git repository
2214 sub git_get_project_description {
2215 my $path = shift;
2217 $git_dir = "$projectroot/$path";
2218 open my $fd, '<', "$git_dir/description"
2219 or return git_get_project_config('description');
2220 my $descr = <$fd>;
2221 close $fd;
2222 if (defined $descr) {
2223 chomp $descr;
2225 return $descr;
2228 sub git_get_project_ctags {
2229 my $path = shift;
2230 my $ctags = {};
2232 $git_dir = "$projectroot/$path";
2233 opendir my $dh, "$git_dir/ctags"
2234 or return $ctags;
2235 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2236 open my $ct, '<', $_ or next;
2237 my $val = <$ct>;
2238 chomp $val;
2239 close $ct;
2240 my $ctag = $_; $ctag =~ s#.*/##;
2241 $ctags->{$ctag} = $val;
2243 closedir $dh;
2244 $ctags;
2247 sub git_populate_project_tagcloud {
2248 my $ctags = shift;
2250 # First, merge different-cased tags; tags vote on casing
2251 my %ctags_lc;
2252 foreach (keys %$ctags) {
2253 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2254 if (not $ctags_lc{lc $_}->{topcount}
2255 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2256 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2257 $ctags_lc{lc $_}->{topname} = $_;
2261 my $cloud;
2262 if (eval { require HTML::TagCloud; 1; }) {
2263 $cloud = HTML::TagCloud->new;
2264 foreach (sort keys %ctags_lc) {
2265 # Pad the title with spaces so that the cloud looks
2266 # less crammed.
2267 my $title = $ctags_lc{$_}->{topname};
2268 $title =~ s/ /&nbsp;/g;
2269 $title =~ s/^/&nbsp;/g;
2270 $title =~ s/$/&nbsp;/g;
2271 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2273 } else {
2274 $cloud = \%ctags_lc;
2276 $cloud;
2279 sub git_show_project_tagcloud {
2280 my ($cloud, $count) = @_;
2281 print STDERR ref($cloud)."..\n";
2282 if (ref $cloud eq 'HTML::TagCloud') {
2283 return $cloud->html_and_css($count);
2284 } else {
2285 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2286 return '<p align="center">' . join (', ', map {
2287 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2288 } splice(@tags, 0, $count)) . '</p>';
2292 sub git_get_project_url_list {
2293 my $path = shift;
2295 $git_dir = "$projectroot/$path";
2296 open my $fd, '<', "$git_dir/cloneurl"
2297 or return wantarray ?
2298 @{ config_to_multi(git_get_project_config('url')) } :
2299 config_to_multi(git_get_project_config('url'));
2300 my @git_project_url_list = map { chomp; $_ } <$fd>;
2301 close $fd;
2303 return wantarray ? @git_project_url_list : \@git_project_url_list;
2306 sub git_get_projects_list {
2307 my ($filter) = @_;
2308 my @list;
2310 $filter ||= '';
2311 $filter =~ s/\.git$//;
2313 my $check_forks = gitweb_check_feature('forks');
2315 if (-d $projects_list) {
2316 # search in directory
2317 my $dir = $projects_list . ($filter ? "/$filter" : '');
2318 # remove the trailing "/"
2319 $dir =~ s!/+$!!;
2320 my $pfxlen = length("$dir");
2321 my $pfxdepth = ($dir =~ tr!/!!);
2323 File::Find::find({
2324 follow_fast => 1, # follow symbolic links
2325 follow_skip => 2, # ignore duplicates
2326 dangling_symlinks => 0, # ignore dangling symlinks, silently
2327 wanted => sub {
2328 # skip project-list toplevel, if we get it.
2329 return if (m!^[/.]$!);
2330 # only directories can be git repositories
2331 return unless (-d $_);
2332 # don't traverse too deep (Find is super slow on os x)
2333 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2334 $File::Find::prune = 1;
2335 return;
2338 my $subdir = substr($File::Find::name, $pfxlen + 1);
2339 # we check related file in $projectroot
2340 my $path = ($filter ? "$filter/" : '') . $subdir;
2341 if (check_export_ok("$projectroot/$path")) {
2342 push @list, { path => $path };
2343 $File::Find::prune = 1;
2346 }, "$dir");
2348 } elsif (-f $projects_list) {
2349 # read from file(url-encoded):
2350 # 'git%2Fgit.git Linus+Torvalds'
2351 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2352 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2353 my %paths;
2354 open my $fd, '<', $projects_list or return;
2355 PROJECT:
2356 while (my $line = <$fd>) {
2357 chomp $line;
2358 my ($path, $owner) = split ' ', $line;
2359 $path = unescape($path);
2360 $owner = unescape($owner);
2361 if (!defined $path) {
2362 next;
2364 if ($filter ne '') {
2365 # looking for forks;
2366 my $pfx = substr($path, 0, length($filter));
2367 if ($pfx ne $filter) {
2368 next PROJECT;
2370 my $sfx = substr($path, length($filter));
2371 if ($sfx !~ /^\/.*\.git$/) {
2372 next PROJECT;
2374 } elsif ($check_forks) {
2375 PATH:
2376 foreach my $filter (keys %paths) {
2377 # looking for forks;
2378 my $pfx = substr($path, 0, length($filter));
2379 if ($pfx ne $filter) {
2380 next PATH;
2382 my $sfx = substr($path, length($filter));
2383 if ($sfx !~ /^\/.*\.git$/) {
2384 next PATH;
2386 # is a fork, don't include it in
2387 # the list
2388 next PROJECT;
2391 if (check_export_ok("$projectroot/$path")) {
2392 my $pr = {
2393 path => $path,
2394 owner => to_utf8($owner),
2396 push @list, $pr;
2397 (my $forks_path = $path) =~ s/\.git$//;
2398 $paths{$forks_path}++;
2401 close $fd;
2403 return @list;
2406 our $gitweb_project_owner = undef;
2407 sub git_get_project_list_from_file {
2409 return if (defined $gitweb_project_owner);
2411 $gitweb_project_owner = {};
2412 # read from file (url-encoded):
2413 # 'git%2Fgit.git Linus+Torvalds'
2414 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2415 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2416 if (-f $projects_list) {
2417 open(my $fd, '<', $projects_list);
2418 while (my $line = <$fd>) {
2419 chomp $line;
2420 my ($pr, $ow) = split ' ', $line;
2421 $pr = unescape($pr);
2422 $ow = unescape($ow);
2423 $gitweb_project_owner->{$pr} = to_utf8($ow);
2425 close $fd;
2429 sub git_get_project_owner {
2430 my $project = shift;
2431 my $owner;
2433 return undef unless $project;
2434 $git_dir = "$projectroot/$project";
2436 if (!defined $gitweb_project_owner) {
2437 git_get_project_list_from_file();
2440 if (exists $gitweb_project_owner->{$project}) {
2441 $owner = $gitweb_project_owner->{$project};
2443 if (!defined $owner){
2444 $owner = git_get_project_config('owner');
2446 if (!defined $owner) {
2447 $owner = get_file_owner("$git_dir");
2450 return $owner;
2453 sub git_get_last_activity {
2454 my ($path) = @_;
2455 my $fd;
2457 $git_dir = "$projectroot/$path";
2458 open($fd, "-|", git_cmd(), 'for-each-ref',
2459 '--format=%(committer)',
2460 '--sort=-committerdate',
2461 '--count=1',
2462 'refs/heads') or return;
2463 my $most_recent = <$fd>;
2464 close $fd or return;
2465 if (defined $most_recent &&
2466 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2467 my $timestamp = $1;
2468 my $age = time - $timestamp;
2469 return ($age, age_string($age));
2471 return (undef, undef);
2474 sub git_get_references {
2475 my $type = shift || "";
2476 my %refs;
2477 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2478 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2479 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2480 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2481 or return;
2483 while (my $line = <$fd>) {
2484 chomp $line;
2485 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2486 if (defined $refs{$1}) {
2487 push @{$refs{$1}}, $2;
2488 } else {
2489 $refs{$1} = [ $2 ];
2493 close $fd or return;
2494 return \%refs;
2497 sub git_get_rev_name_tags {
2498 my $hash = shift || return undef;
2500 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2501 or return;
2502 my $name_rev = <$fd>;
2503 close $fd;
2505 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2506 return $1;
2507 } else {
2508 # catches also '$hash undefined' output
2509 return undef;
2513 ## ----------------------------------------------------------------------
2514 ## parse to hash functions
2516 sub parse_date {
2517 my $epoch = shift;
2518 my $tz = shift || "-0000";
2520 my %date;
2521 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2522 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2523 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2524 $date{'hour'} = $hour;
2525 $date{'minute'} = $min;
2526 $date{'mday'} = $mday;
2527 $date{'day'} = $days[$wday];
2528 $date{'month'} = $months[$mon];
2529 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2530 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2531 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2532 $mday, $months[$mon], $hour ,$min;
2533 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2534 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2536 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2537 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2538 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2539 $date{'hour_local'} = $hour;
2540 $date{'minute_local'} = $min;
2541 $date{'tz_local'} = $tz;
2542 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2543 1900+$year, $mon+1, $mday,
2544 $hour, $min, $sec, $tz);
2545 return %date;
2548 sub parse_tag {
2549 my $tag_id = shift;
2550 my %tag;
2551 my @comment;
2553 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2554 $tag{'id'} = $tag_id;
2555 while (my $line = <$fd>) {
2556 chomp $line;
2557 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2558 $tag{'object'} = $1;
2559 } elsif ($line =~ m/^type (.+)$/) {
2560 $tag{'type'} = $1;
2561 } elsif ($line =~ m/^tag (.+)$/) {
2562 $tag{'name'} = $1;
2563 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2564 $tag{'author'} = $1;
2565 $tag{'author_epoch'} = $2;
2566 $tag{'author_tz'} = $3;
2567 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2568 $tag{'author_name'} = $1;
2569 $tag{'author_email'} = $2;
2570 } else {
2571 $tag{'author_name'} = $tag{'author'};
2573 } elsif ($line =~ m/--BEGIN/) {
2574 push @comment, $line;
2575 last;
2576 } elsif ($line eq "") {
2577 last;
2580 push @comment, <$fd>;
2581 $tag{'comment'} = \@comment;
2582 close $fd or return;
2583 if (!defined $tag{'name'}) {
2584 return
2586 return %tag
2589 sub parse_commit_text {
2590 my ($commit_text, $withparents) = @_;
2591 my @commit_lines = split '\n', $commit_text;
2592 my %co;
2594 pop @commit_lines; # Remove '\0'
2596 if (! @commit_lines) {
2597 return;
2600 my $header = shift @commit_lines;
2601 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2602 return;
2604 ($co{'id'}, my @parents) = split ' ', $header;
2605 while (my $line = shift @commit_lines) {
2606 last if $line eq "\n";
2607 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2608 $co{'tree'} = $1;
2609 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2610 push @parents, $1;
2611 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2612 $co{'author'} = to_utf8($1);
2613 $co{'author_epoch'} = $2;
2614 $co{'author_tz'} = $3;
2615 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2616 $co{'author_name'} = $1;
2617 $co{'author_email'} = $2;
2618 } else {
2619 $co{'author_name'} = $co{'author'};
2621 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2622 $co{'committer'} = to_utf8($1);
2623 $co{'committer_epoch'} = $2;
2624 $co{'committer_tz'} = $3;
2625 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2626 $co{'committer_name'} = $1;
2627 $co{'committer_email'} = $2;
2628 } else {
2629 $co{'committer_name'} = $co{'committer'};
2633 if (!defined $co{'tree'}) {
2634 return;
2636 $co{'parents'} = \@parents;
2637 $co{'parent'} = $parents[0];
2639 foreach my $title (@commit_lines) {
2640 $title =~ s/^ //;
2641 if ($title ne "") {
2642 $co{'title'} = chop_str($title, 80, 5);
2643 # remove leading stuff of merges to make the interesting part visible
2644 if (length($title) > 50) {
2645 $title =~ s/^Automatic //;
2646 $title =~ s/^merge (of|with) /Merge ... /i;
2647 if (length($title) > 50) {
2648 $title =~ s/(http|rsync):\/\///;
2650 if (length($title) > 50) {
2651 $title =~ s/(master|www|rsync)\.//;
2653 if (length($title) > 50) {
2654 $title =~ s/kernel.org:?//;
2656 if (length($title) > 50) {
2657 $title =~ s/\/pub\/scm//;
2660 $co{'title_short'} = chop_str($title, 50, 5);
2661 last;
2664 if (! defined $co{'title'} || $co{'title'} eq "") {
2665 $co{'title'} = $co{'title_short'} = '(no commit message)';
2667 # remove added spaces
2668 foreach my $line (@commit_lines) {
2669 $line =~ s/^ //;
2671 $co{'comment'} = \@commit_lines;
2673 my $age = time - $co{'committer_epoch'};
2674 $co{'age'} = $age;
2675 $co{'age_string'} = age_string($age);
2676 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2677 if ($age > 60*60*24*7*2) {
2678 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2679 $co{'age_string_age'} = $co{'age_string'};
2680 } else {
2681 $co{'age_string_date'} = $co{'age_string'};
2682 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2684 return %co;
2687 sub parse_commit {
2688 my ($commit_id) = @_;
2689 my %co;
2691 local $/ = "\0";
2693 open my $fd, "-|", git_cmd(), "rev-list",
2694 "--parents",
2695 "--header",
2696 "--max-count=1",
2697 $commit_id,
2698 "--",
2699 or die_error(500, "Open git-rev-list failed");
2700 %co = parse_commit_text(<$fd>, 1);
2701 close $fd;
2703 return %co;
2706 sub parse_commits {
2707 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2708 my @cos;
2710 $maxcount ||= 1;
2711 $skip ||= 0;
2713 local $/ = "\0";
2715 open my $fd, "-|", git_cmd(), "rev-list",
2716 "--header",
2717 @args,
2718 ("--max-count=" . $maxcount),
2719 ("--skip=" . $skip),
2720 @extra_options,
2721 $commit_id,
2722 "--",
2723 ($filename ? ($filename) : ())
2724 or die_error(500, "Open git-rev-list failed");
2725 while (my $line = <$fd>) {
2726 my %co = parse_commit_text($line);
2727 push @cos, \%co;
2729 close $fd;
2731 return wantarray ? @cos : \@cos;
2734 # parse line of git-diff-tree "raw" output
2735 sub parse_difftree_raw_line {
2736 my $line = shift;
2737 my %res;
2739 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2740 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2741 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2742 $res{'from_mode'} = $1;
2743 $res{'to_mode'} = $2;
2744 $res{'from_id'} = $3;
2745 $res{'to_id'} = $4;
2746 $res{'status'} = $5;
2747 $res{'similarity'} = $6;
2748 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2749 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2750 } else {
2751 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2754 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2755 # combined diff (for merge commit)
2756 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2757 $res{'nparents'} = length($1);
2758 $res{'from_mode'} = [ split(' ', $2) ];
2759 $res{'to_mode'} = pop @{$res{'from_mode'}};
2760 $res{'from_id'} = [ split(' ', $3) ];
2761 $res{'to_id'} = pop @{$res{'from_id'}};
2762 $res{'status'} = [ split('', $4) ];
2763 $res{'to_file'} = unquote($5);
2765 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2766 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2767 $res{'commit'} = $1;
2770 return wantarray ? %res : \%res;
2773 # wrapper: return parsed line of git-diff-tree "raw" output
2774 # (the argument might be raw line, or parsed info)
2775 sub parsed_difftree_line {
2776 my $line_or_ref = shift;
2778 if (ref($line_or_ref) eq "HASH") {
2779 # pre-parsed (or generated by hand)
2780 return $line_or_ref;
2781 } else {
2782 return parse_difftree_raw_line($line_or_ref);
2786 # parse line of git-ls-tree output
2787 sub parse_ls_tree_line {
2788 my $line = shift;
2789 my %opts = @_;
2790 my %res;
2792 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2793 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2795 $res{'mode'} = $1;
2796 $res{'type'} = $2;
2797 $res{'hash'} = $3;
2798 if ($opts{'-z'}) {
2799 $res{'name'} = $4;
2800 } else {
2801 $res{'name'} = unquote($4);
2804 return wantarray ? %res : \%res;
2807 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2808 sub parse_from_to_diffinfo {
2809 my ($diffinfo, $from, $to, @parents) = @_;
2811 if ($diffinfo->{'nparents'}) {
2812 # combined diff
2813 $from->{'file'} = [];
2814 $from->{'href'} = [];
2815 fill_from_file_info($diffinfo, @parents)
2816 unless exists $diffinfo->{'from_file'};
2817 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2818 $from->{'file'}[$i] =
2819 defined $diffinfo->{'from_file'}[$i] ?
2820 $diffinfo->{'from_file'}[$i] :
2821 $diffinfo->{'to_file'};
2822 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2823 $from->{'href'}[$i] = href(action=>"blob",
2824 hash_base=>$parents[$i],
2825 hash=>$diffinfo->{'from_id'}[$i],
2826 file_name=>$from->{'file'}[$i]);
2827 } else {
2828 $from->{'href'}[$i] = undef;
2831 } else {
2832 # ordinary (not combined) diff
2833 $from->{'file'} = $diffinfo->{'from_file'};
2834 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2835 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2836 hash=>$diffinfo->{'from_id'},
2837 file_name=>$from->{'file'});
2838 } else {
2839 delete $from->{'href'};
2843 $to->{'file'} = $diffinfo->{'to_file'};
2844 if (!is_deleted($diffinfo)) { # file exists in result
2845 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2846 hash=>$diffinfo->{'to_id'},
2847 file_name=>$to->{'file'});
2848 } else {
2849 delete $to->{'href'};
2853 ## ......................................................................
2854 ## parse to array of hashes functions
2856 sub git_get_heads_list {
2857 my $limit = shift;
2858 my @headslist;
2860 open my $fd, '-|', git_cmd(), 'for-each-ref',
2861 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2862 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2863 'refs/heads'
2864 or return;
2865 while (my $line = <$fd>) {
2866 my %ref_item;
2868 chomp $line;
2869 my ($refinfo, $committerinfo) = split(/\0/, $line);
2870 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2871 my ($committer, $epoch, $tz) =
2872 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2873 $ref_item{'fullname'} = $name;
2874 $name =~ s!^refs/heads/!!;
2876 $ref_item{'name'} = $name;
2877 $ref_item{'id'} = $hash;
2878 $ref_item{'title'} = $title || '(no commit message)';
2879 $ref_item{'epoch'} = $epoch;
2880 if ($epoch) {
2881 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2882 } else {
2883 $ref_item{'age'} = "unknown";
2886 push @headslist, \%ref_item;
2888 close $fd;
2890 return wantarray ? @headslist : \@headslist;
2893 sub git_get_tags_list {
2894 my $limit = shift;
2895 my @tagslist;
2897 open my $fd, '-|', git_cmd(), 'for-each-ref',
2898 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2899 '--format=%(objectname) %(objecttype) %(refname) '.
2900 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2901 'refs/tags'
2902 or return;
2903 while (my $line = <$fd>) {
2904 my %ref_item;
2906 chomp $line;
2907 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2908 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2909 my ($creator, $epoch, $tz) =
2910 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2911 $ref_item{'fullname'} = $name;
2912 $name =~ s!^refs/tags/!!;
2914 $ref_item{'type'} = $type;
2915 $ref_item{'id'} = $id;
2916 $ref_item{'name'} = $name;
2917 if ($type eq "tag") {
2918 $ref_item{'subject'} = $title;
2919 $ref_item{'reftype'} = $reftype;
2920 $ref_item{'refid'} = $refid;
2921 } else {
2922 $ref_item{'reftype'} = $type;
2923 $ref_item{'refid'} = $id;
2926 if ($type eq "tag" || $type eq "commit") {
2927 $ref_item{'epoch'} = $epoch;
2928 if ($epoch) {
2929 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2930 } else {
2931 $ref_item{'age'} = "unknown";
2935 push @tagslist, \%ref_item;
2937 close $fd;
2939 return wantarray ? @tagslist : \@tagslist;
2942 ## ----------------------------------------------------------------------
2943 ## filesystem-related functions
2945 sub get_file_owner {
2946 my $path = shift;
2948 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2949 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2950 if (!defined $gcos) {
2951 return undef;
2953 my $owner = $gcos;
2954 $owner =~ s/[,;].*$//;
2955 return to_utf8($owner);
2958 # assume that file exists
2959 sub insert_file {
2960 my $filename = shift;
2962 open my $fd, '<', $filename;
2963 print map { to_utf8($_) } <$fd>;
2964 close $fd;
2967 ## ......................................................................
2968 ## mimetype related functions
2970 sub mimetype_guess_file {
2971 my $filename = shift;
2972 my $mimemap = shift;
2973 -r $mimemap or return undef;
2975 my %mimemap;
2976 open(my $mh, '<', $mimemap) or return undef;
2977 while (<$mh>) {
2978 next if m/^#/; # skip comments
2979 my ($mimetype, $exts) = split(/\t+/);
2980 if (defined $exts) {
2981 my @exts = split(/\s+/, $exts);
2982 foreach my $ext (@exts) {
2983 $mimemap{$ext} = $mimetype;
2987 close($mh);
2989 $filename =~ /\.([^.]*)$/;
2990 return $mimemap{$1};
2993 sub mimetype_guess {
2994 my $filename = shift;
2995 my $mime;
2996 $filename =~ /\./ or return undef;
2998 if ($mimetypes_file) {
2999 my $file = $mimetypes_file;
3000 if ($file !~ m!^/!) { # if it is relative path
3001 # it is relative to project
3002 $file = "$projectroot/$project/$file";
3004 $mime = mimetype_guess_file($filename, $file);
3006 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3007 return $mime;
3010 sub blob_mimetype {
3011 my $fd = shift;
3012 my $filename = shift;
3014 if ($filename) {
3015 my $mime = mimetype_guess($filename);
3016 $mime and return $mime;
3019 # just in case
3020 return $default_blob_plain_mimetype unless $fd;
3022 if (-T $fd) {
3023 return 'text/plain';
3024 } elsif (! $filename) {
3025 return 'application/octet-stream';
3026 } elsif ($filename =~ m/\.png$/i) {
3027 return 'image/png';
3028 } elsif ($filename =~ m/\.gif$/i) {
3029 return 'image/gif';
3030 } elsif ($filename =~ m/\.jpe?g$/i) {
3031 return 'image/jpeg';
3032 } else {
3033 return 'application/octet-stream';
3037 sub blob_contenttype {
3038 my ($fd, $file_name, $type) = @_;
3040 $type ||= blob_mimetype($fd, $file_name);
3041 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3042 $type .= "; charset=$default_text_plain_charset";
3045 return $type;
3048 ## ======================================================================
3049 ## functions printing HTML: header, footer, error page
3051 sub git_header_html {
3052 my $status = shift || "200 OK";
3053 my $expires = shift;
3055 my $title = "$site_name";
3056 if (defined $project) {
3057 $title .= " - " . to_utf8($project);
3058 if (defined $action) {
3059 $title .= "/$action";
3060 if (defined $file_name) {
3061 $title .= " - " . esc_path($file_name);
3062 if ($action eq "tree" && $file_name !~ m|/$|) {
3063 $title .= "/";
3068 my $content_type;
3069 # require explicit support from the UA if we are to send the page as
3070 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3071 # we have to do this because MSIE sometimes globs '*/*', pretending to
3072 # support xhtml+xml but choking when it gets what it asked for.
3073 if (defined $cgi->http('HTTP_ACCEPT') &&
3074 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3075 $cgi->Accept('application/xhtml+xml') != 0) {
3076 $content_type = 'application/xhtml+xml';
3077 } else {
3078 $content_type = 'text/html';
3080 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3081 -status=> $status, -expires => $expires);
3082 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3083 print <<EOF;
3084 <?xml version="1.0" encoding="utf-8"?>
3085 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3086 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3087 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3088 <!-- git core binaries version $git_version -->
3089 <head>
3090 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3091 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3092 <meta name="robots" content="index, nofollow"/>
3093 <title>$title</title>
3095 # the stylesheet, favicon etc urls won't work correctly with path_info
3096 # unless we set the appropriate base URL
3097 if ($ENV{'PATH_INFO'}) {
3098 print "<base href=\"".esc_url($base_url)."\" />\n";
3100 # print out each stylesheet that exist, providing backwards capability
3101 # for those people who defined $stylesheet in a config file
3102 if (defined $stylesheet) {
3103 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3104 } else {
3105 foreach my $stylesheet (@stylesheets) {
3106 next unless $stylesheet;
3107 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3110 if (defined $project) {
3111 my %href_params = get_feed_info();
3112 if (!exists $href_params{'-title'}) {
3113 $href_params{'-title'} = 'log';
3116 foreach my $format qw(RSS Atom) {
3117 my $type = lc($format);
3118 my %link_attr = (
3119 '-rel' => 'alternate',
3120 '-title' => "$project - $href_params{'-title'} - $format feed",
3121 '-type' => "application/$type+xml"
3124 $href_params{'action'} = $type;
3125 $link_attr{'-href'} = href(%href_params);
3126 print "<link ".
3127 "rel=\"$link_attr{'-rel'}\" ".
3128 "title=\"$link_attr{'-title'}\" ".
3129 "href=\"$link_attr{'-href'}\" ".
3130 "type=\"$link_attr{'-type'}\" ".
3131 "/>\n";
3133 $href_params{'extra_options'} = '--no-merges';
3134 $link_attr{'-href'} = href(%href_params);
3135 $link_attr{'-title'} .= ' (no merges)';
3136 print "<link ".
3137 "rel=\"$link_attr{'-rel'}\" ".
3138 "title=\"$link_attr{'-title'}\" ".
3139 "href=\"$link_attr{'-href'}\" ".
3140 "type=\"$link_attr{'-type'}\" ".
3141 "/>\n";
3144 } else {
3145 printf('<link rel="alternate" title="%s projects list" '.
3146 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3147 $site_name, href(project=>undef, action=>"project_index"));
3148 printf('<link rel="alternate" title="%s projects feeds" '.
3149 'href="%s" type="text/x-opml" />'."\n",
3150 $site_name, href(project=>undef, action=>"opml"));
3152 if (defined $favicon) {
3153 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3156 print "</head>\n" .
3157 "<body>\n";
3159 if (-f $site_header) {
3160 insert_file($site_header);
3163 print "<div class=\"page_header\">\n" .
3164 $cgi->a({-href => esc_url($logo_url),
3165 -title => $logo_label},
3166 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3167 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3168 if (defined $project) {
3169 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3170 if (defined $action) {
3171 print " / $action";
3173 print "\n";
3175 print "</div>\n";
3177 my $have_search = gitweb_check_feature('search');
3178 if (defined $project && $have_search) {
3179 if (!defined $searchtext) {
3180 $searchtext = "";
3182 my $search_hash;
3183 if (defined $hash_base) {
3184 $search_hash = $hash_base;
3185 } elsif (defined $hash) {
3186 $search_hash = $hash;
3187 } else {
3188 $search_hash = "HEAD";
3190 my $action = $my_uri;
3191 my $use_pathinfo = gitweb_check_feature('pathinfo');
3192 if ($use_pathinfo) {
3193 $action .= "/".esc_url($project);
3195 print $cgi->startform(-method => "get", -action => $action) .
3196 "<div class=\"search\">\n" .
3197 (!$use_pathinfo &&
3198 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3199 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3200 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3201 $cgi->popup_menu(-name => 'st', -default => 'commit',
3202 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3203 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3204 " search:\n",
3205 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3206 "<span title=\"Extended regular expression\">" .
3207 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3208 -checked => $search_use_regexp) .
3209 "</span>" .
3210 "</div>" .
3211 $cgi->end_form() . "\n";
3215 sub git_footer_html {
3216 my $feed_class = 'rss_logo';
3218 print "<div class=\"page_footer\">\n";
3219 if (defined $project) {
3220 my $descr = git_get_project_description($project);
3221 if (defined $descr) {
3222 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3225 my %href_params = get_feed_info();
3226 if (!%href_params) {
3227 $feed_class .= ' generic';
3229 $href_params{'-title'} ||= 'log';
3231 foreach my $format qw(RSS Atom) {
3232 $href_params{'action'} = lc($format);
3233 print $cgi->a({-href => href(%href_params),
3234 -title => "$href_params{'-title'} $format feed",
3235 -class => $feed_class}, $format)."\n";
3238 } else {
3239 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3240 -class => $feed_class}, "OPML") . " ";
3241 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3242 -class => $feed_class}, "TXT") . "\n";
3244 print "</div>\n"; # class="page_footer"
3246 if (-f $site_footer) {
3247 insert_file($site_footer);
3250 print "</body>\n" .
3251 "</html>";
3254 # die_error(<http_status_code>, <error_message>)
3255 # Example: die_error(404, 'Hash not found')
3256 # By convention, use the following status codes (as defined in RFC 2616):
3257 # 400: Invalid or missing CGI parameters, or
3258 # requested object exists but has wrong type.
3259 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3260 # this server or project.
3261 # 404: Requested object/revision/project doesn't exist.
3262 # 500: The server isn't configured properly, or
3263 # an internal error occurred (e.g. failed assertions caused by bugs), or
3264 # an unknown error occurred (e.g. the git binary died unexpectedly).
3265 sub die_error {
3266 my $status = shift || 500;
3267 my $error = shift || "Internal server error";
3269 my %http_responses = (400 => '400 Bad Request',
3270 403 => '403 Forbidden',
3271 404 => '404 Not Found',
3272 500 => '500 Internal Server Error');
3273 git_header_html($http_responses{$status});
3274 print <<EOF;
3275 <div class="page_body">
3276 <br /><br />
3277 $status - $error
3278 <br />
3279 </div>
3281 git_footer_html();
3282 exit;
3285 ## ----------------------------------------------------------------------
3286 ## functions printing or outputting HTML: navigation
3288 sub git_print_page_nav {
3289 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3290 $extra = '' if !defined $extra; # pager or formats
3292 my @navs = qw(summary shortlog log commit commitdiff tree);
3293 if ($suppress) {
3294 @navs = grep { $_ ne $suppress } @navs;
3297 my %arg = map { $_ => {action=>$_} } @navs;
3298 if (defined $head) {
3299 for (qw(commit commitdiff)) {
3300 $arg{$_}{'hash'} = $head;
3302 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3303 for (qw(shortlog log)) {
3304 $arg{$_}{'hash'} = $head;
3309 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3310 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3312 my @actions = gitweb_get_feature('actions');
3313 my %repl = (
3314 '%' => '%',
3315 'n' => $project, # project name
3316 'f' => $git_dir, # project path within filesystem
3317 'h' => $treehead || '', # current hash ('h' parameter)
3318 'b' => $treebase || '', # hash base ('hb' parameter)
3320 while (@actions) {
3321 my ($label, $link, $pos) = splice(@actions,0,3);
3322 # insert
3323 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3324 # munch munch
3325 $link =~ s/%([%nfhb])/$repl{$1}/g;
3326 $arg{$label}{'_href'} = $link;
3329 print "<div class=\"page_nav\">\n" .
3330 (join " | ",
3331 map { $_ eq $current ?
3332 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3333 } @navs);
3334 print "<br/>\n$extra<br/>\n" .
3335 "</div>\n";
3338 sub format_paging_nav {
3339 my ($action, $hash, $head, $page, $has_next_link) = @_;
3340 my $paging_nav;
3343 if ($hash ne $head || $page) {
3344 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3345 } else {
3346 $paging_nav .= "HEAD";
3349 if ($page > 0) {
3350 $paging_nav .= " &sdot; " .
3351 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3352 -accesskey => "p", -title => "Alt-p"}, "prev");
3353 } else {
3354 $paging_nav .= " &sdot; prev";
3357 if ($has_next_link) {
3358 $paging_nav .= " &sdot; " .
3359 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3360 -accesskey => "n", -title => "Alt-n"}, "next");
3361 } else {
3362 $paging_nav .= " &sdot; next";
3365 return $paging_nav;
3368 ## ......................................................................
3369 ## functions printing or outputting HTML: div
3371 sub git_print_header_div {
3372 my ($action, $title, $hash, $hash_base) = @_;
3373 my %args = ();
3375 $args{'action'} = $action;
3376 $args{'hash'} = $hash if $hash;
3377 $args{'hash_base'} = $hash_base if $hash_base;
3379 print "<div class=\"header\">\n" .
3380 $cgi->a({-href => href(%args), -class => "title"},
3381 $title ? $title : $action) .
3382 "\n</div>\n";
3385 sub print_local_time {
3386 my %date = @_;
3387 if ($date{'hour_local'} < 6) {
3388 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3389 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3390 } else {
3391 printf(" (%02d:%02d %s)",
3392 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3396 # Outputs the author name and date in long form
3397 sub git_print_authorship {
3398 my $co = shift;
3399 my %opts = @_;
3400 my $tag = $opts{-tag} || 'div';
3402 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3403 print "<$tag class=\"author_date\">" .
3404 esc_html($co->{'author_name'}) .
3405 " [$ad{'rfc2822'}";
3406 print_local_time(%ad) if ($opts{-localtime});
3407 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3408 . "</$tag>\n";
3411 # Outputs table rows containing the full author or committer information,
3412 # in the format expected for 'commit' view (& similia).
3413 # Parameters are a commit hash reference, followed by the list of people
3414 # to output information for. If the list is empty it defalts to both
3415 # author and committer.
3416 sub git_print_authorship_rows {
3417 my $co = shift;
3418 # too bad we can't use @people = @_ || ('author', 'committer')
3419 my @people = @_;
3420 @people = ('author', 'committer') unless @people;
3421 foreach my $who (@people) {
3422 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3423 print "<tr><td>$who</td><td>" . esc_html($co->{$who}) . "</td>" .
3424 "<td rowspan=\"2\">" .
3425 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3426 "</td></tr>\n" .
3427 "<tr>" .
3428 "<td></td><td> $wd{'rfc2822'}";
3429 print_local_time(%wd);
3430 print "</td>" .
3431 "</tr>\n";
3435 sub git_print_page_path {
3436 my $name = shift;
3437 my $type = shift;
3438 my $hb = shift;
3441 print "<div class=\"page_path\">";
3442 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3443 -title => 'tree root'}, to_utf8("[$project]"));
3444 print " / ";
3445 if (defined $name) {
3446 my @dirname = split '/', $name;
3447 my $basename = pop @dirname;
3448 my $fullname = '';
3450 foreach my $dir (@dirname) {
3451 $fullname .= ($fullname ? '/' : '') . $dir;
3452 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3453 hash_base=>$hb),
3454 -title => $fullname}, esc_path($dir));
3455 print " / ";
3457 if (defined $type && $type eq 'blob') {
3458 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3459 hash_base=>$hb),
3460 -title => $name}, esc_path($basename));
3461 } elsif (defined $type && $type eq 'tree') {
3462 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3463 hash_base=>$hb),
3464 -title => $name}, esc_path($basename));
3465 print " / ";
3466 } else {
3467 print esc_path($basename);
3470 print "<br/></div>\n";
3473 sub git_print_log {
3474 my $log = shift;
3475 my %opts = @_;
3477 if ($opts{'-remove_title'}) {
3478 # remove title, i.e. first line of log
3479 shift @$log;
3481 # remove leading empty lines
3482 while (defined $log->[0] && $log->[0] eq "") {
3483 shift @$log;
3486 # print log
3487 my $signoff = 0;
3488 my $empty = 0;
3489 foreach my $line (@$log) {
3490 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3491 $signoff = 1;
3492 $empty = 0;
3493 if (! $opts{'-remove_signoff'}) {
3494 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3495 next;
3496 } else {
3497 # remove signoff lines
3498 next;
3500 } else {
3501 $signoff = 0;
3504 # print only one empty line
3505 # do not print empty line after signoff
3506 if ($line eq "") {
3507 next if ($empty || $signoff);
3508 $empty = 1;
3509 } else {
3510 $empty = 0;
3513 print format_log_line_html($line) . "<br/>\n";
3516 if ($opts{'-final_empty_line'}) {
3517 # end with single empty line
3518 print "<br/>\n" unless $empty;
3522 # return link target (what link points to)
3523 sub git_get_link_target {
3524 my $hash = shift;
3525 my $link_target;
3527 # read link
3528 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3529 or return;
3531 local $/ = undef;
3532 $link_target = <$fd>;
3534 close $fd
3535 or return;
3537 return $link_target;
3540 # given link target, and the directory (basedir) the link is in,
3541 # return target of link relative to top directory (top tree);
3542 # return undef if it is not possible (including absolute links).
3543 sub normalize_link_target {
3544 my ($link_target, $basedir) = @_;
3546 # absolute symlinks (beginning with '/') cannot be normalized
3547 return if (substr($link_target, 0, 1) eq '/');
3549 # normalize link target to path from top (root) tree (dir)
3550 my $path;
3551 if ($basedir) {
3552 $path = $basedir . '/' . $link_target;
3553 } else {
3554 # we are in top (root) tree (dir)
3555 $path = $link_target;
3558 # remove //, /./, and /../
3559 my @path_parts;
3560 foreach my $part (split('/', $path)) {
3561 # discard '.' and ''
3562 next if (!$part || $part eq '.');
3563 # handle '..'
3564 if ($part eq '..') {
3565 if (@path_parts) {
3566 pop @path_parts;
3567 } else {
3568 # link leads outside repository (outside top dir)
3569 return;
3571 } else {
3572 push @path_parts, $part;
3575 $path = join('/', @path_parts);
3577 return $path;
3580 # print tree entry (row of git_tree), but without encompassing <tr> element
3581 sub git_print_tree_entry {
3582 my ($t, $basedir, $hash_base, $have_blame) = @_;
3584 my %base_key = ();
3585 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3587 # The format of a table row is: mode list link. Where mode is
3588 # the mode of the entry, list is the name of the entry, an href,
3589 # and link is the action links of the entry.
3591 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3592 if ($t->{'type'} eq "blob") {
3593 print "<td class=\"list\">" .
3594 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3595 file_name=>"$basedir$t->{'name'}", %base_key),
3596 -class => "list"}, esc_path($t->{'name'}));
3597 if (S_ISLNK(oct $t->{'mode'})) {
3598 my $link_target = git_get_link_target($t->{'hash'});
3599 if ($link_target) {
3600 my $norm_target = normalize_link_target($link_target, $basedir);
3601 if (defined $norm_target) {
3602 print " -> " .
3603 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3604 file_name=>$norm_target),
3605 -title => $norm_target}, esc_path($link_target));
3606 } else {
3607 print " -> " . esc_path($link_target);
3611 print "</td>\n";
3612 print "<td class=\"link\">";
3613 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3614 file_name=>"$basedir$t->{'name'}", %base_key)},
3615 "blob");
3616 if ($have_blame) {
3617 print " | " .
3618 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3619 file_name=>"$basedir$t->{'name'}", %base_key)},
3620 "blame");
3622 if (defined $hash_base) {
3623 print " | " .
3624 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3625 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3626 "history");
3628 print " | " .
3629 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3630 file_name=>"$basedir$t->{'name'}")},
3631 "raw");
3632 print "</td>\n";
3634 } elsif ($t->{'type'} eq "tree") {
3635 print "<td class=\"list\">";
3636 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3637 file_name=>"$basedir$t->{'name'}", %base_key)},
3638 esc_path($t->{'name'}));
3639 print "</td>\n";
3640 print "<td class=\"link\">";
3641 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3642 file_name=>"$basedir$t->{'name'}", %base_key)},
3643 "tree");
3644 if (defined $hash_base) {
3645 print " | " .
3646 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3647 file_name=>"$basedir$t->{'name'}")},
3648 "history");
3650 print "</td>\n";
3651 } else {
3652 # unknown object: we can only present history for it
3653 # (this includes 'commit' object, i.e. submodule support)
3654 print "<td class=\"list\">" .
3655 esc_path($t->{'name'}) .
3656 "</td>\n";
3657 print "<td class=\"link\">";
3658 if (defined $hash_base) {
3659 print $cgi->a({-href => href(action=>"history",
3660 hash_base=>$hash_base,
3661 file_name=>"$basedir$t->{'name'}")},
3662 "history");
3664 print "</td>\n";
3668 ## ......................................................................
3669 ## functions printing large fragments of HTML
3671 # get pre-image filenames for merge (combined) diff
3672 sub fill_from_file_info {
3673 my ($diff, @parents) = @_;
3675 $diff->{'from_file'} = [ ];
3676 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3677 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3678 if ($diff->{'status'}[$i] eq 'R' ||
3679 $diff->{'status'}[$i] eq 'C') {
3680 $diff->{'from_file'}[$i] =
3681 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3685 return $diff;
3688 # is current raw difftree line of file deletion
3689 sub is_deleted {
3690 my $diffinfo = shift;
3692 return $diffinfo->{'to_id'} eq ('0' x 40);
3695 # does patch correspond to [previous] difftree raw line
3696 # $diffinfo - hashref of parsed raw diff format
3697 # $patchinfo - hashref of parsed patch diff format
3698 # (the same keys as in $diffinfo)
3699 sub is_patch_split {
3700 my ($diffinfo, $patchinfo) = @_;
3702 return defined $diffinfo && defined $patchinfo
3703 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3707 sub git_difftree_body {
3708 my ($difftree, $hash, @parents) = @_;
3709 my ($parent) = $parents[0];
3710 my $have_blame = gitweb_check_feature('blame');
3711 print "<div class=\"list_head\">\n";
3712 if ($#{$difftree} > 10) {
3713 print(($#{$difftree} + 1) . " files changed:\n");
3715 print "</div>\n";
3717 print "<table class=\"" .
3718 (@parents > 1 ? "combined " : "") .
3719 "diff_tree\">\n";
3721 # header only for combined diff in 'commitdiff' view
3722 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3723 if ($has_header) {
3724 # table header
3725 print "<thead><tr>\n" .
3726 "<th></th><th></th>\n"; # filename, patchN link
3727 for (my $i = 0; $i < @parents; $i++) {
3728 my $par = $parents[$i];
3729 print "<th>" .
3730 $cgi->a({-href => href(action=>"commitdiff",
3731 hash=>$hash, hash_parent=>$par),
3732 -title => 'commitdiff to parent number ' .
3733 ($i+1) . ': ' . substr($par,0,7)},
3734 $i+1) .
3735 "&nbsp;</th>\n";
3737 print "</tr></thead>\n<tbody>\n";
3740 my $alternate = 1;
3741 my $patchno = 0;
3742 foreach my $line (@{$difftree}) {
3743 my $diff = parsed_difftree_line($line);
3745 if ($alternate) {
3746 print "<tr class=\"dark\">\n";
3747 } else {
3748 print "<tr class=\"light\">\n";
3750 $alternate ^= 1;
3752 if (exists $diff->{'nparents'}) { # combined diff
3754 fill_from_file_info($diff, @parents)
3755 unless exists $diff->{'from_file'};
3757 if (!is_deleted($diff)) {
3758 # file exists in the result (child) commit
3759 print "<td>" .
3760 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3761 file_name=>$diff->{'to_file'},
3762 hash_base=>$hash),
3763 -class => "list"}, esc_path($diff->{'to_file'})) .
3764 "</td>\n";
3765 } else {
3766 print "<td>" .
3767 esc_path($diff->{'to_file'}) .
3768 "</td>\n";
3771 if ($action eq 'commitdiff') {
3772 # link to patch
3773 $patchno++;
3774 print "<td class=\"link\">" .
3775 $cgi->a({-href => "#patch$patchno"}, "patch") .
3776 " | " .
3777 "</td>\n";
3780 my $has_history = 0;
3781 my $not_deleted = 0;
3782 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3783 my $hash_parent = $parents[$i];
3784 my $from_hash = $diff->{'from_id'}[$i];
3785 my $from_path = $diff->{'from_file'}[$i];
3786 my $status = $diff->{'status'}[$i];
3788 $has_history ||= ($status ne 'A');
3789 $not_deleted ||= ($status ne 'D');
3791 if ($status eq 'A') {
3792 print "<td class=\"link\" align=\"right\"> | </td>\n";
3793 } elsif ($status eq 'D') {
3794 print "<td class=\"link\">" .
3795 $cgi->a({-href => href(action=>"blob",
3796 hash_base=>$hash,
3797 hash=>$from_hash,
3798 file_name=>$from_path)},
3799 "blob" . ($i+1)) .
3800 " | </td>\n";
3801 } else {
3802 if ($diff->{'to_id'} eq $from_hash) {
3803 print "<td class=\"link nochange\">";
3804 } else {
3805 print "<td class=\"link\">";
3807 print $cgi->a({-href => href(action=>"blobdiff",
3808 hash=>$diff->{'to_id'},
3809 hash_parent=>$from_hash,
3810 hash_base=>$hash,
3811 hash_parent_base=>$hash_parent,
3812 file_name=>$diff->{'to_file'},
3813 file_parent=>$from_path)},
3814 "diff" . ($i+1)) .
3815 " | </td>\n";
3819 print "<td class=\"link\">";
3820 if ($not_deleted) {
3821 print $cgi->a({-href => href(action=>"blob",
3822 hash=>$diff->{'to_id'},
3823 file_name=>$diff->{'to_file'},
3824 hash_base=>$hash)},
3825 "blob");
3826 print " | " if ($has_history);
3828 if ($has_history) {
3829 print $cgi->a({-href => href(action=>"history",
3830 file_name=>$diff->{'to_file'},
3831 hash_base=>$hash)},
3832 "history");
3834 print "</td>\n";
3836 print "</tr>\n";
3837 next; # instead of 'else' clause, to avoid extra indent
3839 # else ordinary diff
3841 my ($to_mode_oct, $to_mode_str, $to_file_type);
3842 my ($from_mode_oct, $from_mode_str, $from_file_type);
3843 if ($diff->{'to_mode'} ne ('0' x 6)) {
3844 $to_mode_oct = oct $diff->{'to_mode'};
3845 if (S_ISREG($to_mode_oct)) { # only for regular file
3846 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3848 $to_file_type = file_type($diff->{'to_mode'});
3850 if ($diff->{'from_mode'} ne ('0' x 6)) {
3851 $from_mode_oct = oct $diff->{'from_mode'};
3852 if (S_ISREG($to_mode_oct)) { # only for regular file
3853 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3855 $from_file_type = file_type($diff->{'from_mode'});
3858 if ($diff->{'status'} eq "A") { # created
3859 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3860 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3861 $mode_chng .= "]</span>";
3862 print "<td>";
3863 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3864 hash_base=>$hash, file_name=>$diff->{'file'}),
3865 -class => "list"}, esc_path($diff->{'file'}));
3866 print "</td>\n";
3867 print "<td>$mode_chng</td>\n";
3868 print "<td class=\"link\">";
3869 if ($action eq 'commitdiff') {
3870 # link to patch
3871 $patchno++;
3872 print $cgi->a({-href => "#patch$patchno"}, "patch");
3873 print " | ";
3875 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3876 hash_base=>$hash, file_name=>$diff->{'file'})},
3877 "blob");
3878 print "</td>\n";
3880 } elsif ($diff->{'status'} eq "D") { # deleted
3881 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3882 print "<td>";
3883 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3884 hash_base=>$parent, file_name=>$diff->{'file'}),
3885 -class => "list"}, esc_path($diff->{'file'}));
3886 print "</td>\n";
3887 print "<td>$mode_chng</td>\n";
3888 print "<td class=\"link\">";
3889 if ($action eq 'commitdiff') {
3890 # link to patch
3891 $patchno++;
3892 print $cgi->a({-href => "#patch$patchno"}, "patch");
3893 print " | ";
3895 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3896 hash_base=>$parent, file_name=>$diff->{'file'})},
3897 "blob") . " | ";
3898 if ($have_blame) {
3899 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3900 file_name=>$diff->{'file'})},
3901 "blame") . " | ";
3903 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3904 file_name=>$diff->{'file'})},
3905 "history");
3906 print "</td>\n";
3908 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3909 my $mode_chnge = "";
3910 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3911 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3912 if ($from_file_type ne $to_file_type) {
3913 $mode_chnge .= " from $from_file_type to $to_file_type";
3915 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3916 if ($from_mode_str && $to_mode_str) {
3917 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3918 } elsif ($to_mode_str) {
3919 $mode_chnge .= " mode: $to_mode_str";
3922 $mode_chnge .= "]</span>\n";
3924 print "<td>";
3925 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3926 hash_base=>$hash, file_name=>$diff->{'file'}),
3927 -class => "list"}, esc_path($diff->{'file'}));
3928 print "</td>\n";
3929 print "<td>$mode_chnge</td>\n";
3930 print "<td class=\"link\">";
3931 if ($action eq 'commitdiff') {
3932 # link to patch
3933 $patchno++;
3934 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3935 " | ";
3936 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3937 # "commit" view and modified file (not onlu mode changed)
3938 print $cgi->a({-href => href(action=>"blobdiff",
3939 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3940 hash_base=>$hash, hash_parent_base=>$parent,
3941 file_name=>$diff->{'file'})},
3942 "diff") .
3943 " | ";
3945 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3946 hash_base=>$hash, file_name=>$diff->{'file'})},
3947 "blob") . " | ";
3948 if ($have_blame) {
3949 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3950 file_name=>$diff->{'file'})},
3951 "blame") . " | ";
3953 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3954 file_name=>$diff->{'file'})},
3955 "history");
3956 print "</td>\n";
3958 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3959 my %status_name = ('R' => 'moved', 'C' => 'copied');
3960 my $nstatus = $status_name{$diff->{'status'}};
3961 my $mode_chng = "";
3962 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3963 # mode also for directories, so we cannot use $to_mode_str
3964 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3966 print "<td>" .
3967 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3968 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3969 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3970 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3971 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3972 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3973 -class => "list"}, esc_path($diff->{'from_file'})) .
3974 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3975 "<td class=\"link\">";
3976 if ($action eq 'commitdiff') {
3977 # link to patch
3978 $patchno++;
3979 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3980 " | ";
3981 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3982 # "commit" view and modified file (not only pure rename or copy)
3983 print $cgi->a({-href => href(action=>"blobdiff",
3984 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3985 hash_base=>$hash, hash_parent_base=>$parent,
3986 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3987 "diff") .
3988 " | ";
3990 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3991 hash_base=>$parent, file_name=>$diff->{'to_file'})},
3992 "blob") . " | ";
3993 if ($have_blame) {
3994 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3995 file_name=>$diff->{'to_file'})},
3996 "blame") . " | ";
3998 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3999 file_name=>$diff->{'to_file'})},
4000 "history");
4001 print "</td>\n";
4003 } # we should not encounter Unmerged (U) or Unknown (X) status
4004 print "</tr>\n";
4006 print "</tbody>" if $has_header;
4007 print "</table>\n";
4010 sub git_patchset_body {
4011 my ($fd, $difftree, $hash, @hash_parents) = @_;
4012 my ($hash_parent) = $hash_parents[0];
4014 my $is_combined = (@hash_parents > 1);
4015 my $patch_idx = 0;
4016 my $patch_number = 0;
4017 my $patch_line;
4018 my $diffinfo;
4019 my $to_name;
4020 my (%from, %to);
4022 print "<div class=\"patchset\">\n";
4024 # skip to first patch
4025 while ($patch_line = <$fd>) {
4026 chomp $patch_line;
4028 last if ($patch_line =~ m/^diff /);
4031 PATCH:
4032 while ($patch_line) {
4034 # parse "git diff" header line
4035 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4036 # $1 is from_name, which we do not use
4037 $to_name = unquote($2);
4038 $to_name =~ s!^b/!!;
4039 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4040 # $1 is 'cc' or 'combined', which we do not use
4041 $to_name = unquote($2);
4042 } else {
4043 $to_name = undef;
4046 # check if current patch belong to current raw line
4047 # and parse raw git-diff line if needed
4048 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4049 # this is continuation of a split patch
4050 print "<div class=\"patch cont\">\n";
4051 } else {
4052 # advance raw git-diff output if needed
4053 $patch_idx++ if defined $diffinfo;
4055 # read and prepare patch information
4056 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4058 # compact combined diff output can have some patches skipped
4059 # find which patch (using pathname of result) we are at now;
4060 if ($is_combined) {
4061 while ($to_name ne $diffinfo->{'to_file'}) {
4062 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4063 format_diff_cc_simplified($diffinfo, @hash_parents) .
4064 "</div>\n"; # class="patch"
4066 $patch_idx++;
4067 $patch_number++;
4069 last if $patch_idx > $#$difftree;
4070 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4074 # modifies %from, %to hashes
4075 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4077 # this is first patch for raw difftree line with $patch_idx index
4078 # we index @$difftree array from 0, but number patches from 1
4079 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4082 # git diff header
4083 #assert($patch_line =~ m/^diff /) if DEBUG;
4084 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4085 $patch_number++;
4086 # print "git diff" header
4087 print format_git_diff_header_line($patch_line, $diffinfo,
4088 \%from, \%to);
4090 # print extended diff header
4091 print "<div class=\"diff extended_header\">\n";
4092 EXTENDED_HEADER:
4093 while ($patch_line = <$fd>) {
4094 chomp $patch_line;
4096 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4098 print format_extended_diff_header_line($patch_line, $diffinfo,
4099 \%from, \%to);
4101 print "</div>\n"; # class="diff extended_header"
4103 # from-file/to-file diff header
4104 if (! $patch_line) {
4105 print "</div>\n"; # class="patch"
4106 last PATCH;
4108 next PATCH if ($patch_line =~ m/^diff /);
4109 #assert($patch_line =~ m/^---/) if DEBUG;
4111 my $last_patch_line = $patch_line;
4112 $patch_line = <$fd>;
4113 chomp $patch_line;
4114 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4116 print format_diff_from_to_header($last_patch_line, $patch_line,
4117 $diffinfo, \%from, \%to,
4118 @hash_parents);
4120 # the patch itself
4121 LINE:
4122 while ($patch_line = <$fd>) {
4123 chomp $patch_line;
4125 next PATCH if ($patch_line =~ m/^diff /);
4127 print format_diff_line($patch_line, \%from, \%to);
4130 } continue {
4131 print "</div>\n"; # class="patch"
4134 # for compact combined (--cc) format, with chunk and patch simpliciaction
4135 # patchset might be empty, but there might be unprocessed raw lines
4136 for (++$patch_idx if $patch_number > 0;
4137 $patch_idx < @$difftree;
4138 ++$patch_idx) {
4139 # read and prepare patch information
4140 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4142 # generate anchor for "patch" links in difftree / whatchanged part
4143 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4144 format_diff_cc_simplified($diffinfo, @hash_parents) .
4145 "</div>\n"; # class="patch"
4147 $patch_number++;
4150 if ($patch_number == 0) {
4151 if (@hash_parents > 1) {
4152 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4153 } else {
4154 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4158 print "</div>\n"; # class="patchset"
4161 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4163 # fills project list info (age, description, owner, forks) for each
4164 # project in the list, removing invalid projects from returned list
4165 # NOTE: modifies $projlist, but does not remove entries from it
4166 sub fill_project_list_info {
4167 my ($projlist, $check_forks) = @_;
4168 my @projects;
4170 my $show_ctags = gitweb_check_feature('ctags');
4171 PROJECT:
4172 foreach my $pr (@$projlist) {
4173 my (@activity) = git_get_last_activity($pr->{'path'});
4174 unless (@activity) {
4175 next PROJECT;
4177 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4178 if (!defined $pr->{'descr'}) {
4179 my $descr = git_get_project_description($pr->{'path'}) || "";
4180 $descr = to_utf8($descr);
4181 $pr->{'descr_long'} = $descr;
4182 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4184 if (!defined $pr->{'owner'}) {
4185 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4187 if ($check_forks) {
4188 my $pname = $pr->{'path'};
4189 if (($pname =~ s/\.git$//) &&
4190 ($pname !~ /\/$/) &&
4191 (-d "$projectroot/$pname")) {
4192 $pr->{'forks'} = "-d $projectroot/$pname";
4193 } else {
4194 $pr->{'forks'} = 0;
4197 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4198 push @projects, $pr;
4201 return @projects;
4204 # print 'sort by' <th> element, generating 'sort by $name' replay link
4205 # if that order is not selected
4206 sub print_sort_th {
4207 my ($name, $order, $header) = @_;
4208 $header ||= ucfirst($name);
4210 if ($order eq $name) {
4211 print "<th>$header</th>\n";
4212 } else {
4213 print "<th>" .
4214 $cgi->a({-href => href(-replay=>1, order=>$name),
4215 -class => "header"}, $header) .
4216 "</th>\n";
4220 sub git_project_list_body {
4221 # actually uses global variable $project
4222 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4224 my $check_forks = gitweb_check_feature('forks');
4225 my @projects = fill_project_list_info($projlist, $check_forks);
4227 $order ||= $default_projects_order;
4228 $from = 0 unless defined $from;
4229 $to = $#projects if (!defined $to || $#projects < $to);
4231 my %order_info = (
4232 project => { key => 'path', type => 'str' },
4233 descr => { key => 'descr_long', type => 'str' },
4234 owner => { key => 'owner', type => 'str' },
4235 age => { key => 'age', type => 'num' }
4237 my $oi = $order_info{$order};
4238 if ($oi->{'type'} eq 'str') {
4239 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4240 } else {
4241 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4244 my $show_ctags = gitweb_check_feature('ctags');
4245 if ($show_ctags) {
4246 my %ctags;
4247 foreach my $p (@projects) {
4248 foreach my $ct (keys %{$p->{'ctags'}}) {
4249 $ctags{$ct} += $p->{'ctags'}->{$ct};
4252 my $cloud = git_populate_project_tagcloud(\%ctags);
4253 print git_show_project_tagcloud($cloud, 64);
4256 print "<table class=\"project_list\">\n";
4257 unless ($no_header) {
4258 print "<tr>\n";
4259 if ($check_forks) {
4260 print "<th></th>\n";
4262 print_sort_th('project', $order, 'Project');
4263 print_sort_th('descr', $order, 'Description');
4264 print_sort_th('owner', $order, 'Owner');
4265 print_sort_th('age', $order, 'Last Change');
4266 print "<th></th>\n" . # for links
4267 "</tr>\n";
4269 my $alternate = 1;
4270 my $tagfilter = $cgi->param('by_tag');
4271 for (my $i = $from; $i <= $to; $i++) {
4272 my $pr = $projects[$i];
4274 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4275 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4276 and not $pr->{'descr_long'} =~ /$searchtext/;
4277 # Weed out forks or non-matching entries of search
4278 if ($check_forks) {
4279 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4280 $forkbase="^$forkbase" if $forkbase;
4281 next if not $searchtext and not $tagfilter and $show_ctags
4282 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4285 if ($alternate) {
4286 print "<tr class=\"dark\">\n";
4287 } else {
4288 print "<tr class=\"light\">\n";
4290 $alternate ^= 1;
4291 if ($check_forks) {
4292 print "<td>";
4293 if ($pr->{'forks'}) {
4294 print "<!-- $pr->{'forks'} -->\n";
4295 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4297 print "</td>\n";
4299 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4300 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4301 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4302 -class => "list", -title => $pr->{'descr_long'}},
4303 esc_html($pr->{'descr'})) . "</td>\n" .
4304 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4305 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4306 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4307 "<td class=\"link\">" .
4308 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4309 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4310 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4311 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4312 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4313 "</td>\n" .
4314 "</tr>\n";
4316 if (defined $extra) {
4317 print "<tr>\n";
4318 if ($check_forks) {
4319 print "<td></td>\n";
4321 print "<td colspan=\"5\">$extra</td>\n" .
4322 "</tr>\n";
4324 print "</table>\n";
4327 sub git_shortlog_body {
4328 # uses global variable $project
4329 my ($commitlist, $from, $to, $refs, $extra) = @_;
4331 $from = 0 unless defined $from;
4332 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4334 print "<table class=\"shortlog\">\n";
4335 my $alternate = 1;
4336 for (my $i = $from; $i <= $to; $i++) {
4337 my %co = %{$commitlist->[$i]};
4338 my $commit = $co{'id'};
4339 my $ref = format_ref_marker($refs, $commit);
4340 if ($alternate) {
4341 print "<tr class=\"dark\">\n";
4342 } else {
4343 print "<tr class=\"light\">\n";
4345 $alternate ^= 1;
4346 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4347 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4348 format_author_html('td', \%co, 10) . "<td>";
4349 print format_subject_html($co{'title'}, $co{'title_short'},
4350 href(action=>"commit", hash=>$commit), $ref);
4351 print "</td>\n" .
4352 "<td class=\"link\">" .
4353 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4354 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4355 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4356 my $snapshot_links = format_snapshot_links($commit);
4357 if (defined $snapshot_links) {
4358 print " | " . $snapshot_links;
4360 print "</td>\n" .
4361 "</tr>\n";
4363 if (defined $extra) {
4364 print "<tr>\n" .
4365 "<td colspan=\"4\">$extra</td>\n" .
4366 "</tr>\n";
4368 print "</table>\n";
4371 sub git_history_body {
4372 # Warning: assumes constant type (blob or tree) during history
4373 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4375 $from = 0 unless defined $from;
4376 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4378 print "<table class=\"history\">\n";
4379 my $alternate = 1;
4380 for (my $i = $from; $i <= $to; $i++) {
4381 my %co = %{$commitlist->[$i]};
4382 if (!%co) {
4383 next;
4385 my $commit = $co{'id'};
4387 my $ref = format_ref_marker($refs, $commit);
4389 if ($alternate) {
4390 print "<tr class=\"dark\">\n";
4391 } else {
4392 print "<tr class=\"light\">\n";
4394 $alternate ^= 1;
4395 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4396 # shortlog: format_author_html('td', \%co, 10)
4397 format_author_html('td', \%co, 15, 3) . "<td>";
4398 # originally git_history used chop_str($co{'title'}, 50)
4399 print format_subject_html($co{'title'}, $co{'title_short'},
4400 href(action=>"commit", hash=>$commit), $ref);
4401 print "</td>\n" .
4402 "<td class=\"link\">" .
4403 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4404 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4406 if ($ftype eq 'blob') {
4407 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4408 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4409 if (defined $blob_current && defined $blob_parent &&
4410 $blob_current ne $blob_parent) {
4411 print " | " .
4412 $cgi->a({-href => href(action=>"blobdiff",
4413 hash=>$blob_current, hash_parent=>$blob_parent,
4414 hash_base=>$hash_base, hash_parent_base=>$commit,
4415 file_name=>$file_name)},
4416 "diff to current");
4419 print "</td>\n" .
4420 "</tr>\n";
4422 if (defined $extra) {
4423 print "<tr>\n" .
4424 "<td colspan=\"4\">$extra</td>\n" .
4425 "</tr>\n";
4427 print "</table>\n";
4430 sub git_tags_body {
4431 # uses global variable $project
4432 my ($taglist, $from, $to, $extra) = @_;
4433 $from = 0 unless defined $from;
4434 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4436 print "<table class=\"tags\">\n";
4437 my $alternate = 1;
4438 for (my $i = $from; $i <= $to; $i++) {
4439 my $entry = $taglist->[$i];
4440 my %tag = %$entry;
4441 my $comment = $tag{'subject'};
4442 my $comment_short;
4443 if (defined $comment) {
4444 $comment_short = chop_str($comment, 30, 5);
4446 if ($alternate) {
4447 print "<tr class=\"dark\">\n";
4448 } else {
4449 print "<tr class=\"light\">\n";
4451 $alternate ^= 1;
4452 if (defined $tag{'age'}) {
4453 print "<td><i>$tag{'age'}</i></td>\n";
4454 } else {
4455 print "<td></td>\n";
4457 print "<td>" .
4458 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4459 -class => "list name"}, esc_html($tag{'name'})) .
4460 "</td>\n" .
4461 "<td>";
4462 if (defined $comment) {
4463 print format_subject_html($comment, $comment_short,
4464 href(action=>"tag", hash=>$tag{'id'}));
4466 print "</td>\n" .
4467 "<td class=\"selflink\">";
4468 if ($tag{'type'} eq "tag") {
4469 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4470 } else {
4471 print "&nbsp;";
4473 print "</td>\n" .
4474 "<td class=\"link\">" . " | " .
4475 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4476 if ($tag{'reftype'} eq "commit") {
4477 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4478 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4479 } elsif ($tag{'reftype'} eq "blob") {
4480 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4482 print "</td>\n" .
4483 "</tr>";
4485 if (defined $extra) {
4486 print "<tr>\n" .
4487 "<td colspan=\"5\">$extra</td>\n" .
4488 "</tr>\n";
4490 print "</table>\n";
4493 sub git_heads_body {
4494 # uses global variable $project
4495 my ($headlist, $head, $from, $to, $extra) = @_;
4496 $from = 0 unless defined $from;
4497 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4499 print "<table class=\"heads\">\n";
4500 my $alternate = 1;
4501 for (my $i = $from; $i <= $to; $i++) {
4502 my $entry = $headlist->[$i];
4503 my %ref = %$entry;
4504 my $curr = $ref{'id'} eq $head;
4505 if ($alternate) {
4506 print "<tr class=\"dark\">\n";
4507 } else {
4508 print "<tr class=\"light\">\n";
4510 $alternate ^= 1;
4511 print "<td><i>$ref{'age'}</i></td>\n" .
4512 ($curr ? "<td class=\"current_head\">" : "<td>") .
4513 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4514 -class => "list name"},esc_html($ref{'name'})) .
4515 "</td>\n" .
4516 "<td class=\"link\">" .
4517 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4518 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4519 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4520 "</td>\n" .
4521 "</tr>";
4523 if (defined $extra) {
4524 print "<tr>\n" .
4525 "<td colspan=\"3\">$extra</td>\n" .
4526 "</tr>\n";
4528 print "</table>\n";
4531 sub git_search_grep_body {
4532 my ($commitlist, $from, $to, $extra) = @_;
4533 $from = 0 unless defined $from;
4534 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4536 print "<table class=\"commit_search\">\n";
4537 my $alternate = 1;
4538 for (my $i = $from; $i <= $to; $i++) {
4539 my %co = %{$commitlist->[$i]};
4540 if (!%co) {
4541 next;
4543 my $commit = $co{'id'};
4544 if ($alternate) {
4545 print "<tr class=\"dark\">\n";
4546 } else {
4547 print "<tr class=\"light\">\n";
4549 $alternate ^= 1;
4550 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4551 format_author_html('td', \%co, 15, 5) .
4552 "<td>" .
4553 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4554 -class => "list subject"},
4555 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4556 my $comment = $co{'comment'};
4557 foreach my $line (@$comment) {
4558 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4559 my ($lead, $match, $trail) = ($1, $2, $3);
4560 $match = chop_str($match, 70, 5, 'center');
4561 my $contextlen = int((80 - length($match))/2);
4562 $contextlen = 30 if ($contextlen > 30);
4563 $lead = chop_str($lead, $contextlen, 10, 'left');
4564 $trail = chop_str($trail, $contextlen, 10, 'right');
4566 $lead = esc_html($lead);
4567 $match = esc_html($match);
4568 $trail = esc_html($trail);
4570 print "$lead<span class=\"match\">$match</span>$trail<br />";
4573 print "</td>\n" .
4574 "<td class=\"link\">" .
4575 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4576 " | " .
4577 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4578 " | " .
4579 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4580 print "</td>\n" .
4581 "</tr>\n";
4583 if (defined $extra) {
4584 print "<tr>\n" .
4585 "<td colspan=\"3\">$extra</td>\n" .
4586 "</tr>\n";
4588 print "</table>\n";
4591 ## ======================================================================
4592 ## ======================================================================
4593 ## actions
4595 sub git_project_list {
4596 my $order = $input_params{'order'};
4597 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4598 die_error(400, "Unknown order parameter");
4601 my @list = git_get_projects_list();
4602 if (!@list) {
4603 die_error(404, "No projects found");
4606 git_header_html();
4607 if (-f $home_text) {
4608 print "<div class=\"index_include\">\n";
4609 insert_file($home_text);
4610 print "</div>\n";
4612 print $cgi->startform(-method => "get") .
4613 "<p class=\"projsearch\">Search:\n" .
4614 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4615 "</p>" .
4616 $cgi->end_form() . "\n";
4617 git_project_list_body(\@list, $order);
4618 git_footer_html();
4621 sub git_forks {
4622 my $order = $input_params{'order'};
4623 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4624 die_error(400, "Unknown order parameter");
4627 my @list = git_get_projects_list($project);
4628 if (!@list) {
4629 die_error(404, "No forks found");
4632 git_header_html();
4633 git_print_page_nav('','');
4634 git_print_header_div('summary', "$project forks");
4635 git_project_list_body(\@list, $order);
4636 git_footer_html();
4639 sub git_project_index {
4640 my @projects = git_get_projects_list($project);
4642 print $cgi->header(
4643 -type => 'text/plain',
4644 -charset => 'utf-8',
4645 -content_disposition => 'inline; filename="index.aux"');
4647 foreach my $pr (@projects) {
4648 if (!exists $pr->{'owner'}) {
4649 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4652 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4653 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4654 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4655 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4656 $path =~ s/ /\+/g;
4657 $owner =~ s/ /\+/g;
4659 print "$path $owner\n";
4663 sub git_summary {
4664 my $descr = git_get_project_description($project) || "none";
4665 my %co = parse_commit("HEAD");
4666 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4667 my $head = $co{'id'};
4669 my $owner = git_get_project_owner($project);
4671 my $refs = git_get_references();
4672 # These get_*_list functions return one more to allow us to see if
4673 # there are more ...
4674 my @taglist = git_get_tags_list(16);
4675 my @headlist = git_get_heads_list(16);
4676 my @forklist;
4677 my $check_forks = gitweb_check_feature('forks');
4679 if ($check_forks) {
4680 @forklist = git_get_projects_list($project);
4683 git_header_html();
4684 git_print_page_nav('summary','', $head);
4686 print "<div class=\"title\">&nbsp;</div>\n";
4687 print "<table class=\"projects_list\">\n" .
4688 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4689 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4690 if (defined $cd{'rfc2822'}) {
4691 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4694 # use per project git URL list in $projectroot/$project/cloneurl
4695 # or make project git URL from git base URL and project name
4696 my $url_tag = "URL";
4697 my @url_list = git_get_project_url_list($project);
4698 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4699 foreach my $git_url (@url_list) {
4700 next unless $git_url;
4701 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4702 $url_tag = "";
4705 # Tag cloud
4706 my $show_ctags = gitweb_check_feature('ctags');
4707 if ($show_ctags) {
4708 my $ctags = git_get_project_ctags($project);
4709 my $cloud = git_populate_project_tagcloud($ctags);
4710 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4711 print "</td>\n<td>" unless %$ctags;
4712 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4713 print "</td>\n<td>" if %$ctags;
4714 print git_show_project_tagcloud($cloud, 48);
4715 print "</td></tr>";
4718 print "</table>\n";
4720 # If XSS prevention is on, we don't include README.html.
4721 # TODO: Allow a readme in some safe format.
4722 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4723 print "<div class=\"title\">readme</div>\n" .
4724 "<div class=\"readme\">\n";
4725 insert_file("$projectroot/$project/README.html");
4726 print "\n</div>\n"; # class="readme"
4729 # we need to request one more than 16 (0..15) to check if
4730 # those 16 are all
4731 my @commitlist = $head ? parse_commits($head, 17) : ();
4732 if (@commitlist) {
4733 git_print_header_div('shortlog');
4734 git_shortlog_body(\@commitlist, 0, 15, $refs,
4735 $#commitlist <= 15 ? undef :
4736 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4739 if (@taglist) {
4740 git_print_header_div('tags');
4741 git_tags_body(\@taglist, 0, 15,
4742 $#taglist <= 15 ? undef :
4743 $cgi->a({-href => href(action=>"tags")}, "..."));
4746 if (@headlist) {
4747 git_print_header_div('heads');
4748 git_heads_body(\@headlist, $head, 0, 15,
4749 $#headlist <= 15 ? undef :
4750 $cgi->a({-href => href(action=>"heads")}, "..."));
4753 if (@forklist) {
4754 git_print_header_div('forks');
4755 git_project_list_body(\@forklist, 'age', 0, 15,
4756 $#forklist <= 15 ? undef :
4757 $cgi->a({-href => href(action=>"forks")}, "..."),
4758 'no_header');
4761 git_footer_html();
4764 sub git_tag {
4765 my $head = git_get_head_hash($project);
4766 git_header_html();
4767 git_print_page_nav('','', $head,undef,$head);
4768 my %tag = parse_tag($hash);
4770 if (! %tag) {
4771 die_error(404, "Unknown tag object");
4774 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4775 print "<div class=\"title_text\">\n" .
4776 "<table class=\"object_header\">\n" .
4777 "<tr>\n" .
4778 "<td>object</td>\n" .
4779 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4780 $tag{'object'}) . "</td>\n" .
4781 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4782 $tag{'type'}) . "</td>\n" .
4783 "</tr>\n";
4784 if (defined($tag{'author'})) {
4785 git_print_authorship_rows(\%tag, 'author');
4787 print "</table>\n\n" .
4788 "</div>\n";
4789 print "<div class=\"page_body\">";
4790 my $comment = $tag{'comment'};
4791 foreach my $line (@$comment) {
4792 chomp $line;
4793 print esc_html($line, -nbsp=>1) . "<br/>\n";
4795 print "</div>\n";
4796 git_footer_html();
4799 sub git_blame {
4800 # permissions
4801 gitweb_check_feature('blame')
4802 or die_error(403, "Blame view not allowed");
4804 # error checking
4805 die_error(400, "No file name given") unless $file_name;
4806 $hash_base ||= git_get_head_hash($project);
4807 die_error(404, "Couldn't find base commit") unless $hash_base;
4808 my %co = parse_commit($hash_base)
4809 or die_error(404, "Commit not found");
4810 my $ftype = "blob";
4811 if (!defined $hash) {
4812 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4813 or die_error(404, "Error looking up file");
4814 } else {
4815 $ftype = git_get_type($hash);
4816 if ($ftype !~ "blob") {
4817 die_error(400, "Object is not a blob");
4821 # run git-blame --porcelain
4822 open my $fd, "-|", git_cmd(), "blame", '-p',
4823 $hash_base, '--', $file_name
4824 or die_error(500, "Open git-blame failed");
4826 # page header
4827 git_header_html();
4828 my $formats_nav =
4829 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4830 "blob") .
4831 " | " .
4832 $cgi->a({-href => href(action=>"history", -replay=>1)},
4833 "history") .
4834 " | " .
4835 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4836 "HEAD");
4837 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4838 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4839 git_print_page_path($file_name, $ftype, $hash_base);
4841 # page body
4842 my @rev_color = qw(light dark);
4843 my $num_colors = scalar(@rev_color);
4844 my $current_color = 0;
4845 my %metainfo = ();
4847 print <<HTML;
4848 <div class="page_body">
4849 <table class="blame">
4850 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4851 HTML
4852 LINE:
4853 while (my $line = <$fd>) {
4854 chomp $line;
4855 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4856 # no <lines in group> for subsequent lines in group of lines
4857 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4858 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
4859 if (!exists $metainfo{$full_rev}) {
4860 $metainfo{$full_rev} = { 'nprevious' => 0 };
4862 my $meta = $metainfo{$full_rev};
4863 my $data;
4864 while ($data = <$fd>) {
4865 chomp $data;
4866 last if ($data =~ s/^\t//); # contents of line
4867 if ($data =~ /^(\S+)(?: (.*))?$/) {
4868 $meta->{$1} = $2 unless exists $meta->{$1};
4870 if ($data =~ /^previous /) {
4871 $meta->{'nprevious'}++;
4874 my $short_rev = substr($full_rev, 0, 8);
4875 my $author = $meta->{'author'};
4876 my %date =
4877 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
4878 my $date = $date{'iso-tz'};
4879 if ($group_size) {
4880 $current_color = ($current_color + 1) % $num_colors;
4882 my $tr_class = $rev_color[$current_color];
4883 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
4884 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
4885 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
4886 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
4887 if ($group_size) {
4888 print "<td class=\"sha1\"";
4889 print " title=\"". esc_html($author) . ", $date\"";
4890 print " rowspan=\"$group_size\"" if ($group_size > 1);
4891 print ">";
4892 print $cgi->a({-href => href(action=>"commit",
4893 hash=>$full_rev,
4894 file_name=>$file_name)},
4895 esc_html($short_rev));
4896 if ($group_size >= 2) {
4897 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
4898 if (@author_initials) {
4899 print "<br />" .
4900 esc_html(join('', @author_initials));
4901 # or join('.', ...)
4904 print "</td>\n";
4906 # 'previous' <sha1 of parent commit> <filename at commit>
4907 if (exists $meta->{'previous'} &&
4908 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
4909 $meta->{'parent'} = $1;
4910 $meta->{'file_parent'} = unquote($2);
4912 my $linenr_commit =
4913 exists($meta->{'parent'}) ?
4914 $meta->{'parent'} : $full_rev;
4915 my $linenr_filename =
4916 exists($meta->{'file_parent'}) ?
4917 $meta->{'file_parent'} : unquote($meta->{'filename'});
4918 my $blamed = href(action => 'blame',
4919 file_name => $linenr_filename,
4920 hash_base => $linenr_commit);
4921 print "<td class=\"linenr\">";
4922 print $cgi->a({ -href => "$blamed#l$orig_lineno",
4923 -class => "linenr" },
4924 esc_html($lineno));
4925 print "</td>";
4926 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4927 print "</tr>\n";
4929 print "</table>\n";
4930 print "</div>";
4931 close $fd
4932 or print "Reading blob failed\n";
4934 # page footer
4935 git_footer_html();
4938 sub git_tags {
4939 my $head = git_get_head_hash($project);
4940 git_header_html();
4941 git_print_page_nav('','', $head,undef,$head);
4942 git_print_header_div('summary', $project);
4944 my @tagslist = git_get_tags_list();
4945 if (@tagslist) {
4946 git_tags_body(\@tagslist);
4948 git_footer_html();
4951 sub git_heads {
4952 my $head = git_get_head_hash($project);
4953 git_header_html();
4954 git_print_page_nav('','', $head,undef,$head);
4955 git_print_header_div('summary', $project);
4957 my @headslist = git_get_heads_list();
4958 if (@headslist) {
4959 git_heads_body(\@headslist, $head);
4961 git_footer_html();
4964 sub git_blob_plain {
4965 my $type = shift;
4966 my $expires;
4968 if (!defined $hash) {
4969 if (defined $file_name) {
4970 my $base = $hash_base || git_get_head_hash($project);
4971 $hash = git_get_hash_by_path($base, $file_name, "blob")
4972 or die_error(404, "Cannot find file");
4973 } else {
4974 die_error(400, "No file name defined");
4976 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4977 # blobs defined by non-textual hash id's can be cached
4978 $expires = "+1d";
4981 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4982 or die_error(500, "Open git-cat-file blob '$hash' failed");
4984 # content-type (can include charset)
4985 $type = blob_contenttype($fd, $file_name, $type);
4987 # "save as" filename, even when no $file_name is given
4988 my $save_as = "$hash";
4989 if (defined $file_name) {
4990 $save_as = $file_name;
4991 } elsif ($type =~ m/^text\//) {
4992 $save_as .= '.txt';
4995 # With XSS prevention on, blobs of all types except a few known safe
4996 # ones are served with "Content-Disposition: attachment" to make sure
4997 # they don't run in our security domain. For certain image types,
4998 # blob view writes an <img> tag referring to blob_plain view, and we
4999 # want to be sure not to break that by serving the image as an
5000 # attachment (though Firefox 3 doesn't seem to care).
5001 my $sandbox = $prevent_xss &&
5002 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5004 print $cgi->header(
5005 -type => $type,
5006 -expires => $expires,
5007 -content_disposition =>
5008 ($sandbox ? 'attachment' : 'inline')
5009 . '; filename="' . $save_as . '"');
5010 local $/ = undef;
5011 binmode STDOUT, ':raw';
5012 print <$fd>;
5013 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5014 close $fd;
5017 sub git_blob {
5018 my $expires;
5020 if (!defined $hash) {
5021 if (defined $file_name) {
5022 my $base = $hash_base || git_get_head_hash($project);
5023 $hash = git_get_hash_by_path($base, $file_name, "blob")
5024 or die_error(404, "Cannot find file");
5025 } else {
5026 die_error(400, "No file name defined");
5028 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5029 # blobs defined by non-textual hash id's can be cached
5030 $expires = "+1d";
5033 my $have_blame = gitweb_check_feature('blame');
5034 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5035 or die_error(500, "Couldn't cat $file_name, $hash");
5036 my $mimetype = blob_mimetype($fd, $file_name);
5037 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5038 close $fd;
5039 return git_blob_plain($mimetype);
5041 # we can have blame only for text/* mimetype
5042 $have_blame &&= ($mimetype =~ m!^text/!);
5044 git_header_html(undef, $expires);
5045 my $formats_nav = '';
5046 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5047 if (defined $file_name) {
5048 if ($have_blame) {
5049 $formats_nav .=
5050 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5051 "blame") .
5052 " | ";
5054 $formats_nav .=
5055 $cgi->a({-href => href(action=>"history", -replay=>1)},
5056 "history") .
5057 " | " .
5058 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5059 "raw") .
5060 " | " .
5061 $cgi->a({-href => href(action=>"blob",
5062 hash_base=>"HEAD", file_name=>$file_name)},
5063 "HEAD");
5064 } else {
5065 $formats_nav .=
5066 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5067 "raw");
5069 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5070 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5071 } else {
5072 print "<div class=\"page_nav\">\n" .
5073 "<br/><br/></div>\n" .
5074 "<div class=\"title\">$hash</div>\n";
5076 git_print_page_path($file_name, "blob", $hash_base);
5077 print "<div class=\"page_body\">\n";
5078 if ($mimetype =~ m!^image/!) {
5079 print qq!<img type="$mimetype"!;
5080 if ($file_name) {
5081 print qq! alt="$file_name" title="$file_name"!;
5083 print qq! src="! .
5084 href(action=>"blob_plain", hash=>$hash,
5085 hash_base=>$hash_base, file_name=>$file_name) .
5086 qq!" />\n!;
5087 } else {
5088 my $nr;
5089 while (my $line = <$fd>) {
5090 chomp $line;
5091 $nr++;
5092 $line = untabify($line);
5093 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5094 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5097 close $fd
5098 or print "Reading blob failed.\n";
5099 print "</div>";
5100 git_footer_html();
5103 sub git_tree {
5104 if (!defined $hash_base) {
5105 $hash_base = "HEAD";
5107 if (!defined $hash) {
5108 if (defined $file_name) {
5109 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5110 } else {
5111 $hash = $hash_base;
5114 die_error(404, "No such tree") unless defined($hash);
5116 my @entries = ();
5118 local $/ = "\0";
5119 open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
5120 or die_error(500, "Open git-ls-tree failed");
5121 @entries = map { chomp; $_ } <$fd>;
5122 close $fd
5123 or die_error(404, "Reading tree failed");
5126 my $refs = git_get_references();
5127 my $ref = format_ref_marker($refs, $hash_base);
5128 git_header_html();
5129 my $basedir = '';
5130 my $have_blame = gitweb_check_feature('blame');
5131 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5132 my @views_nav = ();
5133 if (defined $file_name) {
5134 push @views_nav,
5135 $cgi->a({-href => href(action=>"history", -replay=>1)},
5136 "history"),
5137 $cgi->a({-href => href(action=>"tree",
5138 hash_base=>"HEAD", file_name=>$file_name)},
5139 "HEAD"),
5141 my $snapshot_links = format_snapshot_links($hash);
5142 if (defined $snapshot_links) {
5143 # FIXME: Should be available when we have no hash base as well.
5144 push @views_nav, $snapshot_links;
5146 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
5147 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5148 } else {
5149 undef $hash_base;
5150 print "<div class=\"page_nav\">\n";
5151 print "<br/><br/></div>\n";
5152 print "<div class=\"title\">$hash</div>\n";
5154 if (defined $file_name) {
5155 $basedir = $file_name;
5156 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5157 $basedir .= '/';
5159 git_print_page_path($file_name, 'tree', $hash_base);
5161 print "<div class=\"page_body\">\n";
5162 print "<table class=\"tree\">\n";
5163 my $alternate = 1;
5164 # '..' (top directory) link if possible
5165 if (defined $hash_base &&
5166 defined $file_name && $file_name =~ m![^/]+$!) {
5167 if ($alternate) {
5168 print "<tr class=\"dark\">\n";
5169 } else {
5170 print "<tr class=\"light\">\n";
5172 $alternate ^= 1;
5174 my $up = $file_name;
5175 $up =~ s!/?[^/]+$!!;
5176 undef $up unless $up;
5177 # based on git_print_tree_entry
5178 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5179 print '<td class="list">';
5180 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
5181 file_name=>$up)},
5182 "..");
5183 print "</td>\n";
5184 print "<td class=\"link\"></td>\n";
5186 print "</tr>\n";
5188 foreach my $line (@entries) {
5189 my %t = parse_ls_tree_line($line, -z => 1);
5191 if ($alternate) {
5192 print "<tr class=\"dark\">\n";
5193 } else {
5194 print "<tr class=\"light\">\n";
5196 $alternate ^= 1;
5198 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5200 print "</tr>\n";
5202 print "</table>\n" .
5203 "</div>";
5204 git_footer_html();
5207 sub git_snapshot {
5208 my $format = $input_params{'snapshot_format'};
5209 if (!@snapshot_fmts) {
5210 die_error(403, "Snapshots not allowed");
5212 # default to first supported snapshot format
5213 $format ||= $snapshot_fmts[0];
5214 if ($format !~ m/^[a-z0-9]+$/) {
5215 die_error(400, "Invalid snapshot format parameter");
5216 } elsif (!exists($known_snapshot_formats{$format})) {
5217 die_error(400, "Unknown snapshot format");
5218 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5219 die_error(403, "Snapshot format not allowed");
5220 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5221 die_error(403, "Unsupported snapshot format");
5224 my $type = git_get_type("$hash^{}");
5225 if (!$type) {
5226 die_error(404, 'Object does not exist');
5227 } elsif ($type eq 'blob') {
5228 die_error(400, 'Object is not a tree-ish');
5232 my $full_hash = git_get_full_hash($project, $hash);
5233 if ($full_hash =~ /^$hash/) {
5234 $hash = git_get_short_hash($project, $hash);
5235 } else {
5236 $hash .= '-' . git_get_short_hash($project, $hash);
5238 my $name = $project;
5239 $name =~ s,([^/])/*\.git$,$1,;
5240 $name = basename($name);
5241 my $filename = to_utf8($name);
5242 $name =~ s/\047/\047\\\047\047/g;
5243 my $cmd;
5244 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5245 $cmd = quote_command(
5246 git_cmd(), 'archive',
5247 "--format=$known_snapshot_formats{$format}{'format'}",
5248 "--prefix=$name/", $full_hash);
5249 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5250 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5253 print $cgi->header(
5254 -type => $known_snapshot_formats{$format}{'type'},
5255 -content_disposition => 'inline; filename="' . "$filename" . '"',
5256 -status => '200 OK');
5258 open my $fd, "-|", $cmd
5259 or die_error(500, "Execute git-archive failed");
5260 binmode STDOUT, ':raw';
5261 print <$fd>;
5262 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5263 close $fd;
5266 sub git_log {
5267 my $head = git_get_head_hash($project);
5268 if (!defined $hash) {
5269 $hash = $head;
5271 if (!defined $page) {
5272 $page = 0;
5274 my $refs = git_get_references();
5276 my @commitlist = parse_commits($hash, 101, (100 * $page));
5278 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
5280 my ($patch_max) = gitweb_get_feature('patches');
5281 if ($patch_max) {
5282 if ($patch_max < 0 || @commitlist <= $patch_max) {
5283 $paging_nav .= " &sdot; " .
5284 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5285 "patches");
5289 git_header_html();
5290 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5292 if (!@commitlist) {
5293 my %co = parse_commit($hash);
5295 git_print_header_div('summary', $project);
5296 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5298 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5299 for (my $i = 0; $i <= $to; $i++) {
5300 my %co = %{$commitlist[$i]};
5301 next if !%co;
5302 my $commit = $co{'id'};
5303 my $ref = format_ref_marker($refs, $commit);
5304 my %ad = parse_date($co{'author_epoch'});
5305 git_print_header_div('commit',
5306 "<span class=\"age\">$co{'age_string'}</span>" .
5307 esc_html($co{'title'}) . $ref,
5308 $commit);
5309 print "<div class=\"title_text\">\n" .
5310 "<div class=\"log_link\">\n" .
5311 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5312 " | " .
5313 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5314 " | " .
5315 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5316 "<br/>\n" .
5317 "</div>\n";
5318 git_print_authorship(\%co, -tag => 'span');
5319 print "<br/>\n</div>\n";
5321 print "<div class=\"log_body\">\n";
5322 git_print_log($co{'comment'}, -final_empty_line=> 1);
5323 print "</div>\n";
5325 if ($#commitlist >= 100) {
5326 print "<div class=\"page_nav\">\n";
5327 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5328 -accesskey => "n", -title => "Alt-n"}, "next");
5329 print "</div>\n";
5331 git_footer_html();
5334 sub git_commit {
5335 $hash ||= $hash_base || "HEAD";
5336 my %co = parse_commit($hash)
5337 or die_error(404, "Unknown commit object");
5339 my $parent = $co{'parent'};
5340 my $parents = $co{'parents'}; # listref
5342 # we need to prepare $formats_nav before any parameter munging
5343 my $formats_nav;
5344 if (!defined $parent) {
5345 # --root commitdiff
5346 $formats_nav .= '(initial)';
5347 } elsif (@$parents == 1) {
5348 # single parent commit
5349 $formats_nav .=
5350 '(parent: ' .
5351 $cgi->a({-href => href(action=>"commit",
5352 hash=>$parent)},
5353 esc_html(substr($parent, 0, 7))) .
5354 ')';
5355 } else {
5356 # merge commit
5357 $formats_nav .=
5358 '(merge: ' .
5359 join(' ', map {
5360 $cgi->a({-href => href(action=>"commit",
5361 hash=>$_)},
5362 esc_html(substr($_, 0, 7)));
5363 } @$parents ) .
5364 ')';
5366 if (gitweb_check_feature('patches')) {
5367 $formats_nav .= " | " .
5368 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5369 "patch");
5372 if (!defined $parent) {
5373 $parent = "--root";
5375 my @difftree;
5376 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5377 @diff_opts,
5378 (@$parents <= 1 ? $parent : '-c'),
5379 $hash, "--"
5380 or die_error(500, "Open git-diff-tree failed");
5381 @difftree = map { chomp; $_ } <$fd>;
5382 close $fd or die_error(404, "Reading git-diff-tree failed");
5384 # non-textual hash id's can be cached
5385 my $expires;
5386 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5387 $expires = "+1d";
5389 my $refs = git_get_references();
5390 my $ref = format_ref_marker($refs, $co{'id'});
5392 git_header_html(undef, $expires);
5393 git_print_page_nav('commit', '',
5394 $hash, $co{'tree'}, $hash,
5395 $formats_nav);
5397 if (defined $co{'parent'}) {
5398 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5399 } else {
5400 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5402 print "<div class=\"title_text\">\n" .
5403 "<table class=\"object_header\">\n";
5404 git_print_authorship_rows(\%co);
5405 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5406 print "<tr>" .
5407 "<td>tree</td>" .
5408 "<td class=\"sha1\">" .
5409 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5410 class => "list"}, $co{'tree'}) .
5411 "</td>" .
5412 "<td class=\"link\">" .
5413 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5414 "tree");
5415 my $snapshot_links = format_snapshot_links($hash);
5416 if (defined $snapshot_links) {
5417 print " | " . $snapshot_links;
5419 print "</td>" .
5420 "</tr>\n";
5422 foreach my $par (@$parents) {
5423 print "<tr>" .
5424 "<td>parent</td>" .
5425 "<td class=\"sha1\">" .
5426 $cgi->a({-href => href(action=>"commit", hash=>$par),
5427 class => "list"}, $par) .
5428 "</td>" .
5429 "<td class=\"link\">" .
5430 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5431 " | " .
5432 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5433 "</td>" .
5434 "</tr>\n";
5436 print "</table>".
5437 "</div>\n";
5439 print "<div class=\"page_body\">\n";
5440 git_print_log($co{'comment'});
5441 print "</div>\n";
5443 git_difftree_body(\@difftree, $hash, @$parents);
5445 git_footer_html();
5448 sub git_object {
5449 # object is defined by:
5450 # - hash or hash_base alone
5451 # - hash_base and file_name
5452 my $type;
5454 # - hash or hash_base alone
5455 if ($hash || ($hash_base && !defined $file_name)) {
5456 my $object_id = $hash || $hash_base;
5458 open my $fd, "-|", quote_command(
5459 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5460 or die_error(404, "Object does not exist");
5461 $type = <$fd>;
5462 chomp $type;
5463 close $fd
5464 or die_error(404, "Object does not exist");
5466 # - hash_base and file_name
5467 } elsif ($hash_base && defined $file_name) {
5468 $file_name =~ s,/+$,,;
5470 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5471 or die_error(404, "Base object does not exist");
5473 # here errors should not hapen
5474 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5475 or die_error(500, "Open git-ls-tree failed");
5476 my $line = <$fd>;
5477 close $fd;
5479 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5480 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5481 die_error(404, "File or directory for given base does not exist");
5483 $type = $2;
5484 $hash = $3;
5485 } else {
5486 die_error(400, "Not enough information to find object");
5489 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5490 hash=>$hash, hash_base=>$hash_base,
5491 file_name=>$file_name),
5492 -status => '302 Found');
5495 sub git_blobdiff {
5496 my $format = shift || 'html';
5498 my $fd;
5499 my @difftree;
5500 my %diffinfo;
5501 my $expires;
5503 # preparing $fd and %diffinfo for git_patchset_body
5504 # new style URI
5505 if (defined $hash_base && defined $hash_parent_base) {
5506 if (defined $file_name) {
5507 # read raw output
5508 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5509 $hash_parent_base, $hash_base,
5510 "--", (defined $file_parent ? $file_parent : ()), $file_name
5511 or die_error(500, "Open git-diff-tree failed");
5512 @difftree = map { chomp; $_ } <$fd>;
5513 close $fd
5514 or die_error(404, "Reading git-diff-tree failed");
5515 @difftree
5516 or die_error(404, "Blob diff not found");
5518 } elsif (defined $hash &&
5519 $hash =~ /[0-9a-fA-F]{40}/) {
5520 # try to find filename from $hash
5522 # read filtered raw output
5523 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5524 $hash_parent_base, $hash_base, "--"
5525 or die_error(500, "Open git-diff-tree failed");
5526 @difftree =
5527 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5528 # $hash == to_id
5529 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5530 map { chomp; $_ } <$fd>;
5531 close $fd
5532 or die_error(404, "Reading git-diff-tree failed");
5533 @difftree
5534 or die_error(404, "Blob diff not found");
5536 } else {
5537 die_error(400, "Missing one of the blob diff parameters");
5540 if (@difftree > 1) {
5541 die_error(400, "Ambiguous blob diff specification");
5544 %diffinfo = parse_difftree_raw_line($difftree[0]);
5545 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5546 $file_name ||= $diffinfo{'to_file'};
5548 $hash_parent ||= $diffinfo{'from_id'};
5549 $hash ||= $diffinfo{'to_id'};
5551 # non-textual hash id's can be cached
5552 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5553 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5554 $expires = '+1d';
5557 # open patch output
5558 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5559 '-p', ($format eq 'html' ? "--full-index" : ()),
5560 $hash_parent_base, $hash_base,
5561 "--", (defined $file_parent ? $file_parent : ()), $file_name
5562 or die_error(500, "Open git-diff-tree failed");
5565 # old/legacy style URI -- not generated anymore since 1.4.3.
5566 if (!%diffinfo) {
5567 die_error('404 Not Found', "Missing one of the blob diff parameters")
5570 # header
5571 if ($format eq 'html') {
5572 my $formats_nav =
5573 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5574 "raw");
5575 git_header_html(undef, $expires);
5576 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5577 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5578 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5579 } else {
5580 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5581 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5583 if (defined $file_name) {
5584 git_print_page_path($file_name, "blob", $hash_base);
5585 } else {
5586 print "<div class=\"page_path\"></div>\n";
5589 } elsif ($format eq 'plain') {
5590 print $cgi->header(
5591 -type => 'text/plain',
5592 -charset => 'utf-8',
5593 -expires => $expires,
5594 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5596 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5598 } else {
5599 die_error(400, "Unknown blobdiff format");
5602 # patch
5603 if ($format eq 'html') {
5604 print "<div class=\"page_body\">\n";
5606 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5607 close $fd;
5609 print "</div>\n"; # class="page_body"
5610 git_footer_html();
5612 } else {
5613 while (my $line = <$fd>) {
5614 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5615 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5617 print $line;
5619 last if $line =~ m!^\+\+\+!;
5621 local $/ = undef;
5622 print <$fd>;
5623 close $fd;
5627 sub git_blobdiff_plain {
5628 git_blobdiff('plain');
5631 sub git_commitdiff {
5632 my %params = @_;
5633 my $format = $params{-format} || 'html';
5635 my ($patch_max) = gitweb_get_feature('patches');
5636 if ($format eq 'patch') {
5637 die_error(403, "Patch view not allowed") unless $patch_max;
5640 $hash ||= $hash_base || "HEAD";
5641 my %co = parse_commit($hash)
5642 or die_error(404, "Unknown commit object");
5644 # choose format for commitdiff for merge
5645 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5646 $hash_parent = '--cc';
5648 # we need to prepare $formats_nav before almost any parameter munging
5649 my $formats_nav;
5650 if ($format eq 'html') {
5651 $formats_nav =
5652 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5653 "raw");
5654 if ($patch_max) {
5655 $formats_nav .= " | " .
5656 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5657 "patch");
5660 if (defined $hash_parent &&
5661 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5662 # commitdiff with two commits given
5663 my $hash_parent_short = $hash_parent;
5664 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5665 $hash_parent_short = substr($hash_parent, 0, 7);
5667 $formats_nav .=
5668 ' (from';
5669 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5670 if ($co{'parents'}[$i] eq $hash_parent) {
5671 $formats_nav .= ' parent ' . ($i+1);
5672 last;
5675 $formats_nav .= ': ' .
5676 $cgi->a({-href => href(action=>"commitdiff",
5677 hash=>$hash_parent)},
5678 esc_html($hash_parent_short)) .
5679 ')';
5680 } elsif (!$co{'parent'}) {
5681 # --root commitdiff
5682 $formats_nav .= ' (initial)';
5683 } elsif (scalar @{$co{'parents'}} == 1) {
5684 # single parent commit
5685 $formats_nav .=
5686 ' (parent: ' .
5687 $cgi->a({-href => href(action=>"commitdiff",
5688 hash=>$co{'parent'})},
5689 esc_html(substr($co{'parent'}, 0, 7))) .
5690 ')';
5691 } else {
5692 # merge commit
5693 if ($hash_parent eq '--cc') {
5694 $formats_nav .= ' | ' .
5695 $cgi->a({-href => href(action=>"commitdiff",
5696 hash=>$hash, hash_parent=>'-c')},
5697 'combined');
5698 } else { # $hash_parent eq '-c'
5699 $formats_nav .= ' | ' .
5700 $cgi->a({-href => href(action=>"commitdiff",
5701 hash=>$hash, hash_parent=>'--cc')},
5702 'compact');
5704 $formats_nav .=
5705 ' (merge: ' .
5706 join(' ', map {
5707 $cgi->a({-href => href(action=>"commitdiff",
5708 hash=>$_)},
5709 esc_html(substr($_, 0, 7)));
5710 } @{$co{'parents'}} ) .
5711 ')';
5715 my $hash_parent_param = $hash_parent;
5716 if (!defined $hash_parent_param) {
5717 # --cc for multiple parents, --root for parentless
5718 $hash_parent_param =
5719 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5722 # read commitdiff
5723 my $fd;
5724 my @difftree;
5725 if ($format eq 'html') {
5726 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5727 "--no-commit-id", "--patch-with-raw", "--full-index",
5728 $hash_parent_param, $hash, "--"
5729 or die_error(500, "Open git-diff-tree failed");
5731 while (my $line = <$fd>) {
5732 chomp $line;
5733 # empty line ends raw part of diff-tree output
5734 last unless $line;
5735 push @difftree, scalar parse_difftree_raw_line($line);
5738 } elsif ($format eq 'plain') {
5739 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5740 '-p', $hash_parent_param, $hash, "--"
5741 or die_error(500, "Open git-diff-tree failed");
5742 } elsif ($format eq 'patch') {
5743 # For commit ranges, we limit the output to the number of
5744 # patches specified in the 'patches' feature.
5745 # For single commits, we limit the output to a single patch,
5746 # diverging from the git-format-patch default.
5747 my @commit_spec = ();
5748 if ($hash_parent) {
5749 if ($patch_max > 0) {
5750 push @commit_spec, "-$patch_max";
5752 push @commit_spec, '-n', "$hash_parent..$hash";
5753 } else {
5754 if ($params{-single}) {
5755 push @commit_spec, '-1';
5756 } else {
5757 if ($patch_max > 0) {
5758 push @commit_spec, "-$patch_max";
5760 push @commit_spec, "-n";
5762 push @commit_spec, '--root', $hash;
5764 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5765 '--stdout', @commit_spec
5766 or die_error(500, "Open git-format-patch failed");
5767 } else {
5768 die_error(400, "Unknown commitdiff format");
5771 # non-textual hash id's can be cached
5772 my $expires;
5773 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5774 $expires = "+1d";
5777 # write commit message
5778 if ($format eq 'html') {
5779 my $refs = git_get_references();
5780 my $ref = format_ref_marker($refs, $co{'id'});
5782 git_header_html(undef, $expires);
5783 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5784 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5785 print "<div class=\"title_text\">\n" .
5786 "<table class=\"object_header\">\n";
5787 git_print_authorship_rows(\%co);
5788 print "</table>".
5789 "</div>\n";
5790 print "<div class=\"page_body\">\n";
5791 if (@{$co{'comment'}} > 1) {
5792 print "<div class=\"log\">\n";
5793 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5794 print "</div>\n"; # class="log"
5797 } elsif ($format eq 'plain') {
5798 my $refs = git_get_references("tags");
5799 my $tagname = git_get_rev_name_tags($hash);
5800 my $filename = basename($project) . "-$hash.patch";
5802 print $cgi->header(
5803 -type => 'text/plain',
5804 -charset => 'utf-8',
5805 -expires => $expires,
5806 -content_disposition => 'inline; filename="' . "$filename" . '"');
5807 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5808 print "From: " . to_utf8($co{'author'}) . "\n";
5809 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5810 print "Subject: " . to_utf8($co{'title'}) . "\n";
5812 print "X-Git-Tag: $tagname\n" if $tagname;
5813 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5815 foreach my $line (@{$co{'comment'}}) {
5816 print to_utf8($line) . "\n";
5818 print "---\n\n";
5819 } elsif ($format eq 'patch') {
5820 my $filename = basename($project) . "-$hash.patch";
5822 print $cgi->header(
5823 -type => 'text/plain',
5824 -charset => 'utf-8',
5825 -expires => $expires,
5826 -content_disposition => 'inline; filename="' . "$filename" . '"');
5829 # write patch
5830 if ($format eq 'html') {
5831 my $use_parents = !defined $hash_parent ||
5832 $hash_parent eq '-c' || $hash_parent eq '--cc';
5833 git_difftree_body(\@difftree, $hash,
5834 $use_parents ? @{$co{'parents'}} : $hash_parent);
5835 print "<br/>\n";
5837 git_patchset_body($fd, \@difftree, $hash,
5838 $use_parents ? @{$co{'parents'}} : $hash_parent);
5839 close $fd;
5840 print "</div>\n"; # class="page_body"
5841 git_footer_html();
5843 } elsif ($format eq 'plain') {
5844 local $/ = undef;
5845 print <$fd>;
5846 close $fd
5847 or print "Reading git-diff-tree failed\n";
5848 } elsif ($format eq 'patch') {
5849 local $/ = undef;
5850 print <$fd>;
5851 close $fd
5852 or print "Reading git-format-patch failed\n";
5856 sub git_commitdiff_plain {
5857 git_commitdiff(-format => 'plain');
5860 # format-patch-style patches
5861 sub git_patch {
5862 git_commitdiff(-format => 'patch', -single=> 1);
5865 sub git_patches {
5866 git_commitdiff(-format => 'patch');
5869 sub git_history {
5870 if (!defined $hash_base) {
5871 $hash_base = git_get_head_hash($project);
5873 if (!defined $page) {
5874 $page = 0;
5876 my $ftype;
5877 my %co = parse_commit($hash_base)
5878 or die_error(404, "Unknown commit object");
5880 my $refs = git_get_references();
5881 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5883 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5884 $file_name, "--full-history")
5885 or die_error(404, "No such file or directory on given branch");
5887 if (!defined $hash && defined $file_name) {
5888 # some commits could have deleted file in question,
5889 # and not have it in tree, but one of them has to have it
5890 for (my $i = 0; $i <= @commitlist; $i++) {
5891 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5892 last if defined $hash;
5895 if (defined $hash) {
5896 $ftype = git_get_type($hash);
5898 if (!defined $ftype) {
5899 die_error(500, "Unknown type of object");
5902 my $paging_nav = '';
5903 if ($page > 0) {
5904 $paging_nav .=
5905 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5906 file_name=>$file_name)},
5907 "first");
5908 $paging_nav .= " &sdot; " .
5909 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5910 -accesskey => "p", -title => "Alt-p"}, "prev");
5911 } else {
5912 $paging_nav .= "first";
5913 $paging_nav .= " &sdot; prev";
5915 my $next_link = '';
5916 if ($#commitlist >= 100) {
5917 $next_link =
5918 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5919 -accesskey => "n", -title => "Alt-n"}, "next");
5920 $paging_nav .= " &sdot; $next_link";
5921 } else {
5922 $paging_nav .= " &sdot; next";
5925 git_header_html();
5926 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5927 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5928 git_print_page_path($file_name, $ftype, $hash_base);
5930 git_history_body(\@commitlist, 0, 99,
5931 $refs, $hash_base, $ftype, $next_link);
5933 git_footer_html();
5936 sub git_search {
5937 gitweb_check_feature('search') or die_error(403, "Search is disabled");
5938 if (!defined $searchtext) {
5939 die_error(400, "Text field is empty");
5941 if (!defined $hash) {
5942 $hash = git_get_head_hash($project);
5944 my %co = parse_commit($hash);
5945 if (!%co) {
5946 die_error(404, "Unknown commit object");
5948 if (!defined $page) {
5949 $page = 0;
5952 $searchtype ||= 'commit';
5953 if ($searchtype eq 'pickaxe') {
5954 # pickaxe may take all resources of your box and run for several minutes
5955 # with every query - so decide by yourself how public you make this feature
5956 gitweb_check_feature('pickaxe')
5957 or die_error(403, "Pickaxe is disabled");
5959 if ($searchtype eq 'grep') {
5960 gitweb_check_feature('grep')
5961 or die_error(403, "Grep is disabled");
5964 git_header_html();
5966 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5967 my $greptype;
5968 if ($searchtype eq 'commit') {
5969 $greptype = "--grep=";
5970 } elsif ($searchtype eq 'author') {
5971 $greptype = "--author=";
5972 } elsif ($searchtype eq 'committer') {
5973 $greptype = "--committer=";
5975 $greptype .= $searchtext;
5976 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5977 $greptype, '--regexp-ignore-case',
5978 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5980 my $paging_nav = '';
5981 if ($page > 0) {
5982 $paging_nav .=
5983 $cgi->a({-href => href(action=>"search", hash=>$hash,
5984 searchtext=>$searchtext,
5985 searchtype=>$searchtype)},
5986 "first");
5987 $paging_nav .= " &sdot; " .
5988 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5989 -accesskey => "p", -title => "Alt-p"}, "prev");
5990 } else {
5991 $paging_nav .= "first";
5992 $paging_nav .= " &sdot; prev";
5994 my $next_link = '';
5995 if ($#commitlist >= 100) {
5996 $next_link =
5997 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5998 -accesskey => "n", -title => "Alt-n"}, "next");
5999 $paging_nav .= " &sdot; $next_link";
6000 } else {
6001 $paging_nav .= " &sdot; next";
6004 if ($#commitlist >= 100) {
6007 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6008 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6009 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6012 if ($searchtype eq 'pickaxe') {
6013 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6014 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6016 print "<table class=\"pickaxe search\">\n";
6017 my $alternate = 1;
6018 local $/ = "\n";
6019 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6020 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6021 ($search_use_regexp ? '--pickaxe-regex' : ());
6022 undef %co;
6023 my @files;
6024 while (my $line = <$fd>) {
6025 chomp $line;
6026 next unless $line;
6028 my %set = parse_difftree_raw_line($line);
6029 if (defined $set{'commit'}) {
6030 # finish previous commit
6031 if (%co) {
6032 print "</td>\n" .
6033 "<td class=\"link\">" .
6034 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6035 " | " .
6036 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6037 print "</td>\n" .
6038 "</tr>\n";
6041 if ($alternate) {
6042 print "<tr class=\"dark\">\n";
6043 } else {
6044 print "<tr class=\"light\">\n";
6046 $alternate ^= 1;
6047 %co = parse_commit($set{'commit'});
6048 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6049 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6050 "<td><i>$author</i></td>\n" .
6051 "<td>" .
6052 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6053 -class => "list subject"},
6054 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6055 } elsif (defined $set{'to_id'}) {
6056 next if ($set{'to_id'} =~ m/^0{40}$/);
6058 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6059 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6060 -class => "list"},
6061 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6062 "<br/>\n";
6065 close $fd;
6067 # finish last commit (warning: repetition!)
6068 if (%co) {
6069 print "</td>\n" .
6070 "<td class=\"link\">" .
6071 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6072 " | " .
6073 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6074 print "</td>\n" .
6075 "</tr>\n";
6078 print "</table>\n";
6081 if ($searchtype eq 'grep') {
6082 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6083 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6085 print "<table class=\"grep_search\">\n";
6086 my $alternate = 1;
6087 my $matches = 0;
6088 local $/ = "\n";
6089 open my $fd, "-|", git_cmd(), 'grep', '-n',
6090 $search_use_regexp ? ('-E', '-i') : '-F',
6091 $searchtext, $co{'tree'};
6092 my $lastfile = '';
6093 while (my $line = <$fd>) {
6094 chomp $line;
6095 my ($file, $lno, $ltext, $binary);
6096 last if ($matches++ > 1000);
6097 if ($line =~ /^Binary file (.+) matches$/) {
6098 $file = $1;
6099 $binary = 1;
6100 } else {
6101 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6103 if ($file ne $lastfile) {
6104 $lastfile and print "</td></tr>\n";
6105 if ($alternate++) {
6106 print "<tr class=\"dark\">\n";
6107 } else {
6108 print "<tr class=\"light\">\n";
6110 print "<td class=\"list\">".
6111 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6112 file_name=>"$file"),
6113 -class => "list"}, esc_path($file));
6114 print "</td><td>\n";
6115 $lastfile = $file;
6117 if ($binary) {
6118 print "<div class=\"binary\">Binary file</div>\n";
6119 } else {
6120 $ltext = untabify($ltext);
6121 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6122 $ltext = esc_html($1, -nbsp=>1);
6123 $ltext .= '<span class="match">';
6124 $ltext .= esc_html($2, -nbsp=>1);
6125 $ltext .= '</span>';
6126 $ltext .= esc_html($3, -nbsp=>1);
6127 } else {
6128 $ltext = esc_html($ltext, -nbsp=>1);
6130 print "<div class=\"pre\">" .
6131 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6132 file_name=>"$file").'#l'.$lno,
6133 -class => "linenr"}, sprintf('%4i', $lno))
6134 . ' ' . $ltext . "</div>\n";
6137 if ($lastfile) {
6138 print "</td></tr>\n";
6139 if ($matches > 1000) {
6140 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6142 } else {
6143 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6145 close $fd;
6147 print "</table>\n";
6149 git_footer_html();
6152 sub git_search_help {
6153 git_header_html();
6154 git_print_page_nav('','', $hash,$hash,$hash);
6155 print <<EOT;
6156 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6157 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6158 the pattern entered is recognized as the POSIX extended
6159 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6160 insensitive).</p>
6161 <dl>
6162 <dt><b>commit</b></dt>
6163 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6165 my $have_grep = gitweb_check_feature('grep');
6166 if ($have_grep) {
6167 print <<EOT;
6168 <dt><b>grep</b></dt>
6169 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6170 a different one) are searched for the given pattern. On large trees, this search can take
6171 a while and put some strain on the server, so please use it with some consideration. Note that
6172 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6173 case-sensitive.</dd>
6176 print <<EOT;
6177 <dt><b>author</b></dt>
6178 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6179 <dt><b>committer</b></dt>
6180 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6182 my $have_pickaxe = gitweb_check_feature('pickaxe');
6183 if ($have_pickaxe) {
6184 print <<EOT;
6185 <dt><b>pickaxe</b></dt>
6186 <dd>All commits that caused the string to appear or disappear from any file (changes that
6187 added, removed or "modified" the string) will be listed. This search can take a while and
6188 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6189 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6192 print "</dl>\n";
6193 git_footer_html();
6196 sub git_shortlog {
6197 my $head = git_get_head_hash($project);
6198 if (!defined $hash) {
6199 $hash = $head;
6201 if (!defined $page) {
6202 $page = 0;
6204 my $refs = git_get_references();
6206 my $commit_hash = $hash;
6207 if (defined $hash_parent) {
6208 $commit_hash = "$hash_parent..$hash";
6210 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6212 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6213 my $next_link = '';
6214 if ($#commitlist >= 100) {
6215 $next_link =
6216 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6217 -accesskey => "n", -title => "Alt-n"}, "next");
6219 my $patch_max = gitweb_check_feature('patches');
6220 if ($patch_max) {
6221 if ($patch_max < 0 || @commitlist <= $patch_max) {
6222 $paging_nav .= " &sdot; " .
6223 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6224 "patches");
6228 git_header_html();
6229 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6230 git_print_header_div('summary', $project);
6232 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6234 git_footer_html();
6237 ## ......................................................................
6238 ## feeds (RSS, Atom; OPML)
6240 sub git_feed {
6241 my $format = shift || 'atom';
6242 my $have_blame = gitweb_check_feature('blame');
6244 # Atom: http://www.atomenabled.org/developers/syndication/
6245 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6246 if ($format ne 'rss' && $format ne 'atom') {
6247 die_error(400, "Unknown web feed format");
6250 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6251 my $head = $hash || 'HEAD';
6252 my @commitlist = parse_commits($head, 150, 0, $file_name);
6254 my %latest_commit;
6255 my %latest_date;
6256 my $content_type = "application/$format+xml";
6257 if (defined $cgi->http('HTTP_ACCEPT') &&
6258 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6259 # browser (feed reader) prefers text/xml
6260 $content_type = 'text/xml';
6262 if (defined($commitlist[0])) {
6263 %latest_commit = %{$commitlist[0]};
6264 my $latest_epoch = $latest_commit{'committer_epoch'};
6265 %latest_date = parse_date($latest_epoch);
6266 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6267 if (defined $if_modified) {
6268 my $since;
6269 if (eval { require HTTP::Date; 1; }) {
6270 $since = HTTP::Date::str2time($if_modified);
6271 } elsif (eval { require Time::ParseDate; 1; }) {
6272 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6274 if (defined $since && $latest_epoch <= $since) {
6275 print $cgi->header(
6276 -type => $content_type,
6277 -charset => 'utf-8',
6278 -last_modified => $latest_date{'rfc2822'},
6279 -status => '304 Not Modified');
6280 return;
6283 print $cgi->header(
6284 -type => $content_type,
6285 -charset => 'utf-8',
6286 -last_modified => $latest_date{'rfc2822'});
6287 } else {
6288 print $cgi->header(
6289 -type => $content_type,
6290 -charset => 'utf-8');
6293 # Optimization: skip generating the body if client asks only
6294 # for Last-Modified date.
6295 return if ($cgi->request_method() eq 'HEAD');
6297 # header variables
6298 my $title = "$site_name - $project/$action";
6299 my $feed_type = 'log';
6300 if (defined $hash) {
6301 $title .= " - '$hash'";
6302 $feed_type = 'branch log';
6303 if (defined $file_name) {
6304 $title .= " :: $file_name";
6305 $feed_type = 'history';
6307 } elsif (defined $file_name) {
6308 $title .= " - $file_name";
6309 $feed_type = 'history';
6311 $title .= " $feed_type";
6312 my $descr = git_get_project_description($project);
6313 if (defined $descr) {
6314 $descr = esc_html($descr);
6315 } else {
6316 $descr = "$project " .
6317 ($format eq 'rss' ? 'RSS' : 'Atom') .
6318 " feed";
6320 my $owner = git_get_project_owner($project);
6321 $owner = esc_html($owner);
6323 #header
6324 my $alt_url;
6325 if (defined $file_name) {
6326 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6327 } elsif (defined $hash) {
6328 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6329 } else {
6330 $alt_url = href(-full=>1, action=>"summary");
6332 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6333 if ($format eq 'rss') {
6334 print <<XML;
6335 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6336 <channel>
6338 print "<title>$title</title>\n" .
6339 "<link>$alt_url</link>\n" .
6340 "<description>$descr</description>\n" .
6341 "<language>en</language>\n" .
6342 # project owner is responsible for 'editorial' content
6343 "<managingEditor>$owner</managingEditor>\n";
6344 if (defined $logo || defined $favicon) {
6345 # prefer the logo to the favicon, since RSS
6346 # doesn't allow both
6347 my $img = esc_url($logo || $favicon);
6348 print "<image>\n" .
6349 "<url>$img</url>\n" .
6350 "<title>$title</title>\n" .
6351 "<link>$alt_url</link>\n" .
6352 "</image>\n";
6354 if (%latest_date) {
6355 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6356 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6358 print "<generator>gitweb v.$version/$git_version</generator>\n";
6359 } elsif ($format eq 'atom') {
6360 print <<XML;
6361 <feed xmlns="http://www.w3.org/2005/Atom">
6363 print "<title>$title</title>\n" .
6364 "<subtitle>$descr</subtitle>\n" .
6365 '<link rel="alternate" type="text/html" href="' .
6366 $alt_url . '" />' . "\n" .
6367 '<link rel="self" type="' . $content_type . '" href="' .
6368 $cgi->self_url() . '" />' . "\n" .
6369 "<id>" . href(-full=>1) . "</id>\n" .
6370 # use project owner for feed author
6371 "<author><name>$owner</name></author>\n";
6372 if (defined $favicon) {
6373 print "<icon>" . esc_url($favicon) . "</icon>\n";
6375 if (defined $logo_url) {
6376 # not twice as wide as tall: 72 x 27 pixels
6377 print "<logo>" . esc_url($logo) . "</logo>\n";
6379 if (! %latest_date) {
6380 # dummy date to keep the feed valid until commits trickle in:
6381 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6382 } else {
6383 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6385 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6388 # contents
6389 for (my $i = 0; $i <= $#commitlist; $i++) {
6390 my %co = %{$commitlist[$i]};
6391 my $commit = $co{'id'};
6392 # we read 150, we always show 30 and the ones more recent than 48 hours
6393 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6394 last;
6396 my %cd = parse_date($co{'author_epoch'});
6398 # get list of changed files
6399 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6400 $co{'parent'} || "--root",
6401 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6402 or next;
6403 my @difftree = map { chomp; $_ } <$fd>;
6404 close $fd
6405 or next;
6407 # print element (entry, item)
6408 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6409 if ($format eq 'rss') {
6410 print "<item>\n" .
6411 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6412 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6413 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6414 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6415 "<link>$co_url</link>\n" .
6416 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6417 "<content:encoded>" .
6418 "<![CDATA[\n";
6419 } elsif ($format eq 'atom') {
6420 print "<entry>\n" .
6421 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6422 "<updated>$cd{'iso-8601'}</updated>\n" .
6423 "<author>\n" .
6424 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6425 if ($co{'author_email'}) {
6426 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6428 print "</author>\n" .
6429 # use committer for contributor
6430 "<contributor>\n" .
6431 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6432 if ($co{'committer_email'}) {
6433 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6435 print "</contributor>\n" .
6436 "<published>$cd{'iso-8601'}</published>\n" .
6437 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6438 "<id>$co_url</id>\n" .
6439 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6440 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6442 my $comment = $co{'comment'};
6443 print "<pre>\n";
6444 foreach my $line (@$comment) {
6445 $line = esc_html($line);
6446 print "$line\n";
6448 print "</pre><ul>\n";
6449 foreach my $difftree_line (@difftree) {
6450 my %difftree = parse_difftree_raw_line($difftree_line);
6451 next if !$difftree{'from_id'};
6453 my $file = $difftree{'file'} || $difftree{'to_file'};
6455 print "<li>" .
6456 "[" .
6457 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6458 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6459 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6460 file_name=>$file, file_parent=>$difftree{'from_file'}),
6461 -title => "diff"}, 'D');
6462 if ($have_blame) {
6463 print $cgi->a({-href => href(-full=>1, action=>"blame",
6464 file_name=>$file, hash_base=>$commit),
6465 -title => "blame"}, 'B');
6467 # if this is not a feed of a file history
6468 if (!defined $file_name || $file_name ne $file) {
6469 print $cgi->a({-href => href(-full=>1, action=>"history",
6470 file_name=>$file, hash=>$commit),
6471 -title => "history"}, 'H');
6473 $file = esc_path($file);
6474 print "] ".
6475 "$file</li>\n";
6477 if ($format eq 'rss') {
6478 print "</ul>]]>\n" .
6479 "</content:encoded>\n" .
6480 "</item>\n";
6481 } elsif ($format eq 'atom') {
6482 print "</ul>\n</div>\n" .
6483 "</content>\n" .
6484 "</entry>\n";
6488 # end of feed
6489 if ($format eq 'rss') {
6490 print "</channel>\n</rss>\n";
6491 } elsif ($format eq 'atom') {
6492 print "</feed>\n";
6496 sub git_rss {
6497 git_feed('rss');
6500 sub git_atom {
6501 git_feed('atom');
6504 sub git_opml {
6505 my @list = git_get_projects_list();
6507 print $cgi->header(
6508 -type => 'text/xml',
6509 -charset => 'utf-8',
6510 -content_disposition => 'inline; filename="opml.xml"');
6512 print <<XML;
6513 <?xml version="1.0" encoding="utf-8"?>
6514 <opml version="1.0">
6515 <head>
6516 <title>$site_name OPML Export</title>
6517 </head>
6518 <body>
6519 <outline text="git RSS feeds">
6522 foreach my $pr (@list) {
6523 my %proj = %$pr;
6524 my $head = git_get_head_hash($proj{'path'});
6525 if (!defined $head) {
6526 next;
6528 $git_dir = "$projectroot/$proj{'path'}";
6529 my %co = parse_commit($head);
6530 if (!%co) {
6531 next;
6534 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6535 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6536 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6537 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6539 print <<XML;
6540 </outline>
6541 </body>
6542 </opml>