Merge branch 'jn/gitweb-blame' into pu
[git/spearce.git] / gitweb / gitweb.perl
blobd5f47395d0a52d11ad4c4fe849230321e5d46677
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 our $t0;
22 if (eval { require Time::HiRes; 1; }) {
23 $t0 = [Time::HiRes::gettimeofday()];
25 our $number_of_git_cmds = 0;
27 BEGIN {
28 CGI->compile() if $ENV{'MOD_PERL'};
31 our $cgi = new CGI;
32 our $version = "++GIT_VERSION++";
33 our $my_url = $cgi->url();
34 our $my_uri = $cgi->url(-absolute => 1);
36 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
37 # needed and used only for URLs with nonempty PATH_INFO
38 our $base_url = $my_url;
40 # When the script is used as DirectoryIndex, the URL does not contain the name
41 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
42 # have to do it ourselves. We make $path_info global because it's also used
43 # later on.
45 # Another issue with the script being the DirectoryIndex is that the resulting
46 # $my_url data is not the full script URL: this is good, because we want
47 # generated links to keep implying the script name if it wasn't explicitly
48 # indicated in the URL we're handling, but it means that $my_url cannot be used
49 # as base URL.
50 # Therefore, if we needed to strip PATH_INFO, then we know that we have
51 # to build the base URL ourselves:
52 our $path_info = $ENV{"PATH_INFO"};
53 if ($path_info) {
54 if ($my_url =~ s,\Q$path_info\E$,, &&
55 $my_uri =~ s,\Q$path_info\E$,, &&
56 defined $ENV{'SCRIPT_NAME'}) {
57 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
61 # core git executable to use
62 # this can just be "git" if your webserver has a sensible PATH
63 our $GIT = "++GIT_BINDIR++/git";
65 # absolute fs-path which will be prepended to the project path
66 #our $projectroot = "/pub/scm";
67 our $projectroot = "++GITWEB_PROJECTROOT++";
69 # fs traversing limit for getting project list
70 # the number is relative to the projectroot
71 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
73 # target of the home link on top of all pages
74 our $home_link = $my_uri || "/";
76 # string of the home link on top of all pages
77 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
79 # name of your site or organization to appear in page titles
80 # replace this with something more descriptive for clearer bookmarks
81 our $site_name = "++GITWEB_SITENAME++"
82 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
84 # filename of html text to include at top of each page
85 our $site_header = "++GITWEB_SITE_HEADER++";
86 # html text to include at home page
87 our $home_text = "++GITWEB_HOMETEXT++";
88 # filename of html text to include at bottom of each page
89 our $site_footer = "++GITWEB_SITE_FOOTER++";
91 # URI of stylesheets
92 our @stylesheets = ("++GITWEB_CSS++");
93 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
94 our $stylesheet = undef;
95 # URI of GIT logo (72x27 size)
96 our $logo = "++GITWEB_LOGO++";
97 # URI of GIT favicon, assumed to be image/png type
98 our $favicon = "++GITWEB_FAVICON++";
99 # URI of gitweb.js (JavaScript code for gitweb)
100 our $javascript = "++GITWEB_JS++";
102 # URI and label (title) of GIT logo link
103 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
104 #our $logo_label = "git documentation";
105 our $logo_url = "http://git-scm.com/";
106 our $logo_label = "git homepage";
108 # source of projects list
109 our $projects_list = "++GITWEB_LIST++";
111 # the width (in characters) of the projects list "Description" column
112 our $projects_list_description_width = 25;
114 # default order of projects list
115 # valid values are none, project, descr, owner, and age
116 our $default_projects_order = "project";
118 # show repository only if this file exists
119 # (only effective if this variable evaluates to true)
120 our $export_ok = "++GITWEB_EXPORT_OK++";
122 # show repository only if this subroutine returns true
123 # when given the path to the project, for example:
124 # sub { return -e "$_[0]/git-daemon-export-ok"; }
125 our $export_auth_hook = undef;
127 # only allow viewing of repositories also shown on the overview page
128 our $strict_export = "++GITWEB_STRICT_EXPORT++";
130 # list of git base URLs used for URL to where fetch project from,
131 # i.e. full URL is "$git_base_url/$project"
132 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
134 # default blob_plain mimetype and default charset for text/plain blob
135 our $default_blob_plain_mimetype = 'text/plain';
136 our $default_text_plain_charset = undef;
138 # file to use for guessing MIME types before trying /etc/mime.types
139 # (relative to the current git repository)
140 our $mimetypes_file = undef;
142 # assume this charset if line contains non-UTF-8 characters;
143 # it should be valid encoding (see Encoding::Supported(3pm) for list),
144 # for which encoding all byte sequences are valid, for example
145 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
146 # could be even 'utf-8' for the old behavior)
147 our $fallback_encoding = 'latin1';
149 # rename detection options for git-diff and git-diff-tree
150 # - default is '-M', with the cost proportional to
151 # (number of removed files) * (number of new files).
152 # - more costly is '-C' (which implies '-M'), with the cost proportional to
153 # (number of changed files + number of removed files) * (number of new files)
154 # - even more costly is '-C', '--find-copies-harder' with cost
155 # (number of files in the original tree) * (number of new files)
156 # - one might want to include '-B' option, e.g. '-B', '-M'
157 our @diff_opts = ('-M'); # taken from git_commit
159 # Disables features that would allow repository owners to inject script into
160 # the gitweb domain.
161 our $prevent_xss = 0;
163 # information about snapshot formats that gitweb is capable of serving
164 our %known_snapshot_formats = (
165 # name => {
166 # 'display' => display name,
167 # 'type' => mime type,
168 # 'suffix' => filename suffix,
169 # 'format' => --format for git-archive,
170 # 'compressor' => [compressor command and arguments]
171 # (array reference, optional)
172 # 'disabled' => boolean (optional)}
174 'tgz' => {
175 'display' => 'tar.gz',
176 'type' => 'application/x-gzip',
177 'suffix' => '.tar.gz',
178 'format' => 'tar',
179 'compressor' => ['gzip']},
181 'tbz2' => {
182 'display' => 'tar.bz2',
183 'type' => 'application/x-bzip2',
184 'suffix' => '.tar.bz2',
185 'format' => 'tar',
186 'compressor' => ['bzip2']},
188 'txz' => {
189 'display' => 'tar.xz',
190 'type' => 'application/x-xz',
191 'suffix' => '.tar.xz',
192 'format' => 'tar',
193 'compressor' => ['xz'],
194 'disabled' => 1},
196 'zip' => {
197 'display' => 'zip',
198 'type' => 'application/x-zip',
199 'suffix' => '.zip',
200 'format' => 'zip'},
203 # Aliases so we understand old gitweb.snapshot values in repository
204 # configuration.
205 our %known_snapshot_format_aliases = (
206 'gzip' => 'tgz',
207 'bzip2' => 'tbz2',
208 'xz' => 'txz',
210 # backward compatibility: legacy gitweb config support
211 'x-gzip' => undef, 'gz' => undef,
212 'x-bzip2' => undef, 'bz2' => undef,
213 'x-zip' => undef, '' => undef,
216 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
217 # are changed, it may be appropriate to change these values too via
218 # $GITWEB_CONFIG.
219 our %avatar_size = (
220 'default' => 16,
221 'double' => 32
224 # You define site-wide feature defaults here; override them with
225 # $GITWEB_CONFIG as necessary.
226 our %feature = (
227 # feature => {
228 # 'sub' => feature-sub (subroutine),
229 # 'override' => allow-override (boolean),
230 # 'default' => [ default options...] (array reference)}
232 # if feature is overridable (it means that allow-override has true value),
233 # then feature-sub will be called with default options as parameters;
234 # return value of feature-sub indicates if to enable specified feature
236 # if there is no 'sub' key (no feature-sub), then feature cannot be
237 # overriden
239 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
240 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
241 # is enabled
243 # Enable the 'blame' blob view, showing the last commit that modified
244 # each line in the file. This can be very CPU-intensive.
246 # To enable system wide have in $GITWEB_CONFIG
247 # $feature{'blame'}{'default'} = [1];
248 # To have project specific config enable override in $GITWEB_CONFIG
249 # $feature{'blame'}{'override'} = 1;
250 # and in project config gitweb.blame = 0|1;
251 'blame' => {
252 'sub' => sub { feature_bool('blame', @_) },
253 'override' => 0,
254 'default' => [0]},
256 # Enable the 'snapshot' link, providing a compressed archive of any
257 # tree. This can potentially generate high traffic if you have large
258 # project.
260 # Value is a list of formats defined in %known_snapshot_formats that
261 # you wish to offer.
262 # To disable system wide have in $GITWEB_CONFIG
263 # $feature{'snapshot'}{'default'} = [];
264 # To have project specific config enable override in $GITWEB_CONFIG
265 # $feature{'snapshot'}{'override'} = 1;
266 # and in project config, a comma-separated list of formats or "none"
267 # to disable. Example: gitweb.snapshot = tbz2,zip;
268 'snapshot' => {
269 'sub' => \&feature_snapshot,
270 'override' => 0,
271 'default' => ['tgz']},
273 # Enable text search, which will list the commits which match author,
274 # committer or commit text to a given string. Enabled by default.
275 # Project specific override is not supported.
276 'search' => {
277 'override' => 0,
278 'default' => [1]},
280 # Enable grep search, which will list the files in currently selected
281 # tree containing the given string. Enabled by default. This can be
282 # potentially CPU-intensive, of course.
284 # To enable system wide have in $GITWEB_CONFIG
285 # $feature{'grep'}{'default'} = [1];
286 # To have project specific config enable override in $GITWEB_CONFIG
287 # $feature{'grep'}{'override'} = 1;
288 # and in project config gitweb.grep = 0|1;
289 'grep' => {
290 'sub' => sub { feature_bool('grep', @_) },
291 'override' => 0,
292 'default' => [1]},
294 # Enable the pickaxe search, which will list the commits that modified
295 # a given string in a file. This can be practical and quite faster
296 # alternative to 'blame', but still potentially CPU-intensive.
298 # To enable system wide have in $GITWEB_CONFIG
299 # $feature{'pickaxe'}{'default'} = [1];
300 # To have project specific config enable override in $GITWEB_CONFIG
301 # $feature{'pickaxe'}{'override'} = 1;
302 # and in project config gitweb.pickaxe = 0|1;
303 'pickaxe' => {
304 'sub' => sub { feature_bool('pickaxe', @_) },
305 'override' => 0,
306 'default' => [1]},
308 # Make gitweb use an alternative format of the URLs which can be
309 # more readable and natural-looking: project name is embedded
310 # directly in the path and the query string contains other
311 # auxiliary information. All gitweb installations recognize
312 # URL in either format; this configures in which formats gitweb
313 # generates links.
315 # To enable system wide have in $GITWEB_CONFIG
316 # $feature{'pathinfo'}{'default'} = [1];
317 # Project specific override is not supported.
319 # Note that you will need to change the default location of CSS,
320 # favicon, logo and possibly other files to an absolute URL. Also,
321 # if gitweb.cgi serves as your indexfile, you will need to force
322 # $my_uri to contain the script name in your $GITWEB_CONFIG.
323 'pathinfo' => {
324 'override' => 0,
325 'default' => [0]},
327 # Make gitweb consider projects in project root subdirectories
328 # to be forks of existing projects. Given project $projname.git,
329 # projects matching $projname/*.git will not be shown in the main
330 # projects list, instead a '+' mark will be added to $projname
331 # there and a 'forks' view will be enabled for the project, listing
332 # all the forks. If project list is taken from a file, forks have
333 # to be listed after the main project.
335 # To enable system wide have in $GITWEB_CONFIG
336 # $feature{'forks'}{'default'} = [1];
337 # Project specific override is not supported.
338 'forks' => {
339 'override' => 0,
340 'default' => [0]},
342 # Insert custom links to the action bar of all project pages.
343 # This enables you mainly to link to third-party scripts integrating
344 # into gitweb; e.g. git-browser for graphical history representation
345 # or custom web-based repository administration interface.
347 # The 'default' value consists of a list of triplets in the form
348 # (label, link, position) where position is the label after which
349 # to insert the link and link is a format string where %n expands
350 # to the project name, %f to the project path within the filesystem,
351 # %h to the current hash (h gitweb parameter) and %b to the current
352 # hash base (hb gitweb parameter); %% expands to %.
354 # To enable system wide have in $GITWEB_CONFIG e.g.
355 # $feature{'actions'}{'default'} = [('graphiclog',
356 # '/git-browser/by-commit.html?r=%n', 'summary')];
357 # Project specific override is not supported.
358 'actions' => {
359 'override' => 0,
360 'default' => []},
362 # Allow gitweb scan project content tags described in ctags/
363 # of project repository, and display the popular Web 2.0-ish
364 # "tag cloud" near the project list. Note that this is something
365 # COMPLETELY different from the normal Git tags.
367 # gitweb by itself can show existing tags, but it does not handle
368 # tagging itself; you need an external application for that.
369 # For an example script, check Girocco's cgi/tagproj.cgi.
370 # You may want to install the HTML::TagCloud Perl module to get
371 # a pretty tag cloud instead of just a list of tags.
373 # To enable system wide have in $GITWEB_CONFIG
374 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
375 # Project specific override is not supported.
376 'ctags' => {
377 'override' => 0,
378 'default' => [0]},
380 # The maximum number of patches in a patchset generated in patch
381 # view. Set this to 0 or undef to disable patch view, or to a
382 # negative number to remove any limit.
384 # To disable system wide have in $GITWEB_CONFIG
385 # $feature{'patches'}{'default'} = [0];
386 # To have project specific config enable override in $GITWEB_CONFIG
387 # $feature{'patches'}{'override'} = 1;
388 # and in project config gitweb.patches = 0|n;
389 # where n is the maximum number of patches allowed in a patchset.
390 'patches' => {
391 'sub' => \&feature_patches,
392 'override' => 0,
393 'default' => [16]},
395 # Avatar support. When this feature is enabled, views such as
396 # shortlog or commit will display an avatar associated with
397 # the email of the committer(s) and/or author(s).
399 # Currently available providers are gravatar and picon.
400 # If an unknown provider is specified, the feature is disabled.
402 # Gravatar depends on Digest::MD5.
403 # Picon currently relies on the indiana.edu database.
405 # To enable system wide have in $GITWEB_CONFIG
406 # $feature{'avatar'}{'default'} = ['<provider>'];
407 # where <provider> is either gravatar or picon.
408 # To have project specific config enable override in $GITWEB_CONFIG
409 # $feature{'avatar'}{'override'} = 1;
410 # and in project config gitweb.avatar = <provider>;
411 'avatar' => {
412 'sub' => \&feature_avatar,
413 'override' => 0,
414 'default' => ['']},
416 # Enable displaying how much time and how many git commands
417 # it took to generate and display page. Disabled by default.
418 # Project specific override is not supported.
419 'timed' => {
420 'override' => 0,
421 'default' => [0]},
424 sub gitweb_get_feature {
425 my ($name) = @_;
426 return unless exists $feature{$name};
427 my ($sub, $override, @defaults) = (
428 $feature{$name}{'sub'},
429 $feature{$name}{'override'},
430 @{$feature{$name}{'default'}});
431 if (!$override) { return @defaults; }
432 if (!defined $sub) {
433 warn "feature $name is not overridable";
434 return @defaults;
436 return $sub->(@defaults);
439 # A wrapper to check if a given feature is enabled.
440 # With this, you can say
442 # my $bool_feat = gitweb_check_feature('bool_feat');
443 # gitweb_check_feature('bool_feat') or somecode;
445 # instead of
447 # my ($bool_feat) = gitweb_get_feature('bool_feat');
448 # (gitweb_get_feature('bool_feat'))[0] or somecode;
450 sub gitweb_check_feature {
451 return (gitweb_get_feature(@_))[0];
455 sub feature_bool {
456 my $key = shift;
457 my ($val) = git_get_project_config($key, '--bool');
459 if (!defined $val) {
460 return ($_[0]);
461 } elsif ($val eq 'true') {
462 return (1);
463 } elsif ($val eq 'false') {
464 return (0);
468 sub feature_snapshot {
469 my (@fmts) = @_;
471 my ($val) = git_get_project_config('snapshot');
473 if ($val) {
474 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
477 return @fmts;
480 sub feature_patches {
481 my @val = (git_get_project_config('patches', '--int'));
483 if (@val) {
484 return @val;
487 return ($_[0]);
490 sub feature_avatar {
491 my @val = (git_get_project_config('avatar'));
493 return @val ? @val : @_;
496 # checking HEAD file with -e is fragile if the repository was
497 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
498 # and then pruned.
499 sub check_head_link {
500 my ($dir) = @_;
501 my $headfile = "$dir/HEAD";
502 return ((-e $headfile) ||
503 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
506 sub check_export_ok {
507 my ($dir) = @_;
508 return (check_head_link($dir) &&
509 (!$export_ok || -e "$dir/$export_ok") &&
510 (!$export_auth_hook || $export_auth_hook->($dir)));
513 # process alternate names for backward compatibility
514 # filter out unsupported (unknown) snapshot formats
515 sub filter_snapshot_fmts {
516 my @fmts = @_;
518 @fmts = map {
519 exists $known_snapshot_format_aliases{$_} ?
520 $known_snapshot_format_aliases{$_} : $_} @fmts;
521 @fmts = grep {
522 exists $known_snapshot_formats{$_} &&
523 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
526 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
527 if (-e $GITWEB_CONFIG) {
528 do $GITWEB_CONFIG;
529 } else {
530 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
531 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
534 # version of the core git binary
535 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
536 $number_of_git_cmds++;
538 $projects_list ||= $projectroot;
540 # ======================================================================
541 # input validation and dispatch
543 # input parameters can be collected from a variety of sources (presently, CGI
544 # and PATH_INFO), so we define an %input_params hash that collects them all
545 # together during validation: this allows subsequent uses (e.g. href()) to be
546 # agnostic of the parameter origin
548 our %input_params = ();
550 # input parameters are stored with the long parameter name as key. This will
551 # also be used in the href subroutine to convert parameters to their CGI
552 # equivalent, and since the href() usage is the most frequent one, we store
553 # the name -> CGI key mapping here, instead of the reverse.
555 # XXX: Warning: If you touch this, check the search form for updating,
556 # too.
558 our @cgi_param_mapping = (
559 project => "p",
560 action => "a",
561 file_name => "f",
562 file_parent => "fp",
563 hash => "h",
564 hash_parent => "hp",
565 hash_base => "hb",
566 hash_parent_base => "hpb",
567 page => "pg",
568 order => "o",
569 searchtext => "s",
570 searchtype => "st",
571 snapshot_format => "sf",
572 extra_options => "opt",
573 search_use_regexp => "sr",
574 # this must be last entry (for manipulation from JavaScript)
575 javascript => "js"
577 our %cgi_param_mapping = @cgi_param_mapping;
579 # we will also need to know the possible actions, for validation
580 our %actions = (
581 "blame" => \&git_blame,
582 "blame_incremental" => \&git_blame_incremental,
583 "blame_data" => \&git_blame_data,
584 "blobdiff" => \&git_blobdiff,
585 "blobdiff_plain" => \&git_blobdiff_plain,
586 "blob" => \&git_blob,
587 "blob_plain" => \&git_blob_plain,
588 "commitdiff" => \&git_commitdiff,
589 "commitdiff_plain" => \&git_commitdiff_plain,
590 "commit" => \&git_commit,
591 "forks" => \&git_forks,
592 "heads" => \&git_heads,
593 "history" => \&git_history,
594 "log" => \&git_log,
595 "patch" => \&git_patch,
596 "patches" => \&git_patches,
597 "rss" => \&git_rss,
598 "atom" => \&git_atom,
599 "search" => \&git_search,
600 "search_help" => \&git_search_help,
601 "shortlog" => \&git_shortlog,
602 "summary" => \&git_summary,
603 "tag" => \&git_tag,
604 "tags" => \&git_tags,
605 "tree" => \&git_tree,
606 "snapshot" => \&git_snapshot,
607 "object" => \&git_object,
608 # those below don't need $project
609 "opml" => \&git_opml,
610 "project_list" => \&git_project_list,
611 "project_index" => \&git_project_index,
614 # finally, we have the hash of allowed extra_options for the commands that
615 # allow them
616 our %allowed_options = (
617 "--no-merges" => [ qw(rss atom log shortlog history) ],
620 # fill %input_params with the CGI parameters. All values except for 'opt'
621 # should be single values, but opt can be an array. We should probably
622 # build an array of parameters that can be multi-valued, but since for the time
623 # being it's only this one, we just single it out
624 while (my ($name, $symbol) = each %cgi_param_mapping) {
625 if ($symbol eq 'opt') {
626 $input_params{$name} = [ $cgi->param($symbol) ];
627 } else {
628 $input_params{$name} = $cgi->param($symbol);
632 # now read PATH_INFO and update the parameter list for missing parameters
633 sub evaluate_path_info {
634 return if defined $input_params{'project'};
635 return if !$path_info;
636 $path_info =~ s,^/+,,;
637 return if !$path_info;
639 # find which part of PATH_INFO is project
640 my $project = $path_info;
641 $project =~ s,/+$,,;
642 while ($project && !check_head_link("$projectroot/$project")) {
643 $project =~ s,/*[^/]*$,,;
645 return unless $project;
646 $input_params{'project'} = $project;
648 # do not change any parameters if an action is given using the query string
649 return if $input_params{'action'};
650 $path_info =~ s,^\Q$project\E/*,,;
652 # next, check if we have an action
653 my $action = $path_info;
654 $action =~ s,/.*$,,;
655 if (exists $actions{$action}) {
656 $path_info =~ s,^$action/*,,;
657 $input_params{'action'} = $action;
660 # list of actions that want hash_base instead of hash, but can have no
661 # pathname (f) parameter
662 my @wants_base = (
663 'tree',
664 'history',
667 # we want to catch
668 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
669 my ($parentrefname, $parentpathname, $refname, $pathname) =
670 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
672 # first, analyze the 'current' part
673 if (defined $pathname) {
674 # we got "branch:filename" or "branch:dir/"
675 # we could use git_get_type(branch:pathname), but:
676 # - it needs $git_dir
677 # - it does a git() call
678 # - the convention of terminating directories with a slash
679 # makes it superfluous
680 # - embedding the action in the PATH_INFO would make it even
681 # more superfluous
682 $pathname =~ s,^/+,,;
683 if (!$pathname || substr($pathname, -1) eq "/") {
684 $input_params{'action'} ||= "tree";
685 $pathname =~ s,/$,,;
686 } else {
687 # the default action depends on whether we had parent info
688 # or not
689 if ($parentrefname) {
690 $input_params{'action'} ||= "blobdiff_plain";
691 } else {
692 $input_params{'action'} ||= "blob_plain";
695 $input_params{'hash_base'} ||= $refname;
696 $input_params{'file_name'} ||= $pathname;
697 } elsif (defined $refname) {
698 # we got "branch". In this case we have to choose if we have to
699 # set hash or hash_base.
701 # Most of the actions without a pathname only want hash to be
702 # set, except for the ones specified in @wants_base that want
703 # hash_base instead. It should also be noted that hand-crafted
704 # links having 'history' as an action and no pathname or hash
705 # set will fail, but that happens regardless of PATH_INFO.
706 $input_params{'action'} ||= "shortlog";
707 if (grep { $_ eq $input_params{'action'} } @wants_base) {
708 $input_params{'hash_base'} ||= $refname;
709 } else {
710 $input_params{'hash'} ||= $refname;
714 # next, handle the 'parent' part, if present
715 if (defined $parentrefname) {
716 # a missing pathspec defaults to the 'current' filename, allowing e.g.
717 # someproject/blobdiff/oldrev..newrev:/filename
718 if ($parentpathname) {
719 $parentpathname =~ s,^/+,,;
720 $parentpathname =~ s,/$,,;
721 $input_params{'file_parent'} ||= $parentpathname;
722 } else {
723 $input_params{'file_parent'} ||= $input_params{'file_name'};
725 # we assume that hash_parent_base is wanted if a path was specified,
726 # or if the action wants hash_base instead of hash
727 if (defined $input_params{'file_parent'} ||
728 grep { $_ eq $input_params{'action'} } @wants_base) {
729 $input_params{'hash_parent_base'} ||= $parentrefname;
730 } else {
731 $input_params{'hash_parent'} ||= $parentrefname;
735 # for the snapshot action, we allow URLs in the form
736 # $project/snapshot/$hash.ext
737 # where .ext determines the snapshot and gets removed from the
738 # passed $refname to provide the $hash.
740 # To be able to tell that $refname includes the format extension, we
741 # require the following two conditions to be satisfied:
742 # - the hash input parameter MUST have been set from the $refname part
743 # of the URL (i.e. they must be equal)
744 # - the snapshot format MUST NOT have been defined already (e.g. from
745 # CGI parameter sf)
746 # It's also useless to try any matching unless $refname has a dot,
747 # so we check for that too
748 if (defined $input_params{'action'} &&
749 $input_params{'action'} eq 'snapshot' &&
750 defined $refname && index($refname, '.') != -1 &&
751 $refname eq $input_params{'hash'} &&
752 !defined $input_params{'snapshot_format'}) {
753 # We loop over the known snapshot formats, checking for
754 # extensions. Allowed extensions are both the defined suffix
755 # (which includes the initial dot already) and the snapshot
756 # format key itself, with a prepended dot
757 while (my ($fmt, $opt) = each %known_snapshot_formats) {
758 my $hash = $refname;
759 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
760 next;
762 my $sfx = $1;
763 # a valid suffix was found, so set the snapshot format
764 # and reset the hash parameter
765 $input_params{'snapshot_format'} = $fmt;
766 $input_params{'hash'} = $hash;
767 # we also set the format suffix to the one requested
768 # in the URL: this way a request for e.g. .tgz returns
769 # a .tgz instead of a .tar.gz
770 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
771 last;
775 evaluate_path_info();
777 our $action = $input_params{'action'};
778 if (defined $action) {
779 if (!validate_action($action)) {
780 die_error(400, "Invalid action parameter");
784 # parameters which are pathnames
785 our $project = $input_params{'project'};
786 if (defined $project) {
787 if (!validate_project($project)) {
788 undef $project;
789 die_error(404, "No such project");
793 our $file_name = $input_params{'file_name'};
794 if (defined $file_name) {
795 if (!validate_pathname($file_name)) {
796 die_error(400, "Invalid file parameter");
800 our $file_parent = $input_params{'file_parent'};
801 if (defined $file_parent) {
802 if (!validate_pathname($file_parent)) {
803 die_error(400, "Invalid file parent parameter");
807 # parameters which are refnames
808 our $hash = $input_params{'hash'};
809 if (defined $hash) {
810 if (!validate_refname($hash)) {
811 die_error(400, "Invalid hash parameter");
815 our $hash_parent = $input_params{'hash_parent'};
816 if (defined $hash_parent) {
817 if (!validate_refname($hash_parent)) {
818 die_error(400, "Invalid hash parent parameter");
822 our $hash_base = $input_params{'hash_base'};
823 if (defined $hash_base) {
824 if (!validate_refname($hash_base)) {
825 die_error(400, "Invalid hash base parameter");
829 our @extra_options = @{$input_params{'extra_options'}};
830 # @extra_options is always defined, since it can only be (currently) set from
831 # CGI, and $cgi->param() returns the empty array in array context if the param
832 # is not set
833 foreach my $opt (@extra_options) {
834 if (not exists $allowed_options{$opt}) {
835 die_error(400, "Invalid option parameter");
837 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
838 die_error(400, "Invalid option parameter for this action");
842 our $hash_parent_base = $input_params{'hash_parent_base'};
843 if (defined $hash_parent_base) {
844 if (!validate_refname($hash_parent_base)) {
845 die_error(400, "Invalid hash parent base parameter");
849 # other parameters
850 our $page = $input_params{'page'};
851 if (defined $page) {
852 if ($page =~ m/[^0-9]/) {
853 die_error(400, "Invalid page parameter");
857 our $searchtype = $input_params{'searchtype'};
858 if (defined $searchtype) {
859 if ($searchtype =~ m/[^a-z]/) {
860 die_error(400, "Invalid searchtype parameter");
864 our $search_use_regexp = $input_params{'search_use_regexp'};
866 our $searchtext = $input_params{'searchtext'};
867 our $search_regexp;
868 if (defined $searchtext) {
869 if (length($searchtext) < 2) {
870 die_error(403, "At least two characters are required for search parameter");
872 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
875 # path to the current git repository
876 our $git_dir;
877 $git_dir = "$projectroot/$project" if $project;
879 # list of supported snapshot formats
880 our @snapshot_fmts = gitweb_get_feature('snapshot');
881 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
883 # check that the avatar feature is set to a known provider name,
884 # and for each provider check if the dependencies are satisfied.
885 # if the provider name is invalid or the dependencies are not met,
886 # reset $git_avatar to the empty string.
887 our ($git_avatar) = gitweb_get_feature('avatar');
888 if ($git_avatar eq 'gravatar') {
889 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
890 } elsif ($git_avatar eq 'picon') {
891 # no dependencies
892 } else {
893 $git_avatar = '';
896 # dispatch
897 if (!defined $action) {
898 if (defined $hash) {
899 $action = git_get_type($hash);
900 } elsif (defined $hash_base && defined $file_name) {
901 $action = git_get_type("$hash_base:$file_name");
902 } elsif (defined $project) {
903 $action = 'summary';
904 } else {
905 $action = 'project_list';
908 if (!defined($actions{$action})) {
909 die_error(400, "Unknown action");
911 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
912 !$project) {
913 die_error(400, "Project needed");
915 $actions{$action}->();
916 exit;
918 ## ======================================================================
919 ## action links
921 sub href {
922 my %params = @_;
923 # default is to use -absolute url() i.e. $my_uri
924 my $href = $params{-full} ? $my_url : $my_uri;
926 $params{'project'} = $project unless exists $params{'project'};
928 if ($params{-replay}) {
929 while (my ($name, $symbol) = each %cgi_param_mapping) {
930 if (!exists $params{$name}) {
931 $params{$name} = $input_params{$name};
936 my $use_pathinfo = gitweb_check_feature('pathinfo');
937 if ($use_pathinfo and defined $params{'project'}) {
938 # try to put as many parameters as possible in PATH_INFO:
939 # - project name
940 # - action
941 # - hash_parent or hash_parent_base:/file_parent
942 # - hash or hash_base:/filename
943 # - the snapshot_format as an appropriate suffix
945 # When the script is the root DirectoryIndex for the domain,
946 # $href here would be something like http://gitweb.example.com/
947 # Thus, we strip any trailing / from $href, to spare us double
948 # slashes in the final URL
949 $href =~ s,/$,,;
951 # Then add the project name, if present
952 $href .= "/".esc_url($params{'project'});
953 delete $params{'project'};
955 # since we destructively absorb parameters, we keep this
956 # boolean that remembers if we're handling a snapshot
957 my $is_snapshot = $params{'action'} eq 'snapshot';
959 # Summary just uses the project path URL, any other action is
960 # added to the URL
961 if (defined $params{'action'}) {
962 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
963 delete $params{'action'};
966 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
967 # stripping nonexistent or useless pieces
968 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
969 || $params{'hash_parent'} || $params{'hash'});
970 if (defined $params{'hash_base'}) {
971 if (defined $params{'hash_parent_base'}) {
972 $href .= esc_url($params{'hash_parent_base'});
973 # skip the file_parent if it's the same as the file_name
974 if (defined $params{'file_parent'}) {
975 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
976 delete $params{'file_parent'};
977 } elsif ($params{'file_parent'} !~ /\.\./) {
978 $href .= ":/".esc_url($params{'file_parent'});
979 delete $params{'file_parent'};
982 $href .= "..";
983 delete $params{'hash_parent'};
984 delete $params{'hash_parent_base'};
985 } elsif (defined $params{'hash_parent'}) {
986 $href .= esc_url($params{'hash_parent'}). "..";
987 delete $params{'hash_parent'};
990 $href .= esc_url($params{'hash_base'});
991 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
992 $href .= ":/".esc_url($params{'file_name'});
993 delete $params{'file_name'};
995 delete $params{'hash'};
996 delete $params{'hash_base'};
997 } elsif (defined $params{'hash'}) {
998 $href .= esc_url($params{'hash'});
999 delete $params{'hash'};
1002 # If the action was a snapshot, we can absorb the
1003 # snapshot_format parameter too
1004 if ($is_snapshot) {
1005 my $fmt = $params{'snapshot_format'};
1006 # snapshot_format should always be defined when href()
1007 # is called, but just in case some code forgets, we
1008 # fall back to the default
1009 $fmt ||= $snapshot_fmts[0];
1010 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1011 delete $params{'snapshot_format'};
1015 # now encode the parameters explicitly
1016 my @result = ();
1017 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1018 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1019 if (defined $params{$name}) {
1020 if (ref($params{$name}) eq "ARRAY") {
1021 foreach my $par (@{$params{$name}}) {
1022 push @result, $symbol . "=" . esc_param($par);
1024 } else {
1025 push @result, $symbol . "=" . esc_param($params{$name});
1029 $href .= "?" . join(';', @result) if scalar @result;
1031 return $href;
1035 ## ======================================================================
1036 ## validation, quoting/unquoting and escaping
1038 sub validate_action {
1039 my $input = shift || return undef;
1040 return undef unless exists $actions{$input};
1041 return $input;
1044 sub validate_project {
1045 my $input = shift || return undef;
1046 if (!validate_pathname($input) ||
1047 !(-d "$projectroot/$input") ||
1048 !check_export_ok("$projectroot/$input") ||
1049 ($strict_export && !project_in_list($input))) {
1050 return undef;
1051 } else {
1052 return $input;
1056 sub validate_pathname {
1057 my $input = shift || return undef;
1059 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1060 # at the beginning, at the end, and between slashes.
1061 # also this catches doubled slashes
1062 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1063 return undef;
1065 # no null characters
1066 if ($input =~ m!\0!) {
1067 return undef;
1069 return $input;
1072 sub validate_refname {
1073 my $input = shift || return undef;
1075 # textual hashes are O.K.
1076 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1077 return $input;
1079 # it must be correct pathname
1080 $input = validate_pathname($input)
1081 or return undef;
1082 # restrictions on ref name according to git-check-ref-format
1083 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1084 return undef;
1086 return $input;
1089 # decode sequences of octets in utf8 into Perl's internal form,
1090 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1091 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1092 sub to_utf8 {
1093 my $str = shift;
1094 if (utf8::valid($str)) {
1095 utf8::decode($str);
1096 return $str;
1097 } else {
1098 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1102 # quote unsafe chars, but keep the slash, even when it's not
1103 # correct, but quoted slashes look too horrible in bookmarks
1104 sub esc_param {
1105 my $str = shift;
1106 $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
1107 $str =~ s/\+/%2B/g;
1108 $str =~ s/ /\+/g;
1109 return $str;
1112 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1113 sub esc_url {
1114 my $str = shift;
1115 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1116 $str =~ s/\+/%2B/g;
1117 $str =~ s/ /\+/g;
1118 return $str;
1121 # replace invalid utf8 character with SUBSTITUTION sequence
1122 sub esc_html {
1123 my $str = shift;
1124 my %opts = @_;
1126 $str = to_utf8($str);
1127 $str = $cgi->escapeHTML($str);
1128 if ($opts{'-nbsp'}) {
1129 $str =~ s/ /&nbsp;/g;
1131 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1132 return $str;
1135 # quote control characters and escape filename to HTML
1136 sub esc_path {
1137 my $str = shift;
1138 my %opts = @_;
1140 $str = to_utf8($str);
1141 $str = $cgi->escapeHTML($str);
1142 if ($opts{'-nbsp'}) {
1143 $str =~ s/ /&nbsp;/g;
1145 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1146 return $str;
1149 # Make control characters "printable", using character escape codes (CEC)
1150 sub quot_cec {
1151 my $cntrl = shift;
1152 my %opts = @_;
1153 my %es = ( # character escape codes, aka escape sequences
1154 "\t" => '\t', # tab (HT)
1155 "\n" => '\n', # line feed (LF)
1156 "\r" => '\r', # carrige return (CR)
1157 "\f" => '\f', # form feed (FF)
1158 "\b" => '\b', # backspace (BS)
1159 "\a" => '\a', # alarm (bell) (BEL)
1160 "\e" => '\e', # escape (ESC)
1161 "\013" => '\v', # vertical tab (VT)
1162 "\000" => '\0', # nul character (NUL)
1164 my $chr = ( (exists $es{$cntrl})
1165 ? $es{$cntrl}
1166 : sprintf('\%2x', ord($cntrl)) );
1167 if ($opts{-nohtml}) {
1168 return $chr;
1169 } else {
1170 return "<span class=\"cntrl\">$chr</span>";
1174 # Alternatively use unicode control pictures codepoints,
1175 # Unicode "printable representation" (PR)
1176 sub quot_upr {
1177 my $cntrl = shift;
1178 my %opts = @_;
1180 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1181 if ($opts{-nohtml}) {
1182 return $chr;
1183 } else {
1184 return "<span class=\"cntrl\">$chr</span>";
1188 # git may return quoted and escaped filenames
1189 sub unquote {
1190 my $str = shift;
1192 sub unq {
1193 my $seq = shift;
1194 my %es = ( # character escape codes, aka escape sequences
1195 't' => "\t", # tab (HT, TAB)
1196 'n' => "\n", # newline (NL)
1197 'r' => "\r", # return (CR)
1198 'f' => "\f", # form feed (FF)
1199 'b' => "\b", # backspace (BS)
1200 'a' => "\a", # alarm (bell) (BEL)
1201 'e' => "\e", # escape (ESC)
1202 'v' => "\013", # vertical tab (VT)
1205 if ($seq =~ m/^[0-7]{1,3}$/) {
1206 # octal char sequence
1207 return chr(oct($seq));
1208 } elsif (exists $es{$seq}) {
1209 # C escape sequence, aka character escape code
1210 return $es{$seq};
1212 # quoted ordinary character
1213 return $seq;
1216 if ($str =~ m/^"(.*)"$/) {
1217 # needs unquoting
1218 $str = $1;
1219 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1221 return $str;
1224 # escape tabs (convert tabs to spaces)
1225 sub untabify {
1226 my $line = shift;
1228 while ((my $pos = index($line, "\t")) != -1) {
1229 if (my $count = (8 - ($pos % 8))) {
1230 my $spaces = ' ' x $count;
1231 $line =~ s/\t/$spaces/;
1235 return $line;
1238 sub project_in_list {
1239 my $project = shift;
1240 my @list = git_get_projects_list();
1241 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1244 ## ----------------------------------------------------------------------
1245 ## HTML aware string manipulation
1247 # Try to chop given string on a word boundary between position
1248 # $len and $len+$add_len. If there is no word boundary there,
1249 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1250 # (marking chopped part) would be longer than given string.
1251 sub chop_str {
1252 my $str = shift;
1253 my $len = shift;
1254 my $add_len = shift || 10;
1255 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1257 # Make sure perl knows it is utf8 encoded so we don't
1258 # cut in the middle of a utf8 multibyte char.
1259 $str = to_utf8($str);
1261 # allow only $len chars, but don't cut a word if it would fit in $add_len
1262 # if it doesn't fit, cut it if it's still longer than the dots we would add
1263 # remove chopped character entities entirely
1265 # when chopping in the middle, distribute $len into left and right part
1266 # return early if chopping wouldn't make string shorter
1267 if ($where eq 'center') {
1268 return $str if ($len + 5 >= length($str)); # filler is length 5
1269 $len = int($len/2);
1270 } else {
1271 return $str if ($len + 4 >= length($str)); # filler is length 4
1274 # regexps: ending and beginning with word part up to $add_len
1275 my $endre = qr/.{$len}\w{0,$add_len}/;
1276 my $begre = qr/\w{0,$add_len}.{$len}/;
1278 if ($where eq 'left') {
1279 $str =~ m/^(.*?)($begre)$/;
1280 my ($lead, $body) = ($1, $2);
1281 if (length($lead) > 4) {
1282 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1283 $lead = " ...";
1285 return "$lead$body";
1287 } elsif ($where eq 'center') {
1288 $str =~ m/^($endre)(.*)$/;
1289 my ($left, $str) = ($1, $2);
1290 $str =~ m/^(.*?)($begre)$/;
1291 my ($mid, $right) = ($1, $2);
1292 if (length($mid) > 5) {
1293 $left =~ s/&[^;]*$//;
1294 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1295 $mid = " ... ";
1297 return "$left$mid$right";
1299 } else {
1300 $str =~ m/^($endre)(.*)$/;
1301 my $body = $1;
1302 my $tail = $2;
1303 if (length($tail) > 4) {
1304 $body =~ s/&[^;]*$//;
1305 $tail = "... ";
1307 return "$body$tail";
1311 # takes the same arguments as chop_str, but also wraps a <span> around the
1312 # result with a title attribute if it does get chopped. Additionally, the
1313 # string is HTML-escaped.
1314 sub chop_and_escape_str {
1315 my ($str) = @_;
1317 my $chopped = chop_str(@_);
1318 if ($chopped eq $str) {
1319 return esc_html($chopped);
1320 } else {
1321 $str =~ s/[[:cntrl:]]/?/g;
1322 return $cgi->span({-title=>$str}, esc_html($chopped));
1326 ## ----------------------------------------------------------------------
1327 ## functions returning short strings
1329 # CSS class for given age value (in seconds)
1330 sub age_class {
1331 my $age = shift;
1333 if (!defined $age) {
1334 return "noage";
1335 } elsif ($age < 60*60*2) {
1336 return "age0";
1337 } elsif ($age < 60*60*24*2) {
1338 return "age1";
1339 } else {
1340 return "age2";
1344 # convert age in seconds to "nn units ago" string
1345 sub age_string {
1346 my $age = shift;
1347 my $age_str;
1349 if ($age > 60*60*24*365*2) {
1350 $age_str = (int $age/60/60/24/365);
1351 $age_str .= " years ago";
1352 } elsif ($age > 60*60*24*(365/12)*2) {
1353 $age_str = int $age/60/60/24/(365/12);
1354 $age_str .= " months ago";
1355 } elsif ($age > 60*60*24*7*2) {
1356 $age_str = int $age/60/60/24/7;
1357 $age_str .= " weeks ago";
1358 } elsif ($age > 60*60*24*2) {
1359 $age_str = int $age/60/60/24;
1360 $age_str .= " days ago";
1361 } elsif ($age > 60*60*2) {
1362 $age_str = int $age/60/60;
1363 $age_str .= " hours ago";
1364 } elsif ($age > 60*2) {
1365 $age_str = int $age/60;
1366 $age_str .= " min ago";
1367 } elsif ($age > 2) {
1368 $age_str = int $age;
1369 $age_str .= " sec ago";
1370 } else {
1371 $age_str .= " right now";
1373 return $age_str;
1376 use constant {
1377 S_IFINVALID => 0030000,
1378 S_IFGITLINK => 0160000,
1381 # submodule/subproject, a commit object reference
1382 sub S_ISGITLINK {
1383 my $mode = shift;
1385 return (($mode & S_IFMT) == S_IFGITLINK)
1388 # convert file mode in octal to symbolic file mode string
1389 sub mode_str {
1390 my $mode = oct shift;
1392 if (S_ISGITLINK($mode)) {
1393 return 'm---------';
1394 } elsif (S_ISDIR($mode & S_IFMT)) {
1395 return 'drwxr-xr-x';
1396 } elsif (S_ISLNK($mode)) {
1397 return 'lrwxrwxrwx';
1398 } elsif (S_ISREG($mode)) {
1399 # git cares only about the executable bit
1400 if ($mode & S_IXUSR) {
1401 return '-rwxr-xr-x';
1402 } else {
1403 return '-rw-r--r--';
1405 } else {
1406 return '----------';
1410 # convert file mode in octal to file type string
1411 sub file_type {
1412 my $mode = shift;
1414 if ($mode !~ m/^[0-7]+$/) {
1415 return $mode;
1416 } else {
1417 $mode = oct $mode;
1420 if (S_ISGITLINK($mode)) {
1421 return "submodule";
1422 } elsif (S_ISDIR($mode & S_IFMT)) {
1423 return "directory";
1424 } elsif (S_ISLNK($mode)) {
1425 return "symlink";
1426 } elsif (S_ISREG($mode)) {
1427 return "file";
1428 } else {
1429 return "unknown";
1433 # convert file mode in octal to file type description string
1434 sub file_type_long {
1435 my $mode = shift;
1437 if ($mode !~ m/^[0-7]+$/) {
1438 return $mode;
1439 } else {
1440 $mode = oct $mode;
1443 if (S_ISGITLINK($mode)) {
1444 return "submodule";
1445 } elsif (S_ISDIR($mode & S_IFMT)) {
1446 return "directory";
1447 } elsif (S_ISLNK($mode)) {
1448 return "symlink";
1449 } elsif (S_ISREG($mode)) {
1450 if ($mode & S_IXUSR) {
1451 return "executable";
1452 } else {
1453 return "file";
1455 } else {
1456 return "unknown";
1461 ## ----------------------------------------------------------------------
1462 ## functions returning short HTML fragments, or transforming HTML fragments
1463 ## which don't belong to other sections
1465 # format line of commit message.
1466 sub format_log_line_html {
1467 my $line = shift;
1469 $line = esc_html($line, -nbsp=>1);
1470 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1471 $cgi->a({-href => href(action=>"object", hash=>$1),
1472 -class => "text"}, $1);
1473 }eg;
1475 return $line;
1478 # format marker of refs pointing to given object
1480 # the destination action is chosen based on object type and current context:
1481 # - for annotated tags, we choose the tag view unless it's the current view
1482 # already, in which case we go to shortlog view
1483 # - for other refs, we keep the current view if we're in history, shortlog or
1484 # log view, and select shortlog otherwise
1485 sub format_ref_marker {
1486 my ($refs, $id) = @_;
1487 my $markers = '';
1489 if (defined $refs->{$id}) {
1490 foreach my $ref (@{$refs->{$id}}) {
1491 # this code exploits the fact that non-lightweight tags are the
1492 # only indirect objects, and that they are the only objects for which
1493 # we want to use tag instead of shortlog as action
1494 my ($type, $name) = qw();
1495 my $indirect = ($ref =~ s/\^\{\}$//);
1496 # e.g. tags/v2.6.11 or heads/next
1497 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1498 $type = $1;
1499 $name = $2;
1500 } else {
1501 $type = "ref";
1502 $name = $ref;
1505 my $class = $type;
1506 $class .= " indirect" if $indirect;
1508 my $dest_action = "shortlog";
1510 if ($indirect) {
1511 $dest_action = "tag" unless $action eq "tag";
1512 } elsif ($action =~ /^(history|(short)?log)$/) {
1513 $dest_action = $action;
1516 my $dest = "";
1517 $dest .= "refs/" unless $ref =~ m!^refs/!;
1518 $dest .= $ref;
1520 my $link = $cgi->a({
1521 -href => href(
1522 action=>$dest_action,
1523 hash=>$dest
1524 )}, $name);
1526 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1527 $link . "</span>";
1531 if ($markers) {
1532 return ' <span class="refs">'. $markers . '</span>';
1533 } else {
1534 return "";
1538 # format, perhaps shortened and with markers, title line
1539 sub format_subject_html {
1540 my ($long, $short, $href, $extra) = @_;
1541 $extra = '' unless defined($extra);
1543 if (length($short) < length($long)) {
1544 $long =~ s/[[:cntrl:]]/?/g;
1545 return $cgi->a({-href => $href, -class => "list subject",
1546 -title => to_utf8($long)},
1547 esc_html($short)) . $extra;
1548 } else {
1549 return $cgi->a({-href => $href, -class => "list subject"},
1550 esc_html($long)) . $extra;
1554 # Rather than recomputing the url for an email multiple times, we cache it
1555 # after the first hit. This gives a visible benefit in views where the avatar
1556 # for the same email is used repeatedly (e.g. shortlog).
1557 # The cache is shared by all avatar engines (currently gravatar only), which
1558 # are free to use it as preferred. Since only one avatar engine is used for any
1559 # given page, there's no risk for cache conflicts.
1560 our %avatar_cache = ();
1562 # Compute the picon url for a given email, by using the picon search service over at
1563 # http://www.cs.indiana.edu/picons/search.html
1564 sub picon_url {
1565 my $email = lc shift;
1566 if (!$avatar_cache{$email}) {
1567 my ($user, $domain) = split('@', $email);
1568 $avatar_cache{$email} =
1569 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1570 "$domain/$user/" .
1571 "users+domains+unknown/up/single";
1573 return $avatar_cache{$email};
1576 # Compute the gravatar url for a given email, if it's not in the cache already.
1577 # Gravatar stores only the part of the URL before the size, since that's the
1578 # one computationally more expensive. This also allows reuse of the cache for
1579 # different sizes (for this particular engine).
1580 sub gravatar_url {
1581 my $email = lc shift;
1582 my $size = shift;
1583 $avatar_cache{$email} ||=
1584 "http://www.gravatar.com/avatar/" .
1585 Digest::MD5::md5_hex($email) . "?s=";
1586 return $avatar_cache{$email} . $size;
1589 # Insert an avatar for the given $email at the given $size if the feature
1590 # is enabled.
1591 sub git_get_avatar {
1592 my ($email, %opts) = @_;
1593 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1594 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1595 $opts{-size} ||= 'default';
1596 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1597 my $url = "";
1598 if ($git_avatar eq 'gravatar') {
1599 $url = gravatar_url($email, $size);
1600 } elsif ($git_avatar eq 'picon') {
1601 $url = picon_url($email);
1603 # Other providers can be added by extending the if chain, defining $url
1604 # as needed. If no variant puts something in $url, we assume avatars
1605 # are completely disabled/unavailable.
1606 if ($url) {
1607 return $pre_white .
1608 "<img width=\"$size\" " .
1609 "class=\"avatar\" " .
1610 "src=\"$url\" " .
1611 "alt=\"\" " .
1612 "/>" . $post_white;
1613 } else {
1614 return "";
1618 # format the author name of the given commit with the given tag
1619 # the author name is chopped and escaped according to the other
1620 # optional parameters (see chop_str).
1621 sub format_author_html {
1622 my $tag = shift;
1623 my $co = shift;
1624 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1625 return "<$tag class=\"author\">" .
1626 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1627 $author . "</$tag>";
1630 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1631 sub format_git_diff_header_line {
1632 my $line = shift;
1633 my $diffinfo = shift;
1634 my ($from, $to) = @_;
1636 if ($diffinfo->{'nparents'}) {
1637 # combined diff
1638 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1639 if ($to->{'href'}) {
1640 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1641 esc_path($to->{'file'}));
1642 } else { # file was deleted (no href)
1643 $line .= esc_path($to->{'file'});
1645 } else {
1646 # "ordinary" diff
1647 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1648 if ($from->{'href'}) {
1649 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1650 'a/' . esc_path($from->{'file'}));
1651 } else { # file was added (no href)
1652 $line .= 'a/' . esc_path($from->{'file'});
1654 $line .= ' ';
1655 if ($to->{'href'}) {
1656 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1657 'b/' . esc_path($to->{'file'}));
1658 } else { # file was deleted
1659 $line .= 'b/' . esc_path($to->{'file'});
1663 return "<div class=\"diff header\">$line</div>\n";
1666 # format extended diff header line, before patch itself
1667 sub format_extended_diff_header_line {
1668 my $line = shift;
1669 my $diffinfo = shift;
1670 my ($from, $to) = @_;
1672 # match <path>
1673 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1674 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1675 esc_path($from->{'file'}));
1677 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1678 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1679 esc_path($to->{'file'}));
1681 # match single <mode>
1682 if ($line =~ m/\s(\d{6})$/) {
1683 $line .= '<span class="info"> (' .
1684 file_type_long($1) .
1685 ')</span>';
1687 # match <hash>
1688 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1689 # can match only for combined diff
1690 $line = 'index ';
1691 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1692 if ($from->{'href'}[$i]) {
1693 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1694 -class=>"hash"},
1695 substr($diffinfo->{'from_id'}[$i],0,7));
1696 } else {
1697 $line .= '0' x 7;
1699 # separator
1700 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1702 $line .= '..';
1703 if ($to->{'href'}) {
1704 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1705 substr($diffinfo->{'to_id'},0,7));
1706 } else {
1707 $line .= '0' x 7;
1710 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1711 # can match only for ordinary diff
1712 my ($from_link, $to_link);
1713 if ($from->{'href'}) {
1714 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1715 substr($diffinfo->{'from_id'},0,7));
1716 } else {
1717 $from_link = '0' x 7;
1719 if ($to->{'href'}) {
1720 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1721 substr($diffinfo->{'to_id'},0,7));
1722 } else {
1723 $to_link = '0' x 7;
1725 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1726 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1729 return $line . "<br/>\n";
1732 # format from-file/to-file diff header
1733 sub format_diff_from_to_header {
1734 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1735 my $line;
1736 my $result = '';
1738 $line = $from_line;
1739 #assert($line =~ m/^---/) if DEBUG;
1740 # no extra formatting for "^--- /dev/null"
1741 if (! $diffinfo->{'nparents'}) {
1742 # ordinary (single parent) diff
1743 if ($line =~ m!^--- "?a/!) {
1744 if ($from->{'href'}) {
1745 $line = '--- a/' .
1746 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1747 esc_path($from->{'file'}));
1748 } else {
1749 $line = '--- a/' .
1750 esc_path($from->{'file'});
1753 $result .= qq!<div class="diff from_file">$line</div>\n!;
1755 } else {
1756 # combined diff (merge commit)
1757 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1758 if ($from->{'href'}[$i]) {
1759 $line = '--- ' .
1760 $cgi->a({-href=>href(action=>"blobdiff",
1761 hash_parent=>$diffinfo->{'from_id'}[$i],
1762 hash_parent_base=>$parents[$i],
1763 file_parent=>$from->{'file'}[$i],
1764 hash=>$diffinfo->{'to_id'},
1765 hash_base=>$hash,
1766 file_name=>$to->{'file'}),
1767 -class=>"path",
1768 -title=>"diff" . ($i+1)},
1769 $i+1) .
1770 '/' .
1771 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1772 esc_path($from->{'file'}[$i]));
1773 } else {
1774 $line = '--- /dev/null';
1776 $result .= qq!<div class="diff from_file">$line</div>\n!;
1780 $line = $to_line;
1781 #assert($line =~ m/^\+\+\+/) if DEBUG;
1782 # no extra formatting for "^+++ /dev/null"
1783 if ($line =~ m!^\+\+\+ "?b/!) {
1784 if ($to->{'href'}) {
1785 $line = '+++ b/' .
1786 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1787 esc_path($to->{'file'}));
1788 } else {
1789 $line = '+++ b/' .
1790 esc_path($to->{'file'});
1793 $result .= qq!<div class="diff to_file">$line</div>\n!;
1795 return $result;
1798 # create note for patch simplified by combined diff
1799 sub format_diff_cc_simplified {
1800 my ($diffinfo, @parents) = @_;
1801 my $result = '';
1803 $result .= "<div class=\"diff header\">" .
1804 "diff --cc ";
1805 if (!is_deleted($diffinfo)) {
1806 $result .= $cgi->a({-href => href(action=>"blob",
1807 hash_base=>$hash,
1808 hash=>$diffinfo->{'to_id'},
1809 file_name=>$diffinfo->{'to_file'}),
1810 -class => "path"},
1811 esc_path($diffinfo->{'to_file'}));
1812 } else {
1813 $result .= esc_path($diffinfo->{'to_file'});
1815 $result .= "</div>\n" . # class="diff header"
1816 "<div class=\"diff nodifferences\">" .
1817 "Simple merge" .
1818 "</div>\n"; # class="diff nodifferences"
1820 return $result;
1823 # format patch (diff) line (not to be used for diff headers)
1824 sub format_diff_line {
1825 my $line = shift;
1826 my ($from, $to) = @_;
1827 my $diff_class = "";
1829 chomp $line;
1831 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1832 # combined diff
1833 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1834 if ($line =~ m/^\@{3}/) {
1835 $diff_class = " chunk_header";
1836 } elsif ($line =~ m/^\\/) {
1837 $diff_class = " incomplete";
1838 } elsif ($prefix =~ tr/+/+/) {
1839 $diff_class = " add";
1840 } elsif ($prefix =~ tr/-/-/) {
1841 $diff_class = " rem";
1843 } else {
1844 # assume ordinary diff
1845 my $char = substr($line, 0, 1);
1846 if ($char eq '+') {
1847 $diff_class = " add";
1848 } elsif ($char eq '-') {
1849 $diff_class = " rem";
1850 } elsif ($char eq '@') {
1851 $diff_class = " chunk_header";
1852 } elsif ($char eq "\\") {
1853 $diff_class = " incomplete";
1856 $line = untabify($line);
1857 if ($from && $to && $line =~ m/^\@{2} /) {
1858 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1859 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1861 $from_lines = 0 unless defined $from_lines;
1862 $to_lines = 0 unless defined $to_lines;
1864 if ($from->{'href'}) {
1865 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1866 -class=>"list"}, $from_text);
1868 if ($to->{'href'}) {
1869 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1870 -class=>"list"}, $to_text);
1872 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1873 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1874 return "<div class=\"diff$diff_class\">$line</div>\n";
1875 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1876 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1877 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1879 @from_text = split(' ', $ranges);
1880 for (my $i = 0; $i < @from_text; ++$i) {
1881 ($from_start[$i], $from_nlines[$i]) =
1882 (split(',', substr($from_text[$i], 1)), 0);
1885 $to_text = pop @from_text;
1886 $to_start = pop @from_start;
1887 $to_nlines = pop @from_nlines;
1889 $line = "<span class=\"chunk_info\">$prefix ";
1890 for (my $i = 0; $i < @from_text; ++$i) {
1891 if ($from->{'href'}[$i]) {
1892 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1893 -class=>"list"}, $from_text[$i]);
1894 } else {
1895 $line .= $from_text[$i];
1897 $line .= " ";
1899 if ($to->{'href'}) {
1900 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1901 -class=>"list"}, $to_text);
1902 } else {
1903 $line .= $to_text;
1905 $line .= " $prefix</span>" .
1906 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1907 return "<div class=\"diff$diff_class\">$line</div>\n";
1909 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1912 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1913 # linked. Pass the hash of the tree/commit to snapshot.
1914 sub format_snapshot_links {
1915 my ($hash) = @_;
1916 my $num_fmts = @snapshot_fmts;
1917 if ($num_fmts > 1) {
1918 # A parenthesized list of links bearing format names.
1919 # e.g. "snapshot (_tar.gz_ _zip_)"
1920 return "snapshot (" . join(' ', map
1921 $cgi->a({
1922 -href => href(
1923 action=>"snapshot",
1924 hash=>$hash,
1925 snapshot_format=>$_
1927 }, $known_snapshot_formats{$_}{'display'})
1928 , @snapshot_fmts) . ")";
1929 } elsif ($num_fmts == 1) {
1930 # A single "snapshot" link whose tooltip bears the format name.
1931 # i.e. "_snapshot_"
1932 my ($fmt) = @snapshot_fmts;
1933 return
1934 $cgi->a({
1935 -href => href(
1936 action=>"snapshot",
1937 hash=>$hash,
1938 snapshot_format=>$fmt
1940 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1941 }, "snapshot");
1942 } else { # $num_fmts == 0
1943 return undef;
1947 ## ......................................................................
1948 ## functions returning values to be passed, perhaps after some
1949 ## transformation, to other functions; e.g. returning arguments to href()
1951 # returns hash to be passed to href to generate gitweb URL
1952 # in -title key it returns description of link
1953 sub get_feed_info {
1954 my $format = shift || 'Atom';
1955 my %res = (action => lc($format));
1957 # feed links are possible only for project views
1958 return unless (defined $project);
1959 # some views should link to OPML, or to generic project feed,
1960 # or don't have specific feed yet (so they should use generic)
1961 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1963 my $branch;
1964 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1965 # from tag links; this also makes possible to detect branch links
1966 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1967 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1968 $branch = $1;
1970 # find log type for feed description (title)
1971 my $type = 'log';
1972 if (defined $file_name) {
1973 $type = "history of $file_name";
1974 $type .= "/" if ($action eq 'tree');
1975 $type .= " on '$branch'" if (defined $branch);
1976 } else {
1977 $type = "log of $branch" if (defined $branch);
1980 $res{-title} = $type;
1981 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
1982 $res{'file_name'} = $file_name;
1984 return %res;
1987 ## ----------------------------------------------------------------------
1988 ## git utility subroutines, invoking git commands
1990 # returns path to the core git executable and the --git-dir parameter as list
1991 sub git_cmd {
1992 $number_of_git_cmds++;
1993 return $GIT, '--git-dir='.$git_dir;
1996 # quote the given arguments for passing them to the shell
1997 # quote_command("command", "arg 1", "arg with ' and ! characters")
1998 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
1999 # Try to avoid using this function wherever possible.
2000 sub quote_command {
2001 return join(' ',
2002 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2005 # get HEAD ref of given project as hash
2006 sub git_get_head_hash {
2007 my $project = shift;
2008 my $o_git_dir = $git_dir;
2009 my $retval = undef;
2010 $git_dir = "$projectroot/$project";
2011 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
2012 my $head = <$fd>;
2013 close $fd;
2014 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
2015 $retval = $1;
2018 if (defined $o_git_dir) {
2019 $git_dir = $o_git_dir;
2021 return $retval;
2024 # get type of given object
2025 sub git_get_type {
2026 my $hash = shift;
2028 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2029 my $type = <$fd>;
2030 close $fd or return;
2031 chomp $type;
2032 return $type;
2035 # repository configuration
2036 our $config_file = '';
2037 our %config;
2039 # store multiple values for single key as anonymous array reference
2040 # single values stored directly in the hash, not as [ <value> ]
2041 sub hash_set_multi {
2042 my ($hash, $key, $value) = @_;
2044 if (!exists $hash->{$key}) {
2045 $hash->{$key} = $value;
2046 } elsif (!ref $hash->{$key}) {
2047 $hash->{$key} = [ $hash->{$key}, $value ];
2048 } else {
2049 push @{$hash->{$key}}, $value;
2053 # return hash of git project configuration
2054 # optionally limited to some section, e.g. 'gitweb'
2055 sub git_parse_project_config {
2056 my $section_regexp = shift;
2057 my %config;
2059 local $/ = "\0";
2061 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2062 or return;
2064 while (my $keyval = <$fh>) {
2065 chomp $keyval;
2066 my ($key, $value) = split(/\n/, $keyval, 2);
2068 hash_set_multi(\%config, $key, $value)
2069 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2071 close $fh;
2073 return %config;
2076 # convert config value to boolean: 'true' or 'false'
2077 # no value, number > 0, 'true' and 'yes' values are true
2078 # rest of values are treated as false (never as error)
2079 sub config_to_bool {
2080 my $val = shift;
2082 return 1 if !defined $val; # section.key
2084 # strip leading and trailing whitespace
2085 $val =~ s/^\s+//;
2086 $val =~ s/\s+$//;
2088 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2089 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2092 # convert config value to simple decimal number
2093 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2094 # to be multiplied by 1024, 1048576, or 1073741824
2095 sub config_to_int {
2096 my $val = shift;
2098 # strip leading and trailing whitespace
2099 $val =~ s/^\s+//;
2100 $val =~ s/\s+$//;
2102 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2103 $unit = lc($unit);
2104 # unknown unit is treated as 1
2105 return $num * ($unit eq 'g' ? 1073741824 :
2106 $unit eq 'm' ? 1048576 :
2107 $unit eq 'k' ? 1024 : 1);
2109 return $val;
2112 # convert config value to array reference, if needed
2113 sub config_to_multi {
2114 my $val = shift;
2116 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2119 sub git_get_project_config {
2120 my ($key, $type) = @_;
2122 # key sanity check
2123 return unless ($key);
2124 $key =~ s/^gitweb\.//;
2125 return if ($key =~ m/\W/);
2127 # type sanity check
2128 if (defined $type) {
2129 $type =~ s/^--//;
2130 $type = undef
2131 unless ($type eq 'bool' || $type eq 'int');
2134 # get config
2135 if (!defined $config_file ||
2136 $config_file ne "$git_dir/config") {
2137 %config = git_parse_project_config('gitweb');
2138 $config_file = "$git_dir/config";
2141 # check if config variable (key) exists
2142 return unless exists $config{"gitweb.$key"};
2144 # ensure given type
2145 if (!defined $type) {
2146 return $config{"gitweb.$key"};
2147 } elsif ($type eq 'bool') {
2148 # backward compatibility: 'git config --bool' returns true/false
2149 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2150 } elsif ($type eq 'int') {
2151 return config_to_int($config{"gitweb.$key"});
2153 return $config{"gitweb.$key"};
2156 # get hash of given path at given ref
2157 sub git_get_hash_by_path {
2158 my $base = shift;
2159 my $path = shift || return undef;
2160 my $type = shift;
2162 $path =~ s,/+$,,;
2164 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2165 or die_error(500, "Open git-ls-tree failed");
2166 my $line = <$fd>;
2167 close $fd or return undef;
2169 if (!defined $line) {
2170 # there is no tree or hash given by $path at $base
2171 return undef;
2174 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2175 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2176 if (defined $type && $type ne $2) {
2177 # type doesn't match
2178 return undef;
2180 return $3;
2183 # get path of entry with given hash at given tree-ish (ref)
2184 # used to get 'from' filename for combined diff (merge commit) for renames
2185 sub git_get_path_by_hash {
2186 my $base = shift || return;
2187 my $hash = shift || return;
2189 local $/ = "\0";
2191 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2192 or return undef;
2193 while (my $line = <$fd>) {
2194 chomp $line;
2196 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2197 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2198 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2199 close $fd;
2200 return $1;
2203 close $fd;
2204 return undef;
2207 ## ......................................................................
2208 ## git utility functions, directly accessing git repository
2210 sub git_get_project_description {
2211 my $path = shift;
2213 $git_dir = "$projectroot/$path";
2214 open my $fd, '<', "$git_dir/description"
2215 or return git_get_project_config('description');
2216 my $descr = <$fd>;
2217 close $fd;
2218 if (defined $descr) {
2219 chomp $descr;
2221 return $descr;
2224 sub git_get_project_ctags {
2225 my $path = shift;
2226 my $ctags = {};
2228 $git_dir = "$projectroot/$path";
2229 opendir my $dh, "$git_dir/ctags"
2230 or return $ctags;
2231 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2232 open my $ct, '<', $_ or next;
2233 my $val = <$ct>;
2234 chomp $val;
2235 close $ct;
2236 my $ctag = $_; $ctag =~ s#.*/##;
2237 $ctags->{$ctag} = $val;
2239 closedir $dh;
2240 $ctags;
2243 sub git_populate_project_tagcloud {
2244 my $ctags = shift;
2246 # First, merge different-cased tags; tags vote on casing
2247 my %ctags_lc;
2248 foreach (keys %$ctags) {
2249 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2250 if (not $ctags_lc{lc $_}->{topcount}
2251 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2252 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2253 $ctags_lc{lc $_}->{topname} = $_;
2257 my $cloud;
2258 if (eval { require HTML::TagCloud; 1; }) {
2259 $cloud = HTML::TagCloud->new;
2260 foreach (sort keys %ctags_lc) {
2261 # Pad the title with spaces so that the cloud looks
2262 # less crammed.
2263 my $title = $ctags_lc{$_}->{topname};
2264 $title =~ s/ /&nbsp;/g;
2265 $title =~ s/^/&nbsp;/g;
2266 $title =~ s/$/&nbsp;/g;
2267 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2269 } else {
2270 $cloud = \%ctags_lc;
2272 $cloud;
2275 sub git_show_project_tagcloud {
2276 my ($cloud, $count) = @_;
2277 print STDERR ref($cloud)."..\n";
2278 if (ref $cloud eq 'HTML::TagCloud') {
2279 return $cloud->html_and_css($count);
2280 } else {
2281 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2282 return '<p align="center">' . join (', ', map {
2283 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2284 } splice(@tags, 0, $count)) . '</p>';
2288 sub git_get_project_url_list {
2289 my $path = shift;
2291 $git_dir = "$projectroot/$path";
2292 open my $fd, '<', "$git_dir/cloneurl"
2293 or return wantarray ?
2294 @{ config_to_multi(git_get_project_config('url')) } :
2295 config_to_multi(git_get_project_config('url'));
2296 my @git_project_url_list = map { chomp; $_ } <$fd>;
2297 close $fd;
2299 return wantarray ? @git_project_url_list : \@git_project_url_list;
2302 sub git_get_projects_list {
2303 my ($filter) = @_;
2304 my @list;
2306 $filter ||= '';
2307 $filter =~ s/\.git$//;
2309 my $check_forks = gitweb_check_feature('forks');
2311 if (-d $projects_list) {
2312 # search in directory
2313 my $dir = $projects_list . ($filter ? "/$filter" : '');
2314 # remove the trailing "/"
2315 $dir =~ s!/+$!!;
2316 my $pfxlen = length("$dir");
2317 my $pfxdepth = ($dir =~ tr!/!!);
2319 File::Find::find({
2320 follow_fast => 1, # follow symbolic links
2321 follow_skip => 2, # ignore duplicates
2322 dangling_symlinks => 0, # ignore dangling symlinks, silently
2323 wanted => sub {
2324 # skip project-list toplevel, if we get it.
2325 return if (m!^[/.]$!);
2326 # only directories can be git repositories
2327 return unless (-d $_);
2328 # don't traverse too deep (Find is super slow on os x)
2329 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2330 $File::Find::prune = 1;
2331 return;
2334 my $subdir = substr($File::Find::name, $pfxlen + 1);
2335 # we check related file in $projectroot
2336 my $path = ($filter ? "$filter/" : '') . $subdir;
2337 if (check_export_ok("$projectroot/$path")) {
2338 push @list, { path => $path };
2339 $File::Find::prune = 1;
2342 }, "$dir");
2344 } elsif (-f $projects_list) {
2345 # read from file(url-encoded):
2346 # 'git%2Fgit.git Linus+Torvalds'
2347 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2348 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2349 my %paths;
2350 open my $fd, '<', $projects_list or return;
2351 PROJECT:
2352 while (my $line = <$fd>) {
2353 chomp $line;
2354 my ($path, $owner) = split ' ', $line;
2355 $path = unescape($path);
2356 $owner = unescape($owner);
2357 if (!defined $path) {
2358 next;
2360 if ($filter ne '') {
2361 # looking for forks;
2362 my $pfx = substr($path, 0, length($filter));
2363 if ($pfx ne $filter) {
2364 next PROJECT;
2366 my $sfx = substr($path, length($filter));
2367 if ($sfx !~ /^\/.*\.git$/) {
2368 next PROJECT;
2370 } elsif ($check_forks) {
2371 PATH:
2372 foreach my $filter (keys %paths) {
2373 # looking for forks;
2374 my $pfx = substr($path, 0, length($filter));
2375 if ($pfx ne $filter) {
2376 next PATH;
2378 my $sfx = substr($path, length($filter));
2379 if ($sfx !~ /^\/.*\.git$/) {
2380 next PATH;
2382 # is a fork, don't include it in
2383 # the list
2384 next PROJECT;
2387 if (check_export_ok("$projectroot/$path")) {
2388 my $pr = {
2389 path => $path,
2390 owner => to_utf8($owner),
2392 push @list, $pr;
2393 (my $forks_path = $path) =~ s/\.git$//;
2394 $paths{$forks_path}++;
2397 close $fd;
2399 return @list;
2402 our $gitweb_project_owner = undef;
2403 sub git_get_project_list_from_file {
2405 return if (defined $gitweb_project_owner);
2407 $gitweb_project_owner = {};
2408 # read from file (url-encoded):
2409 # 'git%2Fgit.git Linus+Torvalds'
2410 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2411 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2412 if (-f $projects_list) {
2413 open(my $fd, '<', $projects_list);
2414 while (my $line = <$fd>) {
2415 chomp $line;
2416 my ($pr, $ow) = split ' ', $line;
2417 $pr = unescape($pr);
2418 $ow = unescape($ow);
2419 $gitweb_project_owner->{$pr} = to_utf8($ow);
2421 close $fd;
2425 sub git_get_project_owner {
2426 my $project = shift;
2427 my $owner;
2429 return undef unless $project;
2430 $git_dir = "$projectroot/$project";
2432 if (!defined $gitweb_project_owner) {
2433 git_get_project_list_from_file();
2436 if (exists $gitweb_project_owner->{$project}) {
2437 $owner = $gitweb_project_owner->{$project};
2439 if (!defined $owner){
2440 $owner = git_get_project_config('owner');
2442 if (!defined $owner) {
2443 $owner = get_file_owner("$git_dir");
2446 return $owner;
2449 sub git_get_last_activity {
2450 my ($path) = @_;
2451 my $fd;
2453 $git_dir = "$projectroot/$path";
2454 open($fd, "-|", git_cmd(), 'for-each-ref',
2455 '--format=%(committer)',
2456 '--sort=-committerdate',
2457 '--count=1',
2458 'refs/heads') or return;
2459 my $most_recent = <$fd>;
2460 close $fd or return;
2461 if (defined $most_recent &&
2462 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2463 my $timestamp = $1;
2464 my $age = time - $timestamp;
2465 return ($age, age_string($age));
2467 return (undef, undef);
2470 sub git_get_references {
2471 my $type = shift || "";
2472 my %refs;
2473 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2474 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2475 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2476 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2477 or return;
2479 while (my $line = <$fd>) {
2480 chomp $line;
2481 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2482 if (defined $refs{$1}) {
2483 push @{$refs{$1}}, $2;
2484 } else {
2485 $refs{$1} = [ $2 ];
2489 close $fd or return;
2490 return \%refs;
2493 sub git_get_rev_name_tags {
2494 my $hash = shift || return undef;
2496 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2497 or return;
2498 my $name_rev = <$fd>;
2499 close $fd;
2501 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2502 return $1;
2503 } else {
2504 # catches also '$hash undefined' output
2505 return undef;
2509 ## ----------------------------------------------------------------------
2510 ## parse to hash functions
2512 sub parse_date {
2513 my $epoch = shift;
2514 my $tz = shift || "-0000";
2516 my %date;
2517 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2518 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2519 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2520 $date{'hour'} = $hour;
2521 $date{'minute'} = $min;
2522 $date{'mday'} = $mday;
2523 $date{'day'} = $days[$wday];
2524 $date{'month'} = $months[$mon];
2525 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2526 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2527 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2528 $mday, $months[$mon], $hour ,$min;
2529 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2530 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2532 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2533 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2534 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2535 $date{'hour_local'} = $hour;
2536 $date{'minute_local'} = $min;
2537 $date{'tz_local'} = $tz;
2538 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2539 1900+$year, $mon+1, $mday,
2540 $hour, $min, $sec, $tz);
2541 return %date;
2544 sub parse_tag {
2545 my $tag_id = shift;
2546 my %tag;
2547 my @comment;
2549 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2550 $tag{'id'} = $tag_id;
2551 while (my $line = <$fd>) {
2552 chomp $line;
2553 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2554 $tag{'object'} = $1;
2555 } elsif ($line =~ m/^type (.+)$/) {
2556 $tag{'type'} = $1;
2557 } elsif ($line =~ m/^tag (.+)$/) {
2558 $tag{'name'} = $1;
2559 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2560 $tag{'author'} = $1;
2561 $tag{'author_epoch'} = $2;
2562 $tag{'author_tz'} = $3;
2563 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2564 $tag{'author_name'} = $1;
2565 $tag{'author_email'} = $2;
2566 } else {
2567 $tag{'author_name'} = $tag{'author'};
2569 } elsif ($line =~ m/--BEGIN/) {
2570 push @comment, $line;
2571 last;
2572 } elsif ($line eq "") {
2573 last;
2576 push @comment, <$fd>;
2577 $tag{'comment'} = \@comment;
2578 close $fd or return;
2579 if (!defined $tag{'name'}) {
2580 return
2582 return %tag
2585 sub parse_commit_text {
2586 my ($commit_text, $withparents) = @_;
2587 my @commit_lines = split '\n', $commit_text;
2588 my %co;
2590 pop @commit_lines; # Remove '\0'
2592 if (! @commit_lines) {
2593 return;
2596 my $header = shift @commit_lines;
2597 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2598 return;
2600 ($co{'id'}, my @parents) = split ' ', $header;
2601 while (my $line = shift @commit_lines) {
2602 last if $line eq "\n";
2603 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2604 $co{'tree'} = $1;
2605 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2606 push @parents, $1;
2607 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2608 $co{'author'} = to_utf8($1);
2609 $co{'author_epoch'} = $2;
2610 $co{'author_tz'} = $3;
2611 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2612 $co{'author_name'} = $1;
2613 $co{'author_email'} = $2;
2614 } else {
2615 $co{'author_name'} = $co{'author'};
2617 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2618 $co{'committer'} = to_utf8($1);
2619 $co{'committer_epoch'} = $2;
2620 $co{'committer_tz'} = $3;
2621 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2622 $co{'committer_name'} = $1;
2623 $co{'committer_email'} = $2;
2624 } else {
2625 $co{'committer_name'} = $co{'committer'};
2629 if (!defined $co{'tree'}) {
2630 return;
2632 $co{'parents'} = \@parents;
2633 $co{'parent'} = $parents[0];
2635 foreach my $title (@commit_lines) {
2636 $title =~ s/^ //;
2637 if ($title ne "") {
2638 $co{'title'} = chop_str($title, 80, 5);
2639 # remove leading stuff of merges to make the interesting part visible
2640 if (length($title) > 50) {
2641 $title =~ s/^Automatic //;
2642 $title =~ s/^merge (of|with) /Merge ... /i;
2643 if (length($title) > 50) {
2644 $title =~ s/(http|rsync):\/\///;
2646 if (length($title) > 50) {
2647 $title =~ s/(master|www|rsync)\.//;
2649 if (length($title) > 50) {
2650 $title =~ s/kernel.org:?//;
2652 if (length($title) > 50) {
2653 $title =~ s/\/pub\/scm//;
2656 $co{'title_short'} = chop_str($title, 50, 5);
2657 last;
2660 if (! defined $co{'title'} || $co{'title'} eq "") {
2661 $co{'title'} = $co{'title_short'} = '(no commit message)';
2663 # remove added spaces
2664 foreach my $line (@commit_lines) {
2665 $line =~ s/^ //;
2667 $co{'comment'} = \@commit_lines;
2669 my $age = time - $co{'committer_epoch'};
2670 $co{'age'} = $age;
2671 $co{'age_string'} = age_string($age);
2672 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2673 if ($age > 60*60*24*7*2) {
2674 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2675 $co{'age_string_age'} = $co{'age_string'};
2676 } else {
2677 $co{'age_string_date'} = $co{'age_string'};
2678 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2680 return %co;
2683 sub parse_commit {
2684 my ($commit_id) = @_;
2685 my %co;
2687 local $/ = "\0";
2689 open my $fd, "-|", git_cmd(), "rev-list",
2690 "--parents",
2691 "--header",
2692 "--max-count=1",
2693 $commit_id,
2694 "--",
2695 or die_error(500, "Open git-rev-list failed");
2696 %co = parse_commit_text(<$fd>, 1);
2697 close $fd;
2699 return %co;
2702 sub parse_commits {
2703 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2704 my @cos;
2706 $maxcount ||= 1;
2707 $skip ||= 0;
2709 local $/ = "\0";
2711 open my $fd, "-|", git_cmd(), "rev-list",
2712 "--header",
2713 @args,
2714 ("--max-count=" . $maxcount),
2715 ("--skip=" . $skip),
2716 @extra_options,
2717 $commit_id,
2718 "--",
2719 ($filename ? ($filename) : ())
2720 or die_error(500, "Open git-rev-list failed");
2721 while (my $line = <$fd>) {
2722 my %co = parse_commit_text($line);
2723 push @cos, \%co;
2725 close $fd;
2727 return wantarray ? @cos : \@cos;
2730 # parse line of git-diff-tree "raw" output
2731 sub parse_difftree_raw_line {
2732 my $line = shift;
2733 my %res;
2735 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2736 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2737 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2738 $res{'from_mode'} = $1;
2739 $res{'to_mode'} = $2;
2740 $res{'from_id'} = $3;
2741 $res{'to_id'} = $4;
2742 $res{'status'} = $5;
2743 $res{'similarity'} = $6;
2744 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2745 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2746 } else {
2747 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2750 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2751 # combined diff (for merge commit)
2752 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2753 $res{'nparents'} = length($1);
2754 $res{'from_mode'} = [ split(' ', $2) ];
2755 $res{'to_mode'} = pop @{$res{'from_mode'}};
2756 $res{'from_id'} = [ split(' ', $3) ];
2757 $res{'to_id'} = pop @{$res{'from_id'}};
2758 $res{'status'} = [ split('', $4) ];
2759 $res{'to_file'} = unquote($5);
2761 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2762 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2763 $res{'commit'} = $1;
2766 return wantarray ? %res : \%res;
2769 # wrapper: return parsed line of git-diff-tree "raw" output
2770 # (the argument might be raw line, or parsed info)
2771 sub parsed_difftree_line {
2772 my $line_or_ref = shift;
2774 if (ref($line_or_ref) eq "HASH") {
2775 # pre-parsed (or generated by hand)
2776 return $line_or_ref;
2777 } else {
2778 return parse_difftree_raw_line($line_or_ref);
2782 # parse line of git-ls-tree output
2783 sub parse_ls_tree_line {
2784 my $line = shift;
2785 my %opts = @_;
2786 my %res;
2788 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2789 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2791 $res{'mode'} = $1;
2792 $res{'type'} = $2;
2793 $res{'hash'} = $3;
2794 if ($opts{'-z'}) {
2795 $res{'name'} = $4;
2796 } else {
2797 $res{'name'} = unquote($4);
2800 return wantarray ? %res : \%res;
2803 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2804 sub parse_from_to_diffinfo {
2805 my ($diffinfo, $from, $to, @parents) = @_;
2807 if ($diffinfo->{'nparents'}) {
2808 # combined diff
2809 $from->{'file'} = [];
2810 $from->{'href'} = [];
2811 fill_from_file_info($diffinfo, @parents)
2812 unless exists $diffinfo->{'from_file'};
2813 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2814 $from->{'file'}[$i] =
2815 defined $diffinfo->{'from_file'}[$i] ?
2816 $diffinfo->{'from_file'}[$i] :
2817 $diffinfo->{'to_file'};
2818 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2819 $from->{'href'}[$i] = href(action=>"blob",
2820 hash_base=>$parents[$i],
2821 hash=>$diffinfo->{'from_id'}[$i],
2822 file_name=>$from->{'file'}[$i]);
2823 } else {
2824 $from->{'href'}[$i] = undef;
2827 } else {
2828 # ordinary (not combined) diff
2829 $from->{'file'} = $diffinfo->{'from_file'};
2830 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2831 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2832 hash=>$diffinfo->{'from_id'},
2833 file_name=>$from->{'file'});
2834 } else {
2835 delete $from->{'href'};
2839 $to->{'file'} = $diffinfo->{'to_file'};
2840 if (!is_deleted($diffinfo)) { # file exists in result
2841 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2842 hash=>$diffinfo->{'to_id'},
2843 file_name=>$to->{'file'});
2844 } else {
2845 delete $to->{'href'};
2849 ## ......................................................................
2850 ## parse to array of hashes functions
2852 sub git_get_heads_list {
2853 my $limit = shift;
2854 my @headslist;
2856 open my $fd, '-|', git_cmd(), 'for-each-ref',
2857 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2858 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2859 'refs/heads'
2860 or return;
2861 while (my $line = <$fd>) {
2862 my %ref_item;
2864 chomp $line;
2865 my ($refinfo, $committerinfo) = split(/\0/, $line);
2866 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2867 my ($committer, $epoch, $tz) =
2868 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2869 $ref_item{'fullname'} = $name;
2870 $name =~ s!^refs/heads/!!;
2872 $ref_item{'name'} = $name;
2873 $ref_item{'id'} = $hash;
2874 $ref_item{'title'} = $title || '(no commit message)';
2875 $ref_item{'epoch'} = $epoch;
2876 if ($epoch) {
2877 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2878 } else {
2879 $ref_item{'age'} = "unknown";
2882 push @headslist, \%ref_item;
2884 close $fd;
2886 return wantarray ? @headslist : \@headslist;
2889 sub git_get_tags_list {
2890 my $limit = shift;
2891 my @tagslist;
2893 open my $fd, '-|', git_cmd(), 'for-each-ref',
2894 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2895 '--format=%(objectname) %(objecttype) %(refname) '.
2896 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2897 'refs/tags'
2898 or return;
2899 while (my $line = <$fd>) {
2900 my %ref_item;
2902 chomp $line;
2903 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2904 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2905 my ($creator, $epoch, $tz) =
2906 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2907 $ref_item{'fullname'} = $name;
2908 $name =~ s!^refs/tags/!!;
2910 $ref_item{'type'} = $type;
2911 $ref_item{'id'} = $id;
2912 $ref_item{'name'} = $name;
2913 if ($type eq "tag") {
2914 $ref_item{'subject'} = $title;
2915 $ref_item{'reftype'} = $reftype;
2916 $ref_item{'refid'} = $refid;
2917 } else {
2918 $ref_item{'reftype'} = $type;
2919 $ref_item{'refid'} = $id;
2922 if ($type eq "tag" || $type eq "commit") {
2923 $ref_item{'epoch'} = $epoch;
2924 if ($epoch) {
2925 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2926 } else {
2927 $ref_item{'age'} = "unknown";
2931 push @tagslist, \%ref_item;
2933 close $fd;
2935 return wantarray ? @tagslist : \@tagslist;
2938 ## ----------------------------------------------------------------------
2939 ## filesystem-related functions
2941 sub get_file_owner {
2942 my $path = shift;
2944 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2945 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2946 if (!defined $gcos) {
2947 return undef;
2949 my $owner = $gcos;
2950 $owner =~ s/[,;].*$//;
2951 return to_utf8($owner);
2954 # assume that file exists
2955 sub insert_file {
2956 my $filename = shift;
2958 open my $fd, '<', $filename;
2959 print map { to_utf8($_) } <$fd>;
2960 close $fd;
2963 ## ......................................................................
2964 ## mimetype related functions
2966 sub mimetype_guess_file {
2967 my $filename = shift;
2968 my $mimemap = shift;
2969 -r $mimemap or return undef;
2971 my %mimemap;
2972 open(my $mh, '<', $mimemap) or return undef;
2973 while (<$mh>) {
2974 next if m/^#/; # skip comments
2975 my ($mimetype, $exts) = split(/\t+/);
2976 if (defined $exts) {
2977 my @exts = split(/\s+/, $exts);
2978 foreach my $ext (@exts) {
2979 $mimemap{$ext} = $mimetype;
2983 close($mh);
2985 $filename =~ /\.([^.]*)$/;
2986 return $mimemap{$1};
2989 sub mimetype_guess {
2990 my $filename = shift;
2991 my $mime;
2992 $filename =~ /\./ or return undef;
2994 if ($mimetypes_file) {
2995 my $file = $mimetypes_file;
2996 if ($file !~ m!^/!) { # if it is relative path
2997 # it is relative to project
2998 $file = "$projectroot/$project/$file";
3000 $mime = mimetype_guess_file($filename, $file);
3002 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3003 return $mime;
3006 sub blob_mimetype {
3007 my $fd = shift;
3008 my $filename = shift;
3010 if ($filename) {
3011 my $mime = mimetype_guess($filename);
3012 $mime and return $mime;
3015 # just in case
3016 return $default_blob_plain_mimetype unless $fd;
3018 if (-T $fd) {
3019 return 'text/plain';
3020 } elsif (! $filename) {
3021 return 'application/octet-stream';
3022 } elsif ($filename =~ m/\.png$/i) {
3023 return 'image/png';
3024 } elsif ($filename =~ m/\.gif$/i) {
3025 return 'image/gif';
3026 } elsif ($filename =~ m/\.jpe?g$/i) {
3027 return 'image/jpeg';
3028 } else {
3029 return 'application/octet-stream';
3033 sub blob_contenttype {
3034 my ($fd, $file_name, $type) = @_;
3036 $type ||= blob_mimetype($fd, $file_name);
3037 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3038 $type .= "; charset=$default_text_plain_charset";
3041 return $type;
3044 ## ======================================================================
3045 ## functions printing HTML: header, footer, error page
3047 sub git_header_html {
3048 my $status = shift || "200 OK";
3049 my $expires = shift;
3051 my $title = "$site_name";
3052 if (defined $project) {
3053 $title .= " - " . to_utf8($project);
3054 if (defined $action) {
3055 $title .= "/$action";
3056 if (defined $file_name) {
3057 $title .= " - " . esc_path($file_name);
3058 if ($action eq "tree" && $file_name !~ m|/$|) {
3059 $title .= "/";
3064 my $content_type;
3065 # require explicit support from the UA if we are to send the page as
3066 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3067 # we have to do this because MSIE sometimes globs '*/*', pretending to
3068 # support xhtml+xml but choking when it gets what it asked for.
3069 if (defined $cgi->http('HTTP_ACCEPT') &&
3070 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3071 $cgi->Accept('application/xhtml+xml') != 0) {
3072 $content_type = 'application/xhtml+xml';
3073 } else {
3074 $content_type = 'text/html';
3076 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3077 -status=> $status, -expires => $expires);
3078 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3079 print <<EOF;
3080 <?xml version="1.0" encoding="utf-8"?>
3081 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3082 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3083 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3084 <!-- git core binaries version $git_version -->
3085 <head>
3086 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3087 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3088 <meta name="robots" content="index, nofollow"/>
3089 <title>$title</title>
3091 # the stylesheet, favicon etc urls won't work correctly with path_info
3092 # unless we set the appropriate base URL
3093 if ($ENV{'PATH_INFO'}) {
3094 print "<base href=\"".esc_url($base_url)."\" />\n";
3096 # print out each stylesheet that exist, providing backwards capability
3097 # for those people who defined $stylesheet in a config file
3098 if (defined $stylesheet) {
3099 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3100 } else {
3101 foreach my $stylesheet (@stylesheets) {
3102 next unless $stylesheet;
3103 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3106 if (defined $project) {
3107 my %href_params = get_feed_info();
3108 if (!exists $href_params{'-title'}) {
3109 $href_params{'-title'} = 'log';
3112 foreach my $format qw(RSS Atom) {
3113 my $type = lc($format);
3114 my %link_attr = (
3115 '-rel' => 'alternate',
3116 '-title' => "$project - $href_params{'-title'} - $format feed",
3117 '-type' => "application/$type+xml"
3120 $href_params{'action'} = $type;
3121 $link_attr{'-href'} = href(%href_params);
3122 print "<link ".
3123 "rel=\"$link_attr{'-rel'}\" ".
3124 "title=\"$link_attr{'-title'}\" ".
3125 "href=\"$link_attr{'-href'}\" ".
3126 "type=\"$link_attr{'-type'}\" ".
3127 "/>\n";
3129 $href_params{'extra_options'} = '--no-merges';
3130 $link_attr{'-href'} = href(%href_params);
3131 $link_attr{'-title'} .= ' (no merges)';
3132 print "<link ".
3133 "rel=\"$link_attr{'-rel'}\" ".
3134 "title=\"$link_attr{'-title'}\" ".
3135 "href=\"$link_attr{'-href'}\" ".
3136 "type=\"$link_attr{'-type'}\" ".
3137 "/>\n";
3140 } else {
3141 printf('<link rel="alternate" title="%s projects list" '.
3142 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3143 $site_name, href(project=>undef, action=>"project_index"));
3144 printf('<link rel="alternate" title="%s projects feeds" '.
3145 'href="%s" type="text/x-opml" />'."\n",
3146 $site_name, href(project=>undef, action=>"opml"));
3148 if (defined $favicon) {
3149 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3152 print "</head>\n" .
3153 "<body>\n";
3155 if (-f $site_header) {
3156 insert_file($site_header);
3159 print "<div class=\"page_header\">\n" .
3160 $cgi->a({-href => esc_url($logo_url),
3161 -title => $logo_label},
3162 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3163 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3164 if (defined $project) {
3165 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3166 if (defined $action) {
3167 print " / $action";
3169 print "\n";
3171 print "</div>\n";
3173 my $have_search = gitweb_check_feature('search');
3174 if (defined $project && $have_search) {
3175 if (!defined $searchtext) {
3176 $searchtext = "";
3178 my $search_hash;
3179 if (defined $hash_base) {
3180 $search_hash = $hash_base;
3181 } elsif (defined $hash) {
3182 $search_hash = $hash;
3183 } else {
3184 $search_hash = "HEAD";
3186 my $action = $my_uri;
3187 my $use_pathinfo = gitweb_check_feature('pathinfo');
3188 if ($use_pathinfo) {
3189 $action .= "/".esc_url($project);
3191 print $cgi->startform(-method => "get", -action => $action) .
3192 "<div class=\"search\">\n" .
3193 (!$use_pathinfo &&
3194 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3195 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3196 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3197 $cgi->popup_menu(-name => 'st', -default => 'commit',
3198 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3199 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3200 " search:\n",
3201 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3202 "<span title=\"Extended regular expression\">" .
3203 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3204 -checked => $search_use_regexp) .
3205 "</span>" .
3206 "</div>" .
3207 $cgi->end_form() . "\n";
3211 sub git_footer_html {
3212 my $feed_class = 'rss_logo';
3214 print "<div class=\"page_footer\">\n";
3215 if (defined $project) {
3216 my $descr = git_get_project_description($project);
3217 if (defined $descr) {
3218 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3221 my %href_params = get_feed_info();
3222 if (!%href_params) {
3223 $feed_class .= ' generic';
3225 $href_params{'-title'} ||= 'log';
3227 foreach my $format qw(RSS Atom) {
3228 $href_params{'action'} = lc($format);
3229 print $cgi->a({-href => href(%href_params),
3230 -title => "$href_params{'-title'} $format feed",
3231 -class => $feed_class}, $format)."\n";
3234 } else {
3235 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3236 -class => $feed_class}, "OPML") . " ";
3237 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3238 -class => $feed_class}, "TXT") . "\n";
3240 print "</div>\n"; # class="page_footer"
3242 if (defined $t0 && gitweb_check_feature('timed')) {
3243 print "<div id=\"generating_info\">\n";
3244 print 'This page took '.
3245 '<span id="generating_time" class="time_span">'.
3246 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
3247 ' seconds </span>'.
3248 ' and '.
3249 '<span id="generating_cmd">'.
3250 $number_of_git_cmds.
3251 '</span> git commands '.
3252 " to generate.\n";
3253 print "</div>\n"; # class="page_footer"
3256 if (-f $site_footer) {
3257 insert_file($site_footer);
3260 print qq!<script type="text/javascript" src="$javascript"></script>\n!;
3261 if ($action eq 'blame_incremental') {
3262 print qq!<script type="text/javascript">\n!.
3263 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3264 qq! "!. href() .qq!");\n!.
3265 qq!</script>\n!;
3266 } else {
3267 print qq!<script type="text/javascript">\n!.
3268 qq!window.onload = fixLinks;\n!.
3269 qq!</script>\n!;
3272 print "</body>\n" .
3273 "</html>";
3276 # die_error(<http_status_code>, <error_message>)
3277 # Example: die_error(404, 'Hash not found')
3278 # By convention, use the following status codes (as defined in RFC 2616):
3279 # 400: Invalid or missing CGI parameters, or
3280 # requested object exists but has wrong type.
3281 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3282 # this server or project.
3283 # 404: Requested object/revision/project doesn't exist.
3284 # 500: The server isn't configured properly, or
3285 # an internal error occurred (e.g. failed assertions caused by bugs), or
3286 # an unknown error occurred (e.g. the git binary died unexpectedly).
3287 sub die_error {
3288 my $status = shift || 500;
3289 my $error = shift || "Internal server error";
3291 my %http_responses = (400 => '400 Bad Request',
3292 403 => '403 Forbidden',
3293 404 => '404 Not Found',
3294 500 => '500 Internal Server Error');
3295 git_header_html($http_responses{$status});
3296 print <<EOF;
3297 <div class="page_body">
3298 <br /><br />
3299 $status - $error
3300 <br />
3301 </div>
3303 git_footer_html();
3304 exit;
3307 ## ----------------------------------------------------------------------
3308 ## functions printing or outputting HTML: navigation
3310 sub git_print_page_nav {
3311 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3312 $extra = '' if !defined $extra; # pager or formats
3314 my @navs = qw(summary shortlog log commit commitdiff tree);
3315 if ($suppress) {
3316 @navs = grep { $_ ne $suppress } @navs;
3319 my %arg = map { $_ => {action=>$_} } @navs;
3320 if (defined $head) {
3321 for (qw(commit commitdiff)) {
3322 $arg{$_}{'hash'} = $head;
3324 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3325 for (qw(shortlog log)) {
3326 $arg{$_}{'hash'} = $head;
3331 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3332 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3334 my @actions = gitweb_get_feature('actions');
3335 my %repl = (
3336 '%' => '%',
3337 'n' => $project, # project name
3338 'f' => $git_dir, # project path within filesystem
3339 'h' => $treehead || '', # current hash ('h' parameter)
3340 'b' => $treebase || '', # hash base ('hb' parameter)
3342 while (@actions) {
3343 my ($label, $link, $pos) = splice(@actions,0,3);
3344 # insert
3345 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3346 # munch munch
3347 $link =~ s/%([%nfhb])/$repl{$1}/g;
3348 $arg{$label}{'_href'} = $link;
3351 print "<div class=\"page_nav\">\n" .
3352 (join " | ",
3353 map { $_ eq $current ?
3354 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3355 } @navs);
3356 print "<br/>\n$extra<br/>\n" .
3357 "</div>\n";
3360 sub format_paging_nav {
3361 my ($action, $hash, $head, $page, $has_next_link) = @_;
3362 my $paging_nav;
3365 if ($hash ne $head || $page) {
3366 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3367 } else {
3368 $paging_nav .= "HEAD";
3371 if ($page > 0) {
3372 $paging_nav .= " &sdot; " .
3373 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3374 -accesskey => "p", -title => "Alt-p"}, "prev");
3375 } else {
3376 $paging_nav .= " &sdot; prev";
3379 if ($has_next_link) {
3380 $paging_nav .= " &sdot; " .
3381 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3382 -accesskey => "n", -title => "Alt-n"}, "next");
3383 } else {
3384 $paging_nav .= " &sdot; next";
3387 return $paging_nav;
3390 ## ......................................................................
3391 ## functions printing or outputting HTML: div
3393 sub git_print_header_div {
3394 my ($action, $title, $hash, $hash_base) = @_;
3395 my %args = ();
3397 $args{'action'} = $action;
3398 $args{'hash'} = $hash if $hash;
3399 $args{'hash_base'} = $hash_base if $hash_base;
3401 print "<div class=\"header\">\n" .
3402 $cgi->a({-href => href(%args), -class => "title"},
3403 $title ? $title : $action) .
3404 "\n</div>\n";
3407 sub print_local_time {
3408 my %date = @_;
3409 if ($date{'hour_local'} < 6) {
3410 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3411 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3412 } else {
3413 printf(" (%02d:%02d %s)",
3414 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3418 # Outputs the author name and date in long form
3419 sub git_print_authorship {
3420 my $co = shift;
3421 my %opts = @_;
3422 my $tag = $opts{-tag} || 'div';
3424 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3425 print "<$tag class=\"author_date\">" .
3426 esc_html($co->{'author_name'}) .
3427 " [$ad{'rfc2822'}";
3428 print_local_time(%ad) if ($opts{-localtime});
3429 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3430 . "</$tag>\n";
3433 # Outputs table rows containing the full author or committer information,
3434 # in the format expected for 'commit' view (& similia).
3435 # Parameters are a commit hash reference, followed by the list of people
3436 # to output information for. If the list is empty it defalts to both
3437 # author and committer.
3438 sub git_print_authorship_rows {
3439 my $co = shift;
3440 # too bad we can't use @people = @_ || ('author', 'committer')
3441 my @people = @_;
3442 @people = ('author', 'committer') unless @people;
3443 foreach my $who (@people) {
3444 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3445 print "<tr><td>$who</td><td>" . esc_html($co->{$who}) . "</td>" .
3446 "<td rowspan=\"2\">" .
3447 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3448 "</td></tr>\n" .
3449 "<tr>" .
3450 "<td></td><td> $wd{'rfc2822'}";
3451 print_local_time(%wd);
3452 print "</td>" .
3453 "</tr>\n";
3457 sub git_print_page_path {
3458 my $name = shift;
3459 my $type = shift;
3460 my $hb = shift;
3463 print "<div class=\"page_path\">";
3464 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3465 -title => 'tree root'}, to_utf8("[$project]"));
3466 print " / ";
3467 if (defined $name) {
3468 my @dirname = split '/', $name;
3469 my $basename = pop @dirname;
3470 my $fullname = '';
3472 foreach my $dir (@dirname) {
3473 $fullname .= ($fullname ? '/' : '') . $dir;
3474 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3475 hash_base=>$hb),
3476 -title => $fullname}, esc_path($dir));
3477 print " / ";
3479 if (defined $type && $type eq 'blob') {
3480 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3481 hash_base=>$hb),
3482 -title => $name}, esc_path($basename));
3483 } elsif (defined $type && $type eq 'tree') {
3484 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3485 hash_base=>$hb),
3486 -title => $name}, esc_path($basename));
3487 print " / ";
3488 } else {
3489 print esc_path($basename);
3492 print "<br/></div>\n";
3495 sub git_print_log {
3496 my $log = shift;
3497 my %opts = @_;
3499 if ($opts{'-remove_title'}) {
3500 # remove title, i.e. first line of log
3501 shift @$log;
3503 # remove leading empty lines
3504 while (defined $log->[0] && $log->[0] eq "") {
3505 shift @$log;
3508 # print log
3509 my $signoff = 0;
3510 my $empty = 0;
3511 foreach my $line (@$log) {
3512 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3513 $signoff = 1;
3514 $empty = 0;
3515 if (! $opts{'-remove_signoff'}) {
3516 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3517 next;
3518 } else {
3519 # remove signoff lines
3520 next;
3522 } else {
3523 $signoff = 0;
3526 # print only one empty line
3527 # do not print empty line after signoff
3528 if ($line eq "") {
3529 next if ($empty || $signoff);
3530 $empty = 1;
3531 } else {
3532 $empty = 0;
3535 print format_log_line_html($line) . "<br/>\n";
3538 if ($opts{'-final_empty_line'}) {
3539 # end with single empty line
3540 print "<br/>\n" unless $empty;
3544 # return link target (what link points to)
3545 sub git_get_link_target {
3546 my $hash = shift;
3547 my $link_target;
3549 # read link
3550 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3551 or return;
3553 local $/ = undef;
3554 $link_target = <$fd>;
3556 close $fd
3557 or return;
3559 return $link_target;
3562 # given link target, and the directory (basedir) the link is in,
3563 # return target of link relative to top directory (top tree);
3564 # return undef if it is not possible (including absolute links).
3565 sub normalize_link_target {
3566 my ($link_target, $basedir) = @_;
3568 # absolute symlinks (beginning with '/') cannot be normalized
3569 return if (substr($link_target, 0, 1) eq '/');
3571 # normalize link target to path from top (root) tree (dir)
3572 my $path;
3573 if ($basedir) {
3574 $path = $basedir . '/' . $link_target;
3575 } else {
3576 # we are in top (root) tree (dir)
3577 $path = $link_target;
3580 # remove //, /./, and /../
3581 my @path_parts;
3582 foreach my $part (split('/', $path)) {
3583 # discard '.' and ''
3584 next if (!$part || $part eq '.');
3585 # handle '..'
3586 if ($part eq '..') {
3587 if (@path_parts) {
3588 pop @path_parts;
3589 } else {
3590 # link leads outside repository (outside top dir)
3591 return;
3593 } else {
3594 push @path_parts, $part;
3597 $path = join('/', @path_parts);
3599 return $path;
3602 # print tree entry (row of git_tree), but without encompassing <tr> element
3603 sub git_print_tree_entry {
3604 my ($t, $basedir, $hash_base, $have_blame) = @_;
3606 my %base_key = ();
3607 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3609 # The format of a table row is: mode list link. Where mode is
3610 # the mode of the entry, list is the name of the entry, an href,
3611 # and link is the action links of the entry.
3613 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3614 if ($t->{'type'} eq "blob") {
3615 print "<td class=\"list\">" .
3616 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3617 file_name=>"$basedir$t->{'name'}", %base_key),
3618 -class => "list"}, esc_path($t->{'name'}));
3619 if (S_ISLNK(oct $t->{'mode'})) {
3620 my $link_target = git_get_link_target($t->{'hash'});
3621 if ($link_target) {
3622 my $norm_target = normalize_link_target($link_target, $basedir);
3623 if (defined $norm_target) {
3624 print " -> " .
3625 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3626 file_name=>$norm_target),
3627 -title => $norm_target}, esc_path($link_target));
3628 } else {
3629 print " -> " . esc_path($link_target);
3633 print "</td>\n";
3634 print "<td class=\"link\">";
3635 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3636 file_name=>"$basedir$t->{'name'}", %base_key)},
3637 "blob");
3638 if ($have_blame) {
3639 print " | " .
3640 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3641 file_name=>"$basedir$t->{'name'}", %base_key)},
3642 "blame");
3644 if (defined $hash_base) {
3645 print " | " .
3646 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3647 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3648 "history");
3650 print " | " .
3651 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3652 file_name=>"$basedir$t->{'name'}")},
3653 "raw");
3654 print "</td>\n";
3656 } elsif ($t->{'type'} eq "tree") {
3657 print "<td class=\"list\">";
3658 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3659 file_name=>"$basedir$t->{'name'}", %base_key)},
3660 esc_path($t->{'name'}));
3661 print "</td>\n";
3662 print "<td class=\"link\">";
3663 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3664 file_name=>"$basedir$t->{'name'}", %base_key)},
3665 "tree");
3666 if (defined $hash_base) {
3667 print " | " .
3668 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3669 file_name=>"$basedir$t->{'name'}")},
3670 "history");
3672 print "</td>\n";
3673 } else {
3674 # unknown object: we can only present history for it
3675 # (this includes 'commit' object, i.e. submodule support)
3676 print "<td class=\"list\">" .
3677 esc_path($t->{'name'}) .
3678 "</td>\n";
3679 print "<td class=\"link\">";
3680 if (defined $hash_base) {
3681 print $cgi->a({-href => href(action=>"history",
3682 hash_base=>$hash_base,
3683 file_name=>"$basedir$t->{'name'}")},
3684 "history");
3686 print "</td>\n";
3690 ## ......................................................................
3691 ## functions printing large fragments of HTML
3693 # get pre-image filenames for merge (combined) diff
3694 sub fill_from_file_info {
3695 my ($diff, @parents) = @_;
3697 $diff->{'from_file'} = [ ];
3698 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3699 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3700 if ($diff->{'status'}[$i] eq 'R' ||
3701 $diff->{'status'}[$i] eq 'C') {
3702 $diff->{'from_file'}[$i] =
3703 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3707 return $diff;
3710 # is current raw difftree line of file deletion
3711 sub is_deleted {
3712 my $diffinfo = shift;
3714 return $diffinfo->{'to_id'} eq ('0' x 40);
3717 # does patch correspond to [previous] difftree raw line
3718 # $diffinfo - hashref of parsed raw diff format
3719 # $patchinfo - hashref of parsed patch diff format
3720 # (the same keys as in $diffinfo)
3721 sub is_patch_split {
3722 my ($diffinfo, $patchinfo) = @_;
3724 return defined $diffinfo && defined $patchinfo
3725 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3729 sub git_difftree_body {
3730 my ($difftree, $hash, @parents) = @_;
3731 my ($parent) = $parents[0];
3732 my $have_blame = gitweb_check_feature('blame');
3733 print "<div class=\"list_head\">\n";
3734 if ($#{$difftree} > 10) {
3735 print(($#{$difftree} + 1) . " files changed:\n");
3737 print "</div>\n";
3739 print "<table class=\"" .
3740 (@parents > 1 ? "combined " : "") .
3741 "diff_tree\">\n";
3743 # header only for combined diff in 'commitdiff' view
3744 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3745 if ($has_header) {
3746 # table header
3747 print "<thead><tr>\n" .
3748 "<th></th><th></th>\n"; # filename, patchN link
3749 for (my $i = 0; $i < @parents; $i++) {
3750 my $par = $parents[$i];
3751 print "<th>" .
3752 $cgi->a({-href => href(action=>"commitdiff",
3753 hash=>$hash, hash_parent=>$par),
3754 -title => 'commitdiff to parent number ' .
3755 ($i+1) . ': ' . substr($par,0,7)},
3756 $i+1) .
3757 "&nbsp;</th>\n";
3759 print "</tr></thead>\n<tbody>\n";
3762 my $alternate = 1;
3763 my $patchno = 0;
3764 foreach my $line (@{$difftree}) {
3765 my $diff = parsed_difftree_line($line);
3767 if ($alternate) {
3768 print "<tr class=\"dark\">\n";
3769 } else {
3770 print "<tr class=\"light\">\n";
3772 $alternate ^= 1;
3774 if (exists $diff->{'nparents'}) { # combined diff
3776 fill_from_file_info($diff, @parents)
3777 unless exists $diff->{'from_file'};
3779 if (!is_deleted($diff)) {
3780 # file exists in the result (child) commit
3781 print "<td>" .
3782 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3783 file_name=>$diff->{'to_file'},
3784 hash_base=>$hash),
3785 -class => "list"}, esc_path($diff->{'to_file'})) .
3786 "</td>\n";
3787 } else {
3788 print "<td>" .
3789 esc_path($diff->{'to_file'}) .
3790 "</td>\n";
3793 if ($action eq 'commitdiff') {
3794 # link to patch
3795 $patchno++;
3796 print "<td class=\"link\">" .
3797 $cgi->a({-href => "#patch$patchno"}, "patch") .
3798 " | " .
3799 "</td>\n";
3802 my $has_history = 0;
3803 my $not_deleted = 0;
3804 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3805 my $hash_parent = $parents[$i];
3806 my $from_hash = $diff->{'from_id'}[$i];
3807 my $from_path = $diff->{'from_file'}[$i];
3808 my $status = $diff->{'status'}[$i];
3810 $has_history ||= ($status ne 'A');
3811 $not_deleted ||= ($status ne 'D');
3813 if ($status eq 'A') {
3814 print "<td class=\"link\" align=\"right\"> | </td>\n";
3815 } elsif ($status eq 'D') {
3816 print "<td class=\"link\">" .
3817 $cgi->a({-href => href(action=>"blob",
3818 hash_base=>$hash,
3819 hash=>$from_hash,
3820 file_name=>$from_path)},
3821 "blob" . ($i+1)) .
3822 " | </td>\n";
3823 } else {
3824 if ($diff->{'to_id'} eq $from_hash) {
3825 print "<td class=\"link nochange\">";
3826 } else {
3827 print "<td class=\"link\">";
3829 print $cgi->a({-href => href(action=>"blobdiff",
3830 hash=>$diff->{'to_id'},
3831 hash_parent=>$from_hash,
3832 hash_base=>$hash,
3833 hash_parent_base=>$hash_parent,
3834 file_name=>$diff->{'to_file'},
3835 file_parent=>$from_path)},
3836 "diff" . ($i+1)) .
3837 " | </td>\n";
3841 print "<td class=\"link\">";
3842 if ($not_deleted) {
3843 print $cgi->a({-href => href(action=>"blob",
3844 hash=>$diff->{'to_id'},
3845 file_name=>$diff->{'to_file'},
3846 hash_base=>$hash)},
3847 "blob");
3848 print " | " if ($has_history);
3850 if ($has_history) {
3851 print $cgi->a({-href => href(action=>"history",
3852 file_name=>$diff->{'to_file'},
3853 hash_base=>$hash)},
3854 "history");
3856 print "</td>\n";
3858 print "</tr>\n";
3859 next; # instead of 'else' clause, to avoid extra indent
3861 # else ordinary diff
3863 my ($to_mode_oct, $to_mode_str, $to_file_type);
3864 my ($from_mode_oct, $from_mode_str, $from_file_type);
3865 if ($diff->{'to_mode'} ne ('0' x 6)) {
3866 $to_mode_oct = oct $diff->{'to_mode'};
3867 if (S_ISREG($to_mode_oct)) { # only for regular file
3868 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3870 $to_file_type = file_type($diff->{'to_mode'});
3872 if ($diff->{'from_mode'} ne ('0' x 6)) {
3873 $from_mode_oct = oct $diff->{'from_mode'};
3874 if (S_ISREG($to_mode_oct)) { # only for regular file
3875 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3877 $from_file_type = file_type($diff->{'from_mode'});
3880 if ($diff->{'status'} eq "A") { # created
3881 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3882 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3883 $mode_chng .= "]</span>";
3884 print "<td>";
3885 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3886 hash_base=>$hash, file_name=>$diff->{'file'}),
3887 -class => "list"}, esc_path($diff->{'file'}));
3888 print "</td>\n";
3889 print "<td>$mode_chng</td>\n";
3890 print "<td class=\"link\">";
3891 if ($action eq 'commitdiff') {
3892 # link to patch
3893 $patchno++;
3894 print $cgi->a({-href => "#patch$patchno"}, "patch");
3895 print " | ";
3897 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3898 hash_base=>$hash, file_name=>$diff->{'file'})},
3899 "blob");
3900 print "</td>\n";
3902 } elsif ($diff->{'status'} eq "D") { # deleted
3903 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3904 print "<td>";
3905 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3906 hash_base=>$parent, file_name=>$diff->{'file'}),
3907 -class => "list"}, esc_path($diff->{'file'}));
3908 print "</td>\n";
3909 print "<td>$mode_chng</td>\n";
3910 print "<td class=\"link\">";
3911 if ($action eq 'commitdiff') {
3912 # link to patch
3913 $patchno++;
3914 print $cgi->a({-href => "#patch$patchno"}, "patch");
3915 print " | ";
3917 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3918 hash_base=>$parent, file_name=>$diff->{'file'})},
3919 "blob") . " | ";
3920 if ($have_blame) {
3921 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3922 file_name=>$diff->{'file'})},
3923 "blame") . " | ";
3925 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3926 file_name=>$diff->{'file'})},
3927 "history");
3928 print "</td>\n";
3930 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3931 my $mode_chnge = "";
3932 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3933 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3934 if ($from_file_type ne $to_file_type) {
3935 $mode_chnge .= " from $from_file_type to $to_file_type";
3937 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3938 if ($from_mode_str && $to_mode_str) {
3939 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3940 } elsif ($to_mode_str) {
3941 $mode_chnge .= " mode: $to_mode_str";
3944 $mode_chnge .= "]</span>\n";
3946 print "<td>";
3947 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3948 hash_base=>$hash, file_name=>$diff->{'file'}),
3949 -class => "list"}, esc_path($diff->{'file'}));
3950 print "</td>\n";
3951 print "<td>$mode_chnge</td>\n";
3952 print "<td class=\"link\">";
3953 if ($action eq 'commitdiff') {
3954 # link to patch
3955 $patchno++;
3956 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3957 " | ";
3958 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3959 # "commit" view and modified file (not onlu mode changed)
3960 print $cgi->a({-href => href(action=>"blobdiff",
3961 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3962 hash_base=>$hash, hash_parent_base=>$parent,
3963 file_name=>$diff->{'file'})},
3964 "diff") .
3965 " | ";
3967 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3968 hash_base=>$hash, file_name=>$diff->{'file'})},
3969 "blob") . " | ";
3970 if ($have_blame) {
3971 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3972 file_name=>$diff->{'file'})},
3973 "blame") . " | ";
3975 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3976 file_name=>$diff->{'file'})},
3977 "history");
3978 print "</td>\n";
3980 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3981 my %status_name = ('R' => 'moved', 'C' => 'copied');
3982 my $nstatus = $status_name{$diff->{'status'}};
3983 my $mode_chng = "";
3984 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3985 # mode also for directories, so we cannot use $to_mode_str
3986 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3988 print "<td>" .
3989 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3990 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3991 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3992 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3993 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3994 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3995 -class => "list"}, esc_path($diff->{'from_file'})) .
3996 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3997 "<td class=\"link\">";
3998 if ($action eq 'commitdiff') {
3999 # link to patch
4000 $patchno++;
4001 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4002 " | ";
4003 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4004 # "commit" view and modified file (not only pure rename or copy)
4005 print $cgi->a({-href => href(action=>"blobdiff",
4006 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4007 hash_base=>$hash, hash_parent_base=>$parent,
4008 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4009 "diff") .
4010 " | ";
4012 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4013 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4014 "blob") . " | ";
4015 if ($have_blame) {
4016 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4017 file_name=>$diff->{'to_file'})},
4018 "blame") . " | ";
4020 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4021 file_name=>$diff->{'to_file'})},
4022 "history");
4023 print "</td>\n";
4025 } # we should not encounter Unmerged (U) or Unknown (X) status
4026 print "</tr>\n";
4028 print "</tbody>" if $has_header;
4029 print "</table>\n";
4032 sub git_patchset_body {
4033 my ($fd, $difftree, $hash, @hash_parents) = @_;
4034 my ($hash_parent) = $hash_parents[0];
4036 my $is_combined = (@hash_parents > 1);
4037 my $patch_idx = 0;
4038 my $patch_number = 0;
4039 my $patch_line;
4040 my $diffinfo;
4041 my $to_name;
4042 my (%from, %to);
4044 print "<div class=\"patchset\">\n";
4046 # skip to first patch
4047 while ($patch_line = <$fd>) {
4048 chomp $patch_line;
4050 last if ($patch_line =~ m/^diff /);
4053 PATCH:
4054 while ($patch_line) {
4056 # parse "git diff" header line
4057 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4058 # $1 is from_name, which we do not use
4059 $to_name = unquote($2);
4060 $to_name =~ s!^b/!!;
4061 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4062 # $1 is 'cc' or 'combined', which we do not use
4063 $to_name = unquote($2);
4064 } else {
4065 $to_name = undef;
4068 # check if current patch belong to current raw line
4069 # and parse raw git-diff line if needed
4070 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4071 # this is continuation of a split patch
4072 print "<div class=\"patch cont\">\n";
4073 } else {
4074 # advance raw git-diff output if needed
4075 $patch_idx++ if defined $diffinfo;
4077 # read and prepare patch information
4078 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4080 # compact combined diff output can have some patches skipped
4081 # find which patch (using pathname of result) we are at now;
4082 if ($is_combined) {
4083 while ($to_name ne $diffinfo->{'to_file'}) {
4084 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4085 format_diff_cc_simplified($diffinfo, @hash_parents) .
4086 "</div>\n"; # class="patch"
4088 $patch_idx++;
4089 $patch_number++;
4091 last if $patch_idx > $#$difftree;
4092 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4096 # modifies %from, %to hashes
4097 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4099 # this is first patch for raw difftree line with $patch_idx index
4100 # we index @$difftree array from 0, but number patches from 1
4101 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4104 # git diff header
4105 #assert($patch_line =~ m/^diff /) if DEBUG;
4106 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4107 $patch_number++;
4108 # print "git diff" header
4109 print format_git_diff_header_line($patch_line, $diffinfo,
4110 \%from, \%to);
4112 # print extended diff header
4113 print "<div class=\"diff extended_header\">\n";
4114 EXTENDED_HEADER:
4115 while ($patch_line = <$fd>) {
4116 chomp $patch_line;
4118 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4120 print format_extended_diff_header_line($patch_line, $diffinfo,
4121 \%from, \%to);
4123 print "</div>\n"; # class="diff extended_header"
4125 # from-file/to-file diff header
4126 if (! $patch_line) {
4127 print "</div>\n"; # class="patch"
4128 last PATCH;
4130 next PATCH if ($patch_line =~ m/^diff /);
4131 #assert($patch_line =~ m/^---/) if DEBUG;
4133 my $last_patch_line = $patch_line;
4134 $patch_line = <$fd>;
4135 chomp $patch_line;
4136 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4138 print format_diff_from_to_header($last_patch_line, $patch_line,
4139 $diffinfo, \%from, \%to,
4140 @hash_parents);
4142 # the patch itself
4143 LINE:
4144 while ($patch_line = <$fd>) {
4145 chomp $patch_line;
4147 next PATCH if ($patch_line =~ m/^diff /);
4149 print format_diff_line($patch_line, \%from, \%to);
4152 } continue {
4153 print "</div>\n"; # class="patch"
4156 # for compact combined (--cc) format, with chunk and patch simpliciaction
4157 # patchset might be empty, but there might be unprocessed raw lines
4158 for (++$patch_idx if $patch_number > 0;
4159 $patch_idx < @$difftree;
4160 ++$patch_idx) {
4161 # read and prepare patch information
4162 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4164 # generate anchor for "patch" links in difftree / whatchanged part
4165 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4166 format_diff_cc_simplified($diffinfo, @hash_parents) .
4167 "</div>\n"; # class="patch"
4169 $patch_number++;
4172 if ($patch_number == 0) {
4173 if (@hash_parents > 1) {
4174 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4175 } else {
4176 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4180 print "</div>\n"; # class="patchset"
4183 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4185 # fills project list info (age, description, owner, forks) for each
4186 # project in the list, removing invalid projects from returned list
4187 # NOTE: modifies $projlist, but does not remove entries from it
4188 sub fill_project_list_info {
4189 my ($projlist, $check_forks) = @_;
4190 my @projects;
4192 my $show_ctags = gitweb_check_feature('ctags');
4193 PROJECT:
4194 foreach my $pr (@$projlist) {
4195 my (@activity) = git_get_last_activity($pr->{'path'});
4196 unless (@activity) {
4197 next PROJECT;
4199 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4200 if (!defined $pr->{'descr'}) {
4201 my $descr = git_get_project_description($pr->{'path'}) || "";
4202 $descr = to_utf8($descr);
4203 $pr->{'descr_long'} = $descr;
4204 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4206 if (!defined $pr->{'owner'}) {
4207 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4209 if ($check_forks) {
4210 my $pname = $pr->{'path'};
4211 if (($pname =~ s/\.git$//) &&
4212 ($pname !~ /\/$/) &&
4213 (-d "$projectroot/$pname")) {
4214 $pr->{'forks'} = "-d $projectroot/$pname";
4215 } else {
4216 $pr->{'forks'} = 0;
4219 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4220 push @projects, $pr;
4223 return @projects;
4226 # print 'sort by' <th> element, generating 'sort by $name' replay link
4227 # if that order is not selected
4228 sub print_sort_th {
4229 my ($name, $order, $header) = @_;
4230 $header ||= ucfirst($name);
4232 if ($order eq $name) {
4233 print "<th>$header</th>\n";
4234 } else {
4235 print "<th>" .
4236 $cgi->a({-href => href(-replay=>1, order=>$name),
4237 -class => "header"}, $header) .
4238 "</th>\n";
4242 sub git_project_list_body {
4243 # actually uses global variable $project
4244 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4246 my $check_forks = gitweb_check_feature('forks');
4247 my @projects = fill_project_list_info($projlist, $check_forks);
4249 $order ||= $default_projects_order;
4250 $from = 0 unless defined $from;
4251 $to = $#projects if (!defined $to || $#projects < $to);
4253 my %order_info = (
4254 project => { key => 'path', type => 'str' },
4255 descr => { key => 'descr_long', type => 'str' },
4256 owner => { key => 'owner', type => 'str' },
4257 age => { key => 'age', type => 'num' }
4259 my $oi = $order_info{$order};
4260 if ($oi->{'type'} eq 'str') {
4261 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4262 } else {
4263 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4266 my $show_ctags = gitweb_check_feature('ctags');
4267 if ($show_ctags) {
4268 my %ctags;
4269 foreach my $p (@projects) {
4270 foreach my $ct (keys %{$p->{'ctags'}}) {
4271 $ctags{$ct} += $p->{'ctags'}->{$ct};
4274 my $cloud = git_populate_project_tagcloud(\%ctags);
4275 print git_show_project_tagcloud($cloud, 64);
4278 print "<table class=\"project_list\">\n";
4279 unless ($no_header) {
4280 print "<tr>\n";
4281 if ($check_forks) {
4282 print "<th></th>\n";
4284 print_sort_th('project', $order, 'Project');
4285 print_sort_th('descr', $order, 'Description');
4286 print_sort_th('owner', $order, 'Owner');
4287 print_sort_th('age', $order, 'Last Change');
4288 print "<th></th>\n" . # for links
4289 "</tr>\n";
4291 my $alternate = 1;
4292 my $tagfilter = $cgi->param('by_tag');
4293 for (my $i = $from; $i <= $to; $i++) {
4294 my $pr = $projects[$i];
4296 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4297 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4298 and not $pr->{'descr_long'} =~ /$searchtext/;
4299 # Weed out forks or non-matching entries of search
4300 if ($check_forks) {
4301 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4302 $forkbase="^$forkbase" if $forkbase;
4303 next if not $searchtext and not $tagfilter and $show_ctags
4304 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4307 if ($alternate) {
4308 print "<tr class=\"dark\">\n";
4309 } else {
4310 print "<tr class=\"light\">\n";
4312 $alternate ^= 1;
4313 if ($check_forks) {
4314 print "<td>";
4315 if ($pr->{'forks'}) {
4316 print "<!-- $pr->{'forks'} -->\n";
4317 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4319 print "</td>\n";
4321 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4322 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4323 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4324 -class => "list", -title => $pr->{'descr_long'}},
4325 esc_html($pr->{'descr'})) . "</td>\n" .
4326 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4327 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4328 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4329 "<td class=\"link\">" .
4330 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4331 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4332 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4333 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4334 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4335 "</td>\n" .
4336 "</tr>\n";
4338 if (defined $extra) {
4339 print "<tr>\n";
4340 if ($check_forks) {
4341 print "<td></td>\n";
4343 print "<td colspan=\"5\">$extra</td>\n" .
4344 "</tr>\n";
4346 print "</table>\n";
4349 sub git_shortlog_body {
4350 # uses global variable $project
4351 my ($commitlist, $from, $to, $refs, $extra) = @_;
4353 $from = 0 unless defined $from;
4354 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4356 print "<table class=\"shortlog\">\n";
4357 my $alternate = 1;
4358 for (my $i = $from; $i <= $to; $i++) {
4359 my %co = %{$commitlist->[$i]};
4360 my $commit = $co{'id'};
4361 my $ref = format_ref_marker($refs, $commit);
4362 if ($alternate) {
4363 print "<tr class=\"dark\">\n";
4364 } else {
4365 print "<tr class=\"light\">\n";
4367 $alternate ^= 1;
4368 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4369 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4370 format_author_html('td', \%co, 10) . "<td>";
4371 print format_subject_html($co{'title'}, $co{'title_short'},
4372 href(action=>"commit", hash=>$commit), $ref);
4373 print "</td>\n" .
4374 "<td class=\"link\">" .
4375 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4376 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4377 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4378 my $snapshot_links = format_snapshot_links($commit);
4379 if (defined $snapshot_links) {
4380 print " | " . $snapshot_links;
4382 print "</td>\n" .
4383 "</tr>\n";
4385 if (defined $extra) {
4386 print "<tr>\n" .
4387 "<td colspan=\"4\">$extra</td>\n" .
4388 "</tr>\n";
4390 print "</table>\n";
4393 sub git_history_body {
4394 # Warning: assumes constant type (blob or tree) during history
4395 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4397 $from = 0 unless defined $from;
4398 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4400 print "<table class=\"history\">\n";
4401 my $alternate = 1;
4402 for (my $i = $from; $i <= $to; $i++) {
4403 my %co = %{$commitlist->[$i]};
4404 if (!%co) {
4405 next;
4407 my $commit = $co{'id'};
4409 my $ref = format_ref_marker($refs, $commit);
4411 if ($alternate) {
4412 print "<tr class=\"dark\">\n";
4413 } else {
4414 print "<tr class=\"light\">\n";
4416 $alternate ^= 1;
4417 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4418 # shortlog: format_author_html('td', \%co, 10)
4419 format_author_html('td', \%co, 15, 3) . "<td>";
4420 # originally git_history used chop_str($co{'title'}, 50)
4421 print format_subject_html($co{'title'}, $co{'title_short'},
4422 href(action=>"commit", hash=>$commit), $ref);
4423 print "</td>\n" .
4424 "<td class=\"link\">" .
4425 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4426 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4428 if ($ftype eq 'blob') {
4429 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4430 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4431 if (defined $blob_current && defined $blob_parent &&
4432 $blob_current ne $blob_parent) {
4433 print " | " .
4434 $cgi->a({-href => href(action=>"blobdiff",
4435 hash=>$blob_current, hash_parent=>$blob_parent,
4436 hash_base=>$hash_base, hash_parent_base=>$commit,
4437 file_name=>$file_name)},
4438 "diff to current");
4441 print "</td>\n" .
4442 "</tr>\n";
4444 if (defined $extra) {
4445 print "<tr>\n" .
4446 "<td colspan=\"4\">$extra</td>\n" .
4447 "</tr>\n";
4449 print "</table>\n";
4452 sub git_tags_body {
4453 # uses global variable $project
4454 my ($taglist, $from, $to, $extra) = @_;
4455 $from = 0 unless defined $from;
4456 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4458 print "<table class=\"tags\">\n";
4459 my $alternate = 1;
4460 for (my $i = $from; $i <= $to; $i++) {
4461 my $entry = $taglist->[$i];
4462 my %tag = %$entry;
4463 my $comment = $tag{'subject'};
4464 my $comment_short;
4465 if (defined $comment) {
4466 $comment_short = chop_str($comment, 30, 5);
4468 if ($alternate) {
4469 print "<tr class=\"dark\">\n";
4470 } else {
4471 print "<tr class=\"light\">\n";
4473 $alternate ^= 1;
4474 if (defined $tag{'age'}) {
4475 print "<td><i>$tag{'age'}</i></td>\n";
4476 } else {
4477 print "<td></td>\n";
4479 print "<td>" .
4480 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4481 -class => "list name"}, esc_html($tag{'name'})) .
4482 "</td>\n" .
4483 "<td>";
4484 if (defined $comment) {
4485 print format_subject_html($comment, $comment_short,
4486 href(action=>"tag", hash=>$tag{'id'}));
4488 print "</td>\n" .
4489 "<td class=\"selflink\">";
4490 if ($tag{'type'} eq "tag") {
4491 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4492 } else {
4493 print "&nbsp;";
4495 print "</td>\n" .
4496 "<td class=\"link\">" . " | " .
4497 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4498 if ($tag{'reftype'} eq "commit") {
4499 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4500 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4501 } elsif ($tag{'reftype'} eq "blob") {
4502 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4504 print "</td>\n" .
4505 "</tr>";
4507 if (defined $extra) {
4508 print "<tr>\n" .
4509 "<td colspan=\"5\">$extra</td>\n" .
4510 "</tr>\n";
4512 print "</table>\n";
4515 sub git_heads_body {
4516 # uses global variable $project
4517 my ($headlist, $head, $from, $to, $extra) = @_;
4518 $from = 0 unless defined $from;
4519 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4521 print "<table class=\"heads\">\n";
4522 my $alternate = 1;
4523 for (my $i = $from; $i <= $to; $i++) {
4524 my $entry = $headlist->[$i];
4525 my %ref = %$entry;
4526 my $curr = $ref{'id'} eq $head;
4527 if ($alternate) {
4528 print "<tr class=\"dark\">\n";
4529 } else {
4530 print "<tr class=\"light\">\n";
4532 $alternate ^= 1;
4533 print "<td><i>$ref{'age'}</i></td>\n" .
4534 ($curr ? "<td class=\"current_head\">" : "<td>") .
4535 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4536 -class => "list name"},esc_html($ref{'name'})) .
4537 "</td>\n" .
4538 "<td class=\"link\">" .
4539 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4540 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4541 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4542 "</td>\n" .
4543 "</tr>";
4545 if (defined $extra) {
4546 print "<tr>\n" .
4547 "<td colspan=\"3\">$extra</td>\n" .
4548 "</tr>\n";
4550 print "</table>\n";
4553 sub git_search_grep_body {
4554 my ($commitlist, $from, $to, $extra) = @_;
4555 $from = 0 unless defined $from;
4556 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4558 print "<table class=\"commit_search\">\n";
4559 my $alternate = 1;
4560 for (my $i = $from; $i <= $to; $i++) {
4561 my %co = %{$commitlist->[$i]};
4562 if (!%co) {
4563 next;
4565 my $commit = $co{'id'};
4566 if ($alternate) {
4567 print "<tr class=\"dark\">\n";
4568 } else {
4569 print "<tr class=\"light\">\n";
4571 $alternate ^= 1;
4572 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4573 format_author_html('td', \%co, 15, 5) .
4574 "<td>" .
4575 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4576 -class => "list subject"},
4577 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4578 my $comment = $co{'comment'};
4579 foreach my $line (@$comment) {
4580 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4581 my ($lead, $match, $trail) = ($1, $2, $3);
4582 $match = chop_str($match, 70, 5, 'center');
4583 my $contextlen = int((80 - length($match))/2);
4584 $contextlen = 30 if ($contextlen > 30);
4585 $lead = chop_str($lead, $contextlen, 10, 'left');
4586 $trail = chop_str($trail, $contextlen, 10, 'right');
4588 $lead = esc_html($lead);
4589 $match = esc_html($match);
4590 $trail = esc_html($trail);
4592 print "$lead<span class=\"match\">$match</span>$trail<br />";
4595 print "</td>\n" .
4596 "<td class=\"link\">" .
4597 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4598 " | " .
4599 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4600 " | " .
4601 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4602 print "</td>\n" .
4603 "</tr>\n";
4605 if (defined $extra) {
4606 print "<tr>\n" .
4607 "<td colspan=\"3\">$extra</td>\n" .
4608 "</tr>\n";
4610 print "</table>\n";
4613 ## ======================================================================
4614 ## ======================================================================
4615 ## actions
4617 sub git_project_list {
4618 my $order = $input_params{'order'};
4619 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4620 die_error(400, "Unknown order parameter");
4623 my @list = git_get_projects_list();
4624 if (!@list) {
4625 die_error(404, "No projects found");
4628 git_header_html();
4629 if (-f $home_text) {
4630 print "<div class=\"index_include\">\n";
4631 insert_file($home_text);
4632 print "</div>\n";
4634 print $cgi->startform(-method => "get") .
4635 "<p class=\"projsearch\">Search:\n" .
4636 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4637 "</p>" .
4638 $cgi->end_form() . "\n";
4639 git_project_list_body(\@list, $order);
4640 git_footer_html();
4643 sub git_forks {
4644 my $order = $input_params{'order'};
4645 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4646 die_error(400, "Unknown order parameter");
4649 my @list = git_get_projects_list($project);
4650 if (!@list) {
4651 die_error(404, "No forks found");
4654 git_header_html();
4655 git_print_page_nav('','');
4656 git_print_header_div('summary', "$project forks");
4657 git_project_list_body(\@list, $order);
4658 git_footer_html();
4661 sub git_project_index {
4662 my @projects = git_get_projects_list($project);
4664 print $cgi->header(
4665 -type => 'text/plain',
4666 -charset => 'utf-8',
4667 -content_disposition => 'inline; filename="index.aux"');
4669 foreach my $pr (@projects) {
4670 if (!exists $pr->{'owner'}) {
4671 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4674 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4675 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4676 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4677 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4678 $path =~ s/ /\+/g;
4679 $owner =~ s/ /\+/g;
4681 print "$path $owner\n";
4685 sub git_summary {
4686 my $descr = git_get_project_description($project) || "none";
4687 my %co = parse_commit("HEAD");
4688 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4689 my $head = $co{'id'};
4691 my $owner = git_get_project_owner($project);
4693 my $refs = git_get_references();
4694 # These get_*_list functions return one more to allow us to see if
4695 # there are more ...
4696 my @taglist = git_get_tags_list(16);
4697 my @headlist = git_get_heads_list(16);
4698 my @forklist;
4699 my $check_forks = gitweb_check_feature('forks');
4701 if ($check_forks) {
4702 @forklist = git_get_projects_list($project);
4705 git_header_html();
4706 git_print_page_nav('summary','', $head);
4708 print "<div class=\"title\">&nbsp;</div>\n";
4709 print "<table class=\"projects_list\">\n" .
4710 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4711 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4712 if (defined $cd{'rfc2822'}) {
4713 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4716 # use per project git URL list in $projectroot/$project/cloneurl
4717 # or make project git URL from git base URL and project name
4718 my $url_tag = "URL";
4719 my @url_list = git_get_project_url_list($project);
4720 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4721 foreach my $git_url (@url_list) {
4722 next unless $git_url;
4723 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4724 $url_tag = "";
4727 # Tag cloud
4728 my $show_ctags = gitweb_check_feature('ctags');
4729 if ($show_ctags) {
4730 my $ctags = git_get_project_ctags($project);
4731 my $cloud = git_populate_project_tagcloud($ctags);
4732 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4733 print "</td>\n<td>" unless %$ctags;
4734 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4735 print "</td>\n<td>" if %$ctags;
4736 print git_show_project_tagcloud($cloud, 48);
4737 print "</td></tr>";
4740 print "</table>\n";
4742 # If XSS prevention is on, we don't include README.html.
4743 # TODO: Allow a readme in some safe format.
4744 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4745 print "<div class=\"title\">readme</div>\n" .
4746 "<div class=\"readme\">\n";
4747 insert_file("$projectroot/$project/README.html");
4748 print "\n</div>\n"; # class="readme"
4751 # we need to request one more than 16 (0..15) to check if
4752 # those 16 are all
4753 my @commitlist = $head ? parse_commits($head, 17) : ();
4754 if (@commitlist) {
4755 git_print_header_div('shortlog');
4756 git_shortlog_body(\@commitlist, 0, 15, $refs,
4757 $#commitlist <= 15 ? undef :
4758 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4761 if (@taglist) {
4762 git_print_header_div('tags');
4763 git_tags_body(\@taglist, 0, 15,
4764 $#taglist <= 15 ? undef :
4765 $cgi->a({-href => href(action=>"tags")}, "..."));
4768 if (@headlist) {
4769 git_print_header_div('heads');
4770 git_heads_body(\@headlist, $head, 0, 15,
4771 $#headlist <= 15 ? undef :
4772 $cgi->a({-href => href(action=>"heads")}, "..."));
4775 if (@forklist) {
4776 git_print_header_div('forks');
4777 git_project_list_body(\@forklist, 'age', 0, 15,
4778 $#forklist <= 15 ? undef :
4779 $cgi->a({-href => href(action=>"forks")}, "..."),
4780 'no_header');
4783 git_footer_html();
4786 sub git_tag {
4787 my $head = git_get_head_hash($project);
4788 git_header_html();
4789 git_print_page_nav('','', $head,undef,$head);
4790 my %tag = parse_tag($hash);
4792 if (! %tag) {
4793 die_error(404, "Unknown tag object");
4796 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4797 print "<div class=\"title_text\">\n" .
4798 "<table class=\"object_header\">\n" .
4799 "<tr>\n" .
4800 "<td>object</td>\n" .
4801 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4802 $tag{'object'}) . "</td>\n" .
4803 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4804 $tag{'type'}) . "</td>\n" .
4805 "</tr>\n";
4806 if (defined($tag{'author'})) {
4807 git_print_authorship_rows(\%tag, 'author');
4809 print "</table>\n\n" .
4810 "</div>\n";
4811 print "<div class=\"page_body\">";
4812 my $comment = $tag{'comment'};
4813 foreach my $line (@$comment) {
4814 chomp $line;
4815 print esc_html($line, -nbsp=>1) . "<br/>\n";
4817 print "</div>\n";
4818 git_footer_html();
4821 sub git_blame_common {
4822 my $format = shift || 'porcelain';
4823 if ($format eq 'porcelain' && $cgi->param('js')) {
4824 $format = 'incremental';
4825 $action = 'blame_incremental'; # for page title etc
4828 # permissions
4829 gitweb_check_feature('blame')
4830 or die_error(403, "Blame view not allowed");
4832 # error checking
4833 die_error(400, "No file name given") unless $file_name;
4834 $hash_base ||= git_get_head_hash($project);
4835 die_error(404, "Couldn't find base commit") unless $hash_base;
4836 my %co = parse_commit($hash_base)
4837 or die_error(404, "Commit not found");
4838 my $ftype = "blob";
4839 if (!defined $hash) {
4840 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4841 or die_error(404, "Error looking up file");
4842 } else {
4843 $ftype = git_get_type($hash);
4844 if ($ftype !~ "blob") {
4845 die_error(400, "Object is not a blob");
4849 my $fd;
4850 if ($format eq 'incremental') {
4851 # get file contents (as base)
4852 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
4853 or die_error(500, "Open git-cat-file failed");
4854 } elsif ($format eq 'data') {
4855 # run git-blame --incremental
4856 open $fd, "-|", git_cmd(), "blame", "--incremental",
4857 $hash_base, "--", $file_name
4858 or die_error(500, "Open git-blame --incremental failed");
4859 } else {
4860 # run git-blame --porcelain
4861 open $fd, "-|", git_cmd(), "blame", '-p',
4862 $hash_base, '--', $file_name
4863 or die_error(500, "Open git-blame --porcelain failed");
4866 # incremental blame data returns early
4867 if ($format eq 'data') {
4868 print $cgi->header(
4869 -type=>"text/plain", -charset => "utf-8",
4870 -status=> "200 OK");
4871 local $| = 1; # output autoflush
4872 print while <$fd>;
4873 close $fd
4874 or print "ERROR $!\n";
4876 print 'END';
4877 if (defined $t0 && gitweb_check_feature('timed')) {
4878 print ' '.
4879 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).
4880 ' '.$number_of_git_cmds;
4882 print "\n";
4884 return;
4887 # page header
4888 git_header_html();
4889 my $formats_nav =
4890 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4891 "blob") .
4892 " | " .
4893 $cgi->a({-href => href(action=>"history", -replay=>1)},
4894 "history") .
4895 " | " .
4896 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
4897 "HEAD");
4898 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4899 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4900 git_print_page_path($file_name, $ftype, $hash_base);
4902 # page body
4903 if ($format eq 'incremental') {
4904 print "<noscript>\n<div class=\"error\"><center><b>\n".
4905 "This page requires JavaScript to run.\n Use ".
4906 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
4907 'this page').
4908 " instead.\n".
4909 "</b></center></div>\n</noscript>\n";
4911 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
4914 print qq!<div class="page_body">\n!;
4915 print qq!<div id="progress_info">... / ...</div>\n!
4916 if ($format eq 'incremental');
4917 print qq!<table id="blame_table" class="blame" width="100%">\n!.
4918 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
4919 qq!<thead>\n!.
4920 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
4921 qq!</thead>\n!.
4922 qq!<tbody>\n!;
4924 my @rev_color = qw(light dark);
4925 my $num_colors = scalar(@rev_color);
4926 my $current_color = 0;
4928 if ($format eq 'incremental') {
4929 my $color_class = $rev_color[$current_color];
4931 #contents of a file
4932 my $linenr = 0;
4933 LINE:
4934 while (my $line = <$fd>) {
4935 chomp $line;
4936 $linenr++;
4938 print qq!<tr id="l$linenr" class="$color_class">!.
4939 qq!<td class="sha1"><a href=""> </a></td>!.
4940 qq!<td class="linenr">!.
4941 qq!<a class="linenr" href="">$linenr</a></td>!;
4942 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
4943 print qq!</tr>\n!;
4946 } else { # porcelain, i.e. ordinary blame
4947 my %metainfo = (); # saves information about commits
4949 # blame data
4950 LINE:
4951 while (my $line = <$fd>) {
4952 chomp $line;
4953 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4954 # no <lines in group> for subsequent lines in group of lines
4955 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4956 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
4957 if (!exists $metainfo{$full_rev}) {
4958 $metainfo{$full_rev} = { 'nprevious' => 0 };
4960 my $meta = $metainfo{$full_rev};
4961 my $data;
4962 while ($data = <$fd>) {
4963 chomp $data;
4964 last if ($data =~ s/^\t//); # contents of line
4965 if ($data =~ /^(\S+)(?: (.*))?$/) {
4966 $meta->{$1} = $2 unless exists $meta->{$1};
4968 if ($data =~ /^previous /) {
4969 $meta->{'nprevious'}++;
4972 my $short_rev = substr($full_rev, 0, 8);
4973 my $author = $meta->{'author'};
4974 my %date =
4975 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
4976 my $date = $date{'iso-tz'};
4977 if ($group_size) {
4978 $current_color = ($current_color + 1) % $num_colors;
4980 my $tr_class = $rev_color[$current_color];
4981 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
4982 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
4983 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
4984 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
4985 if ($group_size) {
4986 print "<td class=\"sha1\"";
4987 print " title=\"". esc_html($author) . ", $date\"";
4988 print " rowspan=\"$group_size\"" if ($group_size > 1);
4989 print ">";
4990 print $cgi->a({-href => href(action=>"commit",
4991 hash=>$full_rev,
4992 file_name=>$file_name)},
4993 esc_html($short_rev));
4994 if ($group_size >= 2) {
4995 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
4996 if (@author_initials) {
4997 print "<br />" .
4998 esc_html(join('', @author_initials));
4999 # or join('.', ...)
5002 print "</td>\n";
5004 # 'previous' <sha1 of parent commit> <filename at commit>
5005 if (exists $meta->{'previous'} &&
5006 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5007 $meta->{'parent'} = $1;
5008 $meta->{'file_parent'} = unquote($2);
5010 my $linenr_commit =
5011 exists($meta->{'parent'}) ?
5012 $meta->{'parent'} : $full_rev;
5013 my $linenr_filename =
5014 exists($meta->{'file_parent'}) ?
5015 $meta->{'file_parent'} : unquote($meta->{'filename'});
5016 my $blamed = href(action => 'blame',
5017 file_name => $linenr_filename,
5018 hash_base => $linenr_commit);
5019 print "<td class=\"linenr\">";
5020 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5021 -class => "linenr" },
5022 esc_html($lineno));
5023 print "</td>";
5024 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5025 print "</tr>\n";
5026 } # end while
5030 # footer
5031 print "</tbody>\n".
5032 "</table>\n"; # class="blame"
5033 print "</div>\n"; # class="blame_body"
5034 close $fd
5035 or print "Reading blob failed\n";
5037 git_footer_html();
5040 sub git_blame {
5041 git_blame_common();
5044 sub git_blame_incremental {
5045 git_blame_common('incremental');
5048 sub git_blame_data {
5049 git_blame_common('data');
5052 sub git_tags {
5053 my $head = git_get_head_hash($project);
5054 git_header_html();
5055 git_print_page_nav('','', $head,undef,$head);
5056 git_print_header_div('summary', $project);
5058 my @tagslist = git_get_tags_list();
5059 if (@tagslist) {
5060 git_tags_body(\@tagslist);
5062 git_footer_html();
5065 sub git_heads {
5066 my $head = git_get_head_hash($project);
5067 git_header_html();
5068 git_print_page_nav('','', $head,undef,$head);
5069 git_print_header_div('summary', $project);
5071 my @headslist = git_get_heads_list();
5072 if (@headslist) {
5073 git_heads_body(\@headslist, $head);
5075 git_footer_html();
5078 sub git_blob_plain {
5079 my $type = shift;
5080 my $expires;
5082 if (!defined $hash) {
5083 if (defined $file_name) {
5084 my $base = $hash_base || git_get_head_hash($project);
5085 $hash = git_get_hash_by_path($base, $file_name, "blob")
5086 or die_error(404, "Cannot find file");
5087 } else {
5088 die_error(400, "No file name defined");
5090 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5091 # blobs defined by non-textual hash id's can be cached
5092 $expires = "+1d";
5095 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5096 or die_error(500, "Open git-cat-file blob '$hash' failed");
5098 # content-type (can include charset)
5099 $type = blob_contenttype($fd, $file_name, $type);
5101 # "save as" filename, even when no $file_name is given
5102 my $save_as = "$hash";
5103 if (defined $file_name) {
5104 $save_as = $file_name;
5105 } elsif ($type =~ m/^text\//) {
5106 $save_as .= '.txt';
5109 # With XSS prevention on, blobs of all types except a few known safe
5110 # ones are served with "Content-Disposition: attachment" to make sure
5111 # they don't run in our security domain. For certain image types,
5112 # blob view writes an <img> tag referring to blob_plain view, and we
5113 # want to be sure not to break that by serving the image as an
5114 # attachment (though Firefox 3 doesn't seem to care).
5115 my $sandbox = $prevent_xss &&
5116 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5118 print $cgi->header(
5119 -type => $type,
5120 -expires => $expires,
5121 -content_disposition =>
5122 ($sandbox ? 'attachment' : 'inline')
5123 . '; filename="' . $save_as . '"');
5124 local $/ = undef;
5125 binmode STDOUT, ':raw';
5126 print <$fd>;
5127 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5128 close $fd;
5131 sub git_blob {
5132 my $expires;
5134 if (!defined $hash) {
5135 if (defined $file_name) {
5136 my $base = $hash_base || git_get_head_hash($project);
5137 $hash = git_get_hash_by_path($base, $file_name, "blob")
5138 or die_error(404, "Cannot find file");
5139 } else {
5140 die_error(400, "No file name defined");
5142 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5143 # blobs defined by non-textual hash id's can be cached
5144 $expires = "+1d";
5147 my $have_blame = gitweb_check_feature('blame');
5148 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5149 or die_error(500, "Couldn't cat $file_name, $hash");
5150 my $mimetype = blob_mimetype($fd, $file_name);
5151 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5152 close $fd;
5153 return git_blob_plain($mimetype);
5155 # we can have blame only for text/* mimetype
5156 $have_blame &&= ($mimetype =~ m!^text/!);
5158 git_header_html(undef, $expires);
5159 my $formats_nav = '';
5160 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5161 if (defined $file_name) {
5162 if ($have_blame) {
5163 $formats_nav .=
5164 $cgi->a({-href => href(action=>"blame", -replay=>1)},
5165 "blame") .
5166 " | ";
5168 $formats_nav .=
5169 $cgi->a({-href => href(action=>"history", -replay=>1)},
5170 "history") .
5171 " | " .
5172 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5173 "raw") .
5174 " | " .
5175 $cgi->a({-href => href(action=>"blob",
5176 hash_base=>"HEAD", file_name=>$file_name)},
5177 "HEAD");
5178 } else {
5179 $formats_nav .=
5180 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5181 "raw");
5183 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5184 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5185 } else {
5186 print "<div class=\"page_nav\">\n" .
5187 "<br/><br/></div>\n" .
5188 "<div class=\"title\">$hash</div>\n";
5190 git_print_page_path($file_name, "blob", $hash_base);
5191 print "<div class=\"page_body\">\n";
5192 if ($mimetype =~ m!^image/!) {
5193 print qq!<img type="$mimetype"!;
5194 if ($file_name) {
5195 print qq! alt="$file_name" title="$file_name"!;
5197 print qq! src="! .
5198 href(action=>"blob_plain", hash=>$hash,
5199 hash_base=>$hash_base, file_name=>$file_name) .
5200 qq!" />\n!;
5201 } else {
5202 my $nr;
5203 while (my $line = <$fd>) {
5204 chomp $line;
5205 $nr++;
5206 $line = untabify($line);
5207 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5208 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5211 close $fd
5212 or print "Reading blob failed.\n";
5213 print "</div>";
5214 git_footer_html();
5217 sub git_tree {
5218 if (!defined $hash_base) {
5219 $hash_base = "HEAD";
5221 if (!defined $hash) {
5222 if (defined $file_name) {
5223 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5224 } else {
5225 $hash = $hash_base;
5228 die_error(404, "No such tree") unless defined($hash);
5230 my @entries = ();
5232 local $/ = "\0";
5233 open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
5234 or die_error(500, "Open git-ls-tree failed");
5235 @entries = map { chomp; $_ } <$fd>;
5236 close $fd
5237 or die_error(404, "Reading tree failed");
5240 my $refs = git_get_references();
5241 my $ref = format_ref_marker($refs, $hash_base);
5242 git_header_html();
5243 my $basedir = '';
5244 my $have_blame = gitweb_check_feature('blame');
5245 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5246 my @views_nav = ();
5247 if (defined $file_name) {
5248 push @views_nav,
5249 $cgi->a({-href => href(action=>"history", -replay=>1)},
5250 "history"),
5251 $cgi->a({-href => href(action=>"tree",
5252 hash_base=>"HEAD", file_name=>$file_name)},
5253 "HEAD"),
5255 my $snapshot_links = format_snapshot_links($hash);
5256 if (defined $snapshot_links) {
5257 # FIXME: Should be available when we have no hash base as well.
5258 push @views_nav, $snapshot_links;
5260 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
5261 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5262 } else {
5263 undef $hash_base;
5264 print "<div class=\"page_nav\">\n";
5265 print "<br/><br/></div>\n";
5266 print "<div class=\"title\">$hash</div>\n";
5268 if (defined $file_name) {
5269 $basedir = $file_name;
5270 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5271 $basedir .= '/';
5273 git_print_page_path($file_name, 'tree', $hash_base);
5275 print "<div class=\"page_body\">\n";
5276 print "<table class=\"tree\">\n";
5277 my $alternate = 1;
5278 # '..' (top directory) link if possible
5279 if (defined $hash_base &&
5280 defined $file_name && $file_name =~ m![^/]+$!) {
5281 if ($alternate) {
5282 print "<tr class=\"dark\">\n";
5283 } else {
5284 print "<tr class=\"light\">\n";
5286 $alternate ^= 1;
5288 my $up = $file_name;
5289 $up =~ s!/?[^/]+$!!;
5290 undef $up unless $up;
5291 # based on git_print_tree_entry
5292 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5293 print '<td class="list">';
5294 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
5295 file_name=>$up)},
5296 "..");
5297 print "</td>\n";
5298 print "<td class=\"link\"></td>\n";
5300 print "</tr>\n";
5302 foreach my $line (@entries) {
5303 my %t = parse_ls_tree_line($line, -z => 1);
5305 if ($alternate) {
5306 print "<tr class=\"dark\">\n";
5307 } else {
5308 print "<tr class=\"light\">\n";
5310 $alternate ^= 1;
5312 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5314 print "</tr>\n";
5316 print "</table>\n" .
5317 "</div>";
5318 git_footer_html();
5321 sub git_snapshot {
5322 my $format = $input_params{'snapshot_format'};
5323 if (!@snapshot_fmts) {
5324 die_error(403, "Snapshots not allowed");
5326 # default to first supported snapshot format
5327 $format ||= $snapshot_fmts[0];
5328 if ($format !~ m/^[a-z0-9]+$/) {
5329 die_error(400, "Invalid snapshot format parameter");
5330 } elsif (!exists($known_snapshot_formats{$format})) {
5331 die_error(400, "Unknown snapshot format");
5332 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5333 die_error(403, "Snapshot format not allowed");
5334 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5335 die_error(403, "Unsupported snapshot format");
5338 if (!defined $hash) {
5339 $hash = git_get_head_hash($project);
5342 my $name = $project;
5343 $name =~ s,([^/])/*\.git$,$1,;
5344 $name = basename($name);
5345 my $filename = to_utf8($name);
5346 $name =~ s/\047/\047\\\047\047/g;
5347 my $cmd;
5348 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5349 $cmd = quote_command(
5350 git_cmd(), 'archive',
5351 "--format=$known_snapshot_formats{$format}{'format'}",
5352 "--prefix=$name/", $hash);
5353 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5354 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5357 print $cgi->header(
5358 -type => $known_snapshot_formats{$format}{'type'},
5359 -content_disposition => 'inline; filename="' . "$filename" . '"',
5360 -status => '200 OK');
5362 open my $fd, "-|", $cmd
5363 or die_error(500, "Execute git-archive failed");
5364 binmode STDOUT, ':raw';
5365 print <$fd>;
5366 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5367 close $fd;
5370 sub git_log {
5371 my $head = git_get_head_hash($project);
5372 if (!defined $hash) {
5373 $hash = $head;
5375 if (!defined $page) {
5376 $page = 0;
5378 my $refs = git_get_references();
5380 my @commitlist = parse_commits($hash, 101, (100 * $page));
5382 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
5384 my ($patch_max) = gitweb_get_feature('patches');
5385 if ($patch_max) {
5386 if ($patch_max < 0 || @commitlist <= $patch_max) {
5387 $paging_nav .= " &sdot; " .
5388 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5389 "patches");
5393 git_header_html();
5394 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5396 if (!@commitlist) {
5397 my %co = parse_commit($hash);
5399 git_print_header_div('summary', $project);
5400 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5402 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5403 for (my $i = 0; $i <= $to; $i++) {
5404 my %co = %{$commitlist[$i]};
5405 next if !%co;
5406 my $commit = $co{'id'};
5407 my $ref = format_ref_marker($refs, $commit);
5408 my %ad = parse_date($co{'author_epoch'});
5409 git_print_header_div('commit',
5410 "<span class=\"age\">$co{'age_string'}</span>" .
5411 esc_html($co{'title'}) . $ref,
5412 $commit);
5413 print "<div class=\"title_text\">\n" .
5414 "<div class=\"log_link\">\n" .
5415 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5416 " | " .
5417 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5418 " | " .
5419 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5420 "<br/>\n" .
5421 "</div>\n";
5422 git_print_authorship(\%co, -tag => 'span');
5423 print "<br/>\n</div>\n";
5425 print "<div class=\"log_body\">\n";
5426 git_print_log($co{'comment'}, -final_empty_line=> 1);
5427 print "</div>\n";
5429 if ($#commitlist >= 100) {
5430 print "<div class=\"page_nav\">\n";
5431 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5432 -accesskey => "n", -title => "Alt-n"}, "next");
5433 print "</div>\n";
5435 git_footer_html();
5438 sub git_commit {
5439 $hash ||= $hash_base || "HEAD";
5440 my %co = parse_commit($hash)
5441 or die_error(404, "Unknown commit object");
5443 my $parent = $co{'parent'};
5444 my $parents = $co{'parents'}; # listref
5446 # we need to prepare $formats_nav before any parameter munging
5447 my $formats_nav;
5448 if (!defined $parent) {
5449 # --root commitdiff
5450 $formats_nav .= '(initial)';
5451 } elsif (@$parents == 1) {
5452 # single parent commit
5453 $formats_nav .=
5454 '(parent: ' .
5455 $cgi->a({-href => href(action=>"commit",
5456 hash=>$parent)},
5457 esc_html(substr($parent, 0, 7))) .
5458 ')';
5459 } else {
5460 # merge commit
5461 $formats_nav .=
5462 '(merge: ' .
5463 join(' ', map {
5464 $cgi->a({-href => href(action=>"commit",
5465 hash=>$_)},
5466 esc_html(substr($_, 0, 7)));
5467 } @$parents ) .
5468 ')';
5470 if (gitweb_check_feature('patches')) {
5471 $formats_nav .= " | " .
5472 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5473 "patch");
5476 if (!defined $parent) {
5477 $parent = "--root";
5479 my @difftree;
5480 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5481 @diff_opts,
5482 (@$parents <= 1 ? $parent : '-c'),
5483 $hash, "--"
5484 or die_error(500, "Open git-diff-tree failed");
5485 @difftree = map { chomp; $_ } <$fd>;
5486 close $fd or die_error(404, "Reading git-diff-tree failed");
5488 # non-textual hash id's can be cached
5489 my $expires;
5490 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5491 $expires = "+1d";
5493 my $refs = git_get_references();
5494 my $ref = format_ref_marker($refs, $co{'id'});
5496 git_header_html(undef, $expires);
5497 git_print_page_nav('commit', '',
5498 $hash, $co{'tree'}, $hash,
5499 $formats_nav);
5501 if (defined $co{'parent'}) {
5502 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5503 } else {
5504 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5506 print "<div class=\"title_text\">\n" .
5507 "<table class=\"object_header\">\n";
5508 git_print_authorship_rows(\%co);
5509 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5510 print "<tr>" .
5511 "<td>tree</td>" .
5512 "<td class=\"sha1\">" .
5513 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5514 class => "list"}, $co{'tree'}) .
5515 "</td>" .
5516 "<td class=\"link\">" .
5517 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5518 "tree");
5519 my $snapshot_links = format_snapshot_links($hash);
5520 if (defined $snapshot_links) {
5521 print " | " . $snapshot_links;
5523 print "</td>" .
5524 "</tr>\n";
5526 foreach my $par (@$parents) {
5527 print "<tr>" .
5528 "<td>parent</td>" .
5529 "<td class=\"sha1\">" .
5530 $cgi->a({-href => href(action=>"commit", hash=>$par),
5531 class => "list"}, $par) .
5532 "</td>" .
5533 "<td class=\"link\">" .
5534 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5535 " | " .
5536 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5537 "</td>" .
5538 "</tr>\n";
5540 print "</table>".
5541 "</div>\n";
5543 print "<div class=\"page_body\">\n";
5544 git_print_log($co{'comment'});
5545 print "</div>\n";
5547 git_difftree_body(\@difftree, $hash, @$parents);
5549 git_footer_html();
5552 sub git_object {
5553 # object is defined by:
5554 # - hash or hash_base alone
5555 # - hash_base and file_name
5556 my $type;
5558 # - hash or hash_base alone
5559 if ($hash || ($hash_base && !defined $file_name)) {
5560 my $object_id = $hash || $hash_base;
5562 open my $fd, "-|", quote_command(
5563 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5564 or die_error(404, "Object does not exist");
5565 $type = <$fd>;
5566 chomp $type;
5567 close $fd
5568 or die_error(404, "Object does not exist");
5570 # - hash_base and file_name
5571 } elsif ($hash_base && defined $file_name) {
5572 $file_name =~ s,/+$,,;
5574 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5575 or die_error(404, "Base object does not exist");
5577 # here errors should not hapen
5578 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5579 or die_error(500, "Open git-ls-tree failed");
5580 my $line = <$fd>;
5581 close $fd;
5583 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5584 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5585 die_error(404, "File or directory for given base does not exist");
5587 $type = $2;
5588 $hash = $3;
5589 } else {
5590 die_error(400, "Not enough information to find object");
5593 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5594 hash=>$hash, hash_base=>$hash_base,
5595 file_name=>$file_name),
5596 -status => '302 Found');
5599 sub git_blobdiff {
5600 my $format = shift || 'html';
5602 my $fd;
5603 my @difftree;
5604 my %diffinfo;
5605 my $expires;
5607 # preparing $fd and %diffinfo for git_patchset_body
5608 # new style URI
5609 if (defined $hash_base && defined $hash_parent_base) {
5610 if (defined $file_name) {
5611 # read raw output
5612 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5613 $hash_parent_base, $hash_base,
5614 "--", (defined $file_parent ? $file_parent : ()), $file_name
5615 or die_error(500, "Open git-diff-tree failed");
5616 @difftree = map { chomp; $_ } <$fd>;
5617 close $fd
5618 or die_error(404, "Reading git-diff-tree failed");
5619 @difftree
5620 or die_error(404, "Blob diff not found");
5622 } elsif (defined $hash &&
5623 $hash =~ /[0-9a-fA-F]{40}/) {
5624 # try to find filename from $hash
5626 # read filtered raw output
5627 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5628 $hash_parent_base, $hash_base, "--"
5629 or die_error(500, "Open git-diff-tree failed");
5630 @difftree =
5631 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5632 # $hash == to_id
5633 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5634 map { chomp; $_ } <$fd>;
5635 close $fd
5636 or die_error(404, "Reading git-diff-tree failed");
5637 @difftree
5638 or die_error(404, "Blob diff not found");
5640 } else {
5641 die_error(400, "Missing one of the blob diff parameters");
5644 if (@difftree > 1) {
5645 die_error(400, "Ambiguous blob diff specification");
5648 %diffinfo = parse_difftree_raw_line($difftree[0]);
5649 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5650 $file_name ||= $diffinfo{'to_file'};
5652 $hash_parent ||= $diffinfo{'from_id'};
5653 $hash ||= $diffinfo{'to_id'};
5655 # non-textual hash id's can be cached
5656 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5657 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5658 $expires = '+1d';
5661 # open patch output
5662 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5663 '-p', ($format eq 'html' ? "--full-index" : ()),
5664 $hash_parent_base, $hash_base,
5665 "--", (defined $file_parent ? $file_parent : ()), $file_name
5666 or die_error(500, "Open git-diff-tree failed");
5669 # old/legacy style URI -- not generated anymore since 1.4.3.
5670 if (!%diffinfo) {
5671 die_error('404 Not Found', "Missing one of the blob diff parameters")
5674 # header
5675 if ($format eq 'html') {
5676 my $formats_nav =
5677 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5678 "raw");
5679 git_header_html(undef, $expires);
5680 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5681 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5682 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5683 } else {
5684 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5685 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5687 if (defined $file_name) {
5688 git_print_page_path($file_name, "blob", $hash_base);
5689 } else {
5690 print "<div class=\"page_path\"></div>\n";
5693 } elsif ($format eq 'plain') {
5694 print $cgi->header(
5695 -type => 'text/plain',
5696 -charset => 'utf-8',
5697 -expires => $expires,
5698 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5700 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5702 } else {
5703 die_error(400, "Unknown blobdiff format");
5706 # patch
5707 if ($format eq 'html') {
5708 print "<div class=\"page_body\">\n";
5710 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5711 close $fd;
5713 print "</div>\n"; # class="page_body"
5714 git_footer_html();
5716 } else {
5717 while (my $line = <$fd>) {
5718 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5719 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5721 print $line;
5723 last if $line =~ m!^\+\+\+!;
5725 local $/ = undef;
5726 print <$fd>;
5727 close $fd;
5731 sub git_blobdiff_plain {
5732 git_blobdiff('plain');
5735 sub git_commitdiff {
5736 my %params = @_;
5737 my $format = $params{-format} || 'html';
5739 my ($patch_max) = gitweb_get_feature('patches');
5740 if ($format eq 'patch') {
5741 die_error(403, "Patch view not allowed") unless $patch_max;
5744 $hash ||= $hash_base || "HEAD";
5745 my %co = parse_commit($hash)
5746 or die_error(404, "Unknown commit object");
5748 # choose format for commitdiff for merge
5749 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5750 $hash_parent = '--cc';
5752 # we need to prepare $formats_nav before almost any parameter munging
5753 my $formats_nav;
5754 if ($format eq 'html') {
5755 $formats_nav =
5756 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5757 "raw");
5758 if ($patch_max) {
5759 $formats_nav .= " | " .
5760 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5761 "patch");
5764 if (defined $hash_parent &&
5765 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5766 # commitdiff with two commits given
5767 my $hash_parent_short = $hash_parent;
5768 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5769 $hash_parent_short = substr($hash_parent, 0, 7);
5771 $formats_nav .=
5772 ' (from';
5773 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5774 if ($co{'parents'}[$i] eq $hash_parent) {
5775 $formats_nav .= ' parent ' . ($i+1);
5776 last;
5779 $formats_nav .= ': ' .
5780 $cgi->a({-href => href(action=>"commitdiff",
5781 hash=>$hash_parent)},
5782 esc_html($hash_parent_short)) .
5783 ')';
5784 } elsif (!$co{'parent'}) {
5785 # --root commitdiff
5786 $formats_nav .= ' (initial)';
5787 } elsif (scalar @{$co{'parents'}} == 1) {
5788 # single parent commit
5789 $formats_nav .=
5790 ' (parent: ' .
5791 $cgi->a({-href => href(action=>"commitdiff",
5792 hash=>$co{'parent'})},
5793 esc_html(substr($co{'parent'}, 0, 7))) .
5794 ')';
5795 } else {
5796 # merge commit
5797 if ($hash_parent eq '--cc') {
5798 $formats_nav .= ' | ' .
5799 $cgi->a({-href => href(action=>"commitdiff",
5800 hash=>$hash, hash_parent=>'-c')},
5801 'combined');
5802 } else { # $hash_parent eq '-c'
5803 $formats_nav .= ' | ' .
5804 $cgi->a({-href => href(action=>"commitdiff",
5805 hash=>$hash, hash_parent=>'--cc')},
5806 'compact');
5808 $formats_nav .=
5809 ' (merge: ' .
5810 join(' ', map {
5811 $cgi->a({-href => href(action=>"commitdiff",
5812 hash=>$_)},
5813 esc_html(substr($_, 0, 7)));
5814 } @{$co{'parents'}} ) .
5815 ')';
5819 my $hash_parent_param = $hash_parent;
5820 if (!defined $hash_parent_param) {
5821 # --cc for multiple parents, --root for parentless
5822 $hash_parent_param =
5823 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5826 # read commitdiff
5827 my $fd;
5828 my @difftree;
5829 if ($format eq 'html') {
5830 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5831 "--no-commit-id", "--patch-with-raw", "--full-index",
5832 $hash_parent_param, $hash, "--"
5833 or die_error(500, "Open git-diff-tree failed");
5835 while (my $line = <$fd>) {
5836 chomp $line;
5837 # empty line ends raw part of diff-tree output
5838 last unless $line;
5839 push @difftree, scalar parse_difftree_raw_line($line);
5842 } elsif ($format eq 'plain') {
5843 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5844 '-p', $hash_parent_param, $hash, "--"
5845 or die_error(500, "Open git-diff-tree failed");
5846 } elsif ($format eq 'patch') {
5847 # For commit ranges, we limit the output to the number of
5848 # patches specified in the 'patches' feature.
5849 # For single commits, we limit the output to a single patch,
5850 # diverging from the git-format-patch default.
5851 my @commit_spec = ();
5852 if ($hash_parent) {
5853 if ($patch_max > 0) {
5854 push @commit_spec, "-$patch_max";
5856 push @commit_spec, '-n', "$hash_parent..$hash";
5857 } else {
5858 if ($params{-single}) {
5859 push @commit_spec, '-1';
5860 } else {
5861 if ($patch_max > 0) {
5862 push @commit_spec, "-$patch_max";
5864 push @commit_spec, "-n";
5866 push @commit_spec, '--root', $hash;
5868 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5869 '--stdout', @commit_spec
5870 or die_error(500, "Open git-format-patch failed");
5871 } else {
5872 die_error(400, "Unknown commitdiff format");
5875 # non-textual hash id's can be cached
5876 my $expires;
5877 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5878 $expires = "+1d";
5881 # write commit message
5882 if ($format eq 'html') {
5883 my $refs = git_get_references();
5884 my $ref = format_ref_marker($refs, $co{'id'});
5886 git_header_html(undef, $expires);
5887 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5888 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5889 print "<div class=\"title_text\">\n" .
5890 "<table class=\"object_header\">\n";
5891 git_print_authorship_rows(\%co);
5892 print "</table>".
5893 "</div>\n";
5894 print "<div class=\"page_body\">\n";
5895 if (@{$co{'comment'}} > 1) {
5896 print "<div class=\"log\">\n";
5897 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5898 print "</div>\n"; # class="log"
5901 } elsif ($format eq 'plain') {
5902 my $refs = git_get_references("tags");
5903 my $tagname = git_get_rev_name_tags($hash);
5904 my $filename = basename($project) . "-$hash.patch";
5906 print $cgi->header(
5907 -type => 'text/plain',
5908 -charset => 'utf-8',
5909 -expires => $expires,
5910 -content_disposition => 'inline; filename="' . "$filename" . '"');
5911 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5912 print "From: " . to_utf8($co{'author'}) . "\n";
5913 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5914 print "Subject: " . to_utf8($co{'title'}) . "\n";
5916 print "X-Git-Tag: $tagname\n" if $tagname;
5917 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5919 foreach my $line (@{$co{'comment'}}) {
5920 print to_utf8($line) . "\n";
5922 print "---\n\n";
5923 } elsif ($format eq 'patch') {
5924 my $filename = basename($project) . "-$hash.patch";
5926 print $cgi->header(
5927 -type => 'text/plain',
5928 -charset => 'utf-8',
5929 -expires => $expires,
5930 -content_disposition => 'inline; filename="' . "$filename" . '"');
5933 # write patch
5934 if ($format eq 'html') {
5935 my $use_parents = !defined $hash_parent ||
5936 $hash_parent eq '-c' || $hash_parent eq '--cc';
5937 git_difftree_body(\@difftree, $hash,
5938 $use_parents ? @{$co{'parents'}} : $hash_parent);
5939 print "<br/>\n";
5941 git_patchset_body($fd, \@difftree, $hash,
5942 $use_parents ? @{$co{'parents'}} : $hash_parent);
5943 close $fd;
5944 print "</div>\n"; # class="page_body"
5945 git_footer_html();
5947 } elsif ($format eq 'plain') {
5948 local $/ = undef;
5949 print <$fd>;
5950 close $fd
5951 or print "Reading git-diff-tree failed\n";
5952 } elsif ($format eq 'patch') {
5953 local $/ = undef;
5954 print <$fd>;
5955 close $fd
5956 or print "Reading git-format-patch failed\n";
5960 sub git_commitdiff_plain {
5961 git_commitdiff(-format => 'plain');
5964 # format-patch-style patches
5965 sub git_patch {
5966 git_commitdiff(-format => 'patch', -single=> 1);
5969 sub git_patches {
5970 git_commitdiff(-format => 'patch');
5973 sub git_history {
5974 if (!defined $hash_base) {
5975 $hash_base = git_get_head_hash($project);
5977 if (!defined $page) {
5978 $page = 0;
5980 my $ftype;
5981 my %co = parse_commit($hash_base)
5982 or die_error(404, "Unknown commit object");
5984 my $refs = git_get_references();
5985 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5987 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5988 $file_name, "--full-history")
5989 or die_error(404, "No such file or directory on given branch");
5991 if (!defined $hash && defined $file_name) {
5992 # some commits could have deleted file in question,
5993 # and not have it in tree, but one of them has to have it
5994 for (my $i = 0; $i <= @commitlist; $i++) {
5995 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5996 last if defined $hash;
5999 if (defined $hash) {
6000 $ftype = git_get_type($hash);
6002 if (!defined $ftype) {
6003 die_error(500, "Unknown type of object");
6006 my $paging_nav = '';
6007 if ($page > 0) {
6008 $paging_nav .=
6009 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
6010 file_name=>$file_name)},
6011 "first");
6012 $paging_nav .= " &sdot; " .
6013 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6014 -accesskey => "p", -title => "Alt-p"}, "prev");
6015 } else {
6016 $paging_nav .= "first";
6017 $paging_nav .= " &sdot; prev";
6019 my $next_link = '';
6020 if ($#commitlist >= 100) {
6021 $next_link =
6022 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6023 -accesskey => "n", -title => "Alt-n"}, "next");
6024 $paging_nav .= " &sdot; $next_link";
6025 } else {
6026 $paging_nav .= " &sdot; next";
6029 git_header_html();
6030 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
6031 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6032 git_print_page_path($file_name, $ftype, $hash_base);
6034 git_history_body(\@commitlist, 0, 99,
6035 $refs, $hash_base, $ftype, $next_link);
6037 git_footer_html();
6040 sub git_search {
6041 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6042 if (!defined $searchtext) {
6043 die_error(400, "Text field is empty");
6045 if (!defined $hash) {
6046 $hash = git_get_head_hash($project);
6048 my %co = parse_commit($hash);
6049 if (!%co) {
6050 die_error(404, "Unknown commit object");
6052 if (!defined $page) {
6053 $page = 0;
6056 $searchtype ||= 'commit';
6057 if ($searchtype eq 'pickaxe') {
6058 # pickaxe may take all resources of your box and run for several minutes
6059 # with every query - so decide by yourself how public you make this feature
6060 gitweb_check_feature('pickaxe')
6061 or die_error(403, "Pickaxe is disabled");
6063 if ($searchtype eq 'grep') {
6064 gitweb_check_feature('grep')
6065 or die_error(403, "Grep is disabled");
6068 git_header_html();
6070 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6071 my $greptype;
6072 if ($searchtype eq 'commit') {
6073 $greptype = "--grep=";
6074 } elsif ($searchtype eq 'author') {
6075 $greptype = "--author=";
6076 } elsif ($searchtype eq 'committer') {
6077 $greptype = "--committer=";
6079 $greptype .= $searchtext;
6080 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6081 $greptype, '--regexp-ignore-case',
6082 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6084 my $paging_nav = '';
6085 if ($page > 0) {
6086 $paging_nav .=
6087 $cgi->a({-href => href(action=>"search", hash=>$hash,
6088 searchtext=>$searchtext,
6089 searchtype=>$searchtype)},
6090 "first");
6091 $paging_nav .= " &sdot; " .
6092 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6093 -accesskey => "p", -title => "Alt-p"}, "prev");
6094 } else {
6095 $paging_nav .= "first";
6096 $paging_nav .= " &sdot; prev";
6098 my $next_link = '';
6099 if ($#commitlist >= 100) {
6100 $next_link =
6101 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6102 -accesskey => "n", -title => "Alt-n"}, "next");
6103 $paging_nav .= " &sdot; $next_link";
6104 } else {
6105 $paging_nav .= " &sdot; next";
6108 if ($#commitlist >= 100) {
6111 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6112 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6113 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6116 if ($searchtype eq 'pickaxe') {
6117 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6118 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6120 print "<table class=\"pickaxe search\">\n";
6121 my $alternate = 1;
6122 local $/ = "\n";
6123 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6124 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6125 ($search_use_regexp ? '--pickaxe-regex' : ());
6126 undef %co;
6127 my @files;
6128 while (my $line = <$fd>) {
6129 chomp $line;
6130 next unless $line;
6132 my %set = parse_difftree_raw_line($line);
6133 if (defined $set{'commit'}) {
6134 # finish previous commit
6135 if (%co) {
6136 print "</td>\n" .
6137 "<td class=\"link\">" .
6138 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6139 " | " .
6140 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6141 print "</td>\n" .
6142 "</tr>\n";
6145 if ($alternate) {
6146 print "<tr class=\"dark\">\n";
6147 } else {
6148 print "<tr class=\"light\">\n";
6150 $alternate ^= 1;
6151 %co = parse_commit($set{'commit'});
6152 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6153 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6154 "<td><i>$author</i></td>\n" .
6155 "<td>" .
6156 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6157 -class => "list subject"},
6158 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6159 } elsif (defined $set{'to_id'}) {
6160 next if ($set{'to_id'} =~ m/^0{40}$/);
6162 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6163 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6164 -class => "list"},
6165 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6166 "<br/>\n";
6169 close $fd;
6171 # finish last commit (warning: repetition!)
6172 if (%co) {
6173 print "</td>\n" .
6174 "<td class=\"link\">" .
6175 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6176 " | " .
6177 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6178 print "</td>\n" .
6179 "</tr>\n";
6182 print "</table>\n";
6185 if ($searchtype eq 'grep') {
6186 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6187 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6189 print "<table class=\"grep_search\">\n";
6190 my $alternate = 1;
6191 my $matches = 0;
6192 local $/ = "\n";
6193 open my $fd, "-|", git_cmd(), 'grep', '-n',
6194 $search_use_regexp ? ('-E', '-i') : '-F',
6195 $searchtext, $co{'tree'};
6196 my $lastfile = '';
6197 while (my $line = <$fd>) {
6198 chomp $line;
6199 my ($file, $lno, $ltext, $binary);
6200 last if ($matches++ > 1000);
6201 if ($line =~ /^Binary file (.+) matches$/) {
6202 $file = $1;
6203 $binary = 1;
6204 } else {
6205 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6207 if ($file ne $lastfile) {
6208 $lastfile and print "</td></tr>\n";
6209 if ($alternate++) {
6210 print "<tr class=\"dark\">\n";
6211 } else {
6212 print "<tr class=\"light\">\n";
6214 print "<td class=\"list\">".
6215 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6216 file_name=>"$file"),
6217 -class => "list"}, esc_path($file));
6218 print "</td><td>\n";
6219 $lastfile = $file;
6221 if ($binary) {
6222 print "<div class=\"binary\">Binary file</div>\n";
6223 } else {
6224 $ltext = untabify($ltext);
6225 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6226 $ltext = esc_html($1, -nbsp=>1);
6227 $ltext .= '<span class="match">';
6228 $ltext .= esc_html($2, -nbsp=>1);
6229 $ltext .= '</span>';
6230 $ltext .= esc_html($3, -nbsp=>1);
6231 } else {
6232 $ltext = esc_html($ltext, -nbsp=>1);
6234 print "<div class=\"pre\">" .
6235 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6236 file_name=>"$file").'#l'.$lno,
6237 -class => "linenr"}, sprintf('%4i', $lno))
6238 . ' ' . $ltext . "</div>\n";
6241 if ($lastfile) {
6242 print "</td></tr>\n";
6243 if ($matches > 1000) {
6244 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6246 } else {
6247 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6249 close $fd;
6251 print "</table>\n";
6253 git_footer_html();
6256 sub git_search_help {
6257 git_header_html();
6258 git_print_page_nav('','', $hash,$hash,$hash);
6259 print <<EOT;
6260 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6261 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6262 the pattern entered is recognized as the POSIX extended
6263 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6264 insensitive).</p>
6265 <dl>
6266 <dt><b>commit</b></dt>
6267 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6269 my $have_grep = gitweb_check_feature('grep');
6270 if ($have_grep) {
6271 print <<EOT;
6272 <dt><b>grep</b></dt>
6273 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6274 a different one) are searched for the given pattern. On large trees, this search can take
6275 a while and put some strain on the server, so please use it with some consideration. Note that
6276 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6277 case-sensitive.</dd>
6280 print <<EOT;
6281 <dt><b>author</b></dt>
6282 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6283 <dt><b>committer</b></dt>
6284 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6286 my $have_pickaxe = gitweb_check_feature('pickaxe');
6287 if ($have_pickaxe) {
6288 print <<EOT;
6289 <dt><b>pickaxe</b></dt>
6290 <dd>All commits that caused the string to appear or disappear from any file (changes that
6291 added, removed or "modified" the string) will be listed. This search can take a while and
6292 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6293 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6296 print "</dl>\n";
6297 git_footer_html();
6300 sub git_shortlog {
6301 my $head = git_get_head_hash($project);
6302 if (!defined $hash) {
6303 $hash = $head;
6305 if (!defined $page) {
6306 $page = 0;
6308 my $refs = git_get_references();
6310 my $commit_hash = $hash;
6311 if (defined $hash_parent) {
6312 $commit_hash = "$hash_parent..$hash";
6314 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6316 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6317 my $next_link = '';
6318 if ($#commitlist >= 100) {
6319 $next_link =
6320 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6321 -accesskey => "n", -title => "Alt-n"}, "next");
6323 my $patch_max = gitweb_check_feature('patches');
6324 if ($patch_max) {
6325 if ($patch_max < 0 || @commitlist <= $patch_max) {
6326 $paging_nav .= " &sdot; " .
6327 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6328 "patches");
6332 git_header_html();
6333 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6334 git_print_header_div('summary', $project);
6336 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6338 git_footer_html();
6341 ## ......................................................................
6342 ## feeds (RSS, Atom; OPML)
6344 sub git_feed {
6345 my $format = shift || 'atom';
6346 my $have_blame = gitweb_check_feature('blame');
6348 # Atom: http://www.atomenabled.org/developers/syndication/
6349 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6350 if ($format ne 'rss' && $format ne 'atom') {
6351 die_error(400, "Unknown web feed format");
6354 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6355 my $head = $hash || 'HEAD';
6356 my @commitlist = parse_commits($head, 150, 0, $file_name);
6358 my %latest_commit;
6359 my %latest_date;
6360 my $content_type = "application/$format+xml";
6361 if (defined $cgi->http('HTTP_ACCEPT') &&
6362 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6363 # browser (feed reader) prefers text/xml
6364 $content_type = 'text/xml';
6366 if (defined($commitlist[0])) {
6367 %latest_commit = %{$commitlist[0]};
6368 my $latest_epoch = $latest_commit{'committer_epoch'};
6369 %latest_date = parse_date($latest_epoch);
6370 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6371 if (defined $if_modified) {
6372 my $since;
6373 if (eval { require HTTP::Date; 1; }) {
6374 $since = HTTP::Date::str2time($if_modified);
6375 } elsif (eval { require Time::ParseDate; 1; }) {
6376 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6378 if (defined $since && $latest_epoch <= $since) {
6379 print $cgi->header(
6380 -type => $content_type,
6381 -charset => 'utf-8',
6382 -last_modified => $latest_date{'rfc2822'},
6383 -status => '304 Not Modified');
6384 return;
6387 print $cgi->header(
6388 -type => $content_type,
6389 -charset => 'utf-8',
6390 -last_modified => $latest_date{'rfc2822'});
6391 } else {
6392 print $cgi->header(
6393 -type => $content_type,
6394 -charset => 'utf-8');
6397 # Optimization: skip generating the body if client asks only
6398 # for Last-Modified date.
6399 return if ($cgi->request_method() eq 'HEAD');
6401 # header variables
6402 my $title = "$site_name - $project/$action";
6403 my $feed_type = 'log';
6404 if (defined $hash) {
6405 $title .= " - '$hash'";
6406 $feed_type = 'branch log';
6407 if (defined $file_name) {
6408 $title .= " :: $file_name";
6409 $feed_type = 'history';
6411 } elsif (defined $file_name) {
6412 $title .= " - $file_name";
6413 $feed_type = 'history';
6415 $title .= " $feed_type";
6416 my $descr = git_get_project_description($project);
6417 if (defined $descr) {
6418 $descr = esc_html($descr);
6419 } else {
6420 $descr = "$project " .
6421 ($format eq 'rss' ? 'RSS' : 'Atom') .
6422 " feed";
6424 my $owner = git_get_project_owner($project);
6425 $owner = esc_html($owner);
6427 #header
6428 my $alt_url;
6429 if (defined $file_name) {
6430 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6431 } elsif (defined $hash) {
6432 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6433 } else {
6434 $alt_url = href(-full=>1, action=>"summary");
6436 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6437 if ($format eq 'rss') {
6438 print <<XML;
6439 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6440 <channel>
6442 print "<title>$title</title>\n" .
6443 "<link>$alt_url</link>\n" .
6444 "<description>$descr</description>\n" .
6445 "<language>en</language>\n" .
6446 # project owner is responsible for 'editorial' content
6447 "<managingEditor>$owner</managingEditor>\n";
6448 if (defined $logo || defined $favicon) {
6449 # prefer the logo to the favicon, since RSS
6450 # doesn't allow both
6451 my $img = esc_url($logo || $favicon);
6452 print "<image>\n" .
6453 "<url>$img</url>\n" .
6454 "<title>$title</title>\n" .
6455 "<link>$alt_url</link>\n" .
6456 "</image>\n";
6458 if (%latest_date) {
6459 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6460 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6462 print "<generator>gitweb v.$version/$git_version</generator>\n";
6463 } elsif ($format eq 'atom') {
6464 print <<XML;
6465 <feed xmlns="http://www.w3.org/2005/Atom">
6467 print "<title>$title</title>\n" .
6468 "<subtitle>$descr</subtitle>\n" .
6469 '<link rel="alternate" type="text/html" href="' .
6470 $alt_url . '" />' . "\n" .
6471 '<link rel="self" type="' . $content_type . '" href="' .
6472 $cgi->self_url() . '" />' . "\n" .
6473 "<id>" . href(-full=>1) . "</id>\n" .
6474 # use project owner for feed author
6475 "<author><name>$owner</name></author>\n";
6476 if (defined $favicon) {
6477 print "<icon>" . esc_url($favicon) . "</icon>\n";
6479 if (defined $logo_url) {
6480 # not twice as wide as tall: 72 x 27 pixels
6481 print "<logo>" . esc_url($logo) . "</logo>\n";
6483 if (! %latest_date) {
6484 # dummy date to keep the feed valid until commits trickle in:
6485 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6486 } else {
6487 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6489 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6492 # contents
6493 for (my $i = 0; $i <= $#commitlist; $i++) {
6494 my %co = %{$commitlist[$i]};
6495 my $commit = $co{'id'};
6496 # we read 150, we always show 30 and the ones more recent than 48 hours
6497 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6498 last;
6500 my %cd = parse_date($co{'author_epoch'});
6502 # get list of changed files
6503 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6504 $co{'parent'} || "--root",
6505 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6506 or next;
6507 my @difftree = map { chomp; $_ } <$fd>;
6508 close $fd
6509 or next;
6511 # print element (entry, item)
6512 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6513 if ($format eq 'rss') {
6514 print "<item>\n" .
6515 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6516 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6517 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6518 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6519 "<link>$co_url</link>\n" .
6520 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6521 "<content:encoded>" .
6522 "<![CDATA[\n";
6523 } elsif ($format eq 'atom') {
6524 print "<entry>\n" .
6525 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6526 "<updated>$cd{'iso-8601'}</updated>\n" .
6527 "<author>\n" .
6528 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6529 if ($co{'author_email'}) {
6530 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6532 print "</author>\n" .
6533 # use committer for contributor
6534 "<contributor>\n" .
6535 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6536 if ($co{'committer_email'}) {
6537 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6539 print "</contributor>\n" .
6540 "<published>$cd{'iso-8601'}</published>\n" .
6541 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6542 "<id>$co_url</id>\n" .
6543 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6544 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6546 my $comment = $co{'comment'};
6547 print "<pre>\n";
6548 foreach my $line (@$comment) {
6549 $line = esc_html($line);
6550 print "$line\n";
6552 print "</pre><ul>\n";
6553 foreach my $difftree_line (@difftree) {
6554 my %difftree = parse_difftree_raw_line($difftree_line);
6555 next if !$difftree{'from_id'};
6557 my $file = $difftree{'file'} || $difftree{'to_file'};
6559 print "<li>" .
6560 "[" .
6561 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6562 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6563 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6564 file_name=>$file, file_parent=>$difftree{'from_file'}),
6565 -title => "diff"}, 'D');
6566 if ($have_blame) {
6567 print $cgi->a({-href => href(-full=>1, action=>"blame",
6568 file_name=>$file, hash_base=>$commit),
6569 -title => "blame"}, 'B');
6571 # if this is not a feed of a file history
6572 if (!defined $file_name || $file_name ne $file) {
6573 print $cgi->a({-href => href(-full=>1, action=>"history",
6574 file_name=>$file, hash=>$commit),
6575 -title => "history"}, 'H');
6577 $file = esc_path($file);
6578 print "] ".
6579 "$file</li>\n";
6581 if ($format eq 'rss') {
6582 print "</ul>]]>\n" .
6583 "</content:encoded>\n" .
6584 "</item>\n";
6585 } elsif ($format eq 'atom') {
6586 print "</ul>\n</div>\n" .
6587 "</content>\n" .
6588 "</entry>\n";
6592 # end of feed
6593 if ($format eq 'rss') {
6594 print "</channel>\n</rss>\n";
6595 } elsif ($format eq 'atom') {
6596 print "</feed>\n";
6600 sub git_rss {
6601 git_feed('rss');
6604 sub git_atom {
6605 git_feed('atom');
6608 sub git_opml {
6609 my @list = git_get_projects_list();
6611 print $cgi->header(
6612 -type => 'text/xml',
6613 -charset => 'utf-8',
6614 -content_disposition => 'inline; filename="opml.xml"');
6616 print <<XML;
6617 <?xml version="1.0" encoding="utf-8"?>
6618 <opml version="1.0">
6619 <head>
6620 <title>$site_name OPML Export</title>
6621 </head>
6622 <body>
6623 <outline text="git RSS feeds">
6626 foreach my $pr (@list) {
6627 my %proj = %$pr;
6628 my $head = git_get_head_hash($proj{'path'});
6629 if (!defined $head) {
6630 next;
6632 $git_dir = "$projectroot/$proj{'path'}";
6633 my %co = parse_commit($head);
6634 if (!%co) {
6635 next;
6638 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6639 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6640 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6641 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6643 print <<XML;
6644 </outline>
6645 </body>
6646 </opml>